import hmac import os from fastapi import Header, HTTPException def require_service_key(x_service_key: str | None = Header(default=None)) -> None: """ Shared-secret gate for the compute endpoints (/extract-resume, /tts). This service is only ever called by the NestJS backend, but on a public host it is reachable by anyone — without this, the TTS and extraction compute is free for whoever finds the URL. Fails closed: if SERVICE_API_KEY is unset the endpoints refuse traffic rather than running open, so a missing env var can't silently expose them. Health checks stay unauthenticated so platform probes keep working. """ expected = os.getenv("SERVICE_API_KEY") if not expected: raise HTTPException( status_code=503, detail="Service authentication is not configured.", ) # compare_digest avoids leaking the key through response timing. if not x_service_key or not hmac.compare_digest(x_service_key, expected): raise HTTPException(status_code=401, detail="Invalid or missing service key.")