keel-core 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 (69) hide show
  1. keel_core/__init__.py +8 -0
  2. keel_core/adapters/__init__.py +1 -0
  3. keel_core/adapters/inbound/__init__.py +1 -0
  4. keel_core/adapters/inbound/http/__init__.py +18 -0
  5. keel_core/adapters/inbound/http/app.py +181 -0
  6. keel_core/adapters/inbound/http/conformance.py +61 -0
  7. keel_core/adapters/inbound/http/edge.py +120 -0
  8. keel_core/adapters/inbound/http/health.py +30 -0
  9. keel_core/adapters/inbound/http/problem.py +88 -0
  10. keel_core/adapters/inbound/http/ratelimit.py +104 -0
  11. keel_core/adapters/inbound/http/request_id.py +46 -0
  12. keel_core/adapters/inbound/http/security.py +91 -0
  13. keel_core/adapters/inbound/rpc/__init__.py +14 -0
  14. keel_core/adapters/inbound/rpc/item_service.py +102 -0
  15. keel_core/adapters/inbound/rpc/server.py +242 -0
  16. keel_core/adapters/outbound/__init__.py +1 -0
  17. keel_core/adapters/outbound/auth/__init__.py +6 -0
  18. keel_core/adapters/outbound/auth/api_key.py +44 -0
  19. keel_core/adapters/outbound/auth/oidc.py +121 -0
  20. keel_core/adapters/outbound/clock.py +13 -0
  21. keel_core/adapters/outbound/logging.py +307 -0
  22. keel_core/adapters/outbound/messaging/__init__.py +11 -0
  23. keel_core/adapters/outbound/messaging/factory.py +132 -0
  24. keel_core/adapters/outbound/messaging/kafka.py +458 -0
  25. keel_core/adapters/outbound/messaging/memory.py +43 -0
  26. keel_core/adapters/outbound/messaging/nats.py +159 -0
  27. keel_core/adapters/outbound/messaging/rabbitmq.py +252 -0
  28. keel_core/adapters/outbound/persistence/__init__.py +14 -0
  29. keel_core/adapters/outbound/persistence/base.py +13 -0
  30. keel_core/adapters/outbound/persistence/database.py +93 -0
  31. keel_core/adapters/outbound/persistence/unit_of_work.py +47 -0
  32. keel_core/adapters/outbound/redaction.py +107 -0
  33. keel_core/adapters/outbound/rpc/__init__.py +9 -0
  34. keel_core/adapters/outbound/rpc/client.py +26 -0
  35. keel_core/adapters/outbound/rpc/tls.py +40 -0
  36. keel_core/adapters/outbound/secrets/__init__.py +22 -0
  37. keel_core/adapters/outbound/secrets/aws.py +145 -0
  38. keel_core/adapters/outbound/secrets/caching.py +188 -0
  39. keel_core/adapters/outbound/secrets/env.py +36 -0
  40. keel_core/adapters/outbound/secrets/factory.py +99 -0
  41. keel_core/adapters/outbound/secrets/gcp.py +186 -0
  42. keel_core/adapters/outbound/secrets/openbao.py +269 -0
  43. keel_core/adapters/outbound/telemetry/__init__.py +21 -0
  44. keel_core/adapters/outbound/telemetry/metrics.py +35 -0
  45. keel_core/adapters/outbound/telemetry/otel.py +59 -0
  46. keel_core/adapters/outbound/telemetry/redacting_exporter.py +132 -0
  47. keel_core/adapters/outbound/telemetry/saturation.py +81 -0
  48. keel_core/application/__init__.py +1 -0
  49. keel_core/config.py +33 -0
  50. keel_core/context.py +19 -0
  51. keel_core/domain/__init__.py +1 -0
  52. keel_core/domain/errors.py +107 -0
  53. keel_core/genproto/__init__.py +27 -0
  54. keel_core/genproto/keel/reference/v1/item_pb2.py +51 -0
  55. keel_core/genproto/keel/reference/v1/item_pb2.pyi +53 -0
  56. keel_core/genproto/keel/reference/v1/item_pb2_grpc.py +178 -0
  57. keel_core/ports/__init__.py +1 -0
  58. keel_core/ports/auth.py +23 -0
  59. keel_core/ports/clock.py +14 -0
  60. keel_core/ports/logging.py +29 -0
  61. keel_core/ports/messaging.py +37 -0
  62. keel_core/py.typed +0 -0
  63. keel_core/testkit/__init__.py +1 -0
  64. keel_core/testkit/contract.py +111 -0
  65. keel_core/testkit/fakes.py +49 -0
  66. keel_core/testkit/messaging.py +76 -0
  67. keel_core-0.1.0.dist-info/METADATA +78 -0
  68. keel_core-0.1.0.dist-info/RECORD +69 -0
  69. keel_core-0.1.0.dist-info/WHEEL +4 -0
