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
37 changes: 36 additions & 1 deletion docs/adapters/grpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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`,
Expand Down Expand Up @@ -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)`.
Expand Down
29 changes: 17 additions & 12 deletions docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down
17 changes: 16 additions & 1 deletion docs/concepts/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 5 additions & 4 deletions docs/operations/checklist.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 16 additions & 2 deletions servicewright/adapters/grpc/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand All @@ -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(
Expand All @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion servicewright/adapters/grpc/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 11 additions & 6 deletions servicewright/adapters/grpc/interceptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -76,17 +77,22 @@ 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__(
self,
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."""
Expand Down Expand Up @@ -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):
Expand All @@ -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
Expand Down
35 changes: 23 additions & 12 deletions servicewright/adapters/grpc/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading