MCP Gateway Security FeaturesΒΆ
Current Version: 0.8.0 (Beta) β The gateway ships with the controls described below. Everything listed here is present in the codebase today; future roadmap items live in docs/docs/architecture/roadmap.md.
Security Posture OverviewΒΆ
- Authentication on by default.
AUTH_REQUIRED=trueensures every API, SSE, and Admin UI route requires an authenticated session unless you explicitly opt out for local testing. - Secure defaults for operators. The service binds to
127.0.0.1unless overridden,MCPGATEWAY_UI_ENABLED=falseandMCPGATEWAY_ADMIN_API_ENABLED=falsekeep the Admin UI/API offline in production, and cookies are hardened withSECURE_COOKIES=true, HttpOnly, andSameSite=lax. - Environment-aware CORS & cookies.
ENVIRONMENTandAPP_DOMAINdrive cors/origin policy, switching between a localhost allowlist in development and strict origin checks in production (mcpgateway/middleware/security_headers.py). - Security posture reporting. Startup invokes
validate_security_configuration()(mcpgateway/main.py) which consumessettings.get_security_status()to log weak secrets, missing auth, or insecure federation setups. SettingREQUIRE_STRONG_SECRETS=trueupgrades warnings to hard failures.
Authentication & IdentityΒΆ
Core Gateway AuthenticationΒΆ
- HTTP Basic Auth protects the Admin UI and optionally the OpenAPI docs (
DOCS_ALLOW_BASIC_AUTH=true). Credentials are defined byBASIC_AUTH_USER/BASIC_AUTH_PASSWORD, and the config endpoint masks secrets (mcpgateway/admin.py). - JWT bearer tokens are required for API access and MCP transports when
MCP_CLIENT_AUTH_ENABLED=true(default). For reverse proxies you can opt intoTRUST_PROXY_AUTH=trueand provide the authenticated identity throughPROXY_USER_HEADER. - Token issuance tooling.
python -m mcpgateway.utils.create_jwt_tokenproduces gateway-signed tokens for automation. The helper respects configured expiry, issuer, and audience claims.
JWT Token ManagementΒΆ
- Algorithm agility.
mcpgateway/utils/jwt_config_helper.pysupports HS256/384/512, RS256/384/512, and ES256/384/512. For asymmetric algorithms the helper validates key paths on startup and reads the PEM material securely. - Secret validation. The Pydantic field validator (
Settings.validate_secrets) logs warnings for default or low-entropy secrets, and whenREQUIRE_STRONG_SECRETS=truestartup fails if critical values remain weak. - Revocation and audit. API tokens are modelled as JWTs with per-token
jtiidentifiers. Revocations (TokenRevocation) and usage logs (TokenUsageLog) persist to the database, enabling immediate invalidation and monitoring.
Email-Based AuthenticationΒΆ
- Argon2id password hashing.
EmailAuthServicehashes credentials with configurableARGON2ID_TIME_COST,ARGON2ID_MEMORY_COST, andARGON2ID_PARALLELISM. - Password policy controls. Minimum length and complexity are driven by
PASSWORD_MIN_LENGTHand related flags. Attempts that fail policy raisePasswordValidationError. - Account lockout & auditing.
MAX_FAILED_LOGIN_ATTEMPTSandACCOUNT_LOCKOUT_DURATION_MINUTESenforce lockouts at the ORM layer (EmailUser.increment_failed_attempts). Every login, registration, or password change emits anEmailAuthEventwith IP and user-agent metadata for investigation. - Admin bootstrap. The first superuser is provisioned from
PLATFORM_ADMIN_EMAIL/PLATFORM_ADMIN_PASSWORD, enabling secure initial access even when SSO is not configured.
Token Catalog & API KeysΒΆ
- Hashed personal and team tokens.
TokenCatalogServicestores only SHA-256 hashes (token_hash) of issued tokens (EmailApiToken) and keeps the raw secret in memory just long enough to present it once. - Fine-grained scopes. Tokens can be confined to a server, a permission list, IP CIDRs, and time-of-day or usage quotas via
TokenScope. - Usage analytics. Every request records method, endpoint, IP, user-agent, latency, and block reason in
TokenUsageLog, supporting anomaly detection. - Immediate revocation.
TokenRevocationentries are enforced before gateway execution, guaranteeing revoked tokens cannot be replayed.
OAuth & SSO FederationΒΆ
- Multi-provider SSO.
mcpgateway/services/sso_service.pysupports GitHub, Google, IBM Security Verify, Microsoft Entra ID, Okta, Keycloak, and generic OIDC providers. Secrets are encrypted with a Fernet key derived fromAUTH_ENCRYPTION_SECRET. - Security-state tracking.
SSOAuthSessionpersists OAuth state tokens, PKCEcode_verifier, and nonces to prevent CSRF and replay attacks. - Per-user OAuth vault.
TokenStorageServiceencrypts access/refresh tokens using AES-GCM (oauth_encryption.py) and keys them by both gateway and gateway user to prevent cross-tenant leakage. - Dynamic Client Registration (DCR).
DcrServicediscovers OAuth metadata (RFC 8414), honours issuer allowlists (DCR_ALLOWED_ISSUERS), registers clients, and encrypts the resulting client secrets and registration access tokens before storing them (RegisteredOAuthClient). - Tool credential encryption. The same
AUTH_ENCRYPTION_SECRETpowersservices_auth.encode_auth()to store upstream tool auth blobs as AES-GCM tokens inside the database.
Authorization & Access ControlΒΆ
- Role-Based Access Control (RBAC).
PermissionServiceandRoleServiceimplement global/team/personal scopes with caching, inheritance, and audit logging (PermissionAuditLog). Admin bypass is explicit, and permission checks default to deny on error. - Multi-tenancy primitives. Teams, invites, and memberships (
EmailTeam,EmailTeamMember,TeamInvitationService) enforce owner-only invitations, configurable expiry, and per-team quotas (MAX_TEAMS_PER_USER,MAX_MEMBERS_PER_TEAM). Personal teams can be auto-created withAUTO_CREATE_PERSONAL_TEAMS=true. - Resource visibility. Tools, prompts, resources, and gateways include a
visibilityflag (private/team/public) that PermissionService respects when resolving access. - Feature gating. Administrative capabilities stay off unless you opt in:
MCPGATEWAY_UI_ENABLED,MCPGATEWAY_ADMIN_API_ENABLED,MCPGATEWAY_BULK_IMPORT_ENABLED,MCPGATEWAY_CATALOG_ENABLED, andMCPGATEWAY_A2A_ENABLEDall default to safe values. - Scoped API credentials. Tokens can be restricted to individual virtual servers, explicit permission strings, and IP ranges; blocked requests are captured via
TokenUsageLog.blocked. - Header passthrough controls.
utils/passthrough_headers.pykeeps passthrough disabled unlessENABLE_HEADER_PASSTHROUGH=true, sanitises header names/values, rejects conflictingAuthorizationheaders, and lets clients safely supplyX-Upstream-Authorizationfor upstream delegation. - Policy-as-code plugins. The plugin framework powers deny/allow decisions before and after prompt/tool/resource execution. Security-focused plugins include
deny_filter,pii_filter,content_moderation,output_length_guard,schema_guard,sql_sanitizer,secrets_detection,rate_limiter,url_reputation,vault,watchdog, and the optional external OPA integration for Rego policies (plugins/external/opa). - Federation safeguards. Startup validation warns when
federation_enabledis combined with unauthenticated deployments, and federation forwarding honours global rate limits to protect upstream peers.
Data Protection & Secret HandlingΒΆ
- AES-GCM secret vault.
mcpgateway/utils/services_auth.pyderives a 32-byte key fromAUTH_ENCRYPTION_SECRETand encrypts tool/resource credentials, ensuring secrets stored in the database or logs are opaque without the passphrase. - Encrypted OAuth/SSO secrets. The SSO service and DCR service wrap client secrets and registration tokens with Fernet and only decrypt them on demand.
- Cookie security helpers.
utils/security_cookies.pysets auth/session cookies with HttpOnly,SameSite, andsecureflags (enforced for production or whenSECURE_COOKIES=true) and provides symmetric deletion helpers to avoid stale cookies. - Security headers middleware.
SecurityHeadersMiddlewareadds CSP, X-Frame-Options (defaultDENY), X-Content-Type-Options (nosniff), X-Download-Options (noopen), Referrer-Policy, HSTS (when HTTPS is detected), and stripsServer/X-Powered-Byheaders. - TLS ready.
make certscreates local certificates,make serve-sslruns Gunicorn with TLS, and the client defaults keepSKIP_SSL_VERIFY=false. The container images trust RHEL certificate bundles for outbound TLS. - Support bundle sanitisation.
SupportBundleServiceredacts passwords, tokens, secrets, and bearer values before writing diagnostic ZIPs. Patterns cover API keys, JWTs, Authorization headers, and database URLs. - Configuration masking.
/admin/config/settingshides sensitive keys using themask_sensitivehelper to prevent secret exfiltration through the Admin UI/API. - Hardened containers.
Containerfile.litebuilds on patched RHEL UBI 10 β¦ scratch, installs dependencies in a venv, strips debugging symbols, removes package managers, deletes setuid/setgid binaries, creates a non-rootUID 1001, preserves the RPM DB for scanning, and sets security-oriented runtime env vars. - Logging controls.
LoggingServicecentralises formatting with JSON or text output, supports log rotation, and the support bundle honours size/line caps to avoid log leakage.
Input Validation & GuardrailsΒΆ
- SecurityValidator centralises sanitisation.
mcpgateway/validators.pyenforces length limits, safe character sets, scheme allowlists, JSON depth (MAX_JSON_DEPTH), and detects dangerous HTML/JS patterns across every Pydantic schema. - Schema-driven enforcement.
mcpgateway/schemas.pyapplies the validator to tool names, URLs, resource URIs, descriptions, prompts, and JSON payloads, trimming or rejecting unsafe values before they hit business logic. - Guardrail plugins. Content filters (PII, harmful content, markdown cleanup), output length guards, regex filters, and SQL sanitizers run as pre/post hooks to block malicious prompt/tool/resource usage.
- Rate limiting & quotas. Admin routes use the
rate_limitdecorator to enforce per-IP quotas (admin.py), bulk import has configurable ceilings (MCPGATEWAY_BULK_IMPORT_RATE_LIMIT,MCPGATEWAY_BULK_IMPORT_MAX_TOOLS), and runtime limits (tool_rate_limit,tool_timeout,tool_concurrent_limit) prevent resource exhaustion. - Header and payload hygiene. Passthrough headers strip control characters, clamp values to 4 KB, and refuse malformed names; request/response retries honour jitter and backoff to mitigate abuse.
- Secure invitation flows. Team invitations use cryptographically random, URL-safe tokens, enforce owner-only issuance, respect expiry, and prevent over-subscribing teams (
TeamInvitationService).
Operational Security & MonitoringΒΆ
- Startup enforcement.
validate_security_configuration()blocks boot when critical issues remain andREQUIRE_STRONG_SECRETS=true, and otherwise prints actionable warnings (default secrets, disabled auth, SSL verification overrides). - Continuous telemetry. Permission checks, OAuth flows, and token usage log structured events with timestamps, IP addresses, user-agent strings, span attributes, and success/failure flags for downstream monitoring.
- Security tooling baked into the build. The
Makefileexposesmake security-all,make security-scan,make security-report,make bandit,make semgrep,make dodgy,make gitleaks,make trivy,make grype-scan,make snyk-all, andmake fuzz-security, providing repeatable security automation for CI/CD. - Observability hooks. OpenTelemetry exports (when configured) tag spans with error flags, latency, and success status, supporting tracing-based detection of anomalies.
- Support bundle hygiene. Operators can gather diagnostics without leaking credentials thanks to sanitisation routines and configurable size/time limits.
Production Hardening ChecklistΒΆ
- Set production posture. Run with
ENVIRONMENT=production, configureAPP_DOMAINand explicitALLOWED_ORIGINS, and leaveSKIP_SSL_VERIFY=false. - Harden secrets. Rotate
BASIC_AUTH_PASSWORD,JWT_SECRET_KEY,AUTH_ENCRYPTION_SECRET,PLATFORM_ADMIN_PASSWORD, and database credentials; enableREQUIRE_STRONG_SECRETS=trueso weak values stop startup. - Keep auth mandatory. Maintain
AUTH_REQUIRED=true,MCP_CLIENT_AUTH_ENABLED=true, and only enableTRUST_PROXY_AUTHbehind a trusted authentication proxy. - Disable unused surfaces. Leave
MCPGATEWAY_UI_ENABLED=false,MCPGATEWAY_ADMIN_API_ENABLED=false,MCPGATEWAY_BULK_IMPORT_ENABLED=false,MCPGATEWAY_A2A_ENABLED=false, andMCPGATEWAY_CATALOG_ENABLED=falseunless you actively use them. - Leave header passthrough off.
ENABLE_HEADER_PASSTHROUGH=false(default) should only change after reviewing downstream requirements and allowlists. - Secure the data plane. Terminate TLS with real certificates (
make certs/make serve-sslor a fronting proxy), and prefer PostgreSQL/MySQL with TLS over SQLite in production. - Monitor activity. Ship
token_usage_logs,email_auth_events, audit trails, and structured logs to your SIEM/observability stack; alert on repeated failures or blocked requests. - Lock down federation. If
federation_enabledremains on, restrictFEDERATION_PEERS, ensure every peer enforces auth, and monitor health-check traffic. - Automate security checks. Integrate the security Make targets into CI/CD so images, dependencies, and IaC are scanned before deployment.
Planned & In-Progress Enhancements (π§ Planned)ΒΆ
The items below are active roadmap work or design explorations. Track status in docs/docs/architecture/roadmap.md and the linked GitHub issues.
Authentication & AuthorizationΒΆ
- π§ Attribute-Based Access Control (ABAC) β Use user attributes and resource metadata to supplement RBAC for multi-tenant servers (#706).
- π§ Policy-as-Code enforcement β Integrate Rego/OPA policies directly into gateway decisions beyond the current optional plugin (#271).
- π§ Per-virtual-server API keys & conditional capabilities β Expand token scopes to cover tool-level capability grants and auto-expiry policies.
Data Protection & SecretsΒΆ
- π§ HashiCorp Vault & external KMS β Native secret backends for tool credentials, JWT keys, and OAuth secrets (#542).
- π§ mTLS and certificate pinning β Stronger upstream trust requirements for MCP servers with automatic pin management (#568).
- π§ Data Loss Prevention (DLP) β Inline scanning for sensitive payloads with redact-or-drop policies.
- π§ Advanced cryptography β Evaluating TEEs, HSM-backed signing, and post-quantum algorithms for long-lived deployments.
Runtime & Infrastructure SecurityΒΆ
- π§ Container runtime enforcement β Integrations for Falco, AppArmor/SELinux profiles, seccomp, and CapDrop during container deployment.
- π§ Service mesh alignment β Dedicated Istio/Linkerd blueprints for mTLS, traffic policies, and zero-trust networking.
- π§ Federated attestation β Signing/verification workflow for MCP gateways and servers to establish trust before federation link-up.
- π§ Sandboxed execution β gVisor, Firecracker, or WebAssembly sandboxes for untrusted MCP servers and plugins.
Monitoring & GovernanceΒΆ
- π§ Dynamic security posture scoring β Automated risk evaluations enriched with runtime metrics and audit history.
- π§ Behavioral analytics β ML-assisted anomaly detection for unusual tool usage, prompt patterns, or federation activity.
- π§ Immutable audit trails β Evaluating tamper-resistant storage (e.g., append-only or ledger-backed logs) for high-assurance environments.
These features remain aspirational until the associated PRs merge. Expect the documentation to move them into the "Current" sections when code lands.
Additional ReferencesΒΆ
- Configuration reference:
.env.exampleandREADME.mdcover every toggle in more depth. - Security policy:
SECURITY.mddocuments vulnerability disclosure expectations. - Multi-tenancy details:
docs/docs/architecture/multitenancy.mddigs deeper into RBAC and team scoping. - Deployment guidance:
docs/docs/deployment/helm.mdandContainerfile.liteshowcase hardened deployment patterns.