StillWorking's picture
Upload backend/core/security.py with huggingface_hub
19d3a8d verified
Raw History Blame Contribute Delete
10.6 kB
"""
core/security.py β€” Sentinel-AI
=================================
Optional authentication and rate limiting for shared deployments.
The local demo is intentionally open: when ``SENTINEL_API_KEY`` is unset the
API behaves exactly as before. Set the variable (and the matching
``VITE_API_KEY`` in the dashboard) to require a Bearer token on every
non-health request.
Rate limiting is a per-client token bucket. It is in-process and therefore
per-worker; put a shared limiter (nginx, API gateway, Redis) in front of a
multi-worker deployment. Both features are deliberately dependency-free.
Middleware ordering
-------------------
Starlette builds its middleware stack in reverse insertion order, so the
middleware added **last** is the outermost one. ``install_security(app)`` is
therefore called *before* ``app.add_middleware(CORSMiddleware, ...)`` in
``main.py``: CORS must stay outermost so preflight ``OPTIONS`` requests are
answered before authentication runs.
"""
from __future__ import annotations
import hashlib
import hmac
import math
import os
import threading
import time
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
# Paths that must remain reachable without a token: liveness probes and the
# generated API documentation. Everything under /api/v1 is protected.
_EXEMPT_PATHS = frozenset({
"/health",
"/docs",
"/redoc",
"/openapi.json",
"/docs/oauth2-redirect",
})
# Security headers applied to every response. The API only serves JSON and
# images, so a restrictive policy is safe and cheap.
_SECURITY_HEADERS = {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer",
"Cache-Control": "no-store",
}
def _env_bool(name: str, default: bool = False) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
def _env_int(name: str, default: int) -> int:
try:
return int(os.getenv(name, str(default)))
except (TypeError, ValueError):
return default
# ─────────────────────────────────────────────────────────────────────────────
# Token bucket
# ─────────────────────────────────────────────────────────────────────────────
class _TokenBucket:
"""A single client's token bucket (not thread-safe on its own)."""
__slots__ = ("capacity", "refill_per_sec", "tokens", "updated")
def __init__(self, capacity: int, refill_per_sec: float) -> None:
self.capacity = float(max(1, capacity))
self.refill_per_sec = max(refill_per_sec, 0.0)
self.tokens = self.capacity
self.updated = time.monotonic()
def consume(self, now: float) -> tuple[bool, int]:
"""Consume one token; return ``(allowed, retry_after_seconds)``."""
elapsed = now - self.updated
if elapsed > 0.0:
self.tokens = min(
self.capacity,
self.tokens + elapsed * self.refill_per_sec,
)
self.updated = now
if self.tokens >= 1.0:
self.tokens -= 1.0
return True, 0
if self.refill_per_sec <= 0.0:
return False, 3600
wait = (1.0 - self.tokens) / self.refill_per_sec
return False, max(1, math.ceil(wait))
class RateLimiter:
"""
Per-client token bucket.
``per_minute`` is the sustained rate; ``burst`` is the bucket size (how
many requests may arrive back-to-back). A non-positive ``per_minute``
disables the limiter.
"""
def __init__(
self,
per_minute: int,
burst: int | None = None,
max_clients: int = 10_000,
) -> None:
self.per_minute = int(per_minute)
self.burst = int(burst) if burst and burst > 0 else max(1, self.per_minute)
self.refill_per_sec = max(self.per_minute, 0) / 60.0
self.max_clients = max(1, int(max_clients))
self._buckets: dict[str, _TokenBucket] = {}
self._lock = threading.Lock()
@property
def enabled(self) -> bool:
return self.per_minute > 0
def check(self, key: str) -> tuple[bool, int]:
"""Return ``(allowed, retry_after_seconds)`` for ``key``."""
if not self.enabled:
return True, 0
now = time.monotonic()
with self._lock:
bucket = self._buckets.get(key)
if bucket is None:
if len(self._buckets) >= self.max_clients:
self._prune(now)
bucket = _TokenBucket(self.burst, self.refill_per_sec)
self._buckets[key] = bucket
return bucket.consume(now)
def _prune(self, now: float) -> None:
"""Drop full, idle buckets; clear everything if still at capacity."""
stale = [
key for key, bucket in self._buckets.items()
if now - bucket.updated > 300.0 and bucket.tokens >= bucket.capacity
]
for key in stale:
self._buckets.pop(key, None)
if len(self._buckets) >= self.max_clients:
# Pathological churn (e.g. spoofed X-Forwarded-For). Resetting is
# safer than growing without bound; normal clients refill normally.
self._buckets.clear()
# ─────────────────────────────────────────────────────────────────────────────
# Middleware
# ─────────────────────────────────────────────────────────────────────────────
def _extract_api_key(request: Request) -> str:
"""Read a Bearer token or X-API-Key header (Bearer wins)."""
authorization = request.headers.get("authorization", "")
if authorization.lower().startswith("bearer "):
return authorization[7:].strip()
return request.headers.get("x-api-key", "").strip()
def _client_key(request: Request, api_key: str) -> str:
"""
Identify a rate-limit bucket.
Authenticated callers are bucketed by a hash of their key so NATed clients
do not share a quota. Anonymous callers are bucketed by IP. Proxy headers
are only trusted when explicitly enabled, because they are trivially
spoofable otherwise.
"""
if api_key:
return "key:" + hashlib.sha256(api_key.encode("utf-8")).hexdigest()
if _env_bool("TRUST_PROXY_HEADERS", False):
forwarded = request.headers.get("x-forwarded-for", "")
if forwarded:
return "ip:" + forwarded.split(",", 1)[0].strip()
client = getattr(request, "client", None)
host = getattr(client, "host", None) if client is not None else None
return "ip:" + (host or "unknown")
def _is_exempt(path: str) -> bool:
return (
path in _EXEMPT_PATHS
or path.startswith("/docs/")
or path.startswith("/redoc/")
)
def _apply_headers(response: Response) -> Response:
for name, value in _SECURITY_HEADERS.items():
# setdefault preserves deliberate values such as the image cache header.
response.headers.setdefault(name, value)
return response
class SecurityMiddleware(BaseHTTPMiddleware):
"""Optional Bearer auth + per-client rate limiting + security headers."""
def __init__(
self,
app,
api_key: str = "",
rate_limiter: RateLimiter | None = None,
) -> None:
super().__init__(app)
self.api_key = api_key
self.rate_limiter = rate_limiter
async def dispatch(self, request: Request, call_next):
path = request.url.path
# CORS preflight must reach CORSMiddleware, and probes/docs stay open.
if request.method == "OPTIONS" or _is_exempt(path):
return _apply_headers(await call_next(request))
provided_key = _extract_api_key(request)
if self.api_key:
if not provided_key or not hmac.compare_digest(
provided_key.encode("utf-8"),
self.api_key.encode("utf-8"),
):
return _apply_headers(JSONResponse(
status_code=401,
content={"detail": "Invalid or missing API key."},
headers={"WWW-Authenticate": "Bearer"},
))
if self.rate_limiter is not None:
# When auth is disabled, ignore client-supplied key headers for
# bucketing: otherwise rotating a fake key bypasses the limit.
bucket_identity = provided_key if self.api_key else ""
allowed, retry_after = self.rate_limiter.check(
_client_key(request, bucket_identity)
)
if not allowed:
return _apply_headers(JSONResponse(
status_code=429,
content={"detail": "Rate limit exceeded. Retry later."},
headers={"Retry-After": str(retry_after)},
))
return _apply_headers(await call_next(request))
def install_security(
app: FastAPI,
*,
api_key: str | None = None,
rate_limit_per_minute: int | None = None,
rate_limit_burst: int | None = None,
) -> None:
"""
Attach :class:`SecurityMiddleware` to ``app``.
Values default to the environment at call time (not import time) so tests
and one-off deployments can override them. Call this **before**
``app.add_middleware(CORSMiddleware, ...)`` so CORS remains outermost.
"""
if api_key is None:
api_key = os.getenv("SENTINEL_API_KEY", "").strip()
if rate_limit_per_minute is None:
rate_limit_per_minute = _env_int("RATE_LIMIT_PER_MINUTE", 60)
if rate_limit_burst is None:
rate_limit_burst = _env_int("RATE_LIMIT_BURST", 20)
limiter = (
RateLimiter(rate_limit_per_minute, rate_limit_burst)
if rate_limit_per_minute > 0
else None
)
app.add_middleware(
SecurityMiddleware,
api_key=api_key,
rate_limiter=limiter,
)