File size: 10,582 Bytes
19d3a8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""
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,
    )