Harden your live domain headers, OpenAPI schemas & AEO discovery
Test your deployed domain's security headers, HSTS, CSP & DMARC live on ReadyCheck, diff OpenAPI contracts & OWASP API Top 10 risks in SpecDiff, or deploy all 9 production configs in minutes with the $49 ReadyCheck Fix Pack.
import crypto from "node:crypto";
export function verifyWebhook(rawBodyBytes, headers, secret) {
const sig = headers["stripe-signature"] || "";
const parts = Object.fromEntries(sig.split(",").map((p) => p.split("=")));
const signed = `${parts.t}.${rawBodyBytes.toString("utf8")}`;
const expected = crypto.createHmac("sha256", secret).update(signed).digest("hex");
return crypto.timingSafeEqual(Buffer.from(parts.v1 || "", "utf8"), Buffer.from(expected, "utf8"));
}
Live API & Edge AuditZero-Upload SpecDiff
Harden your live domain headers, OpenAPI schemas & AEO discovery
Test your deployed domain's security headers, HSTS, CSP & DMARC live on ReadyCheck, diff OpenAPI contracts & OWASP API Top 10 risks in SpecDiff, or deploy all 9 production configs in minutes with the $49 ReadyCheck Fix Pack.
import hmac, hashlib
from fastapi import APIRouter, Request, HTTPException
router = APIRouter()
@router.post("/webhooks/creem")
async def creem_webhook(request: Request):
raw_body = await request.body() # Exact bytes! Never await request.json() before HMAC!
sig = request.headers.get("creem-signature", "")
expected = hmac.new(b"whsec_...", raw_body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, expected):
raise HTTPException(status_code=401, detail="Invalid signature")
return {"received": True}
Key Engineering Takeaways
FastAPI wraps Starlette's CORSMiddleware: if allow_origins=['*'] and allow_credentials=True are combined, browsers reject the wildcard credentialed response (or Starlette falls back to reflecting arbitrary Origin headers — a critical CSRF risk).
Always register CORSMiddleware after custom auth/logging middlewares so unhandled exceptions or 401 responses still carry Access-Control-Allow-Origin headers.
Using allow_origin_regex='https://.*\.example\.com' safely handles preview deployments when anchored strictly with ^https://...$.
Reading await request.json() and calling json.dumps() before computing webhook HMAC breaks signatures whenever whitespace or key ordering differs.
Forgetting to list custom headers like X-API-Key or Idempotency-Key in allow_headers when allow_credentials=True (wildcard '*' headers are ignored in credentialed requests).
Configure Nginx reverse-proxy CORS safely using map $http_origin, the always directive on 204/4xx/5xx responses, and Vary: Origin without breaking header inheritance.
Implement dynamic multi-origin CORS with Vary: Origin in Next.js App Router route handlers and middleware.ts without the single-origin limitation of static next.config.mjs headers().
Verify GitHub X-Hub-Signature-256 and Slack v0= webhook signatures using constant-time crypto.timingSafeEqual, raw request bytes, and timestamp replay protection.
Implement production-grade billing webhook HMAC-SHA256 verification for Stripe (`t=<ts>,v1=<hex>`) and Creem (`creem-signature: <hex>`) with raw-body preservation and replay checks.
Why does FastAPI return 'CORS error' when my route raises an unhandled 500 exception?
Starlette's ServerErrorMiddleware sits outside user middlewares by default and returns 500 without CORS headers. Catch domain exceptions cleanly and register CORSMiddleware outermost.
Can I use allow_origins=['*'] with Bearer Authorization headers?
Only if credentials: 'omit'/'same-origin' and allow_credentials=False! Even then, explicit origin allowlists are strongly recommended for authenticated APIs.
How do I test my FastAPI CORS policy before deploying?
Configure your origins and headers in the CORS Preflight Linter above to verify simulated 204 preflight output and catch Fetch spec violations.