keel_core/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """keel platform core: ports, cross-cutting adapters, and the test kit.
2
+
3
+ This package is Tier 1 of the reuse model (see docs/adr/0009): the shared
4
+ library every keel Python service depends on. It implements the ports defined
5
+ by the platform contract (platform.yaml); services provide the composition.
6
+ """
7
+
8
+ __version__ = "0.1.0"
@@ -0,0 +1 @@
1
+ """Adapters layer: inbound (driving) and outbound (driven) port implementations."""
@@ -0,0 +1 @@
1
+ """Inbound (driving) adapters: HTTP, CLI, message consumers."""
@@ -0,0 +1,18 @@
1
+ """FastAPI inbound HTTP adapter: app factory, problem+json, health, auth."""
2
+
3
+ from keel_core.adapters.inbound.http.app import create_app
4
+ from keel_core.adapters.inbound.http.conformance import (
5
+ assert_routes_require_auth,
6
+ unprotected_routes,
7
+ )
8
+ from keel_core.adapters.inbound.http.ratelimit import RateLimitMiddleware
9
+ from keel_core.adapters.inbound.http.security import require_roles, require_scopes
10
+
11
+ __all__ = [
12
+ "RateLimitMiddleware",
13
+ "assert_routes_require_auth",
14
+ "create_app",
15
+ "require_roles",
16
+ "require_scopes",
17
+ "unprotected_routes",
18
+ ]
@@ -0,0 +1,181 @@
1
+ """FastAPI application factory (ADR-0013).
2
+
3
+ Deny-by-default is **enforced**, not conventional: at startup a conformance check
4
+ fails if any non-exempt route lacks an auth dependency, so a route added without
5
+ ``require_scopes``/``require_principal`` cannot ship. ``create_app`` also requires an
6
+ ``Authenticator`` and wires request-id, security headers, a body-size limit,
7
+ problem+json errors, metrics, and health endpoints.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import os
14
+ from collections.abc import AsyncIterator, Sequence
15
+ from contextlib import asynccontextmanager
16
+ from typing import TYPE_CHECKING
17
+
18
+ from fastapi import FastAPI
19
+ from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
20
+ from starlette.middleware.cors import CORSMiddleware
21
+ from starlette.middleware.trustedhost import TrustedHostMiddleware
22
+
23
+ # Opt in to the STABLE OpenTelemetry HTTP semantic conventions process-wide, so the
24
+ # ASGI instrumentation emits ``http.server.request.duration`` (seconds) with
25
+ # ``http.request.method`` / ``http.response.status_code`` attributes rather than the
26
+ # legacy ``http.server.duration`` (milliseconds). The opt-in is read once, lazily, the
27
+ # first time any instrumentation initializes; setting it at import (before create_app
28
+ # runs) is what makes the metric names deterministic. ``setdefault`` lets a deployment
29
+ # override it (e.g. ``http/dup`` during a migration) via the real environment.
30
+ os.environ.setdefault("OTEL_SEMCONV_STABILITY_OPT_IN", "http")
31
+
32
+ from keel_core.adapters.inbound.http.conformance import assert_routes_require_auth
33
+ from keel_core.adapters.inbound.http.edge import BodyLimitMiddleware, SecurityHeadersMiddleware
34
+ from keel_core.adapters.inbound.http.health import ReadinessCheck, build_health_router
35
+ from keel_core.adapters.inbound.http.problem import register_exception_handlers
36
+ from keel_core.adapters.inbound.http.ratelimit import RateLimitMiddleware
37
+ from keel_core.adapters.inbound.http.request_id import RequestIdMiddleware
38
+ from keel_core.adapters.inbound.http.security import principal_dependency
39
+ from keel_core.adapters.outbound.logging import StructuredLogger
40
+
41
+ if TYPE_CHECKING:
42
+ from keel_core.ports.auth import Authenticator
43
+ from keel_core.ports.logging import Logger
44
+
45
+
46
+ @asynccontextmanager
47
+ async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
48
+ """Graceful shutdown: dispose the DB, stop the log writer, flush traces.
49
+
50
+ Resources are read lazily from ``app.state`` so the composition root can set
51
+ them after ``create_app`` returns (``database``, ``log_writer``, ``tracer_provider``).
52
+ Startup fails if any non-exempt route lacks an auth dependency (deny-by-default).
53
+ """
54
+ assert_routes_require_auth(app)
55
+ yield
56
+ # Each step is isolated so one failure does not skip the rest, and the log
57
+ # writer is stopped LAST so logs emitted during DB/tracer/meter shutdown are
58
+ # still written.
59
+ database = getattr(app.state, "database", None)
60
+ if database is not None:
61
+ with contextlib.suppress(Exception):
62
+ await database.dispose()
63
+ tracer_provider = getattr(app.state, "tracer_provider", None)
64
+ if tracer_provider is not None:
65
+ with contextlib.suppress(Exception):
66
+ tracer_provider.shutdown()
67
+ meter_provider = getattr(app.state, "meter_provider", None)
68
+ if meter_provider is not None:
69
+ with contextlib.suppress(Exception):
70
+ meter_provider.shutdown()
71
+ log_writer = getattr(app.state, "log_writer", None)
72
+ if log_writer is not None:
73
+ with contextlib.suppress(Exception):
74
+ log_writer.stop()
75
+
76
+
77
+ def create_app(
78
+ *,
79
+ service: str,
80
+ version: str,
81
+ authenticator: Authenticator,
82
+ logger: Logger | None = None,
83
+ readiness_checks: Sequence[ReadinessCheck] = (),
84
+ max_request_bytes: int = 1_048_576,
85
+ expose_docs: bool = True,
86
+ rate_limit: tuple[int, float] | None = None,
87
+ rate_limit_trust_forwarded: bool = False,
88
+ cors_allow_origins: Sequence[str] = (),
89
+ cors_allow_credentials: bool = False,
90
+ trusted_hosts: Sequence[str] = (),
91
+ ) -> FastAPI:
92
+ """Build a FastAPI app wired with the platform's cross-cutting middleware.
93
+
94
+ Args:
95
+ service: logical service name (used in logs and OpenAPI title).
96
+ version: service version.
97
+ authenticator: required; its presence is what makes auth deny-by-default.
98
+ logger: optional Logger; a StructuredLogger is created if omitted.
99
+ readiness_checks: async callables gating ``/readyz``.
100
+ max_request_bytes: reject requests whose Content-Length exceeds this (413).
101
+ rate_limit: optional ``(max_requests, window_seconds)`` enabling the per-instance
102
+ rate-limit middleware (defense-in-depth; the gateway is the primary control).
103
+ rate_limit_trust_forwarded: whether the rate limiter keys on the ``X-Forwarded-For``
104
+ peer. **Defaults to False (fail-closed)**: a directly-exposed instance must not
105
+ trust a client-supplied header, or a client could spoof it to bypass the limit.
106
+ Set ``True`` only when a trusted proxy/gateway appends the real peer.
107
+ expose_docs: serve the OpenAPI schema and Swagger/ReDoc UIs. Keep ``True``
108
+ for local/dev; pass ``False`` in production so the API map is not
109
+ disclosed anonymously (the schema and both doc UIs are disabled).
110
+ cors_allow_origins: explicit allowed origins. **Default-deny**: empty means no
111
+ CORS middleware, so browsers block all cross-origin requests. Origins must be
112
+ listed explicitly (no implicit wildcard).
113
+ cors_allow_credentials: allow credentialed cross-origin requests. Rejected with a
114
+ wildcard origin (``*``), which the CORS spec forbids with credentials.
115
+ trusted_hosts: if non-empty, only these Host headers are accepted (DNS-rebinding
116
+ defense via Starlette's TrustedHostMiddleware); empty disables the check.
117
+ """
118
+ if "*" in cors_allow_origins and cors_allow_credentials:
119
+ msg = "CORS: allow_credentials with a wildcard origin '*' is forbidden by the spec"
120
+ raise ValueError(msg)
121
+ log: Logger = (
122
+ logger if logger is not None else StructuredLogger(service=service, version=version)
123
+ )
124
+ # Disabling ``openapi_url`` removes the schema and, with it, both doc UIs.
125
+ if expose_docs:
126
+ app = FastAPI(title=service, version=version, lifespan=_lifespan)
127
+ else:
128
+ app = FastAPI(
129
+ title=service,
130
+ version=version,
131
+ lifespan=_lifespan,
132
+ docs_url=None,
133
+ redoc_url=None,
134
+ openapi_url=None,
135
+ )
136
+ # add_middleware makes the LAST-added the OUTERMOST. Add inner-to-outer so the
137
+ # final stack is (outer -> inner): CORS, RequestId, SecurityHeaders, RateLimit,
138
+ # BodyLimit, app. Rejections carry the request-id and security headers - they are
139
+ # not invisible to observability.
140
+ app.add_middleware(BodyLimitMiddleware, max_bytes=max_request_bytes)
141
+ if rate_limit is not None:
142
+ max_requests, window_seconds = rate_limit
143
+ app.add_middleware(
144
+ RateLimitMiddleware,
145
+ max_requests=max_requests,
146
+ window_seconds=window_seconds,
147
+ trust_forwarded=rate_limit_trust_forwarded,
148
+ )
149
+ app.add_middleware(SecurityHeadersMiddleware)
150
+ app.add_middleware(RequestIdMiddleware)
151
+ if trusted_hosts:
152
+ # Reject mismatched Host headers (DNS-rebinding defense) before anything else.
153
+ app.add_middleware(TrustedHostMiddleware, allowed_hosts=list(trusted_hosts))
154
+ if cors_allow_origins:
155
+ # Outermost (preflight + headers on every response). Default-deny: only
156
+ # applied when origins are explicitly listed.
157
+ app.add_middleware(
158
+ CORSMiddleware,
159
+ allow_origins=list(cors_allow_origins),
160
+ allow_credentials=cors_allow_credentials,
161
+ allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
162
+ allow_headers=["authorization", "content-type", "x-api-key"],
163
+ )
164
+ register_exception_handlers(app, log)
165
+ app.include_router(build_health_router(readiness_checks))
166
+ # Authenticator on state powers require_scopes/require_roles; require_principal is
167
+ # the bound authn-only dependency for routers that don't need scope checks.
168
+ app.state.authenticator = authenticator
169
+ app.state.require_principal = principal_dependency(authenticator)
170
+ # Instrument explicitly so the OTel server metrics/spans are owned at the composition
171
+ # point rather than left to FastAPI's implicit native telemetry: the OTel ASGI
172
+ # middleware wraps the whole app and records the duration/active-request metrics and
173
+ # the server span for every request, including RateLimit/BodyLimit rejections
174
+ # (429/413). It reads the global tracer/meter providers configured by the composition
175
+ # root and labels the duration histogram by route TEMPLATE (``http.route``), not the
176
+ # raw path, so cardinality stays bounded. Metrics: ``http.server.request.duration``
177
+ # (histogram, seconds) and ``http.server.active_requests`` (up-down counter). FastAPI's
178
+ # built-in telemetry detects this middleware and defers (no double-emission), so these
179
+ # are recorded exactly once.
180
+ FastAPIInstrumentor.instrument_app(app)
181
+ return app
@@ -0,0 +1,61 @@
1
+ """Route-auth conformance: every non-exempt route must carry an auth dependency.
2
+
3
+ This is what makes deny-by-default real rather than a convention: an unprotected
4
+ business route fails app startup (and the shipped test), so forgetting the auth
5
+ dependency can't ship silently.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterable
11
+
12
+ from fastapi import FastAPI
13
+ from fastapi.routing import APIRoute, APIWebSocketRoute
14
+
15
+ DEFAULT_EXEMPT: frozenset[str] = frozenset(
16
+ {"/healthz", "/readyz", "/openapi.json", "/docs", "/docs/oauth2-redirect", "/redoc"},
17
+ )
18
+
19
+
20
+ def _route_has_auth(route: APIRoute | APIWebSocketRoute) -> bool:
21
+ stack = list(route.dependant.dependencies)
22
+ while stack:
23
+ dependant = stack.pop()
24
+ if getattr(dependant.call, "__keel_auth__", False):
25
+ return True
26
+ stack.extend(dependant.dependencies)
27
+ return False
28
+
29
+
30
+ def unprotected_routes(app: FastAPI, *, exempt: Iterable[str] = DEFAULT_EXEMPT) -> list[str]:
31
+ """Return a label for every non-exempt route not provably carrying auth.
32
+
33
+ Covers HTTP and WebSocket routes. A non-exempt route of a type we cannot
34
+ inspect for an auth dependency (a raw Starlette Route or a Mount) is reported
35
+ too, so it must be explicitly exempted rather than silently allowed through.
36
+ """
37
+ exempt_set = set(exempt)
38
+ missing: list[str] = []
39
+ for route in app.routes:
40
+ path = getattr(route, "path", None)
41
+ if path is None or path in exempt_set:
42
+ continue
43
+ if isinstance(route, APIRoute):
44
+ if not _route_has_auth(route):
45
+ missing.append(f"{','.join(sorted(route.methods or set()))} {path}")
46
+ elif isinstance(route, APIWebSocketRoute):
47
+ if not _route_has_auth(route):
48
+ missing.append(f"WS {path}")
49
+ else:
50
+ # Raw Starlette Route / Mount: no dependant to inspect, so it cannot be
51
+ # proven protected. Deny by default; the service must exempt it explicitly.
52
+ missing.append(f"UNVERIFIED {path}")
53
+ return missing
54
+
55
+
56
+ def assert_routes_require_auth(app: FastAPI, *, exempt: Iterable[str] = DEFAULT_EXEMPT) -> None:
57
+ """Raise if any non-exempt route lacks an auth dependency (deny-by-default)."""
58
+ missing = unprotected_routes(app, exempt=exempt)
59
+ if missing:
60
+ msg = f"deny-by-default violation: routes without an auth dependency: {', '.join(missing)}"
61
+ raise RuntimeError(msg)
@@ -0,0 +1,120 @@
1
+ """Edge-hardening ASGI middleware: security headers and a request body-size limit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from starlette.datastructures import Headers, MutableHeaders
8
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
9
+
10
+ # Always safe for a JSON API (no HTML/scripts of our own to allow).
11
+ _BASE_HEADERS: tuple[tuple[str, str], ...] = (
12
+ ("x-content-type-options", "nosniff"),
13
+ ("x-frame-options", "DENY"),
14
+ ("referrer-policy", "no-referrer"),
15
+ ("content-security-policy", "default-src 'none'; frame-ancestors 'none'"),
16
+ ("permissions-policy", "geolocation=(), camera=(), microphone=(), payment=(), usb=()"),
17
+ )
18
+ _HSTS_VALUE = "max-age=31536000; includeSubDomains"
19
+
20
+ _DEFAULT_MAX_BYTES = 1_048_576 # 1 MiB
21
+
22
+
23
+ class _BodyTooLargeError(Exception):
24
+ """Raised mid-stream when the accumulated request body exceeds the limit."""
25
+
26
+
27
+ class SecurityHeadersMiddleware:
28
+ """Adds baseline security headers to every HTTP response."""
29
+
30
+ def __init__(self, app: ASGIApp) -> None:
31
+ """Wrap the downstream ASGI app."""
32
+ self._app = app
33
+
34
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
35
+ """Append the security headers on the response start message."""
36
+ if scope["type"] != "http":
37
+ await self._app(scope, receive, send)
38
+ return
39
+
40
+ # HSTS is only meaningful over TLS; emitting it on plaintext is misleading.
41
+ is_https = scope.get("scheme") == "https"
42
+
43
+ async def send_wrapper(message: Message) -> None:
44
+ if message["type"] == "http.response.start":
45
+ headers = MutableHeaders(scope=message)
46
+ for key, value in _BASE_HEADERS:
47
+ headers.setdefault(key, value)
48
+ if is_https:
49
+ headers.setdefault("strict-transport-security", _HSTS_VALUE)
50
+ await send(message)
51
+
52
+ await self._app(scope, receive, send_wrapper)
53
+
54
+
55
+ class BodyLimitMiddleware:
56
+ """Rejects requests whose body exceeds ``max_bytes`` (413).
57
+
58
+ Guards the common large-payload DoS vector before auth/handlers run. Enforces
59
+ both a ``Content-Length`` header fast-path and a streaming byte cap: for chunked
60
+ or mismatched-length bodies it counts bytes as they arrive and aborts once the
61
+ limit is crossed.
62
+ """
63
+
64
+ def __init__(self, app: ASGIApp, *, max_bytes: int = _DEFAULT_MAX_BYTES) -> None:
65
+ """Wrap the app with a maximum request body size."""
66
+ self._app = app
67
+ self._max_bytes = max_bytes
68
+
69
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
70
+ """Reject over-limit requests with a problem+json 413 (header fast-path + streaming)."""
71
+ if scope["type"] != "http":
72
+ await self._app(scope, receive, send)
73
+ return
74
+ content_length = Headers(scope=scope).get("content-length")
75
+ too_large = (
76
+ content_length is not None
77
+ and content_length.isdigit()
78
+ and int(content_length) > self._max_bytes
79
+ )
80
+ if too_large:
81
+ await self._reject(send)
82
+ return
83
+
84
+ # Also enforce on the body stream: chunked / lying Content-Length requests
85
+ # are capped as bytes arrive, not trusted on the header alone.
86
+ received = 0
87
+
88
+ async def guarded_receive() -> Message:
89
+ nonlocal received
90
+ message = await receive()
91
+ if message["type"] == "http.request":
92
+ received += len(message.get("body", b""))
93
+ if received > self._max_bytes:
94
+ raise _BodyTooLargeError
95
+ return message
96
+
97
+ try:
98
+ await self._app(scope, guarded_receive, send)
99
+ except _BodyTooLargeError:
100
+ await self._reject(send)
101
+
102
+ async def _reject(self, send: Send) -> None:
103
+ body = json.dumps(
104
+ {
105
+ "type": "urn:keel:error:payload_too_large",
106
+ "title": "Payload Too Large",
107
+ "status": 413,
108
+ },
109
+ ).encode()
110
+ await send(
111
+ {
112
+ "type": "http.response.start",
113
+ "status": 413,
114
+ "headers": [
115
+ (b"content-type", b"application/problem+json"),
116
+ (b"content-length", str(len(body)).encode()),
117
+ ],
118
+ },
119
+ )
120
+ await send({"type": "http.response.body", "body": body})
@@ -0,0 +1,30 @@
1
+ """Liveness and readiness endpoints (platform.yaml health)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable, Sequence
6
+
7
+ from fastapi import APIRouter, Response
8
+ from fastapi.responses import JSONResponse
9
+
10
+ ReadinessCheck = Callable[[], Awaitable[bool]]
11
+
12
+
13
+ def build_health_router(readiness_checks: Sequence[ReadinessCheck]) -> APIRouter:
14
+ """Return a router exposing ``/healthz`` (liveness) and ``/readyz`` (readiness)."""
15
+ router = APIRouter()
16
+
17
+ @router.get("/healthz")
18
+ async def liveness() -> dict[str, str]:
19
+ """Liveness: the process is up."""
20
+ return {"status": "ok"}
21
+
22
+ @router.get("/readyz")
23
+ async def readiness() -> Response:
24
+ """Readiness: all dependency checks pass."""
25
+ for check in readiness_checks:
26
+ if not await check():
27
+ return JSONResponse(status_code=503, content={"status": "not ready"})
28
+ return JSONResponse(status_code=200, content={"status": "ready"})
29
+
30
+ return router
@@ -0,0 +1,88 @@
1
+ """RFC 9457 problem+json error responses for domain errors (platform.yaml errors)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, cast
6
+
7
+ from fastapi import FastAPI, Request, Response
8
+ from fastapi.exceptions import RequestValidationError
9
+ from fastapi.responses import JSONResponse
10
+
11
+ from keel_core.domain.errors import DomainError, ValidationFailed
12
+
13
+ if TYPE_CHECKING:
14
+ from keel_core.ports.logging import Logger
15
+
16
+ PROBLEM_CONTENT_TYPE = "application/problem+json"
17
+
18
+
19
+ def _problem(
20
+ *,
21
+ status: int,
22
+ title: str,
23
+ category: str,
24
+ detail: str | None,
25
+ instance: str,
26
+ extra: dict[str, object] | None = None,
27
+ ) -> JSONResponse:
28
+ body: dict[str, object] = {
29
+ "type": f"urn:keel:error:{category}",
30
+ "title": title,
31
+ "status": status,
32
+ "instance": instance,
33
+ }
34
+ if detail is not None:
35
+ body["detail"] = detail
36
+ if extra:
37
+ body.update(extra) # RFC 9457 extension members (e.g. invalid-params)
38
+ return JSONResponse(status_code=status, content=body, media_type=PROBLEM_CONTENT_TYPE)
39
+
40
+
41
+ def register_exception_handlers(app: FastAPI, logger: Logger) -> None:
42
+ """Install problem+json handlers for domain, validation, and unhandled errors."""
43
+
44
+ async def _domain(request: Request, exc: Exception) -> Response:
45
+ error = cast("DomainError", exc)
46
+ if error.status >= 500:
47
+ logger.error("domain error", category=error.category.value, status=error.status)
48
+ return _problem(
49
+ status=error.status,
50
+ title=error.title,
51
+ category=error.category.value,
52
+ detail=error.detail,
53
+ instance=request.url.path,
54
+ )
55
+
56
+ async def _validation(request: Request, exc: Exception) -> Response:
57
+ # RFC 9457 extension: name each field that failed so clients can fix them.
58
+ invalid_params = [
59
+ {
60
+ "name": ".".join(str(part) for part in error.get("loc", ())),
61
+ "reason": error.get("msg", ""),
62
+ }
63
+ for error in cast("RequestValidationError", exc).errors()
64
+ ]
65
+ return _problem(
66
+ status=400,
67
+ title=ValidationFailed.title,
68
+ category=ValidationFailed.category.value,
69
+ detail="Request validation failed",
70
+ instance=request.url.path,
71
+ extra={"invalid-params": invalid_params},
72
+ )
73
+
74
+ async def _unhandled(request: Request, exc: Exception) -> Response:
75
+ # Starlette invokes this inside an `except`, so the exception is active and
76
+ # its traceback is captured; it goes to logs only, never to the client.
77
+ logger.exception("unhandled error") # noqa: LOG004
78
+ return _problem(
79
+ status=500,
80
+ title="Internal Server Error",
81
+ category="internal",
82
+ detail=None,
83
+ instance=request.url.path,
84
+ )
85
+
86
+ app.add_exception_handler(DomainError, _domain)
87
+ app.add_exception_handler(RequestValidationError, _validation)
88
+ app.add_exception_handler(Exception, _unhandled)
@@ -0,0 +1,104 @@
1
+ """Optional in-app request rate limiting (defense-in-depth).
2
+
3
+ The primary rate-limit control is the API gateway (APISIX; ADR-0005), which is
4
+ shared across replicas. This per-instance token-bucket middleware is opt-in and
5
+ exists for single-instance deployments and local defense-in-depth; it is keyed
6
+ by client address and holds state in memory, so it does not coordinate across
7
+ replicas. Over the limit it returns a 429 ``problem+json`` with ``Retry-After``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import time
14
+ from collections import OrderedDict
15
+
16
+ from starlette.datastructures import Headers
17
+ from starlette.types import ASGIApp, Receive, Scope, Send
18
+
19
+ from keel_core.adapters.inbound.http.problem import PROBLEM_CONTENT_TYPE
20
+
21
+ # Cap on distinct clients tracked at once; evicted LRU so the map cannot grow
22
+ # without bound (a spoofed-source flood would otherwise exhaust memory).
23
+ _DEFAULT_MAX_CLIENTS = 100_000
24
+
25
+
26
+ class RateLimitMiddleware:
27
+ """Per-client token-bucket limiter: ``max_requests`` per ``window_seconds``.
28
+
29
+ Keyed by the real client IP. Behind a trusted proxy/gateway (the documented
30
+ topology) that is the first ``X-Forwarded-For`` hop; set ``trust_forwarded``
31
+ to ``False`` for direct exposure so a client cannot spoof the header. State
32
+ is an LRU bounded at ``max_clients`` entries.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ app: ASGIApp,
38
+ *,
39
+ max_requests: int,
40
+ window_seconds: float,
41
+ trust_forwarded: bool = True,
42
+ max_clients: int = _DEFAULT_MAX_CLIENTS,
43
+ ) -> None:
44
+ """Configure bucket capacity/refill, the forwarded-header trust, and the LRU cap."""
45
+ self._app = app
46
+ self._capacity = float(max_requests)
47
+ self._refill_per_sec = max_requests / window_seconds
48
+ self._retry_after = max(1, round(window_seconds / max_requests))
49
+ self._trust_forwarded = trust_forwarded
50
+ self._max_clients = max_clients
51
+ self._buckets: OrderedDict[str, tuple[float, float]] = OrderedDict()
52
+
53
+ def _client_key(self, scope: Scope) -> str:
54
+ if self._trust_forwarded:
55
+ xff = Headers(scope=scope).get("x-forwarded-for")
56
+ if xff:
57
+ # Rightmost hop = the peer the trusted proxy actually observed. The
58
+ # leftmost entries are client-supplied and spoofable, so keying on
59
+ # them lets a client mint a fresh bucket (bypass) or drain a victim's
60
+ # bucket per request. Assumes a single trusted proxy appends the peer.
61
+ return xff.split(",")[-1].strip()
62
+ client = scope.get("client")
63
+ return client[0] if client else "unknown"
64
+
65
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
66
+ """Consume a token for the client; reject with 429 when the bucket is empty."""
67
+ if scope["type"] != "http":
68
+ await self._app(scope, receive, send)
69
+ return
70
+ key = self._client_key(scope)
71
+ now = time.monotonic()
72
+ tokens, last = self._buckets.get(key, (self._capacity, now))
73
+ tokens = min(self._capacity, tokens + (now - last) * self._refill_per_sec)
74
+ allowed = tokens >= 1.0
75
+ self._buckets[key] = (tokens - 1.0 if allowed else tokens, now)
76
+ self._buckets.move_to_end(key)
77
+ if len(self._buckets) > self._max_clients:
78
+ self._buckets.popitem(last=False) # evict least-recently-seen
79
+ if not allowed:
80
+ await self._reject(scope, send)
81
+ return
82
+ await self._app(scope, receive, send)
83
+
84
+ async def _reject(self, scope: Scope, send: Send) -> None:
85
+ body = json.dumps(
86
+ {
87
+ "type": "urn:keel:error:rate_limited",
88
+ "title": "Too Many Requests",
89
+ "status": 429,
90
+ "instance": scope.get("path", ""),
91
+ "detail": "Rate limit exceeded; retry later.",
92
+ }
93
+ ).encode()
94
+ await send(
95
+ {
96
+ "type": "http.response.start",
97
+ "status": 429,
98
+ "headers": [
99
+ (b"content-type", PROBLEM_CONTENT_TYPE.encode()),
100
+ (b"retry-after", str(self._retry_after).encode()),
101
+ ],
102
+ }
103
+ )
104
+ await send({"type": "http.response.body", "body": body})
@@ -0,0 +1,46 @@
1
+ """Request-id middleware (pure ASGI, so the contextvar reaches the endpoint and its logs)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import uuid
7
+
8
+ from starlette.datastructures import Headers, MutableHeaders
9
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
10
+
11
+ from keel_core import context
12
+
13
+ _HEADER = "x-request-id"
14
+ # A client-supplied id is only propagated if it is a bounded, safe token; anything
15
+ # else is replaced with a fresh id so an attacker cannot reflect arbitrary content
16
+ # into the response header or log field.
17
+ _VALID_REQUEST_ID = re.compile(r"\A[A-Za-z0-9._-]{1,128}\Z")
18
+
19
+
20
+ class RequestIdMiddleware:
21
+ """Mint or propagate ``x-request-id``, expose it on logs (via context) and the response."""
22
+
23
+ def __init__(self, app: ASGIApp) -> None:
24
+ """Wrap the downstream ASGI app."""
25
+ self._app = app
26
+
27
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
28
+ """Set the request id for the scope's lifetime and echo it on the response."""
29
+ if scope["type"] != "http":
30
+ await self._app(scope, receive, send)
31
+ return
32
+ incoming = Headers(scope=scope).get(_HEADER)
33
+ request_id = (
34
+ incoming if incoming and _VALID_REQUEST_ID.match(incoming) else uuid.uuid4().hex
35
+ )
36
+ token = context.request_id_var.set(request_id)
37
+
38
+ async def send_wrapper(message: Message) -> None:
39
+ if message["type"] == "http.response.start":
40
+ MutableHeaders(scope=message)[_HEADER] = request_id
41
+ await send(message)
42
+
43
+ try:
44
+ await self._app(scope, receive, send_wrapper)
45
+ finally:
46
+ context.request_id_var.reset(token)