Skip to content

Commit 2948c13

Browse files
feat(grpc): choose which metadata keys bind the request context (#118)
1 parent acc3254 commit 2948c13

10 files changed

Lines changed: 300 additions & 41 deletions

File tree

‎docs/adapters/grpc.md‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,23 @@ from servicewright.adapters.grpc import (
7474
)
7575
```
7676

77+
### Which metadata keys are read
78+
79+
By default `UnitScopeInterceptor` binds `x-request-id`, `x-user-id`, `x-tenant-id` and `x-trace-id`
80+
from every call. They are client input, and they reach the logs, OTel baggage and outbound
81+
propagation. That is fine behind an edge that strips or sets them. On a port that untrusted
82+
clients reach, read only the request id:
83+
84+
```python
85+
GrpcConfig(context_metadata={"x-request-id": "request_id"}) # {metadata_key: context_key}
86+
GrpcConfig(context_metadata={}) # no metadata; the id is always minted
87+
```
88+
89+
`None`, the default, keeps the four. `idempotency_key`, `client_ip` and `user_agent` are read as
90+
before. grpc-server-kit's settings model has no such field; [From settings](#from-settings) shows
91+
how to read it from the environment. See
92+
[Request context](../concepts/context.md#the-identity-headers-are-client-input) for the trust model.
93+
7794
## Error mapping
7895

7996
A `ServiceError` raised anywhere in your servicer is converted into the matching abort:
@@ -227,6 +244,7 @@ The main knobs:
227244
| `reflection_service_names` | `None` | Extra names to advertise via reflection |
228245
| `health_service_names` | `()` | Concrete services to report health for |
229246
| `health_refresh_interval` | `5.0` | Readiness poll interval; `0` disables polling |
247+
| `context_metadata` | `None` | Metadata bound into the context, `{metadata_key: context_key}`; `None` reads the four correlation keys |
230248
| `max_concurrent_rpcs` | `None` | Server-side concurrency cap |
231249

232250
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
268286
object or in the table below, so a knob added to `GrpcConfig` cannot leave the mapping silently
269287
incomplete.
270288

271-
Three fields have no source on a settings object and are keyword arguments instead:
289+
Four fields have no source on a settings object and are keyword arguments instead:
272290

273291
| Keyword | Default | Why it is not read from settings |
274292
| --- | --- | --- |
275293
| `health_service_names` | `()` | Your own servicers' names: code, not environment |
276294
| `reflection_service_names` | `None` | Same |
277295
| `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 |
296+
| `context_metadata` | `None` | The kit's settings model has no such field |
297+
298+
To set `context_metadata` from the environment, add the field to your own subclass of the kit's
299+
model and pass it through:
300+
301+
```python
302+
class GrpcSettings(BaseGrpcServerSettings):
303+
context_metadata: dict[str, str] | None = None
304+
305+
306+
class Settings(BaseServiceSettings):
307+
grpc: GrpcSettings = GrpcSettings()
308+
309+
310+
settings = Settings() # GRPC__CONTEXT_METADATA='{"x-request-id":"request_id"}'
311+
config = GrpcConfig.from_settings(settings.grpc, context_metadata=settings.grpc.context_metadata)
312+
```
278313

279314
The kit's `metrics_enabled` has no `GrpcConfig` field either; that switch is
280315
`GrpcEntrypoint(enable_metrics=settings.grpc.metrics_enabled)`.

‎docs/agents.md‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -357,12 +357,15 @@ Entrypoint constructors, all keyword-only:
357357
metrics_prefix=None, kind="grpc", essential=True)`. `GrpcConfig` defaults:
358358
`port=50051`, `grace_period=30.0`, `enable_reflection=False`, `enable_channelz=False`,
359359
`health_service_names=()`, `health_refresh_interval=5.0`.
360+
`GrpcConfig.context_metadata: dict[str, str] | None = None` is `{metadata_key: context_key}`
361+
for `UnitScopeInterceptor`: `None` reads `x-request-id`, `x-user-id`, `x-tenant-id` and
362+
`x-trace-id`, `{}` reads none and always mints the request id (rule 21).
360363
`GrpcConfig.from_settings(settings, *, health_service_names=(), health_refresh_interval=5.0,
361-
reflection_service_names=None)` reads every other field off anything satisfying
362-
grpc-server-kit's `GrpcServerSettingsProtocol` (`BaseGrpcServerSettings`, `GrpcServerConfig`),
363-
the kit's defaults included (`[::]`, `grace_period=5.0`); the three keywords are the fields no
364-
settings object carries, and `health_refresh_interval` is deliberately not the kit's
365-
`health.cache_ttl` (opposite meaning at `0`). Interceptor chain, outermost first:
364+
reflection_service_names=None, context_metadata=None)` reads every other field off anything
365+
satisfying grpc-server-kit's `GrpcServerSettingsProtocol` (`BaseGrpcServerSettings`,
366+
`GrpcServerConfig`), the kit's defaults included (`[::]`, `grace_period=5.0`); the four keywords
367+
are the fields no settings object carries, and `health_refresh_interval` is deliberately not the
368+
kit's `health.cache_ttl` (opposite meaning at `0`). Interceptor chain, outermost first:
366369
`UnitScopeInterceptor`, `UnhandledErrorInterceptor`, metrics, yours,
367370
`ServiceErrorInterceptor`.
368371
* `SchedulerEntrypoint(jobs, enable_metrics=False, metrics_prefix=None,
@@ -486,14 +489,16 @@ Each `*Plugin` takes exactly the same arguments as its entrypoint and exposes `.
486489
`min(host drain_grace_seconds, its own cap)`: `GrpcConfig.grace_period` for gRPC,
487490
`graceful_timeout` for FastAPI and Litestar (`0` there sets no cap). Both caps default to
488491
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
492+
21. **The FastAPI context headers and the gRPC context metadata are client input.** By default
493+
`x-user-id`, `x-tenant-id` and `x-trace-id` are bound from any request or RPC into the logs,
494+
the Sentry user and tags (HTTP), OTel baggage, and `propagation_metadata()`, which forwards
495+
them downstream. `is_safe_context_id` checks the characters, not the sender. Behind an edge
496+
that strips or sets them this is fine; on a port untrusted clients reach, pass
494497
`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.
498+
`SERVER__MIDDLEWARES__CONTEXT_HEADERS='{"x-request-id":"request_id"}'`. Over gRPC pass
499+
`GrpcConfig(context_metadata={"x-request-id": "request_id"})`; the kit's settings model has
500+
no such field, so an environment variable needs a settings field of your own passed to
501+
`GrpcConfig.from_settings(..., context_metadata=...)`.
497502

498503
## Common mistakes
499504

‎docs/concepts/context.md‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,22 @@ SERVER__MIDDLEWARES__CONTEXT_HEADERS='{"x-request-id":"request_id"}'
9696

9797
`context_headers` maps a request header to the context key it binds. `None`, the default, reads
9898
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.
99+
100+
The gRPC interceptor reads the same four keys from metadata. `GrpcConfig.context_metadata` is the
101+
same choice there, `{metadata_key: context_key}` with the same `None` and `{}`:
102+
103+
```python
104+
from servicewright.adapters.grpc import GrpcConfig, GrpcEntrypoint
105+
106+
GrpcEntrypoint(
107+
config=GrpcConfig(context_metadata={"x-request-id": "request_id"}),
108+
servicers=register_servicers,
109+
)
110+
```
111+
112+
grpc-server-kit's settings model has no such field, so there is no environment variable out of the
113+
box. [gRPC](../adapters/grpc.md#from-settings) shows how to add one to your settings and pass it to
114+
`GrpcConfig.from_settings`.
100115

101116
## Writing
102117

‎docs/operations/checklist.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,11 @@ 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.
71+
- [ ] An HTTP or gRPC port that untrusted clients reach either sits behind an edge that strips or
72+
sets `X-User-Id`, `X-Tenant-Id` and `X-Trace-Id` (headers or metadata), or sets
73+
`MiddlewareConfig(context_headers={"x-request-id": "request_id"})` over HTTP and
74+
`GrpcConfig(context_metadata={"x-request-id": "request_id"})` over gRPC. Otherwise the client
75+
picks the `user_id` in your logs, on Sentry and in outbound propagation.
7576
- [ ] Secrets reach the process through settings, not through code — sink setup happens before the
7677
DI container exists.
7778
- [ ] `max_receive_message_length` and request size limits are set for public endpoints.

‎servicewright/adapters/grpc/config.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,16 @@ class GrpcConfig:
109109
# service and the reflection service itself). Typically your own servicers.
110110
reflection_service_names: list[str] | None = None
111111

112+
context_metadata: dict[str, str] | None = None
113+
"""Request metadata ``UnitScopeInterceptor`` binds, as ``{metadata_key: context_key}``.
114+
115+
``None`` reads ``x-request-id``, ``x-user-id``, ``x-tenant-id`` and
116+
``x-trace-id``. They are client input, and they reach every log line, OTel
117+
baggage and outbound propagation, so on a port untrusted clients reach pass
118+
``{"x-request-id": "request_id"}``. ``{}`` reads no metadata, and the
119+
request id is then always minted by the service.
120+
"""
121+
112122
# --- GrpcServerSettingsProtocol surface (server tuning) -----------------
113123
max_concurrent_rpcs: int | None = None
114124

@@ -154,6 +164,7 @@ def from_settings(
154164
health_service_names: tuple[str, ...] = (),
155165
health_refresh_interval: float = DEFAULT_HEALTH_REFRESH_INTERVAL_SECONDS,
156166
reflection_service_names: list[str] | None = None,
167+
context_metadata: dict[str, str] | None = None,
157168
) -> GrpcConfig:
158169
"""Build the config from a grpc-server-kit settings object.
159170
@@ -165,13 +176,15 @@ def from_settings(
165176
drains for 30 s, and the kit's values win. The mapping lives here so a
166177
field added to this class cannot go missing from a service's copy of it.
167178
168-
The keyword arguments are the three fields no settings object carries.
179+
The keyword arguments are the four fields no settings object carries.
169180
``health_service_names`` and ``reflection_service_names`` name your own
170181
servicers, which is code, not environment. ``health_refresh_interval``
171182
is deliberately not derived from the kit's ``health.cache_ttl``: the two
172183
agree while positive and disagree at zero, where ``cache_ttl=0`` means
173184
"re-check on every probe" and ``health_refresh_interval=0`` means "never
174-
re-evaluate". The kit's ``metrics_enabled`` has no field here either;
185+
re-evaluate". ``context_metadata`` is not a field of the kit's settings
186+
model; to read it from the environment, add a field of your own and pass
187+
it through. The kit's ``metrics_enabled`` has no field here either;
175188
that switch is ``GrpcEntrypoint(enable_metrics=...)``.
176189
"""
177190
return cls(
@@ -183,6 +196,7 @@ def from_settings(
183196
health_service_names=health_service_names,
184197
health_refresh_interval=health_refresh_interval,
185198
reflection_service_names=reflection_service_names,
199+
context_metadata=context_metadata,
186200
max_concurrent_rpcs=settings.max_concurrent_rpcs,
187201
keepalive_time_ms=settings.keepalive_time_ms,
188202
keepalive_timeout_ms=settings.keepalive_timeout_ms,

‎servicewright/adapters/grpc/entrypoint.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,9 @@ async def _collect_interceptors(self, ctx: ServiceContext[Any, Any]) -> list[grp
203203
# OUTERMOST wrapper. UnitScopeInterceptor is therefore first: every
204204
# downstream interceptor and the servicer see a live per-RPC scope.
205205
setters = get_default_context_setters() if self._context_setters is None else self._context_setters
206-
interceptors: list[grpc.aio.ServerInterceptor] = [UnitScopeInterceptor(ctx.container, context_setters=setters)]
206+
interceptors: list[grpc.aio.ServerInterceptor] = [
207+
UnitScopeInterceptor(ctx.container, context_setters=setters, context_metadata=self._config.context_metadata)
208+
]
207209

208210
# Inside the unit scope (so the masked abort is logged with the RPC's
209211
# correlation ids) but outside everything else: nothing below may leave

‎servicewright/adapters/grpc/interceptors.py‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,10 @@ class UnitScopeInterceptor(AsyncServerInterceptor):
6161
every downstream interceptor and the servicer see a live unit scope. The
6262
scope carries the RPC payload (method name, correlation ids, idempotency
6363
key, client ip / user agent) as its ``context``, mirrored into the core
64-
context store. Correlation ids come from ``x-request-id`` / ``x-user-id`` /
65-
``x-tenant-id`` / ``x-trace-id`` metadata (like the HTTP middleware), with
66-
the request id auto-generated when the client sent none.
64+
context store. Correlation ids come from the ``context_metadata`` keys, by
65+
default ``x-request-id`` / ``x-user-id`` / ``x-tenant-id`` / ``x-trace-id``
66+
(like the HTTP middleware), with the request id auto-generated when the
67+
client sent none.
6768
6869
The same values are pushed into the supplied
6970
:class:`~servicewright.core.context.ContextSetter`s, which is what bridges
@@ -76,17 +77,22 @@ class UnitScopeInterceptor(AsyncServerInterceptor):
7677
Args:
7778
container: The DI container the per-RPC unit scope is opened on.
7879
context_setters: Bridges pushing the RPC context into external systems.
80+
context_metadata: Request metadata bound into the context, as
81+
``{metadata_key: context_key}``. ``None`` reads the four keys above;
82+
``{}`` reads none, so the request id is always minted.
7983
"""
8084

8185
def __init__(
8286
self,
8387
container: DependencyContainerProtocol,
8488
*,
8589
context_setters: Sequence[ContextSetter] = (),
90+
context_metadata: dict[str, str] | None = None,
8691
) -> None:
8792
super().__init__()
8893
self._container = container
8994
self._context_setters = tuple(context_setters)
95+
self._context_metadata = context_metadata
9096

9197
async def around_call(self, call: RpcCall) -> AsyncIterator[None]:
9298
"""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:
128134
except Exception:
129135
logger.exception("Failed to call gRPC context cleanup remover")
130136

131-
@staticmethod
132-
def _build_context(context: grpc.aio.ServicerContext, method_name: str) -> dict[str, Any]:
137+
def _build_context(self, context: grpc.aio.ServicerContext, method_name: str) -> dict[str, Any]:
133138
client_ip, user_agent = get_client_context(context)
134139
idempotency_key = get_idempotency_key(context)
135140
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[
141146
"client_ip": client_ip,
142147
"user_agent": user_agent,
143148
}
144-
unit_context.update(get_correlation_ids(context))
149+
unit_context.update(get_correlation_ids(context, self._context_metadata))
145150
if "request_id" not in unit_context:
146151
unit_context["request_id"] = str(uuid.uuid4())
147152
return unit_context

‎servicewright/adapters/grpc/metadata.py‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from ...core.context import is_safe_context_id
1111

1212
if TYPE_CHECKING:
13+
from collections.abc import Mapping
14+
1315
import grpc.aio
1416

1517
IDEMPOTENCY_KEY_METADATA = "x-idempotency-key"
@@ -24,13 +26,13 @@
2426
_X_FORWARDED_FOR = "x-forwarded-for"
2527
_X_REAL_IP = "x-real-ip"
2628

27-
# Correlation metadata -> context-key mapping (mirrors the HTTP middleware).
28-
_CORRELATION_METADATA_KEYS: tuple[tuple[str, str], ...] = (
29-
(REQUEST_ID_METADATA, "request_id"),
30-
(USER_ID_METADATA, "user_id"),
31-
(TENANT_ID_METADATA, "tenant_id"),
32-
(TRACE_ID_METADATA, "trace_id"),
33-
)
29+
# The default correlation metadata -> context-key mapping (mirrors the HTTP middleware).
30+
_CORRELATION_METADATA_KEYS: dict[str, str] = {
31+
REQUEST_ID_METADATA: "request_id",
32+
USER_ID_METADATA: "user_id",
33+
TENANT_ID_METADATA: "tenant_id",
34+
TRACE_ID_METADATA: "trace_id",
35+
}
3436

3537

3638
def _decode(value: str | bytes) -> str:
@@ -94,20 +96,29 @@ def get_client_context(context: grpc.aio.ServicerContext) -> tuple[str | None, s
9496
return get_client_ip(context), get_user_agent(context)
9597

9698

97-
def get_correlation_ids(context: grpc.aio.ServicerContext) -> dict[str, str]:
99+
def get_correlation_ids(
100+
context: grpc.aio.ServicerContext,
101+
keys: Mapping[str, str] | None = None,
102+
) -> dict[str, str]:
98103
"""Extract correlation identifiers from gRPC metadata (mirrors the HTTP middleware).
99104
100-
Reads ``x-request-id`` / ``x-user-id`` / ``x-tenant-id`` / ``x-trace-id``
101-
(case-insensitive); malformed values (log-unsafe or overlong) are dropped.
105+
Metadata keys match case-insensitively; malformed values (log-unsafe or
106+
overlong) are dropped.
107+
108+
Args:
109+
context: The servicer context of the RPC.
110+
keys: ``{metadata_key: context_key}`` to read; ``None`` reads
111+
``x-request-id`` / ``x-user-id`` / ``x-tenant-id`` / ``x-trace-id``.
102112
"""
103113
metadata = context.invocation_metadata()
104114
if not metadata:
105115
return {}
106116

117+
mapping = _CORRELATION_METADATA_KEYS if keys is None else keys
107118
metadata_dict = {key.lower(): value for key, value in metadata}
108119
correlation: dict[str, str] = {}
109-
for header, ctx_key in _CORRELATION_METADATA_KEYS:
110-
raw = metadata_dict.get(header)
120+
for header, ctx_key in mapping.items():
121+
raw = metadata_dict.get(header.lower())
111122
if raw is None:
112123
continue
113124
value = _decode(raw)

0 commit comments

Comments
 (0)