-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_app_middleware_api_key_security.py
More file actions
217 lines (191 loc) · 8.67 KB
/
diff_app_middleware_api_key_security.py
File metadata and controls
217 lines (191 loc) · 8.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
diff --git a/app/middleware/api_key_security.py b/app/middleware/api_key_security.py
index 3e342fd7..38ce1de7 100644
--- a/app/middleware/api_key_security.py
+++ b/app/middleware/api_key_security.py
@@ -3,17 +3,18 @@ Enhanced API Key Security Middleware
Enforces rotation policies, IP whitelisting, and usage tracking
"""
import logging
-import asyncio
-from datetime import datetime
+from datetime import datetime, timezone
from typing import Optional
from fastapi import Request, Response, HTTPException, status
from starlette.middleware.base import BaseHTTPMiddleware
-from sqlalchemy.orm import Session
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
-from app.db import get_db
+from app.db import get_async_session
from app.models import ApiKey, Tenant
from app.services.api_key_security import api_key_security_service
from app.utils.api_key_utils import hash_api_key
+from app.utils.auth import derive_api_key_role
logger = logging.getLogger(__name__)
@@ -49,19 +50,20 @@ class ApiKeySecurityMiddleware(BaseHTTPMiddleware):
# Extract API key from request
api_key = self._extract_api_key(request)
if not api_key:
- # No API key provided - let the request continue for public endpoints
- return await call_next(request)
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="API key required"
+ )
- try:
- # Get database session
- db = next(get_db())
+ endpoint = request.url.path
+ client_ip = self._get_client_ip(request)
- try:
- # Validate API key and get associated records
+ try:
+ async with get_async_session() as db:
api_key_record, tenant = await self._validate_api_key(db, api_key)
if not api_key_record:
- logger.warning(f"Invalid API key attempt from {self._get_client_ip(request)}")
+ logger.warning(f"Invalid API key attempt from {client_ip}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or inactive API key"
@@ -87,7 +89,6 @@ class ApiKeySecurityMiddleware(BaseHTTPMiddleware):
)
# Check IP whitelist
- client_ip = self._get_client_ip(request)
if not self.security_service.is_ip_allowed(client_ip, api_key_record):
logger.warning(f"IP not whitelisted: {client_ip} for key {api_key_record.prefix}")
raise HTTPException(
@@ -98,21 +99,18 @@ class ApiKeySecurityMiddleware(BaseHTTPMiddleware):
}
)
- # Track usage (async, non-blocking)
- endpoint = request.url.path
- asyncio.create_task(
- self.security_service.track_usage(
- db, api_key_record.id, tenant.id, endpoint
- )
- )
+ # Update last used timestamp and track usage
+ api_key_record.last_used_at = datetime.now(timezone.utc)
+ await self.security_service.track_usage(db, api_key_record.id, tenant.id, endpoint)
+ await db.commit()
- # Update last used timestamp
- api_key_record.last_used_at = datetime.now()
- db.commit()
+ role = derive_api_key_role(api_key_record, tenant)
# Inject security context into request
request.state.api_key_id = api_key_record.id
request.state.tenant_id = tenant.id
+ request.state.tenant_role = role
+ request.state.tenant_active = tenant.active
request.state.tenant = tenant
request.state.api_key_prefix = api_key_record.prefix
@@ -123,15 +121,12 @@ class ApiKeySecurityMiddleware(BaseHTTPMiddleware):
"tenant_id": tenant.id,
"client_ip": client_ip,
"endpoint": endpoint,
- "method": request.method
+ "method": request.method,
+ "role": role
}
)
- finally:
- db.close()
-
except HTTPException:
- # Re-raise HTTP exceptions
raise
except Exception as e:
logger.error(f"API key security check failed: {str(e)}", exc_info=True)
@@ -150,29 +145,26 @@ class ApiKeySecurityMiddleware(BaseHTTPMiddleware):
def _should_skip_security(self, path: str) -> bool:
"""Check if security should be skipped for this path"""
- skip_paths = [
+ normalized = path.rstrip("/") or "/"
+ skip_paths = {
"/health",
"/docs",
"/openapi.json",
"/redoc",
- "/signup", # Public signup endpoint
- "/metrics", # Monitoring endpoints
+ "/signup",
+ "/metrics",
"/favicon.ico",
- ]
- return any(path.startswith(skip_path) for skip_path in skip_paths)
+ }
+ return normalized in skip_paths
def _extract_api_key(self, request: Request) -> Optional[str]:
"""Extract API key from Authorization header"""
auth_header = request.headers.get("Authorization")
- if not auth_header:
- return None
-
- if not auth_header.startswith("Bearer "):
+ if not auth_header or not auth_header.startswith("Bearer "):
return None
+ return auth_header.replace("Bearer ", "", 1)
- return auth_header.replace("Bearer ", "")
-
- async def _validate_api_key(self, db: Session, api_key: str) -> tuple:
+ async def _validate_api_key(self, db: AsyncSession, api_key: str) -> tuple:
"""
Validate API key and return associated records
@@ -180,27 +172,28 @@ class ApiKeySecurityMiddleware(BaseHTTPMiddleware):
tuple: (api_key_record, tenant) or (None, None) if invalid
"""
try:
- # Hash the provided key for lookup
key_hash = hash_api_key(api_key)
- # Look up API key record
- api_key_record = db.query(ApiKey).filter(
- ApiKey.key_hash == key_hash,
- ApiKey.active == True
- ).first()
+ api_key_result = await db.execute(
+ select(ApiKey).where(
+ ApiKey.key_hash == key_hash,
+ ApiKey.active == True
+ )
+ )
+ api_key_record = api_key_result.scalar_one_or_none()
if not api_key_record:
return None, None
- # Check if API key has expired (expires_at field)
- if api_key_record.expires_at and api_key_record.expires_at < datetime.now():
+ now = datetime.now(timezone.utc)
+ if api_key_record.expires_at and api_key_record.expires_at <= now:
logger.warning(f"Expired API key used: {api_key_record.prefix}")
return None, None
- # Get associated tenant
- tenant = db.query(Tenant).filter(
- Tenant.id == api_key_record.tenant_id
- ).first()
+ tenant_result = await db.execute(
+ select(Tenant).where(Tenant.id == api_key_record.tenant_id)
+ )
+ tenant = tenant_result.scalar_one_or_none()
return api_key_record, tenant
@@ -214,18 +207,14 @@ class ApiKeySecurityMiddleware(BaseHTTPMiddleware):
Handles X-Forwarded-For headers for proxy setups
"""
- # Check X-Forwarded-For header first (for reverse proxies)
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
- # Take the first IP in the chain
return forwarded_for.split(",")[0].strip()
- # Check X-Real-IP header
real_ip = request.headers.get("X-Real-IP")
if real_ip:
return real_ip.strip()
- # Fallback to direct client IP
if hasattr(request, "client") and request.client:
return request.client.host
@@ -237,4 +226,4 @@ class ApiKeySecurityMiddleware(BaseHTTPMiddleware):
response.headers["X-Tenant-ID"] = getattr(request.state, "tenant_id", "unknown")
response.headers["X-Rate-Limit-Remaining"] = "1000" # Placeholder for rate limiting
response.headers["X-Content-Type-Options"] = "nosniff"
- response.headers["X-Frame-Options"] = "DENY"
\ No newline at end of file
+ response.headers["X-Frame-Options"] = "DENY"