resource-engine-fastapi 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.
Files changed (39) hide show
  1. resource_engine_fastapi/__init__.py +39 -0
  2. resource_engine_fastapi/access.py +110 -0
  3. resource_engine_fastapi/asyncapi.py +47 -0
  4. resource_engine_fastapi/auth.py +158 -0
  5. resource_engine_fastapi/authz.py +100 -0
  6. resource_engine_fastapi/caching.py +111 -0
  7. resource_engine_fastapi/docs.py +77 -0
  8. resource_engine_fastapi/documents.py +219 -0
  9. resource_engine_fastapi/email_events.py +85 -0
  10. resource_engine_fastapi/errors.py +178 -0
  11. resource_engine_fastapi/events.py +109 -0
  12. resource_engine_fastapi/explorer/__init__.py +441 -0
  13. resource_engine_fastapi/explorer/assets/auth.js +171 -0
  14. resource_engine_fastapi/explorer/assets/console.js +340 -0
  15. resource_engine_fastapi/explorer/assets/events.js +189 -0
  16. resource_engine_fastapi/explorer/assets/explorer.css +156 -0
  17. resource_engine_fastapi/explorer/assets/explorer.js +275 -0
  18. resource_engine_fastapi/explorer/assets/jobs.js +143 -0
  19. resource_engine_fastapi/explorer/assets/messages.js +85 -0
  20. resource_engine_fastapi/explorer/assets/publish.js +117 -0
  21. resource_engine_fastapi/explorer/data.py +84 -0
  22. resource_engine_fastapi/explorer/events.py +182 -0
  23. resource_engine_fastapi/explorer/jobs.py +167 -0
  24. resource_engine_fastapi/explorer/labels.py +198 -0
  25. resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.mo +0 -0
  26. resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.po +417 -0
  27. resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.mo +0 -0
  28. resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.po +417 -0
  29. resource_engine_fastapi/explorer/messages.py +73 -0
  30. resource_engine_fastapi/explorer/publish.py +85 -0
  31. resource_engine_fastapi/exports.py +186 -0
  32. resource_engine_fastapi/i18n.py +76 -0
  33. resource_engine_fastapi/py.typed +0 -0
  34. resource_engine_fastapi/router.py +1031 -0
  35. resource_engine_fastapi/versioning.py +49 -0
  36. resource_engine_fastapi-0.1.0.dist-info/METADATA +32 -0
  37. resource_engine_fastapi-0.1.0.dist-info/RECORD +39 -0
  38. resource_engine_fastapi-0.1.0.dist-info/WHEEL +4 -0
  39. resource_engine_fastapi-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,39 @@
