Production security hardening and operational guidelines
Overview
Implement these security best practices to harden your MCP Server deployment for production. This guide covers configuration, deployment, and operational security.
Security is an ongoing process, not a one-time setup. Regularly review and update your security posture.
Authentication Best Practices
Use Strong Authentication
Enforce MFA
Always require multi-factor authentication in production:
@app.post("/message")async def send_message(user: User = Depends(get_current_user)): if not user.mfa_verified: raise HTTPException( status_code=403, detail="MFA required for this operation" ) # Process request
import refrom zxcvbn import zxcvbndef validate_password(password: str, user_inputs: list) -> bool: # Check length if len(password) < 12: raise ValueError("Password must be at least 12 characters") # Check complexity if not re.search(r"[A-Z]", password): raise ValueError("Password must contain uppercase letter") if not re.search(r"[a-z]", password): raise ValueError("Password must contain lowercase letter") if not re.search(r"[0-9]", password): raise ValueError("Password must contain number") if not re.search(r"[!@#$%^&*]", password): raise ValueError("Password must contain special character") # Check strength result = zxcvbn(password, user_inputs=user_inputs) if result['score'] < 3: raise ValueError("Password is too weak") return True
# Session settingsSESSION_CONFIG = { "ttl": 3600, # 1 hour "sliding_window": True, # Extend on activity "max_concurrent_sessions": 3, # Limit per user "secure": True, # HTTPS only "httponly": True, # No JS access "samesite": "strict", # CSRF protection "session_fixation_protection": True, "regenerate_on_login": True}# Implement session timeoutasync def check_session_activity(session_id: str): session = await redis.get(f"session:{session_id}") if not session: raise SessionExpired() last_activity = session.get("last_activity") if datetime.utcnow() - last_activity > timedelta(hours=1): await redis.delete(f"session:{session_id}") raise SessionExpired()
Authorization Best Practices
Principle of Least Privilege
## Default deny, explicit allowDEFAULT_PERMISSIONS = { "user": ["viewer"], # Minimal by default "admin": ["admin", "member", "viewer"]}## Grant minimum required permissionsasync def onboard_user(user_id: str, role: str = "user"): """Add user with minimal permissions""" # Default viewer access only await openfga_client.write_tuples([{ "user": f"user:{user_id}", "relation": "viewer", "object": "organization:default" }]) # Require explicit grant for elevated access if role == "admin": # Requires admin approval await request_admin_approval(user_id)
Regular Permission Audits
#!/usr/bin/env python3## audit-permissions.pyasync def audit_permissions(): """Monthly permission audit""" # Find users with admin access admins = await openfga_client.list_users( relation="admin", object="organization:default" ) # Check if still needed for admin in admins: # Get user info user = await get_user(admin) # Check last activity if user.last_login < datetime.utcnow() - timedelta(days=90): logger.warning(f"Inactive admin: {admin}") await notify_security_team(f"Remove admin access for {admin}?") # Find overly permissive tuples all_tuples = await openfga_client.read_tuples() for tuple in all_tuples: if tuple['relation'] == 'owner' and tuple['object'].startswith('organization:'): # Multiple org owners is risky owners = await openfga_client.list_users( relation="owner", object=tuple['object'] ) if len(owners) > 3: logger.warning(f"Too many owners for {tuple['object']}: {owners}")
Resource Isolation
## Enforce organization boundariesasync def check_resource_access( user_id: str, resource_id: str, action: str): """Ensure users can only access resources in their org""" # Get user's organizations user_orgs = await openfga_client.list_objects( user=f"user:{user_id}", relation="member", object_type="organization" ) # Get resource's organization resource_org = await get_resource_organization(resource_id) # Check org membership if resource_org not in user_orgs: logger.security( "cross_org_access_attempt", user_id=user_id, resource_id=resource_id, user_orgs=user_orgs, resource_org=resource_org ) raise PermissionError("Cross-organization access denied") # Check specific permission allowed = await openfga_client.check_permission( user=f"user:{user_id}", relation=action, object=resource_id ) if not allowed: raise PermissionError(f"Action '{action}' not allowed") return True
Data Security Best Practices
Encryption
At Rest
In Transit
Application-Level
PostgreSQL Encryption:
-- Enable transparent data encryptionALTER SYSTEM SET ssl = on;ALTER SYSTEM SET ssl_ciphers = 'HIGH:!aNULL:!MD5';ALTER SYSTEM SET ssl_prefer_server_ciphers = on;ALTER SYSTEM SET ssl_min_protocol_version = 'TLSv1.3';-- Column-level encryption for sensitive dataCREATE EXTENSION IF NOT EXISTS pgcrypto;CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT, email_encrypted BYTEA DEFAULT pgp_sym_encrypt(email, current_setting('app.encryption_key')));
## Only collect necessary dataclass MessageRequest(BaseModel): query: str # Required # Don't collect: IP, user agent, etc. unless needed## Automatic PII removaldef sanitize_logs(log_data: dict) -> dict: """Remove PII from logs""" pii_fields = ['email', 'phone', 'ssn', 'credit_card'] sanitized = log_data.copy() for field in pii_fields: if field in sanitized: sanitized[field] = '***REDACTED***' return sanitized## Data retention policiesasync def enforce_retention_policy(): """Delete old data according to policy""" # Delete conversations older than 90 days cutoff = datetime.utcnow() - timedelta(days=90) await db.delete_conversations(older_than=cutoff) # Anonymize audit logs older than 1 year log_cutoff = datetime.utcnow() - timedelta(days=365) await db.anonymize_audit_logs(older_than=log_cutoff)
Secure Data Deletion
async def secure_delete_user(user_id: str): """GDPR-compliant user deletion""" # 1. Delete user data await db.execute("DELETE FROM users WHERE id = %s", (user_id,)) await db.execute("DELETE FROM conversations WHERE user_id = %s", (user_id,)) await db.execute("DELETE FROM sessions WHERE user_id = %s", (user_id,)) # 2. Remove from authorization system tuples = await openfga_client.read_tuples(user=f"user:{user_id}") await openfga_client.delete_tuples(tuples) # 3. Anonymize audit logs (keep for compliance) await db.execute( "UPDATE audit_logs SET user_id = 'deleted_user' WHERE user_id = %s", (user_id,) ) # 4. Clear caches await redis.delete(f"user:{user_id}:*") # 5. Log deletion logger.audit("user_deleted", user_id=user_id, timestamp=datetime.utcnow()) # 6. Overwrite sensitive data (defense in depth) # PostgreSQL VACUUM FULL reclaims space await db.execute("VACUUM FULL users")
## Use Infisical, not environment variablesfrom mcp_server_langgraph.core.config import settings## BAD - hardcodedAPI_KEY = "sk-1234567890abcdef"## BAD - environment variable (better but not ideal)API_KEY = os.getenv("API_KEY")## GOOD - secret managerAPI_KEY = settings.anthropic_api_key # Loaded from Infisical
Rotate Secrets Regularly
## Automated secret rotationasync def rotate_jwt_secret(): """Rotate JWT signing key monthly""" # Generate new key private_key = rsa.generate_private_key( public_exponent=65537, key_size=4096 ) # Store in Infisical await infisical_client.create_secret( secret_name=f"JWT_PRIVATE_KEY_{datetime.now().strftime('%Y%m')}", secret_value=private_key.private_bytes(...).decode(), project_id=settings.infisical_project_id, environment="production" ) # Update application config await update_config("JWT_KEY_ID", f"key-{datetime.now().strftime('%Y%m')}") # Keep old key for 24h for token validation await schedule_key_deletion(old_key_id, delay_hours=24)## Schedule rotationschedule.every().month.do(rotate_jwt_secret)