Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/adapters/fastapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ flowchart TD
generates one otherwise, binds it into the [context store](../concepts/context.md) and returns it
in the response header.

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

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

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

### Which request headers are read

By default `ContextMiddleware` binds `X-Request-ID`, `X-User-Id`, `X-Tenant-Id` and `X-Trace-Id`
Expand Down
4 changes: 2 additions & 2 deletions docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,8 +338,8 @@ Entrypoint constructors, all keyword-only:
`redirect_slashes=False`. `MiddlewareConfig` defaults have unit scope, context, sentry,
processing time, logging, correlation id, gzip and CORS all on.
`MiddlewareConfig.context_headers: dict[str, str] | None = None` is `{header: context_key}`
for `ContextMiddleware`: `None` reads `x-request-id`, `x-user-id`, `x-tenant-id` and
`x-trace-id`, `{}` reads none and always mints the request id (rule 21).
for `ContextMiddleware`: `None` reads the `correlation_id.header_name` header (`x-request-id`
by default), `x-user-id`, `x-tenant-id` and `x-trace-id`, `{}` reads none and always mints the request id (rule 21).
`HttpServerSettings` is `HttpConfig` as a settings model — a plain pydantic `BaseModel` the
adapter exports; nest it as `server: HttpServerSettings = HttpServerSettings()` in your
settings class and it is `SERVER__*` in the environment. Same fields and defaults, `health` and
Expand Down
8 changes: 6 additions & 2 deletions servicewright/adapters/fastapi/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,14 @@ class GZipMiddlewareConfig:

@dataclass(slots=True)
class CorrelationIdMiddlewareConfig:
"""How the request id is returned to the client.
"""Which header carries the request id, in and out, and whether it is echoed.

The id itself is owned by :class:`ContextMiddleware` — the same value that
lands in the context store, the logs and outbound propagation. Echoing it
is what lets a caller quote an id that actually appears in your logs.
``header_name`` is the header the id is read from and echoed in. A
``MiddlewareConfig.context_headers`` mapping replaces the default headers,
so with both set, the mapping has to name this header too.
"""

enabled: bool = True
Expand Down Expand Up @@ -120,7 +123,8 @@ class MiddlewareConfig:
context_headers: dict[str, str] | None = None
"""Request headers ``ContextMiddleware`` binds, as ``{header: context_key}``.

``None`` reads ``x-request-id``, ``x-user-id``, ``x-tenant-id`` and
``None`` reads the request id header (``correlation_id.header_name``,
``x-request-id`` by default), ``x-user-id``, ``x-tenant-id`` and
``x-trace-id``. They are client input, and they reach every log line, the
Sentry scope and outbound propagation, so on a port untrusted clients reach
pass ``{"x-request-id": "request_id"}``. ``{}`` reads no header, and the
Expand Down
7 changes: 4 additions & 3 deletions servicewright/adapters/fastapi/middlewares/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,12 @@ def __init__(
) -> None:
self.app = app
self.echo_request_id = echo_request_id
self.request_id_header = request_id_header.lower()
self.request_id_context_key = request_id_context_key
if header_extractors is None:
# The request id is read from the header it is echoed in.
header_extractors = {
"x-request-id": "request_id",
self.request_id_header: request_id_context_key,
"x-user-id": "user_id",
"x-tenant-id": "tenant_id",
"x-trace-id": "trace_id",
Expand All @@ -70,8 +73,6 @@ def __init__(
self.cookie_extractors = cookie_extractors or {}
self.custom_extractors = custom_extractors or []
self.auto_generate_request_id = auto_generate_request_id
self.request_id_header = request_id_header.lower()
self.request_id_context_key = request_id_context_key
self.context_setters = context_setters or []
# Header/cookie values are client input bound into logs and outbound
# propagation — drop log-unsafe or overlong ones (a dropped request id
Expand Down
9 changes: 6 additions & 3 deletions servicewright/adapters/fastapi/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ class CorrelationIdMiddlewareSettings(BaseModel):
"""``CorrelationIdMiddlewareConfig`` as settings: how the request id is echoed."""

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

def to_config(self) -> CorrelationIdMiddlewareConfig:
return CorrelationIdMiddlewareConfig(enabled=self.enabled, header_name=self.header_name)
Expand Down Expand Up @@ -151,8 +153,9 @@ class MiddlewareSettings(BaseModel):
processing_time: bool = Field(default=True, description="X-Process-Time response header")
context_headers: dict[str, str] | None = Field(
default=None,
description="Request headers ContextMiddleware binds, {header: context_key}; None reads x-request-id, "
"x-user-id, x-tenant-id and x-trace-id, {} reads none; JSON in the environment",
description="Request headers ContextMiddleware binds, {header: context_key}; None reads the "
"correlation_id header (x-request-id by default), x-user-id, x-tenant-id and x-trace-id, {} reads none; "
"JSON in the environment",
)
logging: LoggingMiddlewareSettings = Field(default_factory=LoggingMiddlewareSettings)
correlation_id: CorrelationIdMiddlewareSettings = Field(default_factory=CorrelationIdMiddlewareSettings)
Expand Down
40 changes: 40 additions & 0 deletions tests/unit/test_fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from servicewright.adapters import _uvicorn as uvicorn_mod
from servicewright.adapters.fastapi import (
AuthorizationHeader,
CorrelationIdMiddlewareConfig,
CORSMiddlewareConfig,
FastApiEntrypoint,
FastApiPlugin,
Expand Down Expand Up @@ -1741,6 +1742,45 @@ async def test__context_middleware__client_supplied_id__is_preserved_end_to_end(
assert response.headers["x-request-id"] == "order-sync-42"


async def _client_with_request_id_header(header_name: str) -> TestClient:
"""A client over the default stack with the request id moved to ``header_name``."""
middlewares = MiddlewareConfig(correlation_id=CorrelationIdMiddlewareConfig(header_name=header_name))
ep = FastApiEntrypoint(config=HttpConfig(port=0), middlewares=middlewares)
app = await ep.build_app(_make_service_ctx(FakeContainer()))

@app.get("/echo")
def echo() -> dict[str, Any]:
return {"request_id": get_context_value("request_id")}

return TestClient(app)


async def test__context_middleware__custom_request_id_header__reads_the_id_from_it() -> None:
# Arrange
client = await _client_with_request_id_header("X-Correlation-ID")

# Act
response = client.get("/echo", headers={"X-Correlation-ID": "order-sync-42"})

# Assert
assert response.json()["request_id"] == "order-sync-42"
assert response.headers["x-correlation-id"] == "order-sync-42"


async def test__context_middleware__custom_request_id_header__no_longer_reads_x_request_id() -> None:
# Arrange
client = await _client_with_request_id_header("X-Correlation-ID")

# Act
response = client.get("/echo", headers={"X-Request-ID": "order-sync-42"})

# Assert
minted = response.json()["request_id"]
assert minted != "order-sync-42"
assert UUID(minted)
assert response.headers["x-correlation-id"] == minted


async def test__unhandled_exception__masked_500__still_carries_the_request_id(correlated_client: Any) -> None:
# Act
response = correlated_client.get("/boom")
Expand Down
Loading