runapi 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- runapi/__init__.py +174 -0
- runapi/auth.py +359 -0
- runapi/cli.py +576 -0
- runapi/config.py +141 -0
- runapi/core.py +219 -0
- runapi/errors.py +338 -0
- runapi/middleware.py +383 -0
- runapi-0.1.0.dist-info/METADATA +797 -0
- runapi-0.1.0.dist-info/RECORD +12 -0
- runapi-0.1.0.dist-info/WHEEL +4 -0
- runapi-0.1.0.dist-info/entry_points.txt +2 -0
- runapi-0.1.0.dist-info/licenses/LICENSE +21 -0
runapi/middleware.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Callable, Dict, Any, List, Optional
|
|
5
|
+
from fastapi import Request, Response, HTTPException
|
|
6
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
7
|
+
from fastapi.middleware.cors import CORSMiddleware as FastAPICORSMiddleware
|
|
8
|
+
from fastapi.responses import JSONResponse
|
|
9
|
+
from collections import defaultdict
|
|
10
|
+
import asyncio
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RunApiMiddleware(BaseHTTPMiddleware):
|
|
14
|
+
"""Base middleware class for RunApi framework."""
|
|
15
|
+
|
|
16
|
+
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
|
17
|
+
"""Override this method in subclasses."""
|
|
18
|
+
return await call_next(request)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RequestLoggingMiddleware(RunApiMiddleware):
|
|
22
|
+
"""Middleware for logging HTTP requests and responses."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, app, logger: Optional[logging.Logger] = None):
|
|
25
|
+
super().__init__(app)
|
|
26
|
+
self.logger = logger or logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
|
29
|
+
start_time = time.time()
|
|
30
|
+
|
|
31
|
+
# Log request
|
|
32
|
+
self.logger.info(f"Request: {request.method} {request.url}")
|
|
33
|
+
|
|
34
|
+
response = await call_next(request)
|
|
35
|
+
|
|
36
|
+
# Calculate processing time
|
|
37
|
+
process_time = time.time() - start_time
|
|
38
|
+
|
|
39
|
+
# Log response
|
|
40
|
+
self.logger.info(
|
|
41
|
+
f"Response: {response.status_code} - "
|
|
42
|
+
f"Time: {process_time:.4f}s - "
|
|
43
|
+
f"Size: {response.headers.get('content-length', 'unknown')}"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
response.headers["X-Process-Time"] = str(process_time)
|
|
47
|
+
return response
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class RateLimitMiddleware(RunApiMiddleware):
|
|
51
|
+
"""Rate limiting middleware using in-memory storage."""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
app,
|
|
56
|
+
calls: int = 100,
|
|
57
|
+
period: int = 60, # seconds
|
|
58
|
+
key_func: Optional[Callable[[Request], str]] = None
|
|
59
|
+
):
|
|
60
|
+
super().__init__(app)
|
|
61
|
+
self.calls = calls
|
|
62
|
+
self.period = period
|
|
63
|
+
self.key_func = key_func or self._default_key_func
|
|
64
|
+
self.requests: Dict[str, List[float]] = defaultdict(list)
|
|
65
|
+
self.lock = asyncio.Lock()
|
|
66
|
+
|
|
67
|
+
def _default_key_func(self, request: Request) -> str:
|
|
68
|
+
"""Default key function using client IP."""
|
|
69
|
+
forwarded = request.headers.get("X-Forwarded-For")
|
|
70
|
+
if forwarded:
|
|
71
|
+
return forwarded.split(",")[0].strip()
|
|
72
|
+
return request.client.host if request.client else "unknown"
|
|
73
|
+
|
|
74
|
+
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
|
75
|
+
key = self.key_func(request)
|
|
76
|
+
current_time = time.time()
|
|
77
|
+
|
|
78
|
+
async with self.lock:
|
|
79
|
+
# Clean old requests
|
|
80
|
+
self.requests[key] = [
|
|
81
|
+
req_time for req_time in self.requests[key]
|
|
82
|
+
if current_time - req_time < self.period
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
# Check rate limit
|
|
86
|
+
if len(self.requests[key]) >= self.calls:
|
|
87
|
+
return JSONResponse(
|
|
88
|
+
status_code=429,
|
|
89
|
+
content={
|
|
90
|
+
"error": "Rate limit exceeded",
|
|
91
|
+
"message": f"Maximum {self.calls} requests per {self.period} seconds"
|
|
92
|
+
},
|
|
93
|
+
headers={"Retry-After": str(self.period)}
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# Record this request
|
|
97
|
+
self.requests[key].append(current_time)
|
|
98
|
+
|
|
99
|
+
response = await call_next(request)
|
|
100
|
+
|
|
101
|
+
# Add rate limit headers
|
|
102
|
+
response.headers["X-RateLimit-Limit"] = str(self.calls)
|
|
103
|
+
response.headers["X-RateLimit-Remaining"] = str(
|
|
104
|
+
max(0, self.calls - len(self.requests[key]))
|
|
105
|
+
)
|
|
106
|
+
response.headers["X-RateLimit-Reset"] = str(
|
|
107
|
+
int(current_time + self.period)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
return response
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class AuthMiddleware(RunApiMiddleware):
|
|
114
|
+
"""JWT-based authentication middleware."""
|
|
115
|
+
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
app,
|
|
119
|
+
secret_key: str,
|
|
120
|
+
algorithm: str = "HS256",
|
|
121
|
+
protected_paths: Optional[List[str]] = None,
|
|
122
|
+
excluded_paths: Optional[List[str]] = None,
|
|
123
|
+
header_name: str = "Authorization",
|
|
124
|
+
token_prefix: str = "Bearer "
|
|
125
|
+
):
|
|
126
|
+
super().__init__(app)
|
|
127
|
+
self.secret_key = secret_key
|
|
128
|
+
self.algorithm = algorithm
|
|
129
|
+
self.protected_paths = protected_paths or []
|
|
130
|
+
self.excluded_paths = excluded_paths or ["/docs", "/redoc", "/openapi.json"]
|
|
131
|
+
self.header_name = header_name
|
|
132
|
+
self.token_prefix = token_prefix
|
|
133
|
+
|
|
134
|
+
def _is_protected_path(self, path: str) -> bool:
|
|
135
|
+
"""Check if path requires authentication."""
|
|
136
|
+
# If no protected paths specified, protect all except excluded
|
|
137
|
+
if not self.protected_paths:
|
|
138
|
+
return path not in self.excluded_paths
|
|
139
|
+
|
|
140
|
+
# Check if path matches any protected pattern
|
|
141
|
+
for pattern in self.protected_paths:
|
|
142
|
+
if path.startswith(pattern):
|
|
143
|
+
return True
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
def _extract_token(self, request: Request) -> Optional[str]:
|
|
147
|
+
"""Extract JWT token from request headers."""
|
|
148
|
+
auth_header = request.headers.get(self.header_name)
|
|
149
|
+
if not auth_header or not auth_header.startswith(self.token_prefix):
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
return auth_header[len(self.token_prefix):].strip()
|
|
153
|
+
|
|
154
|
+
def _verify_token(self, token: str) -> Optional[Dict[str, Any]]:
|
|
155
|
+
"""Verify JWT token and return payload."""
|
|
156
|
+
try:
|
|
157
|
+
# Note: In real implementation, you'd use python-jose or similar
|
|
158
|
+
# This is a simplified version
|
|
159
|
+
import base64
|
|
160
|
+
import hmac
|
|
161
|
+
import hashlib
|
|
162
|
+
|
|
163
|
+
parts = token.split('.')
|
|
164
|
+
if len(parts) != 3:
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
header, payload, signature = parts
|
|
168
|
+
|
|
169
|
+
# Verify signature (simplified)
|
|
170
|
+
expected_sig = base64.urlsafe_b64encode(
|
|
171
|
+
hmac.new(
|
|
172
|
+
self.secret_key.encode(),
|
|
173
|
+
f"{header}.{payload}".encode(),
|
|
174
|
+
hashlib.sha256
|
|
175
|
+
).digest()
|
|
176
|
+
).decode().rstrip('=')
|
|
177
|
+
|
|
178
|
+
if not hmac.compare_digest(signature, expected_sig):
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
# Decode payload
|
|
182
|
+
payload_data = json.loads(
|
|
183
|
+
base64.urlsafe_b64decode(payload + '==')
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
# Check expiration
|
|
187
|
+
if 'exp' in payload_data and payload_data['exp'] < time.time():
|
|
188
|
+
return None
|
|
189
|
+
|
|
190
|
+
return payload_data
|
|
191
|
+
|
|
192
|
+
except Exception:
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
|
196
|
+
path = request.url.path
|
|
197
|
+
|
|
198
|
+
# Skip authentication for excluded paths
|
|
199
|
+
if not self._is_protected_path(path):
|
|
200
|
+
return await call_next(request)
|
|
201
|
+
|
|
202
|
+
# Extract and verify token
|
|
203
|
+
token = self._extract_token(request)
|
|
204
|
+
if not token:
|
|
205
|
+
return JSONResponse(
|
|
206
|
+
status_code=401,
|
|
207
|
+
content={"error": "Authentication required", "message": "Missing or invalid token"}
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
payload = self._verify_token(token)
|
|
211
|
+
if not payload:
|
|
212
|
+
return JSONResponse(
|
|
213
|
+
status_code=401,
|
|
214
|
+
content={"error": "Authentication failed", "message": "Invalid or expired token"}
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
# Add user info to request state
|
|
218
|
+
request.state.user = payload
|
|
219
|
+
|
|
220
|
+
return await call_next(request)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class SecurityHeadersMiddleware(RunApiMiddleware):
|
|
224
|
+
"""Add security headers to responses."""
|
|
225
|
+
|
|
226
|
+
def __init__(
|
|
227
|
+
self,
|
|
228
|
+
app,
|
|
229
|
+
include_server: bool = False,
|
|
230
|
+
csp_policy: Optional[str] = None,
|
|
231
|
+
hsts_max_age: int = 31536000 # 1 year
|
|
232
|
+
):
|
|
233
|
+
super().__init__(app)
|
|
234
|
+
self.include_server = include_server
|
|
235
|
+
self.csp_policy = csp_policy
|
|
236
|
+
self.hsts_max_age = hsts_max_age
|
|
237
|
+
|
|
238
|
+
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
|
239
|
+
response = await call_next(request)
|
|
240
|
+
|
|
241
|
+
# Remove server header if requested
|
|
242
|
+
if not self.include_server:
|
|
243
|
+
if "Server" in response.headers:
|
|
244
|
+
del response.headers["Server"]
|
|
245
|
+
|
|
246
|
+
# Add security headers
|
|
247
|
+
response.headers["X-Content-Type-Options"] = "nosniff"
|
|
248
|
+
response.headers["X-Frame-Options"] = "DENY"
|
|
249
|
+
response.headers["X-XSS-Protection"] = "1; mode=block"
|
|
250
|
+
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
|
|
251
|
+
|
|
252
|
+
# Add HSTS header for HTTPS
|
|
253
|
+
if request.url.scheme == "https":
|
|
254
|
+
response.headers["Strict-Transport-Security"] = f"max-age={self.hsts_max_age}; includeSubDomains"
|
|
255
|
+
|
|
256
|
+
# Add CSP header if policy is defined
|
|
257
|
+
if self.csp_policy:
|
|
258
|
+
response.headers["Content-Security-Policy"] = self.csp_policy
|
|
259
|
+
|
|
260
|
+
return response
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class CompressionMiddleware(RunApiMiddleware):
|
|
264
|
+
"""Simple compression middleware for JSON responses."""
|
|
265
|
+
|
|
266
|
+
def __init__(self, app, minimum_size: int = 1000):
|
|
267
|
+
super().__init__(app)
|
|
268
|
+
self.minimum_size = minimum_size
|
|
269
|
+
|
|
270
|
+
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
|
271
|
+
response = await call_next(request)
|
|
272
|
+
|
|
273
|
+
# Check if client accepts compression
|
|
274
|
+
accept_encoding = request.headers.get("Accept-Encoding", "")
|
|
275
|
+
if "gzip" not in accept_encoding.lower():
|
|
276
|
+
return response
|
|
277
|
+
|
|
278
|
+
# Check content type and size
|
|
279
|
+
content_type = response.headers.get("Content-Type", "")
|
|
280
|
+
if not (content_type.startswith("application/json") or content_type.startswith("text/")):
|
|
281
|
+
return response
|
|
282
|
+
|
|
283
|
+
# Get response body
|
|
284
|
+
body = b""
|
|
285
|
+
async for chunk in response.body_iterator:
|
|
286
|
+
body += chunk
|
|
287
|
+
|
|
288
|
+
if len(body) < self.minimum_size:
|
|
289
|
+
return Response(
|
|
290
|
+
content=body,
|
|
291
|
+
status_code=response.status_code,
|
|
292
|
+
headers=dict(response.headers),
|
|
293
|
+
media_type=response.media_type
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
# Compress with gzip
|
|
297
|
+
import gzip
|
|
298
|
+
compressed_body = gzip.compress(body)
|
|
299
|
+
|
|
300
|
+
# Create new response with compressed content
|
|
301
|
+
new_response = Response(
|
|
302
|
+
content=compressed_body,
|
|
303
|
+
status_code=response.status_code,
|
|
304
|
+
headers=dict(response.headers),
|
|
305
|
+
media_type=response.media_type
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
new_response.headers["Content-Encoding"] = "gzip"
|
|
309
|
+
new_response.headers["Content-Length"] = str(len(compressed_body))
|
|
310
|
+
|
|
311
|
+
return new_response
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class CORSMiddleware:
|
|
315
|
+
"""CORS middleware wrapper for FastAPI's CORS middleware."""
|
|
316
|
+
|
|
317
|
+
def __init__(
|
|
318
|
+
self,
|
|
319
|
+
allow_origins: List[str] = None,
|
|
320
|
+
allow_credentials: bool = False,
|
|
321
|
+
allow_methods: List[str] = None,
|
|
322
|
+
allow_headers: List[str] = None,
|
|
323
|
+
expose_headers: List[str] = None,
|
|
324
|
+
max_age: int = 600
|
|
325
|
+
):
|
|
326
|
+
self.allow_origins = allow_origins or ["*"]
|
|
327
|
+
self.allow_credentials = allow_credentials
|
|
328
|
+
self.allow_methods = allow_methods or ["*"]
|
|
329
|
+
self.allow_headers = allow_headers or ["*"]
|
|
330
|
+
self.expose_headers = expose_headers or []
|
|
331
|
+
self.max_age = max_age
|
|
332
|
+
|
|
333
|
+
def get_middleware(self):
|
|
334
|
+
"""Get FastAPI CORS middleware instance."""
|
|
335
|
+
return FastAPICORSMiddleware(
|
|
336
|
+
allow_origins=self.allow_origins,
|
|
337
|
+
allow_credentials=self.allow_credentials,
|
|
338
|
+
allow_methods=self.allow_methods,
|
|
339
|
+
allow_headers=self.allow_headers,
|
|
340
|
+
expose_headers=self.expose_headers,
|
|
341
|
+
max_age=self.max_age
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
# Convenience functions
|
|
346
|
+
def create_rate_limit_middleware(app, calls: int = 100, period: int = 60):
|
|
347
|
+
"""Create rate limiting middleware."""
|
|
348
|
+
return RateLimitMiddleware(app, calls=calls, period=period)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def create_auth_middleware(
|
|
352
|
+
app,
|
|
353
|
+
secret_key: str,
|
|
354
|
+
protected_paths: List[str] = None,
|
|
355
|
+
excluded_paths: List[str] = None
|
|
356
|
+
):
|
|
357
|
+
"""Create authentication middleware."""
|
|
358
|
+
return AuthMiddleware(
|
|
359
|
+
app,
|
|
360
|
+
secret_key=secret_key,
|
|
361
|
+
protected_paths=protected_paths,
|
|
362
|
+
excluded_paths=excluded_paths
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def create_logging_middleware(app, logger: logging.Logger = None):
|
|
367
|
+
"""Create request logging middleware."""
|
|
368
|
+
return RequestLoggingMiddleware(app, logger=logger)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def create_security_middleware(
|
|
372
|
+
app,
|
|
373
|
+
include_server: bool = False,
|
|
374
|
+
csp_policy: str = None,
|
|
375
|
+
hsts_max_age: int = 31536000
|
|
376
|
+
):
|
|
377
|
+
"""Create security headers middleware."""
|
|
378
|
+
return SecurityHeadersMiddleware(
|
|
379
|
+
app,
|
|
380
|
+
include_server=include_server,
|
|
381
|
+
csp_policy=csp_policy,
|
|
382
|
+
hsts_max_age=hsts_max_age
|
|
383
|
+
)
|