Integrity Failures in Fastapi with Api Keys
Integrity Failures in Fastapi with Api Keys
In FastAPI, using API keys for authentication can lead to integrity failures when keys are transmitted insecurely, stored without adequate protection, or validated inconsistently across endpoints. Integrity failures occur when an attacker can alter the request path, headers, or parameters in a way that bypasses intended authorization checks or causes the server to process requests with incorrect assumptions about identity and permissions.
When API keys are passed via query parameters or non-HTTPS channels, they can be intercepted or logged, enabling an attacker to impersonate a client and execute actions on behalf of the legitimate caller. FastAPI applications that concatenate user input directly into database queries or configuration lookups—even when using API keys for initial access—risk integrity violations if the key is treated as the sole authority for access control. For example, an endpoint that reads api_key = request.query_params.get("api_key") and then uses it to select a tenant without additional scope validation may allow horizontal privilege escalation across tenants.
Another common pattern is storing API keys in plaintext configuration or environment variables without runtime integrity verification. If an attacker gains read access to the deployment environment (for instance, via a compromised container or misconfigured secret manager), they can extract keys and craft requests that the server accepts as authentic. Because FastAPI does not enforce schema-level validation on headers and query parameters by default, keys may be silently coerced or truncated, leading to inconsistent authorization decisions.
Middleware that sets request.state.api_key based on a header or query parameter can inadvertently propagate a key that hasn’t been verified for scope or context, allowing a caller to reuse a key intended for read-only operations against write endpoints. If route dependencies rely solely on the presence of a key rather than binding the key to a specific set of permissions, integrity checks become inconsistent across the attack surface. This inconsistency is especially dangerous when combined with path parameters that influence resource selection without additional authorization checks, as an attacker may modify the resource identifier while retaining a valid key, leading to unauthorized data access or modification.
OpenAPI/Swagger spec analysis can expose these integrity risks by comparing declared security schemes with actual runtime behavior. For instance, if the spec defines an apiKey security scheme but the implementation does not enforce HTTPS or validate key scope per operation, the discrepancy can be leveraged. middleBrick’s OpenAPI/Swagger spec analysis resolves $ref definitions and cross-references them with runtime findings to highlight missing integrity constraints such as missing security requirements on write operations.
Real-world attack patterns such as parameter tampering and IDOR often intersect with integrity failures in FastAPI when API keys are used without binding to a subject or tenant context. A request like /v1/tenants/{tenant_id}/users that accepts an API key in a header may still allow an attacker to change tenant_id if the key is not validated against that tenant. The server may incorrectly assume that possession of a valid key implies authorization for any tenant identifier, violating integrity and enabling BOLA or IDOR.
Api Keys-Specific Remediation in Fastapi
Remediation focuses on binding API keys to a scope, enforcing transport integrity, and validating permissions on every request. Use HTTPS exclusively and avoid exposing keys in URLs. Store keys securely and validate them against an access control list that includes allowed paths and operations. In FastAPI, implement dependency injection that checks both the key and the requested resource context.
Below is a concrete FastAPI example that demonstrates secure API key usage with scope-based validation. The key is passed in a header, verified against a predefined mapping that includes allowed scopes, and used to constrain the tenant context. This prevents integrity failures by ensuring that a valid key cannot be reused across tenants or operations without explicit authorization.
from fastapi import FastAPI, Depends, Header, HTTPException, status
from typing import Dict
app = FastAPI()
# Example mapping: in production, store this securely and rotate keys
API_KEYS = {
"s3cr3tk3y-tenantA": {"tenant_id": "tenantA", "scopes": ["read:users", "write:users"]},
"s3cr3tk3y-tenantB": {"tenant_id": "tenantB", "scopes": ["read:users"]},
}
def get_api_key(x_api_key: str = Header(None)):
if not x_api_key:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing API key",
)
key_info = API_KEYS.get(x_api_key)
if not key_info:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid API key",
)
return key_info
@app.get("/v1/me")
def read_me(tenant: str, api_key_info: Dict = Depends(get_api_key)):
# Ensure the request context matches the key's tenant
if f"tenant/{tenant}" not in request.url.path:
raise HTTPException(status_code=400, detail="Tenant mismatch")
# Scope check example (extend per operation)
if "read:users" not in api_key_info["scopes"]:
raise HTTPException(status_code=403, detail="Insufficient scope")
return {"tenant": tenant, "user": "current_user"}
@app.post("/v1/users")
def create_user(tenant: str, api_key_info: Dict = Depends(get_api_key)):
if "write:users" not in api_key_info["scopes"]:
raise HTTPException(status_code=403, detail="Insufficient scope for write")
# Process creation within the tenant context bound to the key
return {"tenant": tenant, "status": "created"}
To further reduce integrity risks, enforce HTTPS via middleware, avoid logging keys, and rotate them periodically. Combine API key validation with per-endpoint role and scope checks rather than relying on the key alone. middleBrick’s CLI tool can be used in scripts to validate that your security rules are consistently applied across endpoints, and the Pro plan’s continuous monitoring can alert you if a key is used from unexpected contexts or if new endpoints lack required integrity checks.
For CI/CD integration, the GitHub Action can enforce a minimum security score before deployment, ensuring that new routes include proper key binding and scope validation. This reduces the likelihood of integrity failures reaching production. The MCP Server allows AI coding assistants to invoke scans directly, helping developers understand the security implications of key usage patterns during implementation.