1
+ """FastAPI adapter for Resource Engine."""
2
+
3
+ from resource_engine_fastapi.access import AccessLogMiddleware, install_access_log
4
+ from resource_engine_fastapi.asyncapi import mount_asyncapi
5
+ from resource_engine_fastapi.auth import (
6
+ bearer_actor,
7
+ bearer_token,
8
+ forwarded_client_certificate,
9
+ request_credentials,
10
+ )
11
+ from resource_engine_fastapi.docs import mount_docs
12
+ from resource_engine_fastapi.email_events import mount_email_events
13
+ from resource_engine_fastapi.errors import install_exception_handlers, status_for
14
+ from resource_engine_fastapi.events import build_event_receiver, default_decoder
15
+ from resource_engine_fastapi.explorer import mount_explorer
16
+ from resource_engine_fastapi.i18n import LocaleMiddleware, install_locale
17
+ from resource_engine_fastapi.router import build_resource_router, build_router, mount_resources
18
+
19
+ __all__ = [
20
+ "AccessLogMiddleware",
21
+ "LocaleMiddleware",
22
+ "bearer_actor",
23
+ "bearer_token",
24
+ "build_event_receiver",
25
+ "build_resource_router",
26
+ "build_router",
27
+ "default_decoder",
28
+ "forwarded_client_certificate",
29
+ "install_access_log",
30
+ "install_exception_handlers",
31
+ "install_locale",
32
+ "mount_asyncapi",
33
+ "mount_docs",
34
+ "mount_email_events",
35
+ "mount_explorer",
36
+ "mount_resources",
37
+ "request_credentials",
38
+ "status_for",
39
+ ]
@@ -0,0 +1,110 @@
1
+ """Access log and request ids for the HTTP adapter.
2
+
3
+ ``install_access_log(app)`` (or ``mount_resources(..., access_log=True)``)
4
+ writes one line per request on ``resource_engine.access``: method, route
5
+ template, status, duration, the caller and the request id. The request id
6
+ comes from ``X-Request-Id`` (or is generated), is returned in the response, and
7
+ is in the log context of everything the request does (operation logs, error
8
+ reports), so one id finds all of it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import re
15
+ import time
16
+ import uuid
17
+ from typing import Any
18
+
19
+ from resource_engine.logs import bind_log_context
20
+ from starlette.applications import Starlette
21
+
22
+ logger = logging.getLogger("resource_engine.access")
23
+
24
+ _VALID = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
25
+
26
+
27
+ class AccessLogMiddleware:
28
+ """ASGI middleware: request ids and one access log line per HTTP request.
29
+
30
+ Args:
31
+ header: The request id header (accepted when it looks like an id).
32
+ skip: Paths not logged (health checks).
33
+ level: Log level of successful requests; 4xx log at the same level, 5xx at
34
+ ``ERROR`` is left to the error reporter, so they log at ``WARNING``.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ app: Any,
40
+ *,
41
+ header: str = "x-request-id",
42
+ skip: tuple[str, ...] = ("/health", "/healthz", "/ready"),
43
+ level: int = logging.INFO,
44
+ ) -> None:
45
+ self.app = app
46
+ self.header = header.lower().encode()
47
+ self.skip = skip
48
+ self.level = level
49
+
50
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
51
+ """Handle one ASGI call: set the request id and log the response."""
52
+ if scope["type"] != "http":
53
+ await self.app(scope, receive, send)
54
+ return
55
+ sent = dict(scope.get("headers") or ())
56
+ raw = sent.get(self.header, b"").decode("latin-1")
57
+ request_id = raw if _VALID.match(raw) else uuid.uuid4().hex
58
+ status = 500
59
+ started = time.perf_counter()
60
+
61
+ async def send_with_id(message: dict[str, Any]) -> None:
62
+ nonlocal status
63
+ if message["type"] == "http.response.start":
64
+ status = message["status"]
65
+ headers = list(message.get("headers") or ())
66
+ headers.append((self.header, request_id.encode()))
67
+ message = {**message, "headers": headers}
68
+ await send(message)
69
+
70
+ with bind_log_context(request_id=request_id):
71
+ try:
72
+ await self.app(scope, receive, send_with_id)
73
+ finally:
74
+ path = scope.get("path", "")
75
+ if not path.startswith(self.skip):
76
+ self._log(scope, status, time.perf_counter() - started, request_id)
77
+
78
+ def _log(self, scope: Any, status: int, seconds: float, request_id: str) -> None:
79
+ route = getattr(scope.get("route"), "path", None) or scope.get("path", "")
80
+ state = scope.get("state") or {}
81
+ principal = state.get("principal") if isinstance(state, dict) else None
82
+ level = self.level if status < 500 else logging.WARNING
83
+ logger.log(
84
+ level,
85
+ "%s %s %s %.1f ms",
86
+ scope.get("method"),
87
+ route,
88
+ status,
89
+ seconds * 1000,
90
+ extra={
91
+ "http_method": scope.get("method"),
92
+ "http_route": route,
93
+ "http_status": status,
94
+ "duration_ms": round(seconds * 1000, 1),
95
+ "principal": getattr(principal, "id", None),
96
+ "request_id": request_id,
97
+ },
98
+ )
99
+
100
+
101
+ def install_access_log(
102
+ app: Starlette,
103
+ *,
104
+ header: str = "x-request-id",
105
+ skip: tuple[str, ...] = ("/health", "/healthz", "/ready"),
106
+ level: int = logging.INFO,
107
+ ) -> None:
108
+ """Add ``AccessLogMiddleware`` to a FastAPI or Starlette ``app``, with its
109
+ options (see ``AccessLogMiddleware``)."""
110
+ app.add_middleware(AccessLogMiddleware, header=header, skip=skip, level=level)
@@ -0,0 +1,47 @@
1
+ """Serve the AsyncAPI document next to OpenAPI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from typing import Any
7
+
8
+ from fastapi import FastAPI
9
+ from fastapi.responses import JSONResponse
10
+ from resource_engine import ResourceRegistry
11
+ from resource_engine.messaging import EventRouter, asyncapi_document
12
+
13
+
14
+ def mount_asyncapi(
15
+ app: FastAPI,
16
+ registry: ResourceRegistry,
17
+ *,
18
+ path: str = "/asyncapi.json",
19
+ consumers: Sequence[EventRouter] = (),
20
+ document: Mapping[str, Any] | None = None,
21
+ **options: Any,
22
+ ) -> dict[str, Any]:
23
+ """Serve the AsyncAPI 3.0 document of the app's events at ``path``.
24
+
25
+ The document is built once, from ``registry`` and ``consumers`` with the
26
+ ``asyncapi_document`` ``options`` (``title``, ``servers``, ``channels``,
27
+ ``format``...), or given as ``document`` (for example the file written by
28
+ ``resource-engine docs asyncapi``). The title and version default to the
29
+ app's. Returns the document.
30
+ """
31
+ if document is None:
32
+ options.setdefault("title", app.title)
33
+ options.setdefault("version", app.version)
34
+ document = asyncapi_document(registry, consumers=consumers, **options)
35
+ body = dict(document)
36
+
37
+ async def asyncapi() -> JSONResponse:
38
+ return JSONResponse(body)
39
+
40
+ app.add_api_route(
41
+ path,
42
+ asyncapi,
43
+ methods=["GET"],
44
+ include_in_schema=False,
45
+ summary="AsyncAPI document",
46
+ )
47
+ return body
@@ -0,0 +1,158 @@
1
+ """Bearer-token authentication for the generated routes.
2
+
3
+ Use the returned dependency as ``actor_dependency``::
4
+
5
+ mount_resources(app, registry, manager, actor_dependency=bearer_actor(authenticator))
6
+
7
+ The engine then receives a ``Principal`` as ``actor``; with an authorizer
8
+ (``ResourceManager(authorizer=...)``) it decides what the principal may do.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import binascii
15
+ from collections.abc import Awaitable, Callable
16
+ from typing import Any
17
+ from urllib.parse import unquote
18
+
19
+ from fastapi import Request
20
+ from resource_engine.errors import AuthenticationFailed
21
+ from resource_engine.identity import authenticate, parse_authorization
22
+ from resource_engine.ports.identity import Authenticator, Credentials, Principal
23
+
24
+ type CertificateSource = Callable[[Request], bytes | None]
25
+
26
+
27
+ def bearer_token(request: Request) -> str | None:
28
+ """``Authorization: Bearer|DPoP <token>``, or an API key in ``X-API-Key``."""
29
+ parsed = parse_authorization(request.headers.get("authorization"))
30
+ if parsed is not None:
31
+ return parsed[1]
32
+ api_key = request.headers.get("x-api-key", "").strip()
33
+ return api_key or None
34
+
35
+
36
+ def request_credentials(
37
+ request: Request,
38
+ *,
39
+ client_certificate: CertificateSource | None = None,
40
+ public_url: str | None = None,
41
+ ) -> Credentials | None:
42
+ """The request's token, scheme, DPoP proof and client certificate.
43
+
44
+ ``public_url`` (``https://api.example.com``) replaces the scheme and host
45
+ the server sees, for the URL a DPoP proof must name behind a proxy.
46
+ """
47
+ parsed = parse_authorization(request.headers.get("authorization"))
48
+ if parsed is None:
49
+ api_key = request.headers.get("x-api-key", "").strip()
50
+ if not api_key:
51
+ return None
52
+ parsed = ("bearer", api_key)
53
+ scheme, token = parsed
54
+ proofs = request.headers.getlist("dpop")
55
+ if len(proofs) > 1:
56
+ raise AuthenticationFailed("Send a single DPoP header", reason="invalid_dpop_proof")
57
+ base = public_url.rstrip("/") if public_url else f"{request.url.scheme}://{request.url.netloc}"
58
+ return Credentials(
59
+ token=token,
60
+ scheme=scheme,
61
+ method=request.method,
62
+ url=base + request.url.path,
63
+ proof=proofs[0] if proofs else None,
64
+ client_certificate=client_certificate(request) if client_certificate else None,
65
+ )
66
+
67
+
68
+ def forwarded_client_certificate(header: str = "x-client-cert") -> CertificateSource:
69
+ """The client certificate a TLS-terminating proxy forwards in ``header``:
70
+ PEM, URL-encoded PEM (nginx ``$ssl_client_escaped_cert``) or base64 DER
71
+ (``X-Forwarded-Client-Cert`` from Envoy needs its ``Cert=`` element).
72
+
73
+ Only use it behind a proxy that verifies the certificate and always
74
+ overwrites the header: anyone can send it otherwise.
75
+ """
76
+ name = header.lower()
77
+
78
+ def source(request: Request) -> bytes | None:
79
+ value = request.headers.get(name, "").strip()
80
+ if not value:
81
+ return None
82
+ text = unquote(value) if "%" in value else value
83
+ if "-----BEGIN" in text:
84
+ body = text.split("-----BEGIN CERTIFICATE-----", 1)[-1]
85
+ body = body.split("-----END CERTIFICATE-----", 1)[0]
86
+ text = "".join(body.split())
87
+ try:
88
+ return base64.b64decode(text, validate=True)
89
+ except (binascii.Error, ValueError):
90
+ raise AuthenticationFailed(
91
+ "The forwarded client certificate is malformed", reason="invalid_certificate"
92
+ ) from None
93
+
94
+ return source
95
+
96
+
97
+ def bearer_actor(
98
+ authenticator: Authenticator,
99
+ *,
100
+ required: bool = True,
101
+ rate_limiter: Any = None,
102
+ client_certificate: CertificateSource | None = None,
103
+ public_url: str | None = None,
104
+ translations: Any = None,
105
+ ) -> Callable[[Request], Awaitable[Principal | None]]:
106
+ """FastAPI dependency: ``Authorization: Bearer <token>`` → ``Principal``.
107
+
108
+ Sender-constrained tokens (``Authorization: DPoP`` with a ``DPoP`` proof,
109
+ or certificate-bound tokens) need an authenticator that checks them
110
+ (``resource_engine_oidc.SenderConstrained``); ``client_certificate``
111
+ reads the TLS client certificate (``forwarded_client_certificate()``)
112
+ and ``public_url`` fixes the URL proofs name behind a proxy.
113
+
114
+ With ``translations``, a ``locale`` claim in the token sets the request's
115
+ language (see ``install_locale``).
116
+
117
+ With ``required=False`` anonymous requests get ``actor=None`` (invalid tokens
118
+ are still rejected). With a ``RateLimiter``, callers get its ``default``
119
+ limit, anonymous clients its ``anonymous`` one by IP, and addresses that
120
+ failed authentication ``failed_auth`` times are refused before their
121
+ credentials are checked (429, RE-E710; see docs/rate-limits.md). The client
122
+ address is ``request.client.host``: behind a proxy, run uvicorn with
123
+ ``--proxy-headers --forwarded-allow-ips`` so it is the real client's.
124
+ """
125
+
126
+ async def actor(request: Request) -> Principal | None:
127
+ address = request.client.host if request.client else None
128
+ credentials = request_credentials(
129
+ request, client_certificate=client_certificate, public_url=public_url
130
+ )
131
+ if credentials is None:
132
+ if required:
133
+ raise AuthenticationFailed(
134
+ "Missing bearer token",
135
+ reason="missing",
136
+ hint="Send 'Authorization: Bearer <access token>'.",
137
+ )
138
+ if rate_limiter is not None:
139
+ request.state.rate_limit = await rate_limiter.client(address)
140
+ return None
141
+ if rate_limiter is not None:
142
+ await rate_limiter.before_auth(address)
143
+ try:
144
+ principal = await authenticate(authenticator, credentials)
145
+ except AuthenticationFailed:
146
+ if rate_limiter is not None:
147
+ await rate_limiter.failed(address)
148
+ raise
149
+ request.state.principal = principal # for the access log and error reports
150
+ if translations is not None: # the user's own language beats the browser's
151
+ from resource_engine_fastapi.i18n import principal_locale
152
+
153
+ principal_locale(principal, translations)
154
+ if rate_limiter is not None:
155
+ request.state.rate_limit = await rate_limiter.caller(principal)
156
+ return principal
157
+
158
+ return actor
@@ -0,0 +1,100 @@
1
+ """Routes a permission-management front end needs besides the CRUD of the
2
+ ``authz_*`` resources (which ``mount_resources`` generates like any other)."""
3
+
4
+ from typing import Any
5
+
6
+ from fastapi import APIRouter, Depends
7
+ from pydantic import BaseModel, Field
8
+ from resource_engine import ResourceManager
9
+ from resource_engine.errors import EntityNotFound, PermissionDenied
10
+ from resource_engine.ports.identity import Principal
11
+
12
+
13
+ class ExplainAs(BaseModel):
14
+ """A hypothetical caller, described as its identity provider would."""
15
+
16
+ subject: str = "explain"
17
+ roles: list[str] = Field(default_factory=list, description="Provider roles")
18
+ groups: list[str] = Field(default_factory=list)
19
+ tenant: str | None = None
20
+
21
+
22
+ class ExplainRequest(BaseModel):
23
+ """Body of ``POST /authz/explain``: the action to explain, the record, and optionally another
24
+ caller."""
25
+
26
+ action: str = Field(description="Full action name, e.g. invoices:transition:approve")
27
+ entity_id: Any = Field(default=None, description="Record to evaluate against")
28
+ as_principal: ExplainAs | None = Field(
29
+ default=None, alias="as", description="Evaluate for this caller instead of yourself"
30
+ )
31
+
32
+
33
+ def build_authz_router(manager: ResourceManager, *, actor_dependency: Any) -> APIRouter:
34
+ """The ``/authz`` routes: the catalogue, what the caller may do, and why a decision was made."""
35
+ authz: Any = manager.authorizer # PolicyAuthorizer or another with roles and a catalogue
36
+ router = APIRouter(prefix="/authz", tags=["authz"])
37
+
38
+ async def require_reader(actor: Any) -> None:
39
+ if (await authz.check(actor, "authz_policies:list")).allowed is not True:
40
+ raise PermissionDenied(
41
+ "Not allowed: authz_policies:list",
42
+ details={"action": "authz_policies:list"},
43
+ )
44
+
45
+ @router.get("/catalog", summary="Actions, attributes and operators for policy editors")
46
+ async def catalog(actor: Any = Depends(actor_dependency)) -> dict[str, Any]:
47
+ await require_reader(actor)
48
+ data: dict[str, Any] = authz.catalog.to_dict()
49
+ data["system_roles"] = [
50
+ {
51
+ "name": r.name,
52
+ "grants": list(r.grants),
53
+ "description": r.description,
54
+ "system": True,
55
+ }
56
+ for r in authz.config.system_roles
57
+ ]
58
+ return data
59
+
60
+ @router.get("/me", summary="The caller's roles and permitted actions")
61
+ async def me(actor: Any = Depends(actor_dependency)) -> dict[str, Any]:
62
+ if not isinstance(actor, Principal):
63
+ return {"principal": None, "roles": [], "actions": {}, "fields": {}}
64
+ fields = getattr(authz, "field_permissions", None)
65
+ return {
66
+ "principal": actor.id,
67
+ "roles": sorted(await authz.roles_of(actor)),
68
+ "actions": await authz.permissions(actor),
69
+ "fields": await fields(actor) if fields else {},
70
+ }
71
+
72
+ @router.post("/explain", summary="Why an action is allowed or denied")
73
+ async def explain(
74
+ request: ExplainRequest, actor: Any = Depends(actor_dependency)
75
+ ) -> dict[str, Any]:
76
+ await require_reader(actor)
77
+ target = actor
78
+ if request.as_principal is not None:
79
+ a = request.as_principal
80
+ target = Principal(
81
+ subject=a.subject,
82
+ issuer="explain",
83
+ roles=frozenset(a.roles),
84
+ groups=frozenset(a.groups),
85
+ tenant=a.tenant,
86
+ )
87
+ resource: Any = ...
88
+ if request.entity_id is not None:
89
+ name = request.action.split(":", 1)[0]
90
+ async with manager.uow_factory() as uow:
91
+ resource = await uow.repository(name).get(request.entity_id)
92
+ if resource is None:
93
+ raise EntityNotFound(f"{name} {request.entity_id!r} does not exist")
94
+ decision = await authz.check(target, request.action, resource=resource)
95
+ else:
96
+ decision = await authz.check(target, request.action)
97
+ roles = sorted(await authz.roles_of(target)) if isinstance(target, Principal) else []
98
+ return {"action": request.action, "roles": roles, **decision.to_dict()}
99
+
100
+ return router
@@ -0,0 +1,111 @@
1
+ """HTTP caching for ``GET``: an ``ETag`` on every JSON answer, ``304 Not
2
+ Modified`` when the client already has it (``If-None-Match``), ``Vary`` on
3
+ the credentials and the resource's ``cache_control``. See docs/caching.md.
4
+
5
+ Answers depend on the caller (permissions, field rules, tenancy), so they are
6
+ private: ``Vary: Authorization, X-API-Key`` and, unless the resource says
7
+ otherwise, ``Cache-Control: private, no-cache`` (store, but revalidate).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ from typing import Any
14
+
15
+ DEFAULT_CACHE_CONTROL = "private, no-cache"
16
+ VARY = "Authorization, X-API-Key"
17
+ MAX_BODY = 4 * 1024 * 1024 # larger answers pass through without an ETag
18
+
19
+
20
+ class ConditionalGetMiddleware:
21
+ """ASGI middleware that answers ``GET`` and ``HEAD`` with 304 when the ``ETag`` matches ``If-
22
+ None-Match``."""
23
+
24
+ def __init__(self, app: Any) -> None:
25
+ self.app = app
26
+
27
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
28
+ """Handle one ASGI call: a 304 instead of the body when the ETag matches."""
29
+ if scope["type"] != "http" or scope["method"] not in ("GET", "HEAD"):
30
+ await self.app(scope, receive, send)
31
+ return
32
+ request_headers = dict(scope.get("headers") or [])
33
+ if_none_match = request_headers.get(b"if-none-match", b"").decode("latin-1")
34
+ start: dict[str, Any] | None = None
35
+ chunks: list[bytes] = []
36
+ passing = False
37
+
38
+ async def capture(message: Any) -> None:
39
+ nonlocal start, passing
40
+ if message["type"] == "http.response.start":
41
+ headers = {k.lower(): v for k, v in message.get("headers", [])}
42
+ json = headers.get(b"content-type", b"").startswith(b"application/json")
43
+ if message["status"] != 200 or not json:
44
+ passing = True
45
+ await send(message)
46
+ return
47
+ start = message
48
+ return
49
+ if passing or start is None:
50
+ await send(message)
51
+ return
52
+ chunks.append(message.get("body", b""))
53
+ if message.get("more_body"):
54
+ if sum(map(len, chunks)) > MAX_BODY: # too big to hash: let it go
55
+ passing = True
56
+ await send(start)
57
+ await send(
58
+ {"type": "http.response.body", "body": b"".join(chunks), "more_body": True}
59
+ )
60
+ return
61
+ await _finish(scope, send, start, b"".join(chunks), if_none_match)
62
+
63
+ await self.app(scope, receive, capture)
64
+
65
+
66
+ async def _finish(
67
+ scope: Any, send: Any, start: dict[str, Any], body: bytes, if_none_match: str
68
+ ) -> None:
69
+ headers = [(k, v) for k, v in start.get("headers", [])]
70
+ names = {k.lower() for k, _ in headers}
71
+ etag = next((v.decode("latin-1") for k, v in headers if k.lower() == b"etag"), None)
72
+ if etag is None:
73
+ etag = 'W/"' + hashlib.sha256(body).hexdigest()[:32] + '"'
74
+ headers.append((b"etag", etag.encode()))
75
+ if b"cache-control" not in names:
76
+ control = _route_cache_control(scope) or DEFAULT_CACHE_CONTROL
77
+ headers.append((b"cache-control", control.encode()))
78
+ if b"vary" not in names:
79
+ headers.append((b"vary", VARY.encode()))
80
+ if _matches(if_none_match, etag):
81
+ kept = [
82
+ (k, v)
83
+ for k, v in headers
84
+ if k.lower() in (b"etag", b"cache-control", b"vary", b"x-request-id")
85
+ or k.lower().startswith(b"ratelimit")
86
+ ]
87
+ await send({"type": "http.response.start", "status": 304, "headers": kept})
88
+ await send({"type": "http.response.body", "body": b""})
89
+ return
90
+ headers = [(k, v) for k, v in headers if k.lower() != b"content-length"]
91
+ headers.append((b"content-length", str(len(body)).encode()))
92
+ await send({**start, "headers": headers})
93
+ await send({"type": "http.response.body", "body": body})
94
+
95
+
96
+ def _matches(if_none_match: str, etag: str) -> bool:
97
+ """Weak comparison (RFC 9110): ``W/"x"`` matches ``"x"``."""
98
+ if not if_none_match:
99
+ return False
100
+ if if_none_match.strip() == "*":
101
+ return True
102
+ tag = etag.removeprefix("W/")
103
+ return any(t.strip().removeprefix("W/") == tag for t in if_none_match.split(","))
104
+
105
+
106
+ def _route_cache_control(scope: Any) -> str | None:
107
+ route = scope.get("route")
108
+ return getattr(getattr(route, "endpoint", None), "cache_control", None)
109
+
110
+
111
+ __all__ = ["ConditionalGetMiddleware"]
@@ -0,0 +1,77 @@
1
+ """Serve the documentation site from the application.
2
+
3
+ ```bash
4
+ uv run resource-engine docs site --out site # at build time
5
+ ```
6
+
7
+ ```python
8
+ from resource_engine_fastapi import mount_docs
9
+
10
+ mount_docs(app, "site") # http://localhost:8000/documentation/
11
+ ```
12
+
13
+ The site is static files built by ``resource-engine docs site``: the
14
+ functional documentation, with the API's documents (``openapi.json``,
15
+ ``asyncapi.json``) next to it. Nothing here needs devtools at runtime. To try
16
+ the API from the browser, mount the explorer (``mount_explorer``).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from starlette.applications import Starlette
25
+ from starlette.staticfiles import StaticFiles
26
+ from starlette.types import Receive, Scope, Send
27
+
28
+ #: Pages may run their own scripts and Mermaid from its CDN; they only call this
29
+ #: origin (the explorer's page uses the same policy); email previews are
30
+ #: sandboxed frames.
31
+ CSP = (
32
+ "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
33
+ "style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; "
34
+ "frame-src 'self' about:; frame-ancestors 'self'; base-uri 'none'; form-action 'none'"
35
+ )
36
+
37
+
38
+ class _DocsFiles(StaticFiles):
39
+ """Static files with security headers."""
40
+
41
+ def __init__(self, *, directory: str, csp: str | None) -> None:
42
+ super().__init__(directory=directory, html=True)
43
+ self.csp = csp
44
+
45
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
46
+ async def with_headers(message: Any) -> None:
47
+ if message["type"] == "http.response.start":
48
+ headers = list(message.get("headers", []))
49
+ headers.append((b"x-content-type-options", b"nosniff"))
50
+ headers.append((b"referrer-policy", b"no-referrer"))
51
+ if self.csp:
52
+ headers.append((b"content-security-policy", self.csp.encode()))
53
+ message["headers"] = headers
54
+ await send(message)
55
+
56
+ await super().__call__(scope, receive, with_headers)
57
+
58
+
59
+ def mount_docs(
60
+ app: Starlette, directory: str | Path, *, path: str = "/documentation", csp: str | None = CSP
61
+ ) -> None:
62
+ """Serve the site in ``directory`` at ``path`` (``/documentation/``).
63
+
64
+ ``csp``: the Content-Security-Policy of the pages; the default allows
65
+ Mermaid from its CDN and API calls to this origin only. Pass your own when
66
+ the site uses a self-hosted Mermaid or calls an API elsewhere, or ``None``.
67
+ """
68
+ folder = Path(directory)
69
+ if not (folder / "index.html").is_file():
70
+ raise FileNotFoundError(
71
+ f"{folder}/index.html not found: build it with `resource-engine docs site --out "
72
+ f"{folder}`"
73
+ )
74
+ app.mount(path, _DocsFiles(directory=str(folder), csp=csp), name="docs-site")
75
+
76
+
77
+ __all__ = ["CSP", "mount_docs"]