@@ -1398,46 +1398,52 @@ async def dispatch(self, request: Request, call_next):
13981398app .add_middleware (SecurityHeadersMiddleware )
13991399
14001400
1401- class APIKeyRestrictionMiddleware (BaseHTTPMiddleware ):
1402- async def dispatch (self , request : Request , call_next ):
1403- auth_header = request .headers .get ("Authorization" )
1404- token = None
1405-
1406- if auth_header :
1407- parts = auth_header .split (" " , 1 )
1408- if len (parts ) == 2 :
1409- token = parts [1 ]
1410-
1411- # Only apply restrictions if an sk- API key is used
1412- if token and token .startswith ("sk-" ):
1413- # Check if restrictions are enabled
1414- if request .app .state .config .ENABLE_API_KEYS_ENDPOINT_RESTRICTIONS :
1415- allowed_paths = [
1416- path .strip ()
1417- for path in str (
1418- request .app .state .config .API_KEYS_ALLOWED_ENDPOINTS
1419- ).split ("," )
1420- if path .strip ()
1421- ]
1422-
1423- request_path = request .url .path
1424-
1425- # Match exact path or prefix path
1426- is_allowed = any (
1427- request_path == allowed or request_path .startswith (allowed + "/" )
1428- for allowed in allowed_paths
1429- )
1430-
1431- if not is_allowed :
1432- return JSONResponse (
1433- status_code = status .HTTP_403_FORBIDDEN ,
1434- content = {
1435- "detail" : "API key not allowed to access this endpoint."
1436- },
1401+ class APIKeyRestrictionMiddleware :
1402+ def __init__ (self , app ):
1403+ self .app = app
1404+
1405+ async def __call__ (self , scope , receive , send ):
1406+ if scope ["type" ] == "http" :
1407+ request = Request (scope )
1408+ auth_header = request .headers .get ("Authorization" )
1409+ token = None
1410+
1411+ if auth_header :
1412+ parts = auth_header .split (" " , 1 )
1413+ if len (parts ) == 2 :
1414+ token = parts [1 ]
1415+
1416+ # Only apply restrictions if an sk- API key is used
1417+ if token and token .startswith ("sk-" ):
1418+ # Check if restrictions are enabled
1419+ if app .state .config .ENABLE_API_KEYS_ENDPOINT_RESTRICTIONS :
1420+ allowed_paths = [
1421+ path .strip ()
1422+ for path in str (
1423+ app .state .config .API_KEYS_ALLOWED_ENDPOINTS
1424+ ).split ("," )
1425+ if path .strip ()
1426+ ]
1427+
1428+ request_path = request .url .path
1429+
1430+ # Match exact path or prefix path
1431+ is_allowed = any (
1432+ request_path == allowed
1433+ or request_path .startswith (allowed + "/" )
1434+ for allowed in allowed_paths
14371435 )
14381436
1439- response = await call_next (request )
1440- return response
1437+ if not is_allowed :
1438+ await JSONResponse (
1439+ status_code = status .HTTP_403_FORBIDDEN ,
1440+ content = {
1441+ "detail" : "API key not allowed to access this endpoint."
1442+ },
1443+ )(scope , receive , send )
1444+ return
1445+
1446+ await self .app (scope , receive , send )
14411447
14421448
14431449app .add_middleware (APIKeyRestrictionMiddleware )
0 commit comments