diff --git a/docs/adapters/fastapi.md b/docs/adapters/fastapi.md index 545e64b..4437540 100644 --- a/docs/adapters/fastapi.md +++ b/docs/adapters/fastapi.md @@ -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 @@ -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` diff --git a/docs/agents.md b/docs/agents.md index 41eb03e..3a6de44 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -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 diff --git a/servicewright/adapters/fastapi/config.py b/servicewright/adapters/fastapi/config.py index 617faec..d37092c 100644 --- a/servicewright/adapters/fastapi/config.py +++ b/servicewright/adapters/fastapi/config.py @@ -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 @@ -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 diff --git a/servicewright/adapters/fastapi/middlewares/context.py b/servicewright/adapters/fastapi/middlewares/context.py index 17094c4..e981c7a 100644 --- a/servicewright/adapters/fastapi/middlewares/context.py +++ b/servicewright/adapters/fastapi/middlewares/context.py @@ -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", @@ -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 diff --git a/servicewright/adapters/fastapi/settings.py b/servicewright/adapters/fastapi/settings.py index 586d5c5..b0d4c4c 100644 --- a/servicewright/adapters/fastapi/settings.py +++ b/servicewright/adapters/fastapi/settings.py @@ -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) @@ -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) diff --git a/tests/unit/test_fastapi.py b/tests/unit/test_fastapi.py index 67b8c74..52b3515 100644 --- a/tests/unit/test_fastapi.py +++ b/tests/unit/test_fastapi.py @@ -39,6 +39,7 @@ from servicewright.adapters import _uvicorn as uvicorn_mod from servicewright.adapters.fastapi import ( AuthorizationHeader, + CorrelationIdMiddlewareConfig, CORSMiddlewareConfig, FastApiEntrypoint, FastApiPlugin, @@ -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")