Integrity Failures in Fastapi with Hmac Signatures
Integrity Failures in Fastapi with Hmac Signatures — how this specific combination creates or exposes the vulnerability
HMAC-based integrity verification is commonly used in FastAPI services to ensure that request payloads have not been altered in transit. When the implementation is incomplete, such as verifying the signature only for selected endpoints, not validating the signature before processing mutable state, or using a weak or leaked secret, an integrity failure (BFLA/Privilege Escalation) can occur. An attacker who can guess or obtain the shared secret, or can inject data into a part of the request that is excluded from the signature, may forge requests that appear authentic to the application.
In FastAPI, a typical integration pattern uses a dependency that extracts a signature from a header (e.g., X-Signature) and recomputes HMAC over the raw request body. If the comparison is not performed in constant time, timing attacks can leak information about the signature. Moreover, if the endpoint also relies on query parameters or path parameters that are not included in the signed payload, an attacker can manipulate those parameters to change the effective resource identifier (BOLA/IDOR) while keeping the signature valid. For example, an order update endpoint that signs only the JSON body but allows the order_id to be controlled via a URL path can let an authenticated user tamper with another user’s order by iterating over identifiers.
Another common misconfiguration arises when the signature is computed over a serialized representation that differs from what the server expects at runtime (for example, missing or reordered fields, or different handling of nested objects). MiddleBrick’s BFLA/Privilege Escalation and Property Authorization checks detect these mismatches by correlating the OpenAPI spec definitions with runtime behavior, highlighting endpoints where the signed scope does not cover all mutable authorization-sensitive parameters.
Real-world attack patterns include forged webhook notifications and tampered API requests where the attacker preserves a valid HMAC on a subset of fields while modifying an authorization-critical field such as user_id or role. If the server does not enforce integrity across the entire message and does not validate the signature before applying any side effects, this can lead to unauthorized actions or privilege escalation. The LLM/AI Security checks in MiddleBrick additionally probe whether endpoints that accept model-generated tokens or tool calls inadvertently expose integrity-sensitive behavior to indirect inputs.
Hmac Signatures-Specific Remediation in Fastapi — concrete code fixes
To remediate integrity failures, ensure that the HMAC verification covers all inputs that affect authorization or state changes, and that verification occurs before any state mutation. Use a strong algorithm such as HMAC-SHA256, protect the shared secret, and perform constant-time comparison to mitigate timing attacks. Below is a concrete FastAPI example that signs the raw request body with a shared secret and validates the signature before processing the payload.
import hmac
import hashlib
from fastapi import FastAPI, Request, Header, HTTPException, Depends
from fastapi.responses import JSONResponse
app = FastAPI()
SHARED_SECRET = b"super-secure-secret" # store securely, e.g., via environment variable
def get_hmac_signature(body: bytes) -> str:
return hmac.new(SHARED_SECRET, body, hashlib.sha256).hexdigest()
def verify_hmac_signature(body: bytes, received_signature: str) -> bool:
expected = get_hmac_signature(body)
return hmac.compare_digest(expected, received_signature)
async def verify_signature(request: Request, x_signature: str = Header(...)):
body = await request.body()
if not verify_hmac_signature(body, x_signature):
raise HTTPException(status_code=401, detail="Invalid signature")
return body
@app.post("/orders/{order_id}")
async def update_order(
order_id: int,
body: bytes = Depends(verify_signature),
request: Request = None # kept for clarity; body already verified
):
# Process the verified payload only after signature validation
import json
payload = json.loads(body)
# Ensure order_id from path matches payload if present
if "order_id" in payload and payload["order_id"] != order_id:
raise HTTPException(status_code=403, detail="Path-parameter mismatch")
# Continue with update logic...
return JSONResponse(content={"status": "updated", "order_id": order_id})
# Example curl:
# PAYLOAD='{"order_id": 123, "status": "shipped"}'
# SIGNATURE=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "super-secure-secret" | sed 's/^.* //')
# curl -X POST http://localhost:8000/orders/123 -H "X-Signature: $SIGNATURE" -d "$PAYLOAD"
Key practices derived from the checks include: (1) include all mutable and authorization-sensitive parameters—such as identifiers, roles, or tenant context—either in the signed payload or as additional protected inputs; (2) perform verification before any business logic or state changes; (3) use hmac.compare_digest to avoid timing leaks; (4) rotate secrets and scope signatures to the minimal necessary context; and (5) align the signed scope with the API contract described in the OpenAPI spec to prevent desynchronization between specification and implementation.
MiddleBrick’s dashboard can track how these practices affect your security score over time, while the CLI can be integrated into scripts to validate HMAC coverage as part of routine checks. For CI/CD, the GitHub Action can enforce that endpoints with known integrity-sensitive operations fail the build if the signature scope does not match the defined resource model.
Frequently Asked Questions
What should be included in the HMAC signature to prevent integrity failures in FastAPI?
How can I avoid timing attacks when verifying HMAC signatures in FastAPI?
hmac.compare_digest to compare the computed signature with the received signature. Avoid early-exit string comparisons that can leak information through timing differences.