Skip to content

Commit acc3254

Browse files
fix(fastapi): read the request id from the header it is echoed in (#117)
1 parent 61cb3eb commit acc3254

6 files changed

Lines changed: 63 additions & 11 deletions

File tree

‎docs/adapters/fastapi.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ flowchart TD
327327
generates one otherwise, binds it into the [context store](../concepts/context.md) and returns it
328328
in the response header.
329329

330-
Change the header name, or stop echoing:
330+
Change the header it is read from and echoed in, or stop echoing:
331331

332332
```python
333333
from servicewright.adapters.fastapi import CorrelationIdMiddlewareConfig
@@ -336,6 +336,10 @@ MiddlewareConfig(correlation_id=CorrelationIdMiddlewareConfig(header_name="X-Cor
336336
MiddlewareConfig(correlation_id=CorrelationIdMiddlewareConfig(enabled=False)) # bind, do not echo
337337
```
338338

339+
Up to 0.14.1 `header_name` changed only the response header, and the id was still read from
340+
`X-Request-ID`. A `context_headers` mapping (below) replaces the default headers, so when you
341+
set both, name the request id header in the mapping too.
342+
339343
### Which request headers are read
340344

341345
By default `ContextMiddleware` binds `X-Request-ID`, `X-User-Id`, `X-Tenant-Id` and `X-Trace-Id`

‎docs/agents.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -338,8 +338,8 @@ Entrypoint constructors, all keyword-only:
338338
`redirect_slashes=False`. `MiddlewareConfig` defaults have unit scope, context, sentry,
339339
processing time, logging, correlation id, gzip and CORS all on.
340340
`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).
341+
for `ContextMiddleware`: `None` reads the `correlation_id.header_name` header (`x-request-id`
342+
by default), `x-user-id`, `x-tenant-id` and `x-trace-id`, `{}` reads none and always mints the request id (rule 21).
343343
`HttpServerSettings` is `HttpConfig` as a settings model — a plain pydantic `BaseModel` the
344344
adapter exports; nest it as `server: HttpServerSettings = HttpServerSettings()` in your
345345
settings class and it is `SERVER__*` in the environment. Same fields and defaults, `health` and

‎servicewright/adapters/fastapi/config.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,11 +80,14 @@ class GZipMiddlewareConfig:
8080

8181
@dataclass(slots=True)
8282
class CorrelationIdMiddlewareConfig:
83-
"""How the request id is returned to the client.
83+
"""Which header carries the request id, in and out, and whether it is echoed.
8484
8585
The id itself is owned by :class:`ContextMiddleware` — the same value that
8686
lands in the context store, the logs and outbound propagation. Echoing it
8787
is what lets a caller quote an id that actually appears in your logs.
88+
``header_name`` is the header the id is read from and echoed in. A
89+
``MiddlewareConfig.context_headers`` mapping replaces the default headers,
90+
so with both set, the mapping has to name this header too.
8891
"""
8992

9093
enabled: bool = True
@@ -120,7 +123,8 @@ class MiddlewareConfig:
120123
context_headers: dict[str, str] | None = None
121124
"""Request headers ``ContextMiddleware`` binds, as ``{header: context_key}``.
122125
123-
``None`` reads ``x-request-id``, ``x-user-id``, ``x-tenant-id`` and
126+
``None`` reads the request id header (``correlation_id.header_name``,
127+
``x-request-id`` by default), ``x-user-id``, ``x-tenant-id`` and
124128
``x-trace-id``. They are client input, and they reach every log line, the
125129
Sentry scope and outbound propagation, so on a port untrusted clients reach
126130
pass ``{"x-request-id": "request_id"}``. ``{}`` reads no header, and the

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,12 @@ def __init__(
5959
) -> None:
6060
self.app = app
6161
self.echo_request_id = echo_request_id
62+
self.request_id_header = request_id_header.lower()
63+
self.request_id_context_key = request_id_context_key
6264
if header_extractors is None:
65+
# The request id is read from the header it is echoed in.
6366
header_extractors = {
64-
"x-request-id": "request_id",
67+
self.request_id_header: request_id_context_key,
6568
"x-user-id": "user_id",
6669
"x-tenant-id": "tenant_id",
6770
"x-trace-id": "trace_id",
@@ -70,8 +73,6 @@ def __init__(
7073
self.cookie_extractors = cookie_extractors or {}
7174
self.custom_extractors = custom_extractors or []
7275
self.auto_generate_request_id = auto_generate_request_id
73-
self.request_id_header = request_id_header.lower()
74-
self.request_id_context_key = request_id_context_key
7576
self.context_setters = context_setters or []
7677
# Header/cookie values are client input bound into logs and outbound
7778
# propagation — drop log-unsafe or overlong ones (a dropped request id

‎servicewright/adapters/fastapi/settings.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,9 @@ class CorrelationIdMiddlewareSettings(BaseModel):
9292
"""``CorrelationIdMiddlewareConfig`` as settings: how the request id is echoed."""
9393

9494
enabled: bool = Field(default=True, description="Echo the request id in a response header")
95-
header_name: str = Field(default=DEFAULT_CORRELATION_ID_HEADER, description="The header it is echoed in")
95+
header_name: str = Field(
96+
default=DEFAULT_CORRELATION_ID_HEADER, description="The header the request id is read from and echoed in"
97+
)
9698

9799
def to_config(self) -> CorrelationIdMiddlewareConfig:
98100
return CorrelationIdMiddlewareConfig(enabled=self.enabled, header_name=self.header_name)
@@ -151,8 +153,9 @@ class MiddlewareSettings(BaseModel):
151153
processing_time: bool = Field(default=True, description="X-Process-Time response header")
152154
context_headers: dict[str, str] | None = Field(
153155
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+
description="Request headers ContextMiddleware binds, {header: context_key}; None reads the "
157+
"correlation_id header (x-request-id by default), x-user-id, x-tenant-id and x-trace-id, {} reads none; "
158+
"JSON in the environment",
156159
)
157160
logging: LoggingMiddlewareSettings = Field(default_factory=LoggingMiddlewareSettings)
158161
correlation_id: CorrelationIdMiddlewareSettings = Field(default_factory=CorrelationIdMiddlewareSettings)

‎tests/unit/test_fastapi.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
from servicewright.adapters import _uvicorn as uvicorn_mod
4040
from servicewright.adapters.fastapi import (
4141
AuthorizationHeader,
42+
CorrelationIdMiddlewareConfig,
4243
CORSMiddlewareConfig,
4344
FastApiEntrypoint,
4445
FastApiPlugin,
@@ -1741,6 +1742,45 @@ async def test__context_middleware__client_supplied_id__is_preserved_end_to_end(
17411742
assert response.headers["x-request-id"] == "order-sync-42"
17421743

17431744

1745+
async def _client_with_request_id_header(header_name: str) -> TestClient:
1746+
"""A client over the default stack with the request id moved to ``header_name``."""
1747+
middlewares = MiddlewareConfig(correlation_id=CorrelationIdMiddlewareConfig(header_name=header_name))
1748+
ep = FastApiEntrypoint(config=HttpConfig(port=0), middlewares=middlewares)
1749+
app = await ep.build_app(_make_service_ctx(FakeContainer()))
1750+
1751+
@app.get("/echo")
1752+
def echo() -> dict[str, Any]:
1753+
return {"request_id": get_context_value("request_id")}
1754+
1755+
return TestClient(app)
1756+
1757+
1758+
async def test__context_middleware__custom_request_id_header__reads_the_id_from_it() -> None:
1759+
# Arrange
1760+
client = await _client_with_request_id_header("X-Correlation-ID")
1761+
1762+
# Act
1763+
response = client.get("/echo", headers={"X-Correlation-ID": "order-sync-42"})
1764+
1765+
# Assert
1766+
assert response.json()["request_id"] == "order-sync-42"
1767+
assert response.headers["x-correlation-id"] == "order-sync-42"
1768+
1769+
1770+
async def test__context_middleware__custom_request_id_header__no_longer_reads_x_request_id() -> None:
1771+
# Arrange
1772+
client = await _client_with_request_id_header("X-Correlation-ID")
1773+
1774+
# Act
1775+
response = client.get("/echo", headers={"X-Request-ID": "order-sync-42"})
1776+
1777+
# Assert
1778+
minted = response.json()["request_id"]
1779+
assert minted != "order-sync-42"
1780+
assert UUID(minted)
1781+
assert response.headers["x-correlation-id"] == minted
1782+
1783+
17441784
async def test__unhandled_exception__masked_500__still_carries_the_request_id(correlated_client: Any) -> None:
17451785
# Act
17461786
response = correlated_client.get("/boom")

0 commit comments

Comments
 (0)