From 6bf2f4f8d4f54852b179c8b2bbb72ad859f3b271 Mon Sep 17 00:00:00 2001 From: Alexey Shalaev <75322386+AlexeyShalaev@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:36:29 +0400 Subject: [PATCH] feat(grpc): choose which metadata keys bind the request context --- docs/adapters/grpc.md | 37 +++++- docs/agents.md | 29 +++-- docs/concepts/context.md | 17 ++- docs/operations/checklist.md | 9 +- servicewright/adapters/grpc/config.py | 18 ++- servicewright/adapters/grpc/entrypoint.py | 4 +- servicewright/adapters/grpc/interceptors.py | 17 ++- servicewright/adapters/grpc/metadata.py | 35 ++++-- tests/integration/test_grpc_integration.py | 54 ++++++++- tests/unit/test_grpc.py | 121 +++++++++++++++++++- 10 files changed, 300 insertions(+), 41 deletions(-) diff --git a/docs/adapters/grpc.md b/docs/adapters/grpc.md index 39fde6c..ebb9fbb 100644 --- a/docs/adapters/grpc.md +++ b/docs/adapters/grpc.md @@ -74,6 +74,23 @@ from servicewright.adapters.grpc import ( ) ``` +### Which metadata keys are read + +By default `UnitScopeInterceptor` binds `x-request-id`, `x-user-id`, `x-tenant-id` and `x-trace-id` +from every call. They are client input, and they reach the logs, OTel baggage and outbound +propagation. That is fine behind an edge that strips or sets them. On a port that untrusted +clients reach, read only the request id: + +```python +GrpcConfig(context_metadata={"x-request-id": "request_id"}) # {metadata_key: context_key} +GrpcConfig(context_metadata={}) # no metadata; the id is always minted +``` + +`None`, the default, keeps the four. `idempotency_key`, `client_ip` and `user_agent` are read as +before. grpc-server-kit's settings model has no such field; [From settings](#from-settings) shows +how to read it from the environment. See +[Request context](../concepts/context.md#the-identity-headers-are-client-input) for the trust model. + ## Error mapping A `ServiceError` raised anywhere in your servicer is converted into the matching abort: @@ -227,6 +244,7 @@ The main knobs: | `reflection_service_names` | `None` | Extra names to advertise via reflection | | `health_service_names` | `()` | Concrete services to report health for | | `health_refresh_interval` | `5.0` | Readiness poll interval; `0` disables polling | +| `context_metadata` | `None` | Metadata bound into the context, `{metadata_key: context_key}`; `None` reads the four correlation keys | | `max_concurrent_rpcs` | `None` | Server-side concurrency cap | Plus the full server-tuning surface — keepalive (`keepalive_time_ms`, `keepalive_timeout_ms`, @@ -268,13 +286,30 @@ A test in servicewright asserts that every `GrpcConfig` field is either read fro object or in the table below, so a knob added to `GrpcConfig` cannot leave the mapping silently incomplete. -Three fields have no source on a settings object and are keyword arguments instead: +Four fields have no source on a settings object and are keyword arguments instead: | Keyword | Default | Why it is not read from settings | | --- | --- | --- | | `health_service_names` | `()` | Your own servicers' names: code, not environment | | `reflection_service_names` | `None` | Same | | `health_refresh_interval` | `5.0` | The kit's `health.cache_ttl` looks alike but means the opposite at `0`: no caching there, no polling here | +| `context_metadata` | `None` | The kit's settings model has no such field | + +To set `context_metadata` from the environment, add the field to your own subclass of the kit's +model and pass it through: + +```python +class GrpcSettings(BaseGrpcServerSettings): + context_metadata: dict[str, str] | None = None + + +class Settings(BaseServiceSettings): + grpc: GrpcSettings = GrpcSettings() + + +settings = Settings() # GRPC__CONTEXT_METADATA='{"x-request-id":"request_id"}' +config = GrpcConfig.from_settings(settings.grpc, context_metadata=settings.grpc.context_metadata) +``` The kit's `metrics_enabled` has no `GrpcConfig` field either; that switch is `GrpcEntrypoint(enable_metrics=settings.grpc.metrics_enabled)`. diff --git a/docs/agents.md b/docs/agents.md index 41eb03e..e809cfd 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -357,12 +357,15 @@ Entrypoint constructors, all keyword-only: metrics_prefix=None, kind="grpc", essential=True)`. `GrpcConfig` defaults: `port=50051`, `grace_period=30.0`, `enable_reflection=False`, `enable_channelz=False`, `health_service_names=()`, `health_refresh_interval=5.0`. + `GrpcConfig.context_metadata: dict[str, str] | None = None` is `{metadata_key: context_key}` + for `UnitScopeInterceptor`: `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). `GrpcConfig.from_settings(settings, *, health_service_names=(), health_refresh_interval=5.0, - reflection_service_names=None)` reads every other field off anything satisfying - grpc-server-kit's `GrpcServerSettingsProtocol` (`BaseGrpcServerSettings`, `GrpcServerConfig`), - the kit's defaults included (`[::]`, `grace_period=5.0`); the three keywords are the fields no - settings object carries, and `health_refresh_interval` is deliberately not the kit's - `health.cache_ttl` (opposite meaning at `0`). Interceptor chain, outermost first: + reflection_service_names=None, context_metadata=None)` reads every other field off anything + satisfying grpc-server-kit's `GrpcServerSettingsProtocol` (`BaseGrpcServerSettings`, + `GrpcServerConfig`), the kit's defaults included (`[::]`, `grace_period=5.0`); the four keywords + are the fields no settings object carries, and `health_refresh_interval` is deliberately not the + kit's `health.cache_ttl` (opposite meaning at `0`). Interceptor chain, outermost first: `UnitScopeInterceptor`, `UnhandledErrorInterceptor`, metrics, yours, `ServiceErrorInterceptor`. * `SchedulerEntrypoint(jobs, enable_metrics=False, metrics_prefix=None, @@ -486,14 +489,16 @@ Each `*Plugin` takes exactly the same arguments as its entrypoint and exposes `. `min(host drain_grace_seconds, its own cap)`: `GrpcConfig.grace_period` for gRPC, `graceful_timeout` for FastAPI and Litestar (`0` there sets no cap). Both caps default to 30.0, the default grace; raising `drain_grace_seconds` above that needs the cap raised too. -21. **The FastAPI context headers are client input.** By default `x-user-id`, `x-tenant-id` - and `x-trace-id` are bound from any request into the logs, the Sentry user and tags, and - `propagation_metadata()`, which forwards them downstream. `is_safe_context_id` checks the - characters, not the sender. Behind an edge that strips or sets them this is fine; on a port - untrusted clients reach, pass +21. **The FastAPI context headers and the gRPC context metadata are client input.** By default + `x-user-id`, `x-tenant-id` and `x-trace-id` are bound from any request or RPC into the logs, + the Sentry user and tags (HTTP), OTel baggage, and `propagation_metadata()`, which forwards + them downstream. `is_safe_context_id` checks the characters, not the sender. Behind an edge + that strips or sets them this is fine; on a port untrusted clients reach, pass `MiddlewareConfig(context_headers={"x-request-id": "request_id"})`, or set - `SERVER__MIDDLEWARES__CONTEXT_HEADERS='{"x-request-id":"request_id"}'`. The gRPC - interceptor reads the same metadata keys and has no such setting. + `SERVER__MIDDLEWARES__CONTEXT_HEADERS='{"x-request-id":"request_id"}'`. Over gRPC pass + `GrpcConfig(context_metadata={"x-request-id": "request_id"})`; the kit's settings model has + no such field, so an environment variable needs a settings field of your own passed to + `GrpcConfig.from_settings(..., context_metadata=...)`. ## Common mistakes diff --git a/docs/concepts/context.md b/docs/concepts/context.md index 3848355..5c3d540 100644 --- a/docs/concepts/context.md +++ b/docs/concepts/context.md @@ -96,7 +96,22 @@ SERVER__MIDDLEWARES__CONTEXT_HEADERS='{"x-request-id":"request_id"}' `context_headers` maps a request header to the context key it binds. `None`, the default, reads the four headers in the table above. `{}` reads none, so the service always mints the request id. -The gRPC interceptor reads the same four metadata keys and has no such setting. + +The gRPC interceptor reads the same four keys from metadata. `GrpcConfig.context_metadata` is the +same choice there, `{metadata_key: context_key}` with the same `None` and `{}`: + +```python +from servicewright.adapters.grpc import GrpcConfig, GrpcEntrypoint + +GrpcEntrypoint( + config=GrpcConfig(context_metadata={"x-request-id": "request_id"}), + servicers=register_servicers, +) +``` + +grpc-server-kit's settings model has no such field, so there is no environment variable out of the +box. [gRPC](../adapters/grpc.md#from-settings) shows how to add one to your settings and pass it to +`GrpcConfig.from_settings`. ## Writing diff --git a/docs/operations/checklist.md b/docs/operations/checklist.md index 73dd9cc..2c5d710 100644 --- a/docs/operations/checklist.md +++ b/docs/operations/checklist.md @@ -68,10 +68,11 @@ to a failure someone has already had. production port. - [ ] CORS lists explicit origins. `allow_credentials=True` with `allow_origins=["*"]` is rejected at construction, but a bare `["*"]` is still worth a second look. -- [ ] An HTTP port that untrusted clients reach either sits behind an edge that strips or sets - `X-User-Id`, `X-Tenant-Id` and `X-Trace-Id`, or sets - `MiddlewareConfig(context_headers={"x-request-id": "request_id"})`. Otherwise the client picks - the `user_id` in your logs, on Sentry and in outbound propagation. +- [ ] An HTTP or gRPC port that untrusted clients reach either sits behind an edge that strips or + sets `X-User-Id`, `X-Tenant-Id` and `X-Trace-Id` (headers or metadata), or sets + `MiddlewareConfig(context_headers={"x-request-id": "request_id"})` over HTTP and + `GrpcConfig(context_metadata={"x-request-id": "request_id"})` over gRPC. Otherwise the client + picks the `user_id` in your logs, on Sentry and in outbound propagation. - [ ] Secrets reach the process through settings, not through code — sink setup happens before the DI container exists. - [ ] `max_receive_message_length` and request size limits are set for public endpoints. diff --git a/servicewright/adapters/grpc/config.py b/servicewright/adapters/grpc/config.py index 2fb7b88..b94a1b1 100644 --- a/servicewright/adapters/grpc/config.py +++ b/servicewright/adapters/grpc/config.py @@ -109,6 +109,16 @@ class GrpcConfig: # service and the reflection service itself). Typically your own servicers. reflection_service_names: list[str] | None = None + context_metadata: dict[str, str] | None = None + """Request metadata ``UnitScopeInterceptor`` binds, as ``{metadata_key: context_key}``. + + ``None`` reads ``x-request-id``, ``x-user-id``, ``x-tenant-id`` and + ``x-trace-id``. They are client input, and they reach every log line, OTel + baggage and outbound propagation, so on a port untrusted clients reach pass + ``{"x-request-id": "request_id"}``. ``{}`` reads no metadata, and the + request id is then always minted by the service. + """ + # --- GrpcServerSettingsProtocol surface (server tuning) ----------------- max_concurrent_rpcs: int | None = None @@ -154,6 +164,7 @@ def from_settings( health_service_names: tuple[str, ...] = (), health_refresh_interval: float = DEFAULT_HEALTH_REFRESH_INTERVAL_SECONDS, reflection_service_names: list[str] | None = None, + context_metadata: dict[str, str] | None = None, ) -> GrpcConfig: """Build the config from a grpc-server-kit settings object. @@ -165,13 +176,15 @@ def from_settings( drains for 30 s, and the kit's values win. The mapping lives here so a field added to this class cannot go missing from a service's copy of it. - The keyword arguments are the three fields no settings object carries. + The keyword arguments are the four fields no settings object carries. ``health_service_names`` and ``reflection_service_names`` name your own servicers, which is code, not environment. ``health_refresh_interval`` is deliberately not derived from the kit's ``health.cache_ttl``: the two agree while positive and disagree at zero, where ``cache_ttl=0`` means "re-check on every probe" and ``health_refresh_interval=0`` means "never - re-evaluate". The kit's ``metrics_enabled`` has no field here either; + re-evaluate". ``context_metadata`` is not a field of the kit's settings + model; to read it from the environment, add a field of your own and pass + it through. The kit's ``metrics_enabled`` has no field here either; that switch is ``GrpcEntrypoint(enable_metrics=...)``. """ return cls( @@ -183,6 +196,7 @@ def from_settings( health_service_names=health_service_names, health_refresh_interval=health_refresh_interval, reflection_service_names=reflection_service_names, + context_metadata=context_metadata, max_concurrent_rpcs=settings.max_concurrent_rpcs, keepalive_time_ms=settings.keepalive_time_ms, keepalive_timeout_ms=settings.keepalive_timeout_ms, diff --git a/servicewright/adapters/grpc/entrypoint.py b/servicewright/adapters/grpc/entrypoint.py index bd80ac7..4751a9c 100644 --- a/servicewright/adapters/grpc/entrypoint.py +++ b/servicewright/adapters/grpc/entrypoint.py @@ -203,7 +203,9 @@ async def _collect_interceptors(self, ctx: ServiceContext[Any, Any]) -> list[grp # OUTERMOST wrapper. UnitScopeInterceptor is therefore first: every # downstream interceptor and the servicer see a live per-RPC scope. setters = get_default_context_setters() if self._context_setters is None else self._context_setters - interceptors: list[grpc.aio.ServerInterceptor] = [UnitScopeInterceptor(ctx.container, context_setters=setters)] + interceptors: list[grpc.aio.ServerInterceptor] = [ + UnitScopeInterceptor(ctx.container, context_setters=setters, context_metadata=self._config.context_metadata) + ] # Inside the unit scope (so the masked abort is logged with the RPC's # correlation ids) but outside everything else: nothing below may leave diff --git a/servicewright/adapters/grpc/interceptors.py b/servicewright/adapters/grpc/interceptors.py index 26e807a..0694fcf 100644 --- a/servicewright/adapters/grpc/interceptors.py +++ b/servicewright/adapters/grpc/interceptors.py @@ -61,9 +61,10 @@ class UnitScopeInterceptor(AsyncServerInterceptor): every downstream interceptor and the servicer see a live unit scope. The scope carries the RPC payload (method name, correlation ids, idempotency key, client ip / user agent) as its ``context``, mirrored into the core - context store. Correlation ids come from ``x-request-id`` / ``x-user-id`` / - ``x-tenant-id`` / ``x-trace-id`` metadata (like the HTTP middleware), with - the request id auto-generated when the client sent none. + context store. Correlation ids come from the ``context_metadata`` keys, by + default ``x-request-id`` / ``x-user-id`` / ``x-tenant-id`` / ``x-trace-id`` + (like the HTTP middleware), with the request id auto-generated when the + client sent none. The same values are pushed into the supplied :class:`~servicewright.core.context.ContextSetter`s, which is what bridges @@ -76,6 +77,9 @@ class UnitScopeInterceptor(AsyncServerInterceptor): Args: container: The DI container the per-RPC unit scope is opened on. context_setters: Bridges pushing the RPC context into external systems. + context_metadata: Request metadata bound into the context, as + ``{metadata_key: context_key}``. ``None`` reads the four keys above; + ``{}`` reads none, so the request id is always minted. """ def __init__( @@ -83,10 +87,12 @@ def __init__( container: DependencyContainerProtocol, *, context_setters: Sequence[ContextSetter] = (), + context_metadata: dict[str, str] | None = None, ) -> None: super().__init__() self._container = container self._context_setters = tuple(context_setters) + self._context_metadata = context_metadata async def around_call(self, call: RpcCall) -> AsyncIterator[None]: """Wrap the RPC in a fresh unit scope bound to a context variable.""" @@ -128,8 +134,7 @@ def _undo_setters(removers: list[Callable[[], None]]) -> None: except Exception: logger.exception("Failed to call gRPC context cleanup remover") - @staticmethod - def _build_context(context: grpc.aio.ServicerContext, method_name: str) -> dict[str, Any]: + def _build_context(self, context: grpc.aio.ServicerContext, method_name: str) -> dict[str, Any]: client_ip, user_agent = get_client_context(context) idempotency_key = get_idempotency_key(context) if idempotency_key is not None and not is_safe_context_id(idempotency_key): @@ -141,7 +146,7 @@ def _build_context(context: grpc.aio.ServicerContext, method_name: str) -> dict[ "client_ip": client_ip, "user_agent": user_agent, } - unit_context.update(get_correlation_ids(context)) + unit_context.update(get_correlation_ids(context, self._context_metadata)) if "request_id" not in unit_context: unit_context["request_id"] = str(uuid.uuid4()) return unit_context diff --git a/servicewright/adapters/grpc/metadata.py b/servicewright/adapters/grpc/metadata.py index ba5be1c..3cb594b 100644 --- a/servicewright/adapters/grpc/metadata.py +++ b/servicewright/adapters/grpc/metadata.py @@ -10,6 +10,8 @@ from ...core.context import is_safe_context_id if TYPE_CHECKING: + from collections.abc import Mapping + import grpc.aio IDEMPOTENCY_KEY_METADATA = "x-idempotency-key" @@ -24,13 +26,13 @@ _X_FORWARDED_FOR = "x-forwarded-for" _X_REAL_IP = "x-real-ip" -# Correlation metadata -> context-key mapping (mirrors the HTTP middleware). -_CORRELATION_METADATA_KEYS: tuple[tuple[str, str], ...] = ( - (REQUEST_ID_METADATA, "request_id"), - (USER_ID_METADATA, "user_id"), - (TENANT_ID_METADATA, "tenant_id"), - (TRACE_ID_METADATA, "trace_id"), -) +# The default correlation metadata -> context-key mapping (mirrors the HTTP middleware). +_CORRELATION_METADATA_KEYS: dict[str, str] = { + REQUEST_ID_METADATA: "request_id", + USER_ID_METADATA: "user_id", + TENANT_ID_METADATA: "tenant_id", + TRACE_ID_METADATA: "trace_id", +} def _decode(value: str | bytes) -> str: @@ -94,20 +96,29 @@ def get_client_context(context: grpc.aio.ServicerContext) -> tuple[str | None, s return get_client_ip(context), get_user_agent(context) -def get_correlation_ids(context: grpc.aio.ServicerContext) -> dict[str, str]: +def get_correlation_ids( + context: grpc.aio.ServicerContext, + keys: Mapping[str, str] | None = None, +) -> dict[str, str]: """Extract correlation identifiers from gRPC metadata (mirrors the HTTP middleware). - Reads ``x-request-id`` / ``x-user-id`` / ``x-tenant-id`` / ``x-trace-id`` - (case-insensitive); malformed values (log-unsafe or overlong) are dropped. + Metadata keys match case-insensitively; malformed values (log-unsafe or + overlong) are dropped. + + Args: + context: The servicer context of the RPC. + keys: ``{metadata_key: context_key}`` to read; ``None`` reads + ``x-request-id`` / ``x-user-id`` / ``x-tenant-id`` / ``x-trace-id``. """ metadata = context.invocation_metadata() if not metadata: return {} + mapping = _CORRELATION_METADATA_KEYS if keys is None else keys metadata_dict = {key.lower(): value for key, value in metadata} correlation: dict[str, str] = {} - for header, ctx_key in _CORRELATION_METADATA_KEYS: - raw = metadata_dict.get(header) + for header, ctx_key in mapping.items(): + raw = metadata_dict.get(header.lower()) if raw is None: continue value = _decode(raw) diff --git a/tests/integration/test_grpc_integration.py b/tests/integration/test_grpc_integration.py index 75e3440..c9fe0fa 100644 --- a/tests/integration/test_grpc_integration.py +++ b/tests/integration/test_grpc_integration.py @@ -10,6 +10,7 @@ from __future__ import annotations import asyncio +import json from typing import Any import grpc @@ -17,7 +18,7 @@ import pytest from grpc_health.v1 import health_pb2, health_pb2_grpc -from servicewright import AppSpec, Service +from servicewright import AppSpec, Service, propagation_metadata from servicewright.adapters.grpc import GrpcConfig, GrpcEntrypoint from servicewright.testing import FakeContainer, FakeSettings @@ -163,3 +164,54 @@ async def call_then_stop() -> None: assert error.details() == "internal_error" assert dict(error.trailing_metadata() or ())["x-error-code"] == "internal_error" assert _SECRET not in str(error.details()) + + +def _register_propagating_servicer(server: Any, _ctx: Any) -> None: + """Register one RPC that answers with the metadata it would send downstream.""" + + async def outbound(request: bytes, context: Any) -> bytes: + return json.dumps(propagation_metadata()).encode() + + server.add_generic_rpc_handlers( + (grpc.method_handlers_generic_handler(_SERVICE, {"Outbound": grpc.unary_unary_rpc_method_handler(outbound)}),) + ) + + +@pytest.mark.parametrize( + ("context_metadata", "expected"), + [ + (None, {"x-request-id": "req-1", "x-user-id": "user-9", "x-tenant-id": "tenant-3"}), + ({"x-request-id": "request_id"}, {"x-request-id": "req-1"}), + ], + ids=["default", "request-id-only"], +) +async def test__grpc_entrypoint__context_metadata_configured__forwards_only_the_keys_it_maps( + context_metadata: dict[str, str] | None, expected: dict[str, str] +) -> None: + # Arrange + spec: AppSpec[Any, Any] = AppSpec(service_name="grpc-context-it", create_container=lambda _s: FakeContainer()) + config = GrpcConfig( + host="127.0.0.1", port=0, enable_reflection=False, enable_channelz=False, context_metadata=context_metadata + ) + ep = GrpcEntrypoint(config=config, servicers=_register_propagating_servicer) + stop = asyncio.Event() + + async def call_then_stop() -> bytes: + while not (spec.health.ready and ep.bound_port): + await asyncio.sleep(0.01) + await asyncio.sleep(0.05) + async with grpc.aio.insecure_channel(f"127.0.0.1:{ep.bound_port}") as channel: + try: + return await channel.unary_unary(f"/{_SERVICE}/Outbound")( + b"", + metadata=(("x-request-id", "req-1"), ("x-user-id", "user-9"), ("x-tenant-id", "tenant-3")), + timeout=5, + ) + finally: + stop.set() + + # Act + _, response = await asyncio.gather(Service(spec, entrypoints=[ep]).run(FakeSettings(), stop=stop), call_then_stop()) + + # Assert + assert json.loads(response) == expected diff --git a/tests/unit/test_grpc.py b/tests/unit/test_grpc.py index 4d3bad7..872c4e4 100644 --- a/tests/unit/test_grpc.py +++ b/tests/unit/test_grpc.py @@ -21,7 +21,7 @@ from grpc_server_kit.aio.interceptors import AsyncMetricsInterceptor, RpcCall from grpc_server_kit.settings import BaseGrpcServerSettings, BaseHealthSettings -from servicewright import AppSpec, Entrypoint, Plugin, Service +from servicewright import AppSpec, Entrypoint, Plugin, Service, current_context, propagation_metadata from servicewright.adapters.grpc import ( IDEMPOTENCY_KEY_METADATA, GrpcConfig, @@ -38,6 +38,7 @@ get_user_agent, ) from servicewright.adapters.grpc import entrypoint as entrypoint_mod +from servicewright.adapters.grpc.metadata import get_correlation_ids from servicewright.core.health import HealthRegistry from servicewright.core.observability import NullCounter, NullHistogram, ObservabilityManager from servicewright.core.spec import BootstrapContext, ServiceContext @@ -215,6 +216,7 @@ def test__grpc_config__host_and_port_overridden__reports_the_address() -> None: "health_service_names": "your own servicers: code, not environment", "reflection_service_names": "your own servicers: code, not environment", "health_refresh_interval": "the kit's health.cache_ttl means the opposite at zero", + "context_metadata": "not in the kit's settings model: a service passes a field of its own through", } @@ -246,10 +248,12 @@ def test__grpc_config_from_settings__keywords__fill_the_fields_no_settings_carry health_service_names=("my.pkg.Orders",), health_refresh_interval=0.5, reflection_service_names=["my.pkg.Orders"], + context_metadata={"x-request-id": "request_id"}, ) assert config.health_service_names == ("my.pkg.Orders",) assert config.health_refresh_interval == 0.5 assert config.reflection_service_names == ["my.pkg.Orders"] + assert config.context_metadata == {"x-request-id": "request_id"} def test__grpc_config_from_settings__kit_defaults__win_over_the_config_defaults() -> None: @@ -794,6 +798,87 @@ async def test__unit_scope_interceptor__rpc_served__mirrors_the_context_into_the assert get_context_value("grpc_method") is None +# --------------------------------------------------------------------------- # +# Which metadata keys UnitScopeInterceptor reads (#112) +# --------------------------------------------------------------------------- # +_CLIENT_METADATA: list[tuple[str, str | bytes]] = [ + ("x-request-id", "req-1"), + ("x-user-id", "user-9"), + ("x-tenant-id", "tenant-3"), + ("x-trace-id", "trace-7"), +] +_REQUEST_ID_ONLY = {"x-request-id": "request_id"} + + +async def _serve_rpc_reading(context_metadata: dict[str, str] | None) -> dict[str, Any]: + """Serve one RPC carrying ``_CLIENT_METADATA`` and report what got bound inside it.""" + interceptor = UnitScopeInterceptor(FakeContainer(), context_metadata=context_metadata) + async with interceptor.around(_make_call(_FakeServicerContext(_CLIENT_METADATA), "/pkg.Svc/Rpc")): + return {"context": current_context(), "propagation": propagation_metadata()} + + +@pytest.mark.parametrize( + ("context_metadata", "expected"), + [ + (None, {"request_id": "req-1", "user_id": "user-9", "tenant_id": "tenant-3", "trace_id": "trace-7"}), + (_REQUEST_ID_ONLY, {"request_id": "req-1"}), + ], + ids=["default", "request-id-only"], +) +async def test__context_metadata__configured__binds_only_the_keys_it_maps( + context_metadata: dict[str, str] | None, expected: dict[str, str] +) -> None: + # Act + seen = await _serve_rpc_reading(context_metadata) + + # Assert + assert seen["context"] == {"grpc_method": "/pkg.Svc/Rpc", **expected} + + +@pytest.mark.parametrize( + ("context_metadata", "expected"), + [ + (None, {"x-request-id": "req-1", "x-user-id": "user-9", "x-tenant-id": "tenant-3", "x-trace-id": "trace-7"}), + (_REQUEST_ID_ONLY, {"x-request-id": "req-1"}), + ], + ids=["default", "request-id-only"], +) +async def test__context_metadata__configured__propagates_only_the_keys_it_maps( + context_metadata: dict[str, str] | None, expected: dict[str, str] +) -> None: + # Act + seen = await _serve_rpc_reading(context_metadata) + + # Assert + assert seen["propagation"] == expected + + +async def test__context_metadata__empty__binds_no_client_metadata() -> None: + # Act + seen = await _serve_rpc_reading({}) + + # Assert + context = seen["context"] + assert context.keys() == {"grpc_method", "request_id"} + assert uuid.UUID(context["request_id"]) + + +async def test__grpc_entrypoint_bind__context_metadata_in_the_config__the_unit_scope_interceptor_reads_only_it( + patched_server: _FakeAsyncServer, +) -> None: + # Arrange + ep = GrpcEntrypoint(config=GrpcConfig(port=0, context_metadata=_REQUEST_ID_ONLY), servicers=lambda _s, _c: None) + await ep.bind(_make_service_ctx(FakeContainer())) + unit_scope = patched_server.create_calls[0]["interceptors"][0] # type: ignore[attr-defined] + + # Act + async with unit_scope.around(_make_call(_FakeServicerContext(_CLIENT_METADATA), "/pkg.Svc/Rpc")): + propagated = propagation_metadata() + + # Assert + assert propagated == {"x-request-id": "req-1"} + + # --------------------------------------------------------------------------- # # ServiceErrorInterceptor: kind -> grpc.StatusCode mapping # --------------------------------------------------------------------------- # @@ -1119,6 +1204,40 @@ def test__get_client_context__metadata_present__returns_ip_and_agent() -> None: assert get_client_context(ctx) == ("9.9.9.9", "ua/1") +@pytest.mark.parametrize( + ("keys", "expected"), + [ + (None, {"request_id": "req-1", "user_id": "user-9", "tenant_id": "tenant-3", "trace_id": "trace-7"}), + (_REQUEST_ID_ONLY, {"request_id": "req-1"}), + ({"X-Org-Id": "org_id"}, {"org_id": "org-5"}), + ({}, {}), + ], + ids=["default", "request-id-only", "mixed-case-key", "empty"], +) +def test__get_correlation_ids__keys_given__reads_exactly_those( + keys: dict[str, str] | None, expected: dict[str, str] +) -> None: + # Arrange + ctx = _FakeServicerContext([*_CLIENT_METADATA, ("x-org-id", "org-5")]) + + # Act + correlation = get_correlation_ids(ctx, keys) + + # Assert + assert correlation == expected + + +def test__get_correlation_ids__mapped_key_with_a_log_unsafe_value__drops_it() -> None: + # Arrange + ctx = _FakeServicerContext([("x-org-id", "bad\nid")]) + + # Act + correlation = get_correlation_ids(ctx, {"x-org-id": "org_id"}) + + # Assert + assert correlation == {} + + # --------------------------------------------------------------------------- # # GrpcPlugin # --------------------------------------------------------------------------- #