"""Optional bearer-token auth for public deployments. If LWSS_API_KEY is set, every request must carry `Authorization: Bearer ` (constant-time compared). /health is always exempt so container healthchecks and uptime monitors work without the key. If the key is unset, auth is disabled and a warning is logged — intended only for trusted/LAN use. """ import hmac import logging from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import JSONResponse log = logging.getLogger("orchestrator") EXEMPT_PATHS = {"/health"} class BearerAuthMiddleware(BaseHTTPMiddleware): def __init__(self, app, api_key: str): super().__init__(app) self._api_key = api_key if not api_key: log.warning("LWSS_API_KEY is empty; authentication DISABLED (trusted networks only)") async def dispatch(self, request: Request, call_next): if not self._api_key or request.url.path in EXEMPT_PATHS: return await call_next(request) header = request.headers.get("authorization", "") scheme, _, token = header.partition(" ") if scheme.lower() != "bearer" or not hmac.compare_digest(token, self._api_key): return JSONResponse({"detail": "missing or invalid bearer token"}, status_code=401) return await call_next(request)