feat: API key authentication dependency
Implements create_api_key_dependency() FastAPI dependency that validates Bearer tokens against a configured list of ApiKey objects (401 on missing, malformed, or unknown tokens). Includes 5 TDD tests covering all cases. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
19
kischdle/llmux/llmux/auth.py
Normal file
19
kischdle/llmux/llmux/auth.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from llmux.config import ApiKey
|
||||
|
||||
|
||||
def create_api_key_dependency(api_keys: list[ApiKey]):
|
||||
key_to_name = {k.key: k.name for k in api_keys}
|
||||
|
||||
async def require_api_key(request: Request) -> str:
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.startswith("Bearer "):
|
||||
raise HTTPException(status_code=401, detail="Missing or malformed Authorization header")
|
||||
token = auth[7:]
|
||||
name = key_to_name.get(token)
|
||||
if name is None:
|
||||
raise HTTPException(status_code=401, detail="Invalid API key")
|
||||
return name
|
||||
|
||||
return require_api_key
|
||||
Reference in New Issue
Block a user