from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from ..errors import error_response from ..settings import get_settings NO_AUTH_PATHS = {"/api/v1/health", "/api/v1/ready", "/metrics"} class BearerAuthMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): if request.url.path in NO_AUTH_PATHS: return await call_next(request) expected = get_settings().auth_token header = request.headers.get("authorization") if not header or not header.lower().startswith("bearer "): return error_response(request, 401, "unauthorized", "authentication required") token = header.split(" ", 1)[1].strip() if token != expected: return error_response(request, 401, "unauthorized", "authentication required") return await call_next(request)