Skip to content

Commit 61cb3eb

Browse files
feat(fastapi): choose which request headers ContextMiddleware reads (#115)
1 parent 665b758 commit 61cb3eb

11 files changed

Lines changed: 294 additions & 9 deletions

File tree

‎docs/adapters/fastapi.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ SERVER__UVICORN__TIMEOUT_KEEP_ALIVE=30
123123
SERVER__UVICORN__FORWARDED_ALLOW_IPS=*
124124
SERVER__MIDDLEWARES__GZIP__ENABLED=false
125125
SERVER__MIDDLEWARES__CORS__ALLOW_ORIGINS='["https://app.example.com"]'
126+
SERVER__MIDDLEWARES__CONTEXT_HEADERS='{"x-request-id":"request_id"}'
126127
```
127128

128129
Every model is a plain `BaseModel`, never a `BaseSettings`, so the only way into `server.port` is
@@ -279,6 +280,7 @@ middlewares = MiddlewareConfig(
279280
sentry=True,
280281
processing_time=True,
281282
context_setters=None,
283+
context_headers=None,
282284
logging=LoggingMiddlewareConfig(enabled=True, ignored_paths=["/system/health/livez"]),
283285
gzip=GZipMiddlewareConfig(enabled=True, minimum_size=1000),
284286
cors=CORSMiddlewareConfig(allow_origins=["https://app.example.com"]),
@@ -334,6 +336,21 @@ MiddlewareConfig(correlation_id=CorrelationIdMiddlewareConfig(header_name="X-Cor
334336
MiddlewareConfig(correlation_id=CorrelationIdMiddlewareConfig(enabled=False)) # bind, do not echo
335337
```
336338

339+
### Which request headers are read
340+
341+
By default `ContextMiddleware` binds `X-Request-ID`, `X-User-Id`, `X-Tenant-Id` and `X-Trace-Id`
342+
from every request. They are client input, and they reach the logs, the Sentry scope and outbound
343+
propagation. That is fine behind an edge that strips or sets them. On a port that untrusted
344+
clients reach, read only the request id:
345+
346+
```python
347+
MiddlewareConfig(context_headers={"x-request-id": "request_id"}) # {header: context_key}
348+
MiddlewareConfig(context_headers={}) # no header; the id is always minted
349+
```
350+
351+
`None`, the default, keeps the four. See
352+
[Request context](../concepts/context.md#the-identity-headers-are-client-input) for the trust model.
353+
337354
## Error handling
338355

339356
Five handlers are installed by default, all rendering through one pluggable renderer:

‎docs/agents.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,9 @@ Entrypoint constructors, all keyword-only:
337337
`/system/health/livez` and `/system/health/readyz`, docs at `/system/docs`,
338338
`redirect_slashes=False`. `MiddlewareConfig` defaults have unit scope, context, sentry,
339339
processing time, logging, correlation id, gzip and CORS all on.
340+
`MiddlewareConfig.context_headers: dict[str, str] | None = None` is `{header: context_key}`
341+
for `ContextMiddleware`: `None` reads `x-request-id`, `x-user-id`, `x-tenant-id` and
342+
`x-trace-id`, `{}` reads none and always mints the request id (rule 21).
340343
`HttpServerSettings` is `HttpConfig` as a settings model — a plain pydantic `BaseModel` the
341344
adapter exports; nest it as `server: HttpServerSettings = HttpServerSettings()` in your
342345
settings class and it is `SERVER__*` in the environment. Same fields and defaults, `health` and
@@ -483,6 +486,14 @@ Each `*Plugin` takes exactly the same arguments as its entrypoint and exposes `.
483486
`min(host drain_grace_seconds, its own cap)`: `GrpcConfig.grace_period` for gRPC,
484487
`graceful_timeout` for FastAPI and Litestar (`0` there sets no cap). Both caps default to
485488
30.0, the default grace; raising `drain_grace_seconds` above that needs the cap raised too.
489+
21. **The FastAPI context headers are client input.** By default `x-user-id`, `x-tenant-id`
490+
and `x-trace-id` are bound from any request into the logs, the Sentry user and tags, and
491+
`propagation_metadata()`, which forwards them downstream. `is_safe_context_id` checks the
492+
characters, not the sender. Behind an edge that strips or sets them this is fine; on a port
493+
untrusted clients reach, pass
494+
`MiddlewareConfig(context_headers={"x-request-id": "request_id"})`, or set
495+
`SERVER__MIDDLEWARES__CONTEXT_HEADERS='{"x-request-id":"request_id"}'`. The gRPC
496+
interceptor reads the same metadata keys and has no such setting.
486497

487498
## Common mistakes
488499

‎docs/concepts/context.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,29 @@ is_safe_context_id("a\nb: injected") # False
7575

7676
A rejected value is dropped and a fresh id is generated instead.
7777

78+
### The identity headers are client input
79+
80+
The validation checks the characters, not who sent them. Any caller can send `X-User-Id: admin`,
81+
and by default that value lands in every log line, on the Sentry user and tags, and, through
82+
`propagation_metadata()`, in the headers your service sends downstream, which may trust it.
83+
84+
That is fine behind an edge, such as a gateway or a mesh, that strips these headers or sets them
85+
itself. On a port that untrusted clients reach, read only the request id:
86+
87+
```python
88+
from servicewright.adapters.fastapi import FastApiEntrypoint, MiddlewareConfig
89+
90+
FastApiEntrypoint(middlewares=MiddlewareConfig(context_headers={"x-request-id": "request_id"}))
91+
```
92+
93+
```bash
94+
SERVER__MIDDLEWARES__CONTEXT_HEADERS='{"x-request-id":"request_id"}'
95+
```
96+
97+
`context_headers` maps a request header to the context key it binds. `None`, the default, reads
98+
the four headers in the table above. `{}` reads none, so the service always mints the request id.
99+
The gRPC interceptor reads the same four metadata keys and has no such setting.
100+
78101
## Writing
79102

80103
For your own keys, or in code that has no transport:

‎docs/operations/checklist.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ to a failure someone has already had.
6868
production port.
6969
- [ ] CORS lists explicit origins. `allow_credentials=True` with `allow_origins=["*"]` is rejected
7070
at construction, but a bare `["*"]` is still worth a second look.
71+
- [ ] An HTTP port that untrusted clients reach either sits behind an edge that strips or sets
72+
`X-User-Id`, `X-Tenant-Id` and `X-Trace-Id`, or sets
73+
`MiddlewareConfig(context_headers={"x-request-id": "request_id"})`. Otherwise the client picks
74+
the `user_id` in your logs, on Sentry and in outbound propagation.
7175
- [ ] Secrets reach the process through settings, not through code — sink setup happens before the
7276
DI container exists.
7377
- [ ] `max_receive_message_length` and request size limits are set for public endpoints.

‎servicewright/adapters/fastapi/config.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,15 @@ class MiddlewareConfig:
117117
# OTel baggage when opentelemetry is installed); pass your own
118118
# ContextSetter list to replace them.
119119
context_setters: list[Any] | None = None
120+
context_headers: dict[str, str] | None = None
121+
"""Request headers ``ContextMiddleware`` binds, as ``{header: context_key}``.
122+
123+
``None`` reads ``x-request-id``, ``x-user-id``, ``x-tenant-id`` and
124+
``x-trace-id``. They are client input, and they reach every log line, the
125+
Sentry scope and outbound propagation, so on a port untrusted clients reach
126+
pass ``{"x-request-id": "request_id"}``. ``{}`` reads no header, and the
127+
request id is then always minted by the service.
128+
"""
120129

121130
# Complex middlewares.
122131
logging: LoggingMiddlewareConfig = field(default_factory=LoggingMiddlewareConfig)

‎servicewright/adapters/fastapi/configurators.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ def setup_middleware_stack(
131131
setters = config.context_setters if config.context_setters is not None else get_default_context_setters()
132132
app.add_middleware(
133133
ContextMiddleware,
134+
header_extractors=config.context_headers,
134135
context_setters=setters,
135136
request_id_header=config.correlation_id.header_name,
136137
echo_request_id=config.correlation_id.enabled,

‎servicewright/adapters/fastapi/middlewares/context.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,14 @@ def __init__(
5959
) -> None:
6060
self.app = app
6161
self.echo_request_id = echo_request_id
62-
self.header_extractors = header_extractors or {
63-
"x-request-id": "request_id",
64-
"x-user-id": "user_id",
65-
"x-tenant-id": "tenant_id",
66-
"x-trace-id": "trace_id",
67-
}
62+
if header_extractors is None:
63+
header_extractors = {
64+
"x-request-id": "request_id",
65+
"x-user-id": "user_id",
66+
"x-tenant-id": "tenant_id",
67+
"x-trace-id": "trace_id",
68+
}
69+
self.header_extractors = header_extractors
6870
self.cookie_extractors = cookie_extractors or {}
6971
self.custom_extractors = custom_extractors or []
7072
self.auto_generate_request_id = auto_generate_request_id

‎servicewright/adapters/fastapi/settings.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,11 @@ class MiddlewareSettings(BaseModel):
149149
context: bool = Field(default=True, description="ContextMiddleware: correlation ids, bound and echoed")
150150
sentry: bool = Field(default=True, description="SentryMiddleware: enrich the Sentry scope from the request")
151151
processing_time: bool = Field(default=True, description="X-Process-Time response header")
152+
context_headers: dict[str, str] | None = Field(
153+
default=None,
154+
description="Request headers ContextMiddleware binds, {header: context_key}; None reads x-request-id, "
155+
"x-user-id, x-tenant-id and x-trace-id, {} reads none; JSON in the environment",
156+
)
152157
logging: LoggingMiddlewareSettings = Field(default_factory=LoggingMiddlewareSettings)
153158
correlation_id: CorrelationIdMiddlewareSettings = Field(default_factory=CorrelationIdMiddlewareSettings)
154159
gzip: GZipMiddlewareSettings = Field(default_factory=GZipMiddlewareSettings)
@@ -168,6 +173,7 @@ def to_config(
168173
sentry=self.sentry,
169174
processing_time=self.processing_time,
170175
context_setters=context_setters,
176+
context_headers=None if self.context_headers is None else dict(self.context_headers),
171177
logging=self.logging.to_config(),
172178
correlation_id=self.correlation_id.to_config(),
173179
gzip=self.gzip.to_config(),

‎tests/integration/test_fastapi_integration.py‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,18 @@
1616
import pytest
1717
from fastapi import APIRouter
1818

19-
from servicewright import AppSpec, Service
20-
from servicewright.adapters.fastapi import FastApiEntrypoint, HttpConfig
19+
from servicewright import AppSpec, Service, propagation_metadata
20+
from servicewright.adapters.fastapi import FastApiEntrypoint, HttpConfig, HttpServerSettings
21+
from servicewright.adapters.settings import BaseServiceSettings
2122
from servicewright.testing import FakeContainer, FakeSettings
2223

2324
pytestmark = pytest.mark.integration
2425

2526

27+
class _Settings(BaseServiceSettings):
28+
server: HttpServerSettings = HttpServerSettings()
29+
30+
2631
def _free_port() -> int:
2732
"""Reserve and release an ephemeral TCP port (robust on win32)."""
2833
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
@@ -104,3 +109,43 @@ async def request_then_stop() -> httpx.Response:
104109
# Assert
105110
assert response.status_code == 500, "uvicorn cancels the request itself, not a hard stop that orphans it"
106111
assert handler_finished is False
112+
113+
114+
async def test__fastapi_entrypoint__context_headers_from_the_environment__forwards_only_the_request_id(
115+
monkeypatch: pytest.MonkeyPatch,
116+
) -> None:
117+
# Arrange
118+
monkeypatch.setenv("SERVER__MIDDLEWARES__CONTEXT_HEADERS", '{"x-request-id":"request_id"}')
119+
port = _free_port()
120+
spec: AppSpec[Any, Any] = AppSpec(service_name="http-it-service", create_container=lambda _s: FakeContainer())
121+
router = APIRouter()
122+
123+
@router.get("/outbound")
124+
async def outbound() -> dict[str, str]:
125+
return propagation_metadata()
126+
127+
ep = FastApiEntrypoint(
128+
config=HttpConfig(host="127.0.0.1", port=port),
129+
middlewares=_Settings().server.middlewares.to_config(),
130+
routers=(router,),
131+
)
132+
stop = asyncio.Event()
133+
134+
async def request_then_stop() -> httpx.Response:
135+
while not spec.health.ready:
136+
await asyncio.sleep(0.01)
137+
async with httpx.AsyncClient(base_url=f"http://127.0.0.1:{port}", timeout=2.0) as client:
138+
try:
139+
return await client.get(
140+
"/outbound", headers={"X-Request-ID": "req-1", "X-User-Id": "user-9", "X-Tenant-Id": "tenant-3"}
141+
)
142+
finally:
143+
stop.set()
144+
145+
# Act
146+
_, response = await asyncio.gather(
147+
Service(spec, entrypoints=[ep]).run(FakeSettings(), stop=stop), request_then_stop()
148+
)
149+
150+
# Assert
151+
assert response.json() == {"x-request-id": "req-1"}

0 commit comments

Comments
 (0)