perf: convert APIKeyRestrictionMiddleware to pure ASGI (#22188)

This commit is contained in:
Algorithm5838
2026-03-06 14:54:03 -06:00
committed by GitHub
parent 2153c8ec9f
commit 39deadcab1
+15 -9
View File
@@ -1398,8 +1398,13 @@ app.add_middleware(RedirectMiddleware)
app.add_middleware(SecurityHeadersMiddleware) app.add_middleware(SecurityHeadersMiddleware)
class APIKeyRestrictionMiddleware(BaseHTTPMiddleware): class APIKeyRestrictionMiddleware:
async def dispatch(self, request: Request, call_next): def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] == "http":
request = Request(scope)
auth_header = request.headers.get("Authorization") auth_header = request.headers.get("Authorization")
token = None token = None
@@ -1411,11 +1416,11 @@ class APIKeyRestrictionMiddleware(BaseHTTPMiddleware):
# Only apply restrictions if an sk- API key is used # Only apply restrictions if an sk- API key is used
if token and token.startswith("sk-"): if token and token.startswith("sk-"):
# Check if restrictions are enabled # Check if restrictions are enabled
if request.app.state.config.ENABLE_API_KEYS_ENDPOINT_RESTRICTIONS: if app.state.config.ENABLE_API_KEYS_ENDPOINT_RESTRICTIONS:
allowed_paths = [ allowed_paths = [
path.strip() path.strip()
for path in str( for path in str(
request.app.state.config.API_KEYS_ALLOWED_ENDPOINTS app.state.config.API_KEYS_ALLOWED_ENDPOINTS
).split(",") ).split(",")
if path.strip() if path.strip()
] ]
@@ -1424,20 +1429,21 @@ class APIKeyRestrictionMiddleware(BaseHTTPMiddleware):
# Match exact path or prefix path # Match exact path or prefix path
is_allowed = any( is_allowed = any(
request_path == allowed or request_path.startswith(allowed + "/") request_path == allowed
or request_path.startswith(allowed + "/")
for allowed in allowed_paths for allowed in allowed_paths
) )
if not is_allowed: if not is_allowed:
return JSONResponse( await JSONResponse(
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
content={ content={
"detail": "API key not allowed to access this endpoint." "detail": "API key not allowed to access this endpoint."
}, },
) )(scope, receive, send)
return
response = await call_next(request) await self.app(scope, receive, send)
return response
app.add_middleware(APIKeyRestrictionMiddleware) app.add_middleware(APIKeyRestrictionMiddleware)