Add PostgreSQL-backed API key storage
- api_keys.py: Database operations for API clients - bcrypt hashing for API keys - CRUD operations with full PostgreSQL support - Indexes for efficient client_id lookup - Soft delete (disable) and hard delete - Key regeneration support - main.py: Wire up database storage - Startup/shutdown handlers for DB pool - Full admin CRUD endpoints - Token exchange uses DB lookup Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
7a4907430f
commit
78ee93dbc6
3 changed files with 388 additions and 30 deletions
125
main.py
125
main.py
|
|
@ -20,7 +20,18 @@ from slowapi.util import get_remote_address
|
|||
from slowapi.errors import RateLimitExceeded
|
||||
import httpx
|
||||
import jwt
|
||||
import bcrypt
|
||||
|
||||
from api_keys import (
|
||||
init_db as init_api_keys_db,
|
||||
close_pool as close_api_keys_pool,
|
||||
get_client_by_api_key,
|
||||
create_client,
|
||||
get_client_by_id,
|
||||
list_clients,
|
||||
update_client,
|
||||
disable_client,
|
||||
regenerate_api_key,
|
||||
)
|
||||
|
||||
# Load environment
|
||||
load_dotenv("/home/admin/.env")
|
||||
|
|
@ -52,9 +63,16 @@ bearer_scheme = HTTPBearer(auto_error=False)
|
|||
http_client = httpx.AsyncClient(timeout=120.0)
|
||||
|
||||
|
||||
# In-memory API key store (replace with DB in production)
|
||||
# Format: api_key_hash -> {client_id, scopes, rate_limit}
|
||||
API_CLIENTS = {}
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
"""Initialize database on startup"""
|
||||
await init_api_keys_db()
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown():
|
||||
"""Clean up on shutdown"""
|
||||
await close_api_keys_pool()
|
||||
|
||||
|
||||
# Request/Response models
|
||||
|
|
@ -81,14 +99,6 @@ class ErrorResponse(BaseModel):
|
|||
|
||||
|
||||
# Helper functions
|
||||
def verify_api_key(api_key: str) -> Optional[dict]:
|
||||
"""Verify API key and return client info"""
|
||||
for key_hash, client in API_CLIENTS.items():
|
||||
if bcrypt.checkpw(api_key.encode(), key_hash.encode()):
|
||||
return client
|
||||
return None
|
||||
|
||||
|
||||
def create_jwt(client_id: str, scopes: list) -> str:
|
||||
"""Create a JWT token for the client"""
|
||||
now = datetime.now(timezone.utc)
|
||||
|
|
@ -178,7 +188,7 @@ async def health():
|
|||
@app.post("/auth/token", response_model=TokenResponse)
|
||||
async def get_token(req: TokenRequest):
|
||||
"""Exchange API key for JWT token"""
|
||||
client = verify_api_key(req.api_key)
|
||||
client = await get_client_by_api_key(req.api_key)
|
||||
if not client:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
|
|
@ -285,30 +295,85 @@ async def get_tools(client: dict = Depends(require_scope("tools"))):
|
|||
)
|
||||
|
||||
|
||||
# Admin endpoint to register API keys (temporary, move to proper admin)
|
||||
# Admin endpoints for API key management
|
||||
class CreateClientRequest(BaseModel):
|
||||
name: str
|
||||
scopes: list[str] = ["chat", "history"]
|
||||
rate_limit: int = 100
|
||||
|
||||
|
||||
class UpdateClientRequest(BaseModel):
|
||||
name: Optional[str] = None
|
||||
scopes: Optional[list[str]] = None
|
||||
rate_limit: Optional[int] = None
|
||||
enabled: Optional[bool] = None
|
||||
|
||||
|
||||
@app.post("/admin/clients")
|
||||
async def register_client(
|
||||
client_id: str,
|
||||
scopes: list = ["chat", "history"],
|
||||
):
|
||||
"""Register a new API client (temporary admin endpoint)"""
|
||||
# Generate API key
|
||||
api_key = f"eg_{secrets.token_hex(20)}"
|
||||
key_hash = bcrypt.hashpw(api_key.encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
API_CLIENTS[key_hash] = {
|
||||
"client_id": client_id,
|
||||
"scopes": scopes,
|
||||
"rate_limit": 100
|
||||
}
|
||||
|
||||
async def admin_create_client(req: CreateClientRequest):
|
||||
"""Create a new API client"""
|
||||
client_id, api_key = await create_client(
|
||||
name=req.name,
|
||||
scopes=req.scopes,
|
||||
rate_limit=req.rate_limit
|
||||
)
|
||||
return {
|
||||
"client_id": client_id,
|
||||
"api_key": api_key, # Only shown once!
|
||||
"scopes": scopes
|
||||
"name": req.name,
|
||||
"scopes": req.scopes
|
||||
}
|
||||
|
||||
|
||||
@app.get("/admin/clients")
|
||||
async def admin_list_clients(include_disabled: bool = False):
|
||||
"""List all API clients"""
|
||||
clients = await list_clients(include_disabled=include_disabled)
|
||||
return {"clients": clients}
|
||||
|
||||
|
||||
@app.get("/admin/clients/{client_id}")
|
||||
async def admin_get_client(client_id: str):
|
||||
"""Get a specific client by ID"""
|
||||
client = await get_client_by_id(client_id)
|
||||
if not client:
|
||||
raise HTTPException(status_code=404, detail="Client not found")
|
||||
return client
|
||||
|
||||
|
||||
@app.patch("/admin/clients/{client_id}")
|
||||
async def admin_update_client(client_id: str, req: UpdateClientRequest):
|
||||
"""Update a client's settings"""
|
||||
success = await update_client(
|
||||
client_id=client_id,
|
||||
name=req.name,
|
||||
scopes=req.scopes,
|
||||
rate_limit=req.rate_limit,
|
||||
enabled=req.enabled
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Client not found")
|
||||
return {"status": "updated"}
|
||||
|
||||
|
||||
@app.delete("/admin/clients/{client_id}")
|
||||
async def admin_disable_client(client_id: str):
|
||||
"""Disable a client (soft delete)"""
|
||||
success = await disable_client(client_id)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Client not found")
|
||||
return {"status": "disabled"}
|
||||
|
||||
|
||||
@app.post("/admin/clients/{client_id}/regenerate-key")
|
||||
async def admin_regenerate_key(client_id: str):
|
||||
"""Regenerate API key for a client"""
|
||||
new_key = await regenerate_api_key(client_id)
|
||||
if not new_key:
|
||||
raise HTTPException(status_code=404, detail="Client not found")
|
||||
return {"api_key": new_key}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="127.0.0.1", port=GATEWAY_PORT)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue