# ============================================================ # core/security.py # ------------------------------------------------------------ # Provides a reusable FastAPI Dependency that enforces # API-key authentication via the custom header `X-Titan-Key`. # # Design choice: Header-based auth (not Bearer token) keeps # the gateway protocol-agnostic and easy to test with curl. # All routers import `require_titan_key` and declare it as a # FastAPI dependency so protection is opt-in per router, # rather than a blanket middleware that can't be bypassed for # health-check endpoints. # ============================================================ import os from fastapi import Header, HTTPException, status # --------------------------------------------------------------------------- # The master gateway secret. Set this as an environment variable in your # Hugging Face Space: Settings → Variables and Secrets → TITAN_GATEWAY_KEY # --------------------------------------------------------------------------- _TITAN_GATEWAY_KEY: str = os.environ.get("TITAN_GATEWAY_KEY", "change-me-in-production") async def require_titan_key(x_titan_key: str = Header(...)) -> None: """ FastAPI dependency that validates the `X-Titan-Key` request header. Usage in a router: @router.post("/endpoint", dependencies=[Depends(require_titan_key)]) FastAPI automatically returns HTTP 422 if the header is entirely absent. This function raises HTTP 403 if the key value doesn't match the secret. Raises: HTTPException 403 — if the key value does not match the secret. """ if x_titan_key != _TITAN_GATEWAY_KEY: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Invalid or missing X-Titan-Key header.", )