keel-core 0.1.0__tar.gz
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.
- keel_core-0.1.0/.gitignore +78 -0
- keel_core-0.1.0/PKG-INFO +78 -0
- keel_core-0.1.0/README.md +48 -0
- keel_core-0.1.0/pyproject.toml +76 -0
- keel_core-0.1.0/src/keel_core/__init__.py +8 -0
- keel_core-0.1.0/src/keel_core/adapters/__init__.py +1 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/__init__.py +1 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/http/__init__.py +18 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/http/app.py +181 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/http/conformance.py +61 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/http/edge.py +120 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/http/health.py +30 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/http/problem.py +88 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/http/ratelimit.py +104 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/http/request_id.py +46 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/http/security.py +91 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/rpc/__init__.py +14 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/rpc/item_service.py +102 -0
- keel_core-0.1.0/src/keel_core/adapters/inbound/rpc/server.py +242 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/__init__.py +1 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/auth/__init__.py +6 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/auth/api_key.py +44 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/auth/oidc.py +121 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/clock.py +13 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/logging.py +307 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/messaging/__init__.py +11 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/messaging/factory.py +132 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/messaging/kafka.py +458 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/messaging/memory.py +43 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/messaging/nats.py +159 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/messaging/rabbitmq.py +252 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/persistence/__init__.py +14 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/persistence/base.py +13 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/persistence/database.py +93 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/persistence/unit_of_work.py +47 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/redaction.py +107 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/rpc/__init__.py +9 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/rpc/client.py +26 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/rpc/tls.py +40 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/secrets/__init__.py +22 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/secrets/aws.py +145 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/secrets/caching.py +188 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/secrets/env.py +36 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/secrets/factory.py +99 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/secrets/gcp.py +186 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/secrets/openbao.py +269 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/telemetry/__init__.py +21 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/telemetry/metrics.py +35 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/telemetry/otel.py +59 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/telemetry/redacting_exporter.py +132 -0
- keel_core-0.1.0/src/keel_core/adapters/outbound/telemetry/saturation.py +81 -0
- keel_core-0.1.0/src/keel_core/application/__init__.py +1 -0
- keel_core-0.1.0/src/keel_core/config.py +33 -0
- keel_core-0.1.0/src/keel_core/context.py +19 -0
- keel_core-0.1.0/src/keel_core/domain/__init__.py +1 -0
- keel_core-0.1.0/src/keel_core/domain/errors.py +107 -0
- keel_core-0.1.0/src/keel_core/genproto/__init__.py +27 -0
- keel_core-0.1.0/src/keel_core/genproto/keel/reference/v1/item_pb2.py +51 -0
- keel_core-0.1.0/src/keel_core/genproto/keel/reference/v1/item_pb2.pyi +53 -0
- keel_core-0.1.0/src/keel_core/genproto/keel/reference/v1/item_pb2_grpc.py +178 -0
- keel_core-0.1.0/src/keel_core/ports/__init__.py +1 -0
- keel_core-0.1.0/src/keel_core/ports/auth.py +23 -0
- keel_core-0.1.0/src/keel_core/ports/clock.py +14 -0
- keel_core-0.1.0/src/keel_core/ports/logging.py +29 -0
- keel_core-0.1.0/src/keel_core/ports/messaging.py +37 -0
- keel_core-0.1.0/src/keel_core/py.typed +0 -0
- keel_core-0.1.0/src/keel_core/testkit/__init__.py +1 -0
- keel_core-0.1.0/src/keel_core/testkit/contract.py +111 -0
- keel_core-0.1.0/src/keel_core/testkit/fakes.py +49 -0
- keel_core-0.1.0/src/keel_core/testkit/messaging.py +76 -0
- keel_core-0.1.0/tests/test_api_key.py +53 -0
- keel_core-0.1.0/tests/test_app.py +86 -0
- keel_core-0.1.0/tests/test_auth.py +17 -0
- keel_core-0.1.0/tests/test_aws_secrets.py +310 -0
- keel_core-0.1.0/tests/test_aws_secrets_integration.py +42 -0
- keel_core-0.1.0/tests/test_clock.py +15 -0
- keel_core-0.1.0/tests/test_config.py +32 -0
- keel_core-0.1.0/tests/test_conformance_authz.py +67 -0
- keel_core-0.1.0/tests/test_cors.py +41 -0
- keel_core-0.1.0/tests/test_database_timeout.py +38 -0
- keel_core-0.1.0/tests/test_edge.py +70 -0
- keel_core-0.1.0/tests/test_errors.py +53 -0
- keel_core-0.1.0/tests/test_gcp_secrets.py +306 -0
- keel_core-0.1.0/tests/test_gcp_secrets_integration.py +42 -0
- keel_core-0.1.0/tests/test_grpc.py +32 -0
- keel_core-0.1.0/tests/test_grpc_auth.py +141 -0
- keel_core-0.1.0/tests/test_grpc_item_service.py +202 -0
- keel_core-0.1.0/tests/test_kafka_dispatch.py +368 -0
- keel_core-0.1.0/tests/test_kafka_integration.py +98 -0
- keel_core-0.1.0/tests/test_keycloak_integration.py +52 -0
- keel_core-0.1.0/tests/test_lifespan.py +52 -0
- keel_core-0.1.0/tests/test_logging.py +225 -0
- keel_core-0.1.0/tests/test_messaging.py +65 -0
- keel_core-0.1.0/tests/test_messaging_factory.py +114 -0
- keel_core-0.1.0/tests/test_metrics.py +60 -0
- keel_core-0.1.0/tests/test_mtls.py +171 -0
- keel_core-0.1.0/tests/test_nats_dispatch.py +154 -0
- keel_core-0.1.0/tests/test_nats_integration.py +43 -0
- keel_core-0.1.0/tests/test_oidc.py +120 -0
- keel_core-0.1.0/tests/test_oidc_claims.py +60 -0
- keel_core-0.1.0/tests/test_openbao.py +483 -0
- keel_core-0.1.0/tests/test_openbao_integration.py +53 -0
- keel_core-0.1.0/tests/test_persistence.py +89 -0
- keel_core-0.1.0/tests/test_platform_contract.py +34 -0
- keel_core-0.1.0/tests/test_port_coverage.py +39 -0
- keel_core-0.1.0/tests/test_rabbitmq_dispatch.py +188 -0
- keel_core-0.1.0/tests/test_rabbitmq_integration.py +43 -0
- keel_core-0.1.0/tests/test_ratelimit.py +110 -0
- keel_core-0.1.0/tests/test_request_id.py +36 -0
- keel_core-0.1.0/tests/test_require_roles.py +43 -0
- keel_core-0.1.0/tests/test_saturation.py +64 -0
- keel_core-0.1.0/tests/test_secrets.py +22 -0
- keel_core-0.1.0/tests/test_span_redaction.py +210 -0
- keel_core-0.1.0/tests/test_tracing.py +63 -0
- keel_core-0.1.0/tests/test_trusted_host.py +28 -0
- keel_core-0.1.0/tests/test_version.py +5 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# ---- OS ----
|
|
2
|
+
.DS_Store
|
|
3
|
+
Thumbs.db
|
|
4
|
+
|
|
5
|
+
# ---- Editors / IDEs ----
|
|
6
|
+
.idea/
|
|
7
|
+
.vscode/*
|
|
8
|
+
!.vscode/extensions.json
|
|
9
|
+
!.vscode/settings.shared.json
|
|
10
|
+
*.swp
|
|
11
|
+
*~
|
|
12
|
+
|
|
13
|
+
# ---- Secrets / env ----
|
|
14
|
+
.env
|
|
15
|
+
.env.*
|
|
16
|
+
!.env.sample
|
|
17
|
+
!.env.example
|
|
18
|
+
*.pem
|
|
19
|
+
*.key
|
|
20
|
+
secrets.*
|
|
21
|
+
|
|
22
|
+
# ---- Python ----
|
|
23
|
+
__pycache__/
|
|
24
|
+
*.py[cod]
|
|
25
|
+
.venv/
|
|
26
|
+
venv/
|
|
27
|
+
.mypy_cache/
|
|
28
|
+
.ruff_cache/
|
|
29
|
+
.pytest_cache/
|
|
30
|
+
.coverage
|
|
31
|
+
coverage.xml
|
|
32
|
+
htmlcov/
|
|
33
|
+
dist/
|
|
34
|
+
coverage/
|
|
35
|
+
*.egg-info/
|
|
36
|
+
|
|
37
|
+
# ---- Node / TypeScript ----
|
|
38
|
+
node_modules/
|
|
39
|
+
.next/
|
|
40
|
+
.turbo/
|
|
41
|
+
*.tsbuildinfo
|
|
42
|
+
npm-debug.log*
|
|
43
|
+
pnpm-debug.log*
|
|
44
|
+
.pnpm-store/
|
|
45
|
+
|
|
46
|
+
# ---- Rust ----
|
|
47
|
+
/target/
|
|
48
|
+
**/*.rs.bk
|
|
49
|
+
|
|
50
|
+
# ---- Go ----
|
|
51
|
+
/bin/
|
|
52
|
+
*.test
|
|
53
|
+
*.out
|
|
54
|
+
|
|
55
|
+
# ---- Java / JVM ----
|
|
56
|
+
*.class
|
|
57
|
+
target/
|
|
58
|
+
.gradle/
|
|
59
|
+
build/
|
|
60
|
+
!docs/architecture/build/.gitkeep
|
|
61
|
+
|
|
62
|
+
# ---- Build / tooling output ----
|
|
63
|
+
*.log
|
|
64
|
+
tmp/
|
|
65
|
+
.cache/
|
|
66
|
+
site/
|
|
67
|
+
docs/architecture/build-html/
|
|
68
|
+
docs/architecture/build-pdf/
|
|
69
|
+
|
|
70
|
+
# ---- Containers / IaC ----
|
|
71
|
+
*.tfstate
|
|
72
|
+
*.tfstate.*
|
|
73
|
+
.terraform/
|
|
74
|
+
|
|
75
|
+
# Helm dependency build artifacts (regenerated by `helm dependency update`; the base
|
|
76
|
+
# chart is a file:// local dependency, so no lockfile/tarball needs committing).
|
|
77
|
+
deploy/charts/*/charts/
|
|
78
|
+
deploy/charts/*/Chart.lock
|
keel_core-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: keel-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: keel platform core: ports, cross-cutting adapters, and test kit
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Requires-Dist: fastapi>=0.162.2
|
|
7
|
+
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.48b0
|
|
8
|
+
Requires-Dist: opentelemetry-sdk>=1.27
|
|
9
|
+
Requires-Dist: pydantic-settings>=2.5
|
|
10
|
+
Requires-Dist: pyjwt[crypto]>=2.15.1
|
|
11
|
+
Requires-Dist: sqlalchemy[asyncio]>=2.1.8
|
|
12
|
+
Requires-Dist: starlette>=0.37
|
|
13
|
+
Requires-Dist: structlog>=24.4
|
|
14
|
+
Provides-Extra: aws
|
|
15
|
+
Requires-Dist: boto3>=1.42; extra == 'aws'
|
|
16
|
+
Requires-Dist: botocore>=1.42; extra == 'aws'
|
|
17
|
+
Provides-Extra: gcp
|
|
18
|
+
Requires-Dist: google-api-core>=2.20; extra == 'gcp'
|
|
19
|
+
Requires-Dist: google-cloud-secret-manager>=2.20; extra == 'gcp'
|
|
20
|
+
Provides-Extra: grpc
|
|
21
|
+
Requires-Dist: grpcio>=1.60; extra == 'grpc'
|
|
22
|
+
Requires-Dist: opentelemetry-instrumentation-grpc>=0.48b0; extra == 'grpc'
|
|
23
|
+
Provides-Extra: kafka
|
|
24
|
+
Requires-Dist: aiokafka>=0.15; extra == 'kafka'
|
|
25
|
+
Provides-Extra: nats
|
|
26
|
+
Requires-Dist: nats-py>=2.6; extra == 'nats'
|
|
27
|
+
Provides-Extra: rabbitmq
|
|
28
|
+
Requires-Dist: aio-pika>=9.5; extra == 'rabbitmq'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# keel-core (Python)
|
|
32
|
+
|
|
33
|
+
Tier-1 shared library for keel Python services (see [ADR-0009](../../docs/adr/0009-shared-library-vs-generated-code.md)). It implements the platform contract ([`platform.yaml`](../../platform.yaml)) so services stay thin and consistent by construction.
|
|
34
|
+
|
|
35
|
+
## Layout (hexagonal - [ADR-0002](../../docs/adr/0002-hexagonal-architecture.md))
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
keel_core/
|
|
39
|
+
ports/ # Protocols: Logger, Clock, Authenticator (+ Principal)
|
|
40
|
+
domain/ # errors: taxonomy mapped to RFC 9457 (ADR + platform.yaml)
|
|
41
|
+
adapters/
|
|
42
|
+
inbound/http/ # FastAPI app factory, problem+json, health, deny-by-default auth
|
|
43
|
+
inbound/rpc/ # gRPC server factory (OTel-instrumented)
|
|
44
|
+
outbound/ # StructuredLogger, SystemClock
|
|
45
|
+
outbound/rpc/ # gRPC ServiceClient channel factory (trace-propagating)
|
|
46
|
+
outbound/messaging/ # MessageBus port + InMemory, NATS JetStream, Kafka, RabbitMQ adapters
|
|
47
|
+
outbound/auth/ # OIDCAuthenticator + ApiKeyAuthenticator
|
|
48
|
+
outbound/secrets/ # SecretProvider: Env (dev); OpenBao, AWS, GCP (prod)
|
|
49
|
+
outbound/telemetry/ # OpenTelemetry tracing + metrics + saturation
|
|
50
|
+
outbound/persistence/ # async SQLAlchemy: Database, UnitOfWork (repos are service-defined)
|
|
51
|
+
config.py # BaseServiceConfig (typed, 12-factor, fail-fast)
|
|
52
|
+
context.py # request/trace/span contextvars injected into logs
|
|
53
|
+
testkit/ # fakes: FrozenClock, StubAuthenticator, capturing_logger
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## What's here now
|
|
57
|
+
|
|
58
|
+
- **Structured logging** (on structlog, [ADR-0014](../../docs/adr/0014-logging-implementation.md)) - contract-schema JSON, real exception tracebacks, recursive secret redaction + value-pattern/message scrubbing, reserved-field protection, field-size caps, optional rate limiting, non-blocking background writer, correlation ids from `context`, and `configure_logging()` to route stdlib/library logs through the same schema.
|
|
59
|
+
- **Error taxonomy** - `DomainError` hierarchy with category -> HTTP status mapping.
|
|
60
|
+
- **Typed config** - `BaseServiceConfig` (Pydantic Settings), `KEEL_`-prefixed, immutable, fails fast.
|
|
61
|
+
- **Clock** - injectable time for testability.
|
|
62
|
+
- **Auth** - `Authenticator` / `Principal` port with `OIDCAuthenticator` (Bearer JWTs verified against the issuer JWKS; issuer/audience/expiry enforced; claims mapped to a `Principal`) and `ApiKeyAuthenticator` (SHA-256-hashed keys, accepted via `X-API-Key`).
|
|
63
|
+
- **Secrets** - `SecretProvider` port + `EnvSecretProvider` (dev); production backends OpenBao/Vault ([ADR-0023](../../docs/adr/0023-openbao-secretprovider-adapter.md)), AWS Secrets Manager, and GCP Secret Manager ([ADR-0024](../../docs/adr/0024-cloud-secret-manager-adapters.md)) over one caching core, selected fail-closed at most one (`KEEL_VAULT_ADDR` / `KEEL_AWS_SECRET_ID` / `KEEL_GCP_SECRET`); opt-in `[openbao]`/`[aws]`/`[gcp]` extras. Secrets are reached only through the port.
|
|
64
|
+
- **Distributed tracing** - `configure_tracing()` installs an OpenTelemetry provider; FastAPI/Starlette then emit spans and continue inbound W3C trace context natively. The structured logger reads the active span, so every log line carries the correct `trace_id`/`span_id` with no wiring. OTLP export is configured at deployment.
|
|
65
|
+
- **gRPC** - `create_channel` (ServiceClient) and `create_server` (GrpcApi) factories carry the OpenTelemetry interceptors; the server enforces deny-by-default auth + scope authorization and publishes the `Principal` on a contextvar. mTLS credential builders (`mtls_channel_credentials`/`mtls_server_credentials`) via OpenBao PKI.
|
|
66
|
+
- **Messaging** - `MessageBus` port with `InMemoryMessageBus` (dev/test) and durable `NatsMessageBus` (JetStream), `KafkaMessageBus` (`aiokafka`), and `RabbitMqMessageBus` (`aio-pika`) adapters - all at-least-once with ack/nak/dead-letter and W3C trace propagation, selected fail-closed at most one via `message_bus_from_env` (`KEEL_NATS_URL` / `KEEL_KAFKA_BROKERS` / `KEEL_RABBITMQ_URL`; [ADR-0025](../../docs/adr/0025-kafka-and-rabbitmq-messagebus-adapters.md)); opt-in `[nats]`/`[kafka]`/`[rabbitmq]` extras. A reusable `assert_pubsub_roundtrip` contract they all satisfy.
|
|
67
|
+
- **FastAPI app factory** ([ADR-0013](../../docs/adr/0013-python-web-framework.md)) - `create_app` wires request-id, problem+json (RFC 9457, incl. `invalid-params`), health, metrics, optional rate limiting, default-deny CORS, environment-gated docs, and a deny-by-default auth dependency. Requires an `Authenticator`.
|
|
68
|
+
- **Persistence** - async SQLAlchemy 2.0 plumbing: `Database`, `UnitOfWork`, the `Entity` base, and a bounded readiness `ping()`. Repositories are **service-defined** per aggregate (mapping ORM<->domain); keel-core ships no generic repository.
|
|
69
|
+
- **Test kit** - fakes + reusable contracts (messaging, health/problem conformance) so services test against the ports.
|
|
70
|
+
|
|
71
|
+
## Usage
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from keel_core.adapters.outbound.logging import StructuredLogger
|
|
75
|
+
|
|
76
|
+
log = StructuredLogger(service="orders", version="1.0.0")
|
|
77
|
+
log.info("order placed", order_id=42) # -> one JSON line, secrets redacted
|
|
78
|
+
```
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# keel-core (Python)
|
|
2
|
+
|
|
3
|
+
Tier-1 shared library for keel Python services (see [ADR-0009](../../docs/adr/0009-shared-library-vs-generated-code.md)). It implements the platform contract ([`platform.yaml`](../../platform.yaml)) so services stay thin and consistent by construction.
|
|
4
|
+
|
|
5
|
+
## Layout (hexagonal - [ADR-0002](../../docs/adr/0002-hexagonal-architecture.md))
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
keel_core/
|
|
9
|
+
ports/ # Protocols: Logger, Clock, Authenticator (+ Principal)
|
|
10
|
+
domain/ # errors: taxonomy mapped to RFC 9457 (ADR + platform.yaml)
|
|
11
|
+
adapters/
|
|
12
|
+
inbound/http/ # FastAPI app factory, problem+json, health, deny-by-default auth
|
|
13
|
+
inbound/rpc/ # gRPC server factory (OTel-instrumented)
|
|
14
|
+
outbound/ # StructuredLogger, SystemClock
|
|
15
|
+
outbound/rpc/ # gRPC ServiceClient channel factory (trace-propagating)
|
|
16
|
+
outbound/messaging/ # MessageBus port + InMemory, NATS JetStream, Kafka, RabbitMQ adapters
|
|
17
|
+
outbound/auth/ # OIDCAuthenticator + ApiKeyAuthenticator
|
|
18
|
+
outbound/secrets/ # SecretProvider: Env (dev); OpenBao, AWS, GCP (prod)
|
|
19
|
+
outbound/telemetry/ # OpenTelemetry tracing + metrics + saturation
|
|
20
|
+
outbound/persistence/ # async SQLAlchemy: Database, UnitOfWork (repos are service-defined)
|
|
21
|
+
config.py # BaseServiceConfig (typed, 12-factor, fail-fast)
|
|
22
|
+
context.py # request/trace/span contextvars injected into logs
|
|
23
|
+
testkit/ # fakes: FrozenClock, StubAuthenticator, capturing_logger
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## What's here now
|
|
27
|
+
|
|
28
|
+
- **Structured logging** (on structlog, [ADR-0014](../../docs/adr/0014-logging-implementation.md)) - contract-schema JSON, real exception tracebacks, recursive secret redaction + value-pattern/message scrubbing, reserved-field protection, field-size caps, optional rate limiting, non-blocking background writer, correlation ids from `context`, and `configure_logging()` to route stdlib/library logs through the same schema.
|
|
29
|
+
- **Error taxonomy** - `DomainError` hierarchy with category -> HTTP status mapping.
|
|
30
|
+
- **Typed config** - `BaseServiceConfig` (Pydantic Settings), `KEEL_`-prefixed, immutable, fails fast.
|
|
31
|
+
- **Clock** - injectable time for testability.
|
|
32
|
+
- **Auth** - `Authenticator` / `Principal` port with `OIDCAuthenticator` (Bearer JWTs verified against the issuer JWKS; issuer/audience/expiry enforced; claims mapped to a `Principal`) and `ApiKeyAuthenticator` (SHA-256-hashed keys, accepted via `X-API-Key`).
|
|
33
|
+
- **Secrets** - `SecretProvider` port + `EnvSecretProvider` (dev); production backends OpenBao/Vault ([ADR-0023](../../docs/adr/0023-openbao-secretprovider-adapter.md)), AWS Secrets Manager, and GCP Secret Manager ([ADR-0024](../../docs/adr/0024-cloud-secret-manager-adapters.md)) over one caching core, selected fail-closed at most one (`KEEL_VAULT_ADDR` / `KEEL_AWS_SECRET_ID` / `KEEL_GCP_SECRET`); opt-in `[openbao]`/`[aws]`/`[gcp]` extras. Secrets are reached only through the port.
|
|
34
|
+
- **Distributed tracing** - `configure_tracing()` installs an OpenTelemetry provider; FastAPI/Starlette then emit spans and continue inbound W3C trace context natively. The structured logger reads the active span, so every log line carries the correct `trace_id`/`span_id` with no wiring. OTLP export is configured at deployment.
|
|
35
|
+
- **gRPC** - `create_channel` (ServiceClient) and `create_server` (GrpcApi) factories carry the OpenTelemetry interceptors; the server enforces deny-by-default auth + scope authorization and publishes the `Principal` on a contextvar. mTLS credential builders (`mtls_channel_credentials`/`mtls_server_credentials`) via OpenBao PKI.
|
|
36
|
+
- **Messaging** - `MessageBus` port with `InMemoryMessageBus` (dev/test) and durable `NatsMessageBus` (JetStream), `KafkaMessageBus` (`aiokafka`), and `RabbitMqMessageBus` (`aio-pika`) adapters - all at-least-once with ack/nak/dead-letter and W3C trace propagation, selected fail-closed at most one via `message_bus_from_env` (`KEEL_NATS_URL` / `KEEL_KAFKA_BROKERS` / `KEEL_RABBITMQ_URL`; [ADR-0025](../../docs/adr/0025-kafka-and-rabbitmq-messagebus-adapters.md)); opt-in `[nats]`/`[kafka]`/`[rabbitmq]` extras. A reusable `assert_pubsub_roundtrip` contract they all satisfy.
|
|
37
|
+
- **FastAPI app factory** ([ADR-0013](../../docs/adr/0013-python-web-framework.md)) - `create_app` wires request-id, problem+json (RFC 9457, incl. `invalid-params`), health, metrics, optional rate limiting, default-deny CORS, environment-gated docs, and a deny-by-default auth dependency. Requires an `Authenticator`.
|
|
38
|
+
- **Persistence** - async SQLAlchemy 2.0 plumbing: `Database`, `UnitOfWork`, the `Entity` base, and a bounded readiness `ping()`. Repositories are **service-defined** per aggregate (mapping ORM<->domain); keel-core ships no generic repository.
|
|
39
|
+
- **Test kit** - fakes + reusable contracts (messaging, health/problem conformance) so services test against the ports.
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from keel_core.adapters.outbound.logging import StructuredLogger
|
|
45
|
+
|
|
46
|
+
log = StructuredLogger(service="orders", version="1.0.0")
|
|
47
|
+
log.info("order placed", order_id=42) # -> one JSON line, secrets redacted
|
|
48
|
+
```
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "keel-core"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "keel platform core: ports, cross-cutting adapters, and test kit"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"pydantic-settings>=2.5", # pulls pydantic; declare pydantic directly when a module imports it
|
|
9
|
+
"structlog>=24.4",
|
|
10
|
+
"fastapi>=0.162.2",
|
|
11
|
+
"sqlalchemy[asyncio]>=2.1.8",
|
|
12
|
+
"pyjwt[crypto]>=2.15.1",
|
|
13
|
+
"starlette>=0.37", # ASGI middleware types/utilities (fastapi pins a compatible version)
|
|
14
|
+
"opentelemetry-sdk>=1.27", # OTLP exporter added at deployment time
|
|
15
|
+
"opentelemetry-instrumentation-fastapi>=0.48b0", # route-templated http.server.* spans + metrics
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
# gRPC is opt-in: REST-only services should not pull the grpcio C-extension.
|
|
20
|
+
grpc = [
|
|
21
|
+
"grpcio>=1.60",
|
|
22
|
+
"opentelemetry-instrumentation-grpc>=0.48b0",
|
|
23
|
+
]
|
|
24
|
+
# NATS JetStream is opt-in: REST-only services should not pull the client.
|
|
25
|
+
nats = [
|
|
26
|
+
"nats-py>=2.6",
|
|
27
|
+
]
|
|
28
|
+
# RabbitMQ is opt-in (ADR-0025): REST-only services should not pull the client.
|
|
29
|
+
# aio-pika is the async client (over aiormq); it carries its own type hints.
|
|
30
|
+
rabbitmq = [
|
|
31
|
+
"aio-pika>=9.5",
|
|
32
|
+
]
|
|
33
|
+
# Kafka is opt-in (ADR-0025): REST-only services should not pull the client.
|
|
34
|
+
# aiokafka is the pure-Python asyncio client; it has no type stubs (mypy ignores its imports).
|
|
35
|
+
kafka = [
|
|
36
|
+
"aiokafka>=0.15",
|
|
37
|
+
]
|
|
38
|
+
# AWS Secrets Manager backend (ADR-0024) is opt-in: only services using it pull boto3.
|
|
39
|
+
# boto3 handles SigV4 signing and the default credential chain (env, IRSA, instance
|
|
40
|
+
# profile, SSO); the standard AWS_ENDPOINT_URL_SECRETS_MANAGER env var points it at
|
|
41
|
+
# LocalStack in tests, so no custom endpoint config is carried here.
|
|
42
|
+
aws = [
|
|
43
|
+
"boto3>=1.42",
|
|
44
|
+
# botocore is imported directly for botocore.config.Config (bounded client timeouts/retries).
|
|
45
|
+
# It ships with boto3, but declare it since we import it (deptry DEP003).
|
|
46
|
+
"botocore>=1.42",
|
|
47
|
+
]
|
|
48
|
+
# GCP Secret Manager backend (ADR-0024) is opt-in: only services using it pull the SDK.
|
|
49
|
+
# google-cloud-secret-manager handles the OAuth2 exchange and Application Default
|
|
50
|
+
# Credentials (env, Workload Identity, metadata server). google-api-core is imported
|
|
51
|
+
# directly for NotFound and the bounded Retry, so declare it (deptry DEP003) even though
|
|
52
|
+
# it ships transitively with the client.
|
|
53
|
+
gcp = [
|
|
54
|
+
"google-cloud-secret-manager>=2.20",
|
|
55
|
+
"google-api-core>=2.20",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
[build-system]
|
|
59
|
+
requires = ["hatchling"]
|
|
60
|
+
build-backend = "hatchling.build"
|
|
61
|
+
|
|
62
|
+
[tool.hatch.build.targets.wheel]
|
|
63
|
+
packages = ["src/keel_core"]
|
|
64
|
+
|
|
65
|
+
[tool.deptry]
|
|
66
|
+
# genproto/ is the committed buf output for the keel.reference.v1 contract (ADR-0022). Its
|
|
67
|
+
# imports (google.protobuf, the on-path `keel` package) are an artifact of codegen, not real
|
|
68
|
+
# project dependencies; the regeneration dogfood (proto.yml) is its gate, not deptry.
|
|
69
|
+
extend_exclude = ["src/keel_core/genproto"]
|
|
70
|
+
|
|
71
|
+
[tool.deptry.per_rule_ignores]
|
|
72
|
+
# `keel` is not a distribution: it is the vendored keel.reference.v1 stub tree reached via the
|
|
73
|
+
# genproto sys.path shim (ADR-0022), imported by the ItemService adapter. Not a missing dep.
|
|
74
|
+
# `mypy_boto3_secretsmanager` is a type-only stub (boto3-stubs) imported under TYPE_CHECKING in
|
|
75
|
+
# the AWS adapter (ADR-0024); it is a dev/type dependency, never imported at runtime.
|
|
76
|
+
DEP001 = ["keel", "mypy_boto3_secretsmanager"]
|
|
@@ -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)
|