sealgate-server 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.
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
2
+ """HTTP API server for sealgate."""
sealgate_server/app.py ADDED
@@ -0,0 +1,500 @@
1
+ # SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
2
+ """The ASGI application: engine, readiness, health and info routes, and the middleware stack.
3
+
4
+ Middleware, outermost first: header size limit -> security headers -> access log ->
5
+ error guard (any exception becomes a 500 JSON response) -> response signing (only when
6
+ integrity is enabled) -> CORS (only when origins are configured) -> auth (headers only) ->
7
+ admission control and request timeout -> body size limit -> routes. All are pure ASGI, so
8
+ no body byte is read before auth and admission have passed. Signing sits outside auth,
9
+ admission and the body limit so their refusals are signed too.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import logging
16
+ import re
17
+ import threading
18
+ import time
19
+ import uuid
20
+ from collections.abc import AsyncGenerator, Sequence
21
+ from importlib.metadata import version
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ import anyio
26
+ import anyio.to_thread
27
+ from fastapi import FastAPI, Request
28
+ from fastapi.exceptions import RequestValidationError
29
+ from fastapi.responses import JSONResponse
30
+ from fastapi.staticfiles import StaticFiles
31
+ from prometheus_client import CollectorRegistry
32
+ from sealgate.api import Engine
33
+ from sealgate.hardening import ProfileKeyError
34
+ from sealgate.integrity import SigningKey
35
+ from sealgate.matchers import MatcherError, load_library
36
+ from sealgate.observer import Observer
37
+ from sealgate.pipeline import SCHEMA_VERSION
38
+ from sealgate.sandbox import SandboxError, run_worker, sandbox_features
39
+ from sealgate.signals import SignalConfigError
40
+ from sealgate.templates import TemplateError, TemplateStore
41
+ from sealgate.tools.fixtures import minimal_pdf
42
+ from starlette.exceptions import HTTPException
43
+ from starlette.middleware.cors import CORSMiddleware
44
+
45
+ from sealgate_server import routes_templates, routes_verify
46
+ from sealgate_server.auth import AuthMiddleware, TokenEntry, TokenTable
47
+ from sealgate_server.config import ConfigError, ServerConfig
48
+ from sealgate_server.headers_limit import HeaderLimitMiddleware
49
+ from sealgate_server.labels import OTHER, HttpSink
50
+ from sealgate_server.limits import AdmissionMiddleware, AdmissionState, BodyLimitMiddleware, route_path
51
+ from sealgate_server.metrics import MetricsListener, PrometheusObserver
52
+ from sealgate_server.routes_verify import error
53
+ from sealgate_server.signing import SigningMiddleware
54
+ from sealgate_server.telemetry import OtelObserver, setup_otel
55
+
56
+ log = logging.getLogger("sealgate_server.app")
57
+ access_log = logging.getLogger("sealgate_server.access")
58
+
59
+ SERVER_VERSION = version("sealgate-server")
60
+ HSTS = b"max-age=31536000; includeSubDomains"
61
+ UI_DIR = Path(__file__).parent / "ui"
62
+ UI_CSP = (
63
+ b"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; frame-ancestors 'none'"
64
+ )
65
+ _HTTP_CODES = {404: "not_found", 405: "method_not_allowed"}
66
+ _SELF_TEST_PDF = minimal_pdf(
67
+ [
68
+ b"<< /Type /Catalog /Pages 2 0 R >>",
69
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
70
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>",
71
+ ]
72
+ )
73
+
74
+
75
+ def _build_engine(cfg: ServerConfig, observers: Sequence[Observer] = ()) -> Engine | None:
76
+ """The engine, or None (not ready) when templates, matchers, signals or the profile key fail."""
77
+ settings = cfg.settings()
78
+ if settings.templates_dir is None:
79
+ log.error("engine.templates_dir is not set; not ready")
80
+ return None
81
+ try:
82
+ store = TemplateStore(Path(settings.templates_dir), load_library(settings.matchers_path))
83
+ return Engine(store, settings, observers)
84
+ except (TemplateError, ProfileKeyError, MatcherError, SignalConfigError, OSError) as e:
85
+ log.error("engine not loaded: %s; not ready", type(e).__name__)
86
+ return None
87
+
88
+
89
+ SELF_TEST_RETRY_S = 5.0
90
+
91
+
92
+ class Readiness:
93
+ """Sandbox self-test, run at startup or on the first probe. A success is kept; a failure
94
+ is kept for ``SELF_TEST_RETRY_S``, so frequent probes do not start a worker each time."""
95
+
96
+ def __init__(self, cfg: ServerConfig, engine: Engine | None) -> None:
97
+ self.engine = engine
98
+ self.limits = cfg.settings().sandbox
99
+ self.sandbox_ok = False
100
+ self.clock = time.monotonic
101
+ self._failed_at: float | None = None
102
+ self._lock = anyio.Lock()
103
+
104
+ def _self_test(self) -> bool:
105
+ try:
106
+ return (
107
+ run_worker(_SELF_TEST_PDF, {"fieldSets": {}}, self.limits, threading.Event()).get("ok")
108
+ is True
109
+ )
110
+ except SandboxError as e:
111
+ log.error("sandbox self-test failed: %s", e)
112
+ return False
113
+
114
+ async def checks(self) -> dict[str, bool]:
115
+ async with self._lock:
116
+ recent = self._failed_at is not None and self.clock() - self._failed_at < SELF_TEST_RETRY_S
117
+ if not self.sandbox_ok and not recent:
118
+ self.sandbox_ok = await anyio.to_thread.run_sync(self._self_test)
119
+ self._failed_at = None if self.sandbox_ok else self.clock()
120
+ loaded = self.engine is not None
121
+ return {"templates": loaded, "profileKey": loaded, "sandbox": self.sandbox_ok}
122
+
123
+
124
+ class SecurityHeadersMiddleware:
125
+ def __init__(self, app: Any, hsts: bool, ui_path: str | None = None) -> None:
126
+ self.app = app
127
+ self.hsts = hsts
128
+ self.ui_path = ui_path
129
+
130
+ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
131
+ if scope["type"] != "http":
132
+ await self.app(scope, receive, send)
133
+ return
134
+ extra = [(b"x-content-type-options", b"nosniff"), (b"referrer-policy", b"no-referrer")]
135
+ if route_path(scope).startswith("/v1"):
136
+ extra.append((b"cache-control", b"no-store"))
137
+ if self.hsts:
138
+ extra.append((b"strict-transport-security", HSTS))
139
+ path = route_path(scope)
140
+ if self.ui_path is not None and (path == self.ui_path or path.startswith(self.ui_path + "/")):
141
+ extra.append((b"content-security-policy", UI_CSP))
142
+
143
+ async def add_headers(message: dict[str, Any]) -> None:
144
+ if message["type"] == "http.response.start":
145
+ names = {n for n, _ in extra}
146
+ kept = [(n, v) for n, v in message.get("headers", []) if n.lower() not in names]
147
+ message = {**message, "headers": [*kept, *extra]}
148
+ await send(message)
149
+
150
+ await self.app(scope, receive, add_headers)
151
+
152
+
153
+ _sink_reported: set[type] = set()
154
+
155
+
156
+ def _sink_failed(sink: object) -> None:
157
+ """Log a failing sink once per type (type name only)."""
158
+ if type(sink) not in _sink_reported:
159
+ _sink_reported.add(type(sink))
160
+ log.error("http sink %s failed; further failures are not logged", type(sink).__name__)
161
+
162
+
163
+ def _route_table(app: FastAPI, *routers: Any) -> list[tuple[re.Pattern[str], str]]:
164
+ """Path patterns of every route (the app's own and the included routers'), matched on the path alone."""
165
+ table: list[tuple[re.Pattern[str], str]] = []
166
+ for route in [*app.router.routes, *(r for router in routers for r in router.routes)]:
167
+ regex, path = getattr(route, "path_regex", None), getattr(route, "path", None)
168
+ if regex is not None and isinstance(path, str):
169
+ table.append((regex, path))
170
+ return table
171
+
172
+
173
+ class AccessLogMiddleware:
174
+ """One line per request: method, route template (never the raw path or query), status, token id."""
175
+
176
+ def __init__(
177
+ self,
178
+ app: Any,
179
+ router_app: FastAPI,
180
+ enabled: bool,
181
+ sinks: Sequence[HttpSink] = (),
182
+ templates: Sequence[tuple[re.Pattern[str], str]] = (),
183
+ ) -> None:
184
+ self.templates = templates
185
+ self.app = app
186
+ self.router_app = router_app
187
+ self.enabled = enabled
188
+ self.sinks = sinks
189
+
190
+ def _template(self, scope: dict[str, Any]) -> str:
191
+ routed = scope.get("route") # set by the router once a route matched
192
+ path = getattr(routed, "path", None)
193
+ if isinstance(path, str):
194
+ return path
195
+ # requests refused before routing (auth, admission, body limit) have no scope["route"]
196
+ request_path = route_path(scope)
197
+ for pattern, template in self.templates:
198
+ if pattern.match(request_path):
199
+ return template
200
+ return "-"
201
+
202
+ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
203
+ if scope["type"] != "http":
204
+ await self.app(scope, receive, send)
205
+ return
206
+ rid = uuid.uuid4().hex
207
+ scope.setdefault("state", {})["request_id"] = rid
208
+ status = 500
209
+ started = time.perf_counter()
210
+ reported = False
211
+
212
+ def report() -> None:
213
+ # Sinks run before the response leaves, while a tracing span is still open.
214
+ nonlocal reported
215
+ reported = True
216
+ if not self.sinks:
217
+ return
218
+ token: TokenEntry | None = scope.get("state", {}).get("token")
219
+ for sink in self.sinks:
220
+ try:
221
+ template = self._template(scope)
222
+ sink.http_done(
223
+ template if template != "-" else OTHER, status, token.id if token else None
224
+ )
225
+ except Exception:
226
+ _sink_failed(sink)
227
+
228
+ async def record(message: dict[str, Any]) -> None:
229
+ nonlocal status
230
+ if message["type"] == "http.response.start":
231
+ status = message["status"]
232
+ report()
233
+ message = {
234
+ **message,
235
+ "headers": [*message.get("headers", []), (b"x-request-id", rid.encode())],
236
+ }
237
+ await send(message)
238
+
239
+ try:
240
+ await self.app(scope, receive, record)
241
+ finally:
242
+ token: TokenEntry | None = scope.get("state", {}).get("token")
243
+ if not reported:
244
+ report()
245
+ if self.enabled:
246
+ template = self._template(scope)
247
+ duration = round((time.perf_counter() - started) * 1000, 1)
248
+ token_id = token.id if token else "-"
249
+ access_log.info(
250
+ "%s %s %d %.1fms token=%s rid=%s",
251
+ scope["method"],
252
+ template,
253
+ status,
254
+ duration,
255
+ token_id,
256
+ rid,
257
+ extra={
258
+ "method": scope["method"],
259
+ "route": template,
260
+ "status": status,
261
+ "durationMs": duration,
262
+ "token": token_id,
263
+ "requestId": rid,
264
+ },
265
+ )
266
+
267
+
268
+ class ErrorGuardMiddleware:
269
+ """Turns an exception from any inner layer into the app's own 500 JSON response.
270
+
271
+ It sits inside the access log and the security headers, so the 500 carries
272
+ ``x-request-id``, ``nosniff`` and the rest, and nothing reaches Starlette's
273
+ ServerErrorMiddleware or uvicorn (both would log the exception message). Only the
274
+ exception type is logged.
275
+ """
276
+
277
+ def __init__(self, app: Any) -> None:
278
+ self.app = app
279
+
280
+ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
281
+ if scope["type"] != "http":
282
+ await self.app(scope, receive, send)
283
+ return
284
+ started = False
285
+
286
+ async def track(message: dict[str, Any]) -> None:
287
+ nonlocal started
288
+ if message["type"] == "http.response.start":
289
+ started = True
290
+ await send(message)
291
+
292
+ try:
293
+ await self.app(scope, receive, track)
294
+ except Exception as e:
295
+ log.error("unhandled error: %s", type(e).__name__)
296
+ if not started: # otherwise the connection is closed with the response unfinished
297
+ await error(500, "internal_error", "internal error")(scope, receive, send)
298
+
299
+
300
+ def _add_routes(app: FastAPI, cfg: ServerConfig) -> None:
301
+ @app.get("/healthz")
302
+ async def healthz() -> dict[str, str]:
303
+ return {"status": "ok"}
304
+
305
+ @app.get("/readyz")
306
+ async def readyz(request: Request) -> JSONResponse:
307
+ checks = await request.app.state.readiness.checks()
308
+ ready = all(checks.values())
309
+ body: dict[str, Any] = {"status": "ready" if ready else "not_ready"}
310
+ token: TokenEntry | None = getattr(request.state, "token", None)
311
+ if token is not None and "templates:read" in token.scopes:
312
+ body |= {
313
+ "checks": checks,
314
+ "sandbox_features": sandbox_features(request.app.state.readiness.limits),
315
+ "version": SERVER_VERSION,
316
+ }
317
+ return JSONResponse(body, status_code=200 if ready else 503)
318
+
319
+ @app.get("/v1/info")
320
+ async def info(request: Request) -> dict[str, Any]:
321
+ token: TokenEntry = request.state.token
322
+ h = cfg.http
323
+ return {
324
+ "version": SERVER_VERSION,
325
+ "sealgateVersion": version("sealgate"),
326
+ "schemaVersion": SCHEMA_VERSION,
327
+ "limits": {
328
+ "max_upload_bytes": h.max_upload_bytes,
329
+ "max_template_bytes": h.max_template_bytes,
330
+ "max_samples_per_request": h.max_samples_per_request,
331
+ "max_concurrent": h.max_concurrent,
332
+ "queue": h.queue,
333
+ },
334
+ "inlineRules": h.allow_inline_rules,
335
+ "integrity": cfg.integrity.enabled,
336
+ "token": {"id": token.id, "scopes": sorted(token.scopes)},
337
+ }
338
+
339
+
340
+ def _add_ui(app: FastAPI, cfg: ServerConfig) -> None:
341
+ """The static UI at ``ui.path`` and its public config document (no secrets, no token)."""
342
+ base = cfg.ui.path
343
+ api_base = "../" * (base.count("/"))
344
+ config = {"authMode": cfg.auth.mode, "authHeader": cfg.auth.header, "apiBase": api_base}
345
+
346
+ @app.get(base + "/config.json", include_in_schema=False)
347
+ async def ui_config() -> dict[str, str]:
348
+ return config
349
+
350
+ app.mount(base, StaticFiles(directory=UI_DIR, html=True), name="ui")
351
+
352
+
353
+ def _add_error_handlers(app: FastAPI) -> None:
354
+ @app.exception_handler(HTTPException)
355
+ async def http_error(request: Request, exc: HTTPException) -> JSONResponse:
356
+ code = _HTTP_CODES.get(exc.status_code, "http_error")
357
+ return error(exc.status_code, code, code.replace("_", " "), exc.headers)
358
+
359
+ @app.exception_handler(RequestValidationError)
360
+ async def invalid(request: Request, exc: RequestValidationError) -> JSONResponse:
361
+ return error(400, "bad_request", "invalid request")
362
+
363
+ @app.exception_handler(Exception)
364
+ async def internal(request: Request, exc: Exception) -> JSONResponse:
365
+ log.error("unhandled error: %s", type(exc).__name__)
366
+ return error(500, "internal_error", "internal error")
367
+
368
+
369
+ def _observability(
370
+ cfg: ServerConfig, app: FastAPI, admission: AdmissionState
371
+ ) -> tuple[list[Observer], list[HttpSink], MetricsListener | None, OtelObserver | None]:
372
+ """Optional metrics and tracing: engine observers, HTTP sinks, the scrape listener, OTel."""
373
+ observers: list[Observer] = []
374
+ sinks: list[HttpSink] = []
375
+ listener: MetricsListener | None = None
376
+ if cfg.metrics.enabled:
377
+ registry = CollectorRegistry()
378
+ prom = PrometheusObserver(registry, lambda: admission.inflight, lambda: admission.waiting)
379
+ observers.append(prom)
380
+ sinks.append(prom)
381
+ listener = MetricsListener(cfg.metrics, registry)
382
+ app.state.metrics_registry = registry
383
+ otel = setup_otel(cfg.otel, app)
384
+ if otel is not None:
385
+ observers.append(otel)
386
+ sinks.append(otel)
387
+ return observers, sinks, listener, otel
388
+
389
+
390
+ def _signing_key(cfg: ServerConfig) -> SigningKey | None:
391
+ ig = cfg.integrity
392
+ if not ig.enabled:
393
+ return None
394
+ try:
395
+ return SigningKey.from_file(ig.key_file, ig.algorithm, ig.key_id)
396
+ except OSError as e:
397
+ raise ConfigError(f"integrity.key_file: cannot read ({type(e).__name__})") from None
398
+ except ValueError as e: # fixed messages from sealgate.integrity, never key material
399
+ raise ConfigError(f"integrity.key_file: {e}") from None
400
+
401
+
402
+ def _add_cors_and_signing(app: FastAPI, cfg: ServerConfig, signing_key: SigningKey | None) -> None:
403
+ """CORS (only with origins) and, outside it, response signing (only with a key)."""
404
+ signed_request = ["Content-Digest", "Sealgate-Nonce"] if signing_key is not None else []
405
+ signed_response = (
406
+ ["Content-Digest", "Signature", "Signature-Input", "Sealgate-Nonce", "Sealgate-Request-Digest"]
407
+ if signing_key is not None
408
+ else []
409
+ )
410
+ if cfg.http.cors_origins: # outside auth, so preflights are answered without a token
411
+ app.add_middleware(
412
+ CORSMiddleware,
413
+ allow_origins=cfg.http.cors_origins,
414
+ allow_credentials=False,
415
+ allow_methods=["GET", "POST", "PUT", "DELETE"],
416
+ allow_headers=[cfg.auth.header, "Content-Type", *signed_request],
417
+ expose_headers=signed_response,
418
+ )
419
+ if signing_key is not None: # outside auth, admission and limits: their refusals are signed
420
+ app.add_middleware(
421
+ SigningMiddleware,
422
+ key=signing_key,
423
+ cover=cfg.integrity.cover,
424
+ max_template_bytes=cfg.http.max_template_bytes,
425
+ )
426
+
427
+
428
+ def create_app(cfg: ServerConfig) -> FastAPI:
429
+ """Build the application for ``cfg``.
430
+
431
+ Raises:
432
+ ConfigError: The tokens file or the signing key is missing or invalid.
433
+ """
434
+ signing_key = _signing_key(cfg)
435
+ table = None
436
+ if cfg.auth.mode == "token":
437
+ if cfg.auth.tokens_file is None: # config validation already refuses this
438
+ raise ValueError("auth.tokens_file is required")
439
+ table = TokenTable(cfg.auth.tokens_file, cfg.auth.reload_interval_s)
440
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
441
+ admission = AdmissionState()
442
+ app.state.admission = admission
443
+ observers, sinks, listener, otel = _observability(cfg, app, admission)
444
+ engine = _build_engine(cfg, observers)
445
+ if engine is not None and routes_templates.store_read_only(engine.store):
446
+ log.warning("templates directory is read-only; template writes return 409")
447
+ readiness = Readiness(cfg, engine)
448
+
449
+ @contextlib.asynccontextmanager
450
+ async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
451
+ checks = await readiness.checks()
452
+ log.info("startup checks: %s", ", ".join(f"{k}={'ok' if v else 'failed'}" for k, v in checks.items()))
453
+ if listener is not None:
454
+ listener.start()
455
+ try:
456
+ yield
457
+ finally:
458
+ if listener is not None:
459
+ listener.stop()
460
+ if otel is not None:
461
+ otel.shutdown()
462
+
463
+ app.router.lifespan_context = lifespan
464
+ app.state.cfg = cfg
465
+ app.state.engine = engine
466
+ app.state.readiness = readiness
467
+ app.state.tokens = table
468
+ app.state.template_lock = threading.Lock()
469
+ app.state.signing_key = signing_key
470
+ _add_routes(app, cfg)
471
+ app.include_router(routes_verify.router)
472
+ app.include_router(routes_templates.router)
473
+ if cfg.ui.enabled:
474
+ _add_ui(app, cfg)
475
+ _add_error_handlers(app)
476
+ # add_middleware wraps: the last one added is the outermost.
477
+ app.add_middleware(
478
+ BodyLimitMiddleware, max_bytes=cfg.http.max_upload_bytes, check_digest=signing_key is not None
479
+ )
480
+ app.add_middleware(
481
+ AdmissionMiddleware,
482
+ max_concurrent=cfg.http.max_concurrent,
483
+ queue=cfg.http.queue,
484
+ timeout_s=cfg.http.request_timeout_s,
485
+ state=admission,
486
+ )
487
+ ui_path = cfg.ui.path if cfg.ui.enabled else None
488
+ app.add_middleware(AuthMiddleware, table=table, header=cfg.auth.header, ui_path=ui_path)
489
+ _add_cors_and_signing(app, cfg, signing_key)
490
+ app.add_middleware(ErrorGuardMiddleware)
491
+ app.add_middleware(
492
+ AccessLogMiddleware,
493
+ router_app=app,
494
+ enabled=cfg.logging.access_log,
495
+ sinks=sinks,
496
+ templates=_route_table(app, routes_verify.router, routes_templates.router),
497
+ )
498
+ app.add_middleware(SecurityHeadersMiddleware, hsts=cfg.tls.enabled and cfg.http.hsts, ui_path=ui_path)
499
+ app.add_middleware(HeaderLimitMiddleware, max_bytes=cfg.http.max_header_bytes)
500
+ return app