Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /stateset_stateset-agents /stateset_agents /api /middleware.py
| """ | |
| API Middleware Module | |
| Centralized middleware for security, observability, and request handling. | |
| """ | |
| import asyncio | |
| import hmac | |
| import inspect | |
| import logging | |
| import time | |
| import uuid | |
| from collections import defaultdict, deque | |
| from collections.abc import Callable | |
| from dataclasses import dataclass, field | |
| from datetime import datetime | |
| from typing import Any | |
| from fastapi import FastAPI | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.requests import Request | |
| from starlette.responses import JSONResponse, Response | |
| from starlette.types import ASGIApp, Message, Receive, Scope, Send | |
| from stateset_agents.utils.credentials import credential_fingerprint | |
| from .auth import get_jwt_handler | |
| from .config import get_config | |
| from .constants import ( | |
| HEADER_CORRELATION_ID, | |
| HEADER_RATE_LIMIT, | |
| HEADER_RATE_LIMIT_REMAINING, | |
| HEADER_RATE_LIMIT_RESET, | |
| HEADER_REQUEST_ID, | |
| HEADER_RESPONSE_TIME, | |
| HEADER_RETRY_AFTER, | |
| HSTS_HEADER, | |
| PERCENTILE_P50, | |
| PERCENTILE_P95, | |
| PERCENTILE_P99, | |
| RATE_LIMIT_DEQUE_MAXLEN, | |
| SECURITY_HEADERS, | |
| ) | |
| from .rate_limiter import UnifiedRateLimiter, get_rate_limiter | |
| logger = logging.getLogger(__name__) | |
| class RequestSizeLimitMiddleware: | |
| """Reject oversized fixed-length and chunked HTTP request bodies. | |
| Checking only ``Content-Length`` is insufficient because clients may omit | |
| it or use chunked transfer encoding. This pure ASGI middleware buffers up | |
| to the configured bound and counts the bytes actually received before | |
| FastAPI parses the body. | |
| """ | |
| def __init__(self, app: ASGIApp) -> None: | |
| self.app = app | |
| async def _reject(scope: Scope, receive: Receive, send: Send) -> None: | |
| response = JSONResponse( | |
| status_code=413, | |
| content={"detail": "Request body exceeds the configured size limit"}, | |
| ) | |
| await response(scope, receive, send) | |
| async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | |
| if scope["type"] != "http": | |
| await self.app(scope, receive, send) | |
| return | |
| max_bytes = get_config().validation.max_request_size_mb * 1024 * 1024 | |
| content_lengths = [ | |
| value | |
| for name, value in scope.get("headers", []) | |
| if name.lower() == b"content-length" | |
| ] | |
| if len(content_lengths) > 1: | |
| response = JSONResponse( | |
| status_code=400, | |
| content={"detail": "Multiple Content-Length headers are not allowed"}, | |
| ) | |
| await response(scope, receive, send) | |
| return | |
| if content_lengths: | |
| try: | |
| content_length = int(content_lengths[-1]) | |
| except ValueError: | |
| response = JSONResponse( | |
| status_code=400, content={"detail": "Invalid Content-Length header"} | |
| ) | |
| await response(scope, receive, send) | |
| return | |
| if content_length < 0: | |
| response = JSONResponse( | |
| status_code=400, content={"detail": "Invalid Content-Length header"} | |
| ) | |
| await response(scope, receive, send) | |
| return | |
| if content_length > max_bytes: | |
| await self._reject(scope, receive, send) | |
| return | |
| received_bytes = 0 | |
| messages: list[Message] = [] | |
| while True: | |
| message = await receive() | |
| messages.append(message) | |
| if message["type"] == "http.disconnect": | |
| break | |
| if message["type"] != "http.request": | |
| continue | |
| received_bytes += len(message.get("body", b"")) | |
| if received_bytes > max_bytes: | |
| await self._reject(scope, receive, send) | |
| return | |
| if not message.get("more_body", False): | |
| break | |
| message_index = 0 | |
| async def replay_receive() -> Message: | |
| nonlocal message_index | |
| if message_index < len(messages): | |
| message = messages[message_index] | |
| message_index += 1 | |
| return message | |
| return await receive() | |
| await self.app(scope, replay_receive, send) | |
| try: # Optional: only used when Prometheus scraping is enabled. | |
| from prometheus_client import Counter, Gauge, Histogram | |
| HAS_PROMETHEUS = True | |
| except ImportError: # pragma: no cover | |
| HAS_PROMETHEUS = False | |
| PROM_HTTP_REQUESTS_TOTAL: Any | None = None | |
| PROM_HTTP_REQUEST_DURATION_SECONDS: Any | None = None | |
| PROM_HTTP_REQUESTS_IN_PROGRESS: Any | None = None | |
| if HAS_PROMETHEUS: | |
| # Low-cardinality labels: `endpoint` prefers FastAPI route templates. | |
| PROM_HTTP_REQUESTS_TOTAL = Counter( | |
| "stateset_http_requests_total", | |
| "Total HTTP requests", | |
| ["method", "endpoint", "status_code"], | |
| ) | |
| PROM_HTTP_REQUEST_DURATION_SECONDS = Histogram( | |
| "stateset_http_request_duration_seconds", | |
| "HTTP request latency in seconds", | |
| ["method", "endpoint"], | |
| ) | |
| PROM_HTTP_REQUESTS_IN_PROGRESS = Gauge( | |
| "stateset_http_requests_in_progress", | |
| "In-progress HTTP requests", | |
| ["method", "endpoint"], | |
| ) | |
| # ============================================================================ | |
| # Security Headers Middleware | |
| # ============================================================================ | |
| class SecurityHeadersMiddleware(BaseHTTPMiddleware): | |
| """Add comprehensive security headers to all responses.""" | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| response = await call_next(request) | |
| # Add all security headers from constants | |
| for header, value in SECURITY_HEADERS.items(): | |
| response.headers[header] = value | |
| # Add HSTS in production | |
| config = get_config() | |
| if config.is_production(): | |
| response.headers["Strict-Transport-Security"] = HSTS_HEADER | |
| return response | |
| # ============================================================================ | |
| # Request Context Middleware | |
| # ============================================================================ | |
| class RequestContext: | |
| """Request context with tracing information.""" | |
| request_id: str | |
| start_time: float | |
| client_ip: str | |
| user_agent: str | |
| path: str | |
| method: str | |
| user_id: str | None = None | |
| roles: list = field(default_factory=list) | |
| api_key: str | None = None | |
| def elapsed_ms(self) -> float: | |
| """Get elapsed time in milliseconds.""" | |
| return (time.monotonic() - self.start_time) * 1000 | |
| class RequestContextMiddleware(BaseHTTPMiddleware): | |
| """Attach request context and trace ID to all requests.""" | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| # Get or generate request ID | |
| request_id = ( | |
| request.headers.get(HEADER_REQUEST_ID) | |
| or request.headers.get(HEADER_CORRELATION_ID) | |
| or str(uuid.uuid4()) | |
| ) | |
| # Create request context | |
| context = RequestContext( | |
| request_id=request_id, | |
| start_time=time.monotonic(), | |
| client_ip=request.client.host if request.client else "unknown", | |
| user_agent=request.headers.get("User-Agent", "unknown"), | |
| path=str(request.url.path), | |
| method=request.method, | |
| ) | |
| # Attach to request state | |
| request.state.context = context | |
| request.state.request_id = request_id | |
| # Process request | |
| response = await call_next(request) | |
| # Add tracing headers to response | |
| response.headers[HEADER_REQUEST_ID] = request_id | |
| response.headers[HEADER_RESPONSE_TIME] = f"{context.elapsed_ms():.2f}" | |
| return response | |
| # ============================================================================ | |
| # Rate Limiting Middleware | |
| # ============================================================================ | |
| class SlidingWindowRateLimiter: | |
| """Backward-compatible sliding window limiter used by middleware and tests.""" | |
| def __init__(self, window_seconds: int = 60): | |
| self.window_seconds = window_seconds | |
| self._limiter = UnifiedRateLimiter(window_seconds=window_seconds) | |
| self._last_cleanup = 0.0 | |
| self._cleanup_interval = max(1.0, float(window_seconds)) | |
| def windows(self) -> dict[str, deque]: | |
| """Expose internal windows for legacy compatibility.""" | |
| return self._limiter.windows | |
| def _cleanup_if_needed(self) -> None: | |
| """Clean up expired rate-limit buckets when enough time elapsed.""" | |
| now = time.monotonic() | |
| if now - self._last_cleanup >= self._cleanup_interval: | |
| self._limiter.cleanup() | |
| self._last_cleanup = now | |
| def is_allowed(self, key: str, limit: int) -> tuple[bool, int]: | |
| """ | |
| Check if request is allowed under rate limit. | |
| Returns: | |
| Tuple of (allowed, remaining_requests) | |
| """ | |
| self._cleanup_if_needed() | |
| return self._limiter.is_allowed(key, limit) | |
| def reset(self, key: str) -> None: | |
| """Reset rate limit for a key.""" | |
| self._limiter.reset(key) | |
| def cleanup(self) -> None: | |
| """Perform immediate cleanup of expired buckets.""" | |
| self._limiter.cleanup() | |
| class RedisSlidingWindowLimiter: | |
| """Fixed-window rate limiter backed by Redis, for multi-pod deployments. | |
| Implements the same ``is_allowed(key, limit) -> (allowed, remaining)`` | |
| interface as :class:`UnifiedRateLimiter`, but as a coroutine, and uses a | |
| fixed-window (INCR + EXPIRE) approximation rather than a true sliding | |
| window: a burst that straddles a window boundary can momentarily allow | |
| up to ~2x ``limit`` requests across the two windows. This is an accepted | |
| tradeoff for coarse-grained, cross-replica abuse protection; the | |
| in-memory sliding-window limiter remains exact for single-pod deployments. | |
| The ``redis.asyncio`` client is imported lazily so the ``redis`` package | |
| stays an optional dependency (see the ``api`` extra in ``pyproject.toml``). | |
| """ | |
| def __init__( | |
| self, | |
| redis_url: str, | |
| window_seconds: int = 60, | |
| operation_timeout_seconds: float = 2.0, | |
| ): | |
| self.redis_url = redis_url | |
| self.window_seconds = window_seconds | |
| self.operation_timeout_seconds = operation_timeout_seconds | |
| self._client: Any | None = None | |
| async def _get_client(self) -> Any: | |
| if self._client is None: | |
| import redis.asyncio as redis # noqa: PLC0415 - intentional lazy/optional import | |
| self._client = redis.from_url( | |
| self.redis_url, | |
| decode_responses=True, | |
| socket_connect_timeout=self.operation_timeout_seconds, | |
| socket_timeout=self.operation_timeout_seconds, | |
| retry_on_timeout=False, | |
| ) | |
| return self._client | |
| async def is_allowed(self, key: str, limit: int) -> tuple[bool, int]: | |
| """Check and record a request against the fixed window in Redis. | |
| INCR and EXPIRE are issued in a single pipeline (MULTI/EXEC) so the | |
| counter bump and its TTL are applied atomically from Redis's | |
| perspective, instead of two separate round trips that could race | |
| under concurrent requests. ``expire(..., nx=True)`` only sets the | |
| TTL when the key doesn't already have one, so it's safe to send on | |
| every request rather than gating it on ``count == 1``. | |
| """ | |
| client = await self._get_client() | |
| redis_key = f"stateset:ratelimit:{key}" | |
| async with client.pipeline(transaction=True) as pipe: | |
| pipe.incr(redis_key) | |
| pipe.expire(redis_key, self.window_seconds, nx=True) | |
| count, _ = await asyncio.wait_for( | |
| pipe.execute(), timeout=self.operation_timeout_seconds | |
| ) | |
| allowed = count <= limit | |
| remaining = max(0, limit - count) | |
| return allowed, remaining | |
| async def reset(self, key: str) -> None: | |
| client = await self._get_client() | |
| await client.delete(f"stateset:ratelimit:{key}") | |
| async def close(self) -> None: | |
| if self._client is not None: | |
| await self._client.aclose() | |
| self._client = None | |
| def _hash_credential(value: str) -> str: | |
| """Hash a credential (API key / bearer token) for use as a bucket key. | |
| Mirrors the hashing approach used for user identity in ``auth.py`` | |
| (``_derive_api_user_id``) so raw credentials never end up in rate-limit | |
| state or logs. | |
| """ | |
| return credential_fingerprint(value) | |
| def _validate_credential(credential: str, config: Any) -> bool: | |
| """Return True only if ``credential`` validates as a real API key or JWT. | |
| Unvalidated/garbage credentials must NOT get their own rate-limit | |
| bucket (that would let an attacker mint unlimited fresh buckets and | |
| bypass IP-based limits); they fall back to the client-IP bucket. | |
| """ | |
| if any( | |
| hmac.compare_digest(stored_key, credential) | |
| for stored_key in config.security.api_keys | |
| ): | |
| return True | |
| if config.security.jwt_secret: | |
| try: | |
| jwt = get_jwt_handler() | |
| payload = jwt.decode(credential) | |
| except Exception: # noqa: BLE001 - any decode failure means invalid | |
| return False | |
| if payload: | |
| return True | |
| return False | |
| # Cooldown before a failed Redis backend is retried, in seconds. During the | |
| # cooldown window the in-memory limiter is used instead of hammering a | |
| # down/unreachable Redis on every request. | |
| REDIS_RETRY_COOLDOWN_SECONDS = 60.0 | |
| class RateLimitMiddleware(BaseHTTPMiddleware): | |
| """Rate limiting middleware with sliding window algorithm.""" | |
| def __init__(self, app: FastAPI, limiter: UnifiedRateLimiter | None = None): | |
| super().__init__(app) | |
| config = get_config() | |
| self.limiter = limiter or get_rate_limiter( | |
| window_seconds=config.rate_limit.window_seconds | |
| ) | |
| self._last_cleanup = 0.0 | |
| self._cleanup_interval = max(1.0, float(config.rate_limit.window_seconds)) | |
| # Optional Redis backend for multi-pod deployments. Only wired up | |
| # when the caller didn't inject an explicit limiter (tests do) and | |
| # the config asks for it; falls back to the in-memory limiter on | |
| # any import/connection failure. Rather than permanently disabling | |
| # itself, it retries after a cooldown so Redis coming back online | |
| # is picked up automatically. | |
| self._redis_limiter: RedisSlidingWindowLimiter | None = None | |
| self._redis_disabled_until = 0.0 | |
| self._redis_currently_disabled = False | |
| if limiter is None and config.rate_limit.backend == "redis": | |
| redis_url = config.rate_limit.redis_url or "redis://localhost:6379" | |
| self._redis_limiter = RedisSlidingWindowLimiter( | |
| redis_url, config.rate_limit.window_seconds | |
| ) | |
| async def _check_rate_limit(self, key: str, limit: int) -> tuple[bool, int]: | |
| """Check the rate limit, preferring Redis and falling back to memory.""" | |
| if self._redis_limiter is not None: | |
| now = time.monotonic() | |
| if now < self._redis_disabled_until: | |
| return self.limiter.is_allowed(key, limit) | |
| try: | |
| result = await self._redis_limiter.is_allowed(key, limit) | |
| except ( | |
| Exception | |
| ) as exc: # noqa: BLE001 - any redis/import failure triggers fallback | |
| # A failed redis-py pool may retain resolver/connection tasks. | |
| # Close it before fallback so event-loop shutdown cannot wait | |
| # indefinitely; the next post-cooldown attempt creates a new | |
| # client and can recover normally. | |
| close = getattr(self._redis_limiter, "close", None) | |
| if close is not None: | |
| try: | |
| result = close() | |
| if inspect.isawaitable(result): | |
| await result | |
| except Exception: # noqa: BLE001 - fallback must survive cleanup | |
| logger.debug("Failed Redis limiter cleanup", exc_info=True) | |
| self._redis_disabled_until = now + REDIS_RETRY_COOLDOWN_SECONDS | |
| if not self._redis_currently_disabled: | |
| logger.warning( | |
| "Redis rate-limit backend unavailable (%s); " | |
| "falling back to in-memory limiter for %.0fs", | |
| exc, | |
| REDIS_RETRY_COOLDOWN_SECONDS, | |
| ) | |
| self._redis_currently_disabled = True | |
| return self.limiter.is_allowed(key, limit) | |
| else: | |
| if self._redis_currently_disabled: | |
| logger.info("Redis rate-limit backend recovered; resuming") | |
| self._redis_currently_disabled = False | |
| return result | |
| return self.limiter.is_allowed(key, limit) | |
| def _rate_limit_key(self, request: Request, config: Any) -> tuple[str, str | None]: | |
| """Derive the rate-limit bucket key and, if present, the raw API key.""" | |
| api_key = self._extract_api_key(request) | |
| if api_key and _validate_credential(api_key, config): | |
| return f"key:{_hash_credential(api_key)}", api_key | |
| client_ip = self._client_ip(request, config) | |
| return f"ip:{client_ip}", None | |
| def _client_ip(request: Request, config: Any) -> str: | |
| """Resolve the client IP, honoring X-Forwarded-For only when trusted.""" | |
| if config.rate_limit.trust_proxy_headers: | |
| forwarded_for = request.headers.get("X-Forwarded-For") | |
| if forwarded_for: | |
| first_hop = str(forwarded_for).split(",")[0].strip() | |
| if first_hop: | |
| return first_hop | |
| return str(request.client.host) if request.client else "unknown" | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| config = get_config() | |
| if not config.rate_limit.enabled: | |
| return await call_next(request) | |
| # Skip rate limiting for health checks | |
| if request.url.path in ("/health", "/healthz", "/ready"): | |
| return await call_next(request) | |
| # Get rate limit key: hashed credential when present, else client IP. | |
| limit_key, api_key = self._rate_limit_key(request, config) | |
| client_ip = request.client.host if request.client else "unknown" | |
| now = time.monotonic() | |
| if now - self._last_cleanup >= self._cleanup_interval: | |
| if hasattr(self.limiter, "cleanup"): | |
| self.limiter.cleanup() | |
| self._last_cleanup = now | |
| # Check rate limit | |
| allowed, remaining = await self._check_rate_limit( | |
| limit_key, config.rate_limit.requests_per_minute | |
| ) | |
| if not allowed: | |
| logger.warning( | |
| "Rate limit exceeded", | |
| extra={ | |
| "client_ip": client_ip, | |
| "path": request.url.path, | |
| "limit_key": limit_key[:16] + "..." if api_key else limit_key, | |
| }, | |
| ) | |
| return JSONResponse( | |
| status_code=429, | |
| content={ | |
| "error": { | |
| "code": "RATE_LIMIT_EXCEEDED", | |
| "message": "Too many requests. Please retry after a short delay.", | |
| }, | |
| "request_id": getattr( | |
| request.state, "request_id", str(uuid.uuid4()) | |
| ), | |
| "retry_after_seconds": config.rate_limit.window_seconds, | |
| }, | |
| headers={ | |
| HEADER_RETRY_AFTER: str(config.rate_limit.window_seconds), | |
| HEADER_RATE_LIMIT: str(config.rate_limit.requests_per_minute), | |
| HEADER_RATE_LIMIT_REMAINING: "0", | |
| HEADER_RATE_LIMIT_RESET: str( | |
| int(time.time()) + config.rate_limit.window_seconds | |
| ), | |
| }, | |
| ) | |
| # Add rate limit headers to response | |
| response = await call_next(request) | |
| response.headers[HEADER_RATE_LIMIT] = str(config.rate_limit.requests_per_minute) | |
| response.headers[HEADER_RATE_LIMIT_REMAINING] = str(remaining) | |
| response.headers[HEADER_RATE_LIMIT_RESET] = str( | |
| int(time.time()) + config.rate_limit.window_seconds | |
| ) | |
| return response | |
| def _extract_api_key(self, request: Request) -> str | None: | |
| """Extract API key from request headers.""" | |
| # Check Authorization header | |
| auth_header = str(request.headers.get("Authorization", "")) | |
| if auth_header.lower().startswith("bearer "): | |
| return auth_header.split(" ", 1)[1].strip() | |
| # Check X-API-Key header | |
| api_key = request.headers.get("X-API-Key") | |
| return api_key.strip() if api_key else None | |
| # ============================================================================ | |
| # Metrics Middleware | |
| # ============================================================================ | |
| class APIMetrics: | |
| """API metrics collector.""" | |
| request_counts: dict[str, int] = field(default_factory=lambda: defaultdict(int)) | |
| status_counts: dict[int, int] = field(default_factory=lambda: defaultdict(int)) | |
| latencies: deque = field( | |
| default_factory=lambda: deque(maxlen=RATE_LIMIT_DEQUE_MAXLEN) | |
| ) | |
| error_counts: dict[str, int] = field(default_factory=lambda: defaultdict(int)) | |
| rate_limit_hits: int = 0 | |
| def record_request( | |
| self, path: str, method: str, status_code: int, latency_ms: float | |
| ) -> None: | |
| """Record a request.""" | |
| key = f"{method}:{path}" | |
| self.request_counts[key] += 1 | |
| self.status_counts[status_code] += 1 | |
| self.latencies.append(latency_ms) | |
| if status_code >= 400: | |
| self.error_counts[key] += 1 | |
| def record_rate_limit_hit(self) -> None: | |
| """Record a rate limit hit.""" | |
| self.rate_limit_hits += 1 | |
| def get_summary(self) -> dict[str, Any]: | |
| """Get metrics summary.""" | |
| latencies_list = list(self.latencies) | |
| if latencies_list: | |
| avg_latency = sum(latencies_list) / len(latencies_list) | |
| sorted_latencies = sorted(latencies_list) | |
| p50_index = int(PERCENTILE_P50 * (len(sorted_latencies) - 1)) | |
| p95_index = int(PERCENTILE_P95 * (len(sorted_latencies) - 1)) | |
| p99_index = int(PERCENTILE_P99 * (len(sorted_latencies) - 1)) | |
| else: | |
| avg_latency = 0 | |
| sorted_latencies = [] | |
| p50_index = p95_index = p99_index = 0 | |
| return { | |
| "total_requests": sum(self.request_counts.values()), | |
| "requests_by_endpoint": dict(self.request_counts), | |
| "status_codes": dict(self.status_counts), | |
| "errors_by_endpoint": dict(self.error_counts), | |
| "rate_limit_hits": self.rate_limit_hits, | |
| "latency": { | |
| "avg_ms": round(avg_latency, 2), | |
| "p50_ms": ( | |
| round(sorted_latencies[p50_index], 2) if sorted_latencies else 0 | |
| ), | |
| "p95_ms": ( | |
| round(sorted_latencies[p95_index], 2) if sorted_latencies else 0 | |
| ), | |
| "p99_ms": ( | |
| round(sorted_latencies[p99_index], 2) if sorted_latencies else 0 | |
| ), | |
| }, | |
| "timestamp": datetime.utcnow().isoformat(), | |
| } | |
| # Global metrics instance | |
| _metrics = APIMetrics() | |
| def get_metrics() -> APIMetrics: | |
| """Get the global metrics instance.""" | |
| return _metrics | |
| class MetricsMiddleware(BaseHTTPMiddleware): | |
| """Collect API metrics.""" | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| start_time = time.monotonic() | |
| route = request.scope.get("route") | |
| endpoint = getattr(route, "path", None) if route is not None else None | |
| if not endpoint: | |
| endpoint = request.url.path | |
| if HAS_PROMETHEUS and PROM_HTTP_REQUESTS_IN_PROGRESS is not None: | |
| PROM_HTTP_REQUESTS_IN_PROGRESS.labels( | |
| method=request.method, endpoint=endpoint | |
| ).inc() | |
| try: | |
| response = await call_next(request) | |
| finally: | |
| if HAS_PROMETHEUS and PROM_HTTP_REQUESTS_IN_PROGRESS is not None: | |
| PROM_HTTP_REQUESTS_IN_PROGRESS.labels( | |
| method=request.method, endpoint=endpoint | |
| ).dec() | |
| # Record metrics | |
| latency_ms = (time.monotonic() - start_time) * 1000 | |
| _metrics.record_request( | |
| path=request.url.path, | |
| method=request.method, | |
| status_code=response.status_code, | |
| latency_ms=latency_ms, | |
| ) | |
| if HAS_PROMETHEUS and PROM_HTTP_REQUESTS_TOTAL is not None: | |
| PROM_HTTP_REQUESTS_TOTAL.labels( | |
| method=request.method, | |
| endpoint=endpoint, | |
| status_code=str(response.status_code), | |
| ).inc() | |
| if HAS_PROMETHEUS and PROM_HTTP_REQUEST_DURATION_SECONDS is not None: | |
| PROM_HTTP_REQUEST_DURATION_SECONDS.labels( | |
| method=request.method, endpoint=endpoint | |
| ).observe(time.monotonic() - start_time) | |
| return response | |
| # ============================================================================ | |
| # Request Logging Middleware | |
| # ============================================================================ | |
| class RequestLoggingMiddleware(BaseHTTPMiddleware): | |
| """Structured request/response logging.""" | |
| # Paths to exclude from logging | |
| EXCLUDED_PATHS = {"/health", "/healthz", "/ready", "/metrics"} | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| # Skip logging for health checks and metrics | |
| if request.url.path in self.EXCLUDED_PATHS: | |
| return await call_next(request) | |
| context = getattr(request.state, "context", None) | |
| request_id = getattr(request.state, "request_id", str(uuid.uuid4())) | |
| # Log request | |
| logger.info( | |
| "Request started", | |
| extra={ | |
| "request_id": request_id, | |
| "method": request.method, | |
| "path": request.url.path, | |
| "client_ip": context.client_ip if context else "unknown", | |
| "user_agent": context.user_agent if context else "unknown", | |
| }, | |
| ) | |
| response = await call_next(request) | |
| # Log response | |
| elapsed_ms = context.elapsed_ms() if context else 0 | |
| log_level = logging.WARNING if response.status_code >= 400 else logging.INFO | |
| logger.log( | |
| log_level, | |
| "Request completed", | |
| extra={ | |
| "request_id": request_id, | |
| "method": request.method, | |
| "path": request.url.path, | |
| "status_code": response.status_code, | |
| "elapsed_ms": round(elapsed_ms, 2), | |
| }, | |
| ) | |
| return response | |
| # ============================================================================ | |
| # Setup Function | |
| # ============================================================================ | |
| def setup_middleware(app: FastAPI) -> None: | |
| """Set up all middleware in the correct order.""" | |
| config = get_config() | |
| # Order matters! Middleware is executed in reverse order of addition | |
| # So the last added middleware runs first | |
| # 1. Request logging (runs last, sees final response) | |
| app.add_middleware(RequestLoggingMiddleware) | |
| # 2. Metrics collection | |
| app.add_middleware(MetricsMiddleware) | |
| # 3. Rate limiting | |
| if config.rate_limit.enabled: | |
| app.add_middleware(RateLimitMiddleware) | |
| # 4. Request context (runs early, sets up tracing) | |
| app.add_middleware(RequestContextMiddleware) | |
| # 5. Body-size limit (runs before parsing, within security headers) | |
| app.add_middleware(RequestSizeLimitMiddleware) | |
| # 6. Security headers (runs first, adds headers to all responses) | |
| app.add_middleware(SecurityHeadersMiddleware) | |
| logger.info("Middleware configured successfully") | |
Xet Storage Details
- Size:
- 28.6 kB
- Xet hash:
- 2d26220c5e8cac948482fc5afab443ea765a1cf54d91f7a324755456bc1f32ce
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.