Skip to content

Commit 47e40e8

Browse files
committed
feat: add Masker seam with ValueRedactor, ChainRedactor, per-surface redactors and span-attribute redaction
1 parent 08748d5 commit 47e40e8

12 files changed

Lines changed: 512 additions & 15 deletions

File tree

‎docs/concepts/observability.md‎

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,11 @@ into the [context store](context.md) and push them into structlog contextvars an
144144

145145
## Redaction
146146

147-
`KeyRedactor` masks values whose key contains a sensitive fragment, and it is threaded into
148-
**both** the logging and error-tracking sinks:
147+
The cross-cutting `redactor` is threaded into every payload surface — logging, error tracking
148+
**and** span attributes (metrics carry no payloads and are exempt). For spans it runs as the first
149+
span processor, so no exporter ever sees an unredacted attribute.
150+
151+
`KeyRedactor` masks values whose key contains a sensitive fragment:
149152

150153
```python
151154
KeyRedactor(sensitive_keys={"password", "api_key", "ssn"}, mask="[REDACTED]")
@@ -159,6 +162,60 @@ block and ship your credentials in the frame locals.
159162

160163
Any callable `dict -> dict` works in its place.
161164

165+
### Masking by value
166+
167+
Key-based redaction has a structural blind spot: the email inside a free-form log message, the
168+
card number a user pasted into a comment field. No name list can reach those — something has to
169+
look at the *value*. That is the `Masker` seam: any `(str) -> str` callable, lifted over whole
170+
payloads by `ValueRedactor` and composed with the key redactor by `ChainRedactor`:
171+
172+
```python
173+
import re
174+
175+
from servicewright import ChainRedactor, KeyRedactor, ObservabilityManager, ValueRedactor
176+
177+
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
178+
179+
observability = ObservabilityManager(
180+
ObsConfig(),
181+
redactor=ChainRedactor(KeyRedactor(), ValueRedactor(lambda v: EMAIL.sub("<email>", v))),
182+
)
183+
```
184+
185+
Key-first is the conventional order: sensitive fields are already collapsed to the mask before
186+
the (potentially more expensive) value masker sees the payload.
187+
188+
`ValueRedactor` fails closed: a masker that raises turns the value into the mask — never the raw
189+
string — and logs one warning per redactor, so a broken masker is visible without a log storm and
190+
without dropping a single log line or event.
191+
192+
### One redactor per surface
193+
194+
Surfaces differ in volume by orders of magnitude, so one redactor rarely fits all three. The
195+
per-surface overrides — `log_redactor`, `error_redactor`, `trace_redactor` — each win over the
196+
cross-cutting `redactor` on their surface:
197+
198+
```python
199+
observability = ObservabilityManager(
200+
ObsConfig(),
201+
redactor=KeyRedactor(), # every surface: cheap, name-based
202+
error_redactor=ChainRedactor( # error path only: add the ML masker
203+
KeyRedactor(),
204+
ValueRedactor(presidio_masker),
205+
),
206+
)
207+
```
208+
209+
This split is the whole point: the error path is where payloads leak the most (stack-frame
210+
locals, request bodies) *and* where volume is lowest — events are rare and shipped off the
211+
request path. An ML-grade masker (Presidio, GLiNER, DataFog) belongs there. Putting the same
212+
model on every log line of a busy service would cost milliseconds per line; keep the logging
213+
surface on regex-cheap maskers.
214+
215+
One caveat for model-backed maskers: they load hundreds of megabytes and take seconds to
216+
initialize. Build the engine once at process start — [warmup](warmup.md) exists precisely so that
217+
cost lands before readiness, not on the first request that logs an error.
218+
162219
## Lifecycle
163220

164221
Observability is configured **first**, before the container exists, so bootstrap failures are

‎servicewright/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
AsyncWarmer,
1919
BaseServiceSettingsProtocol,
2020
BootstrapContext,
21+
ChainRedactor,
2122
CleanupTimeoutError,
2223
ContextSetter,
2324
DependencyContainerProtocol,
@@ -50,6 +51,7 @@
5051
ServiceWrightError,
5152
TracingSettingsProtocol,
5253
UnitScopeProtocol,
54+
ValueRedactor,
5355
WarmupError,
5456
WarmupTimeoutError,
5557
bind_context,
@@ -77,6 +79,7 @@
7779
"AsyncWarmer",
7880
"BaseServiceSettingsProtocol",
7981
"BootstrapContext",
82+
"ChainRedactor",
8083
"CleanupTimeoutError",
8184
"ContextSetter",
8285
"DaemonEntrypoint",
@@ -115,6 +118,7 @@
115118
"ServiceWrightError",
116119
"TracingSettingsProtocol",
117120
"UnitScopeProtocol",
121+
"ValueRedactor",
118122
"WarmupError",
119123
"WarmupTimeoutError",
120124
"__version__",

‎servicewright/adapters/observability/_tracing/otel.py‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,62 @@
1717
from opentelemetry import trace
1818
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
1919
from opentelemetry.sdk.resources import Resource
20-
from opentelemetry.sdk.trace import TracerProvider
20+
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
2121
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor
2222
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
2323
except ImportError as exc: # pragma: no cover - exercised only without the extra
2424
raise ImportError("OpenTelemetry tracing requires servicewright[observability]; install it.") from exc
2525

2626
if TYPE_CHECKING:
27-
from ....core.contracts.observability import TracerProtocol
27+
from opentelemetry.sdk.trace import ReadableSpan, Span
28+
29+
from ....core.contracts.observability import Redactor, TracerProtocol
2830
from ....core.observability.config import ObsSetupContext
2931

3032
logger = logging.getLogger(__name__)
3133

3234

35+
class _RedactingSpanProcessor(SpanProcessor):
36+
"""Rewrites span attributes through the redactor before any exporter sees them.
37+
38+
Registered FIRST, ahead of the exporting processors: ``on_end`` runs in
39+
registration order, and the batch exporter enqueues the same span object,
40+
so mutating attributes here is what the exporter later serializes. The SDK
41+
offers no public post-end attribute hook — rewriting ``_attributes`` is the
42+
established scrubbing pattern for OTel Python.
43+
44+
Fail closed: if the redactor raises, the span keeps its name and timing but
45+
loses ALL attributes — a failing scrubber must never publish what it was
46+
supposed to scrub. One warning per processor, not per span.
47+
"""
48+
49+
def __init__(self, redactor: Redactor) -> None:
50+
self._redactor = redactor
51+
self._warned = False
52+
53+
def on_end(self, span: ReadableSpan) -> None:
54+
attributes = span._attributes
55+
if not attributes:
56+
return
57+
try:
58+
span._attributes = self._redactor(dict(attributes))
59+
except Exception:
60+
span._attributes = {}
61+
if not self._warned:
62+
self._warned = True
63+
logger.warning("trace redactor raised; dropping span attributes", exc_info=True)
64+
65+
def on_start(self, span: Span, parent_context: object = None) -> None:
66+
"""Nothing to do at span start; redaction happens once, at the end."""
67+
68+
def shutdown(self) -> None:
69+
"""Stateless processor; nothing to flush."""
70+
71+
def force_flush(self, timeout_millis: int = 30000) -> bool:
72+
"""Stateless processor; always already flushed."""
73+
return True
74+
75+
3376
class OtelTracingSink(TracingSink):
3477
"""OpenTelemetry backend driven by ``settings.tracing``."""
3578

@@ -55,6 +98,11 @@ def setup(self, ctx: ObsSetupContext) -> None:
5598
sampler = ParentBased(TraceIdRatioBased(getattr(otel_settings, "sample_ratio", 1.0)))
5699
provider = TracerProvider(resource=resource, sampler=sampler)
57100

101+
# Must be registered before any exporting processor: on_end runs in
102+
# registration order, and exporters must only ever see redacted spans.
103+
if ctx.redactor is not None:
104+
provider.add_span_processor(_RedactingSpanProcessor(ctx.redactor))
105+
58106
collector_url = getattr(otel_settings, "collector_url", None)
59107
if collector_url:
60108
exporter = OTLPSpanExporter(endpoint=collector_url, insecure=getattr(otel_settings, "insecure", True))

‎servicewright/core/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
from .health import HealthRegistry, HealthReport, ProbeStatus
5050
from .lifecycle import Lifecycle
5151
from .observability import (
52+
ChainRedactor,
5253
ErrorTrackingSettingsProtocol,
5354
KeyRedactor,
5455
LoggingSettingsProtocol,
@@ -57,6 +58,7 @@
5758
ObservabilityManager,
5859
ObsSetupContext,
5960
TracingSettingsProtocol,
61+
ValueRedactor,
6062
register_sink,
6163
)
6264
from .service import Service, run
@@ -73,6 +75,7 @@
7375
"AsyncWarmer",
7476
"BaseServiceSettingsProtocol",
7577
"BootstrapContext",
78+
"ChainRedactor",
7679
"CleanupTimeoutError",
7780
"ContextSetter",
7881
"DependencyContainerProtocol",
@@ -105,6 +108,7 @@
105108
"ServiceWrightError",
106109
"TracingSettingsProtocol",
107110
"UnitScopeProtocol",
111+
"ValueRedactor",
108112
"WarmupError",
109113
"WarmupTimeoutError",
110114
"bind_context",

‎servicewright/core/contracts/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from .observability import CounterProtocol as CounterProtocol
1919
from .observability import ErrorReporterProtocol as ErrorReporterProtocol
2020
from .observability import HistogramProtocol as HistogramProtocol
21+
from .observability import Masker as Masker
2122
from .observability import Redactor as Redactor
2223
from .observability import SpanProtocol as SpanProtocol
2324
from .observability import TracerProtocol as TracerProtocol
@@ -36,6 +37,7 @@
3637
"HealthCheckerProtocol",
3738
"HistogramProtocol",
3839
"LifecycleHookProtocol",
40+
"Masker",
3941
"Plugin",
4042
"Redactor",
4143
"ScopedEntrypoint",

‎servicewright/core/contracts/observability.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,17 +99,39 @@ def set_tags(self, **tags: str) -> None:
9999

100100

101101
class Redactor(Protocol):
102-
"""Cross-cutting sensitive-data filter shared by logging and error tracking."""
102+
"""Cross-cutting sensitive-data filter threaded into logging, error tracking and tracing."""
103103

104104
def __call__(self, data: dict[str, Any]) -> dict[str, Any]:
105105
"""Return a redacted copy of ``data``."""
106106
...
107107

108108

109+
class Masker(Protocol):
110+
"""Value-level masker for a single string (the PII scrubbing seam).
111+
112+
Where a :class:`Redactor` decides by *key* ("this field is named password"),
113+
a masker looks at the *value* itself - the email inside a free-form message,
114+
the card number in a path. Any ``(str) -> str`` callable qualifies: a regex
115+
substitution, a format-preserving masker, a locally hosted NER model. Lift
116+
one over whole payloads with
117+
:class:`~servicewright.core.observability.redaction.ValueRedactor`.
118+
119+
Contract: synchronous; runs once per string value on the surface it is
120+
attached to. Pick the surface to match the cost - a regex masker is fine on
121+
every log line, an ML model belongs on the error path, where volume is
122+
lowest and payloads leak the most.
123+
"""
124+
125+
def __call__(self, value: str) -> str:
126+
"""Return the masked form of ``value``."""
127+
...
128+
129+
109130
__all__ = [
110131
"CounterProtocol",
111132
"ErrorReporterProtocol",
112133
"HistogramProtocol",
134+
"Masker",
113135
"Redactor",
114136
"SpanAttributeValue",
115137
"SpanProtocol",

‎servicewright/core/observability/__init__.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
MetricsSettingsProtocol,
2727
TracingSettingsProtocol,
2828
)
29-
from .redaction import DEFAULT_SENSITIVE_KEYS, KeyRedactor
29+
from .redaction import DEFAULT_SENSITIVE_KEYS, MASK, ChainRedactor, KeyRedactor, ValueRedactor
3030
from .registry import register_sink, resolve_sink
3131
from .sinks import (
3232
ErrorTrackingSinkProtocol,
@@ -37,6 +37,8 @@
3737

3838
__all__ = [
3939
"DEFAULT_SENSITIVE_KEYS",
40+
"MASK",
41+
"ChainRedactor",
4042
"ErrorTrackingSettingsProtocol",
4143
"ErrorTrackingSinkProtocol",
4244
"KeyRedactor",
@@ -59,6 +61,7 @@
5961
"ObservabilityManager",
6062
"TracingSettingsProtocol",
6163
"TracingSinkProtocol",
64+
"ValueRedactor",
6265
"make_metric_name",
6366
"register_sink",
6467
"resolve_sink",

‎servicewright/core/observability/config.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ class ObsSetupContext:
3030
Observability config must be reachable from ``settings`` (DSN, collector URL,
3131
tokens): ``setup()`` runs in Bootstrap, *before* the DI container exists, so
3232
container-resolved secrets are unavailable at sink setup time.
33+
34+
``redactor`` arrives already resolved for the receiving sink's surface: the
35+
manager applies its per-surface overrides (``log_redactor`` /
36+
``error_redactor`` / ``trace_redactor``) before handing the context over,
37+
so a sink never has to know which override chain produced it.
3338
"""
3439

3540
service_name: str

‎servicewright/core/observability/manager.py‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
from __future__ import annotations
2222

23+
from dataclasses import replace
2324
from logging import getLogger
2425
from typing import TYPE_CHECKING, Any
2526

@@ -52,8 +53,18 @@ class ObservabilityManager:
5253
config: App-wide backend selection by name. ``None`` selects nothing
5354
(concerns without an instance stay NullObject) — the default for a
5455
bare ``AppSpec``.
55-
redactor: Cross-cutting sensitive-data filter threaded into BOTH the
56-
logging and error-tracking sinks.
56+
redactor: Cross-cutting sensitive-data filter threaded into the
57+
logging, error-tracking and tracing sinks (every payload surface;
58+
metrics carry no payloads and are exempt).
59+
log_redactor: Per-surface override for the logging sink; wins over
60+
``redactor`` there. Surfaces differ in volume by orders of
61+
magnitude — this is how a cheap masker goes on every log line
62+
while an expensive one guards only the error path.
63+
error_redactor: Per-surface override for the error-tracking sink.
64+
The natural home for ML-grade maskers: events are rare, shipped
65+
off the request path, and leak the most (stack-frame locals,
66+
request bodies).
67+
trace_redactor: Per-surface override for span attributes.
5768
metrics: Ready metrics sink instance (wins over ``config.metrics``).
5869
tracing: Ready tracing sink instance (wins over ``config.tracing``).
5970
error_tracking: Ready error-tracking sink instance (wins over
@@ -66,13 +77,21 @@ def __init__(
6677
config: ObsConfig | None = None,
6778
*,
6879
redactor: Redactor | None = None,
80+
log_redactor: Redactor | None = None,
81+
error_redactor: Redactor | None = None,
82+
trace_redactor: Redactor | None = None,
6983
metrics: MetricsSinkProtocol | None = None,
7084
tracing: TracingSinkProtocol | None = None,
7185
error_tracking: ErrorTrackingSinkProtocol | None = None,
7286
logging: LoggingSinkProtocol | None = None,
7387
) -> None:
7488
self._config = config
7589
self._redactor = redactor
90+
self._surface_redactors: dict[str, Redactor | None] = {
91+
"logging": log_redactor,
92+
"error_tracking": error_redactor,
93+
"tracing": trace_redactor,
94+
}
7695
self._configured = False
7796
# (concern, sink) pairs in setup order; sinks are registry-resolved and
7897
# therefore dynamically typed at this boundary.
@@ -143,7 +162,10 @@ def configure(self, settings: BaseServiceSettingsProtocol, *, service_name: str
143162
if backend is None or not gates[concern](settings):
144163
continue
145164
sink = resolve_sink(concern, backend)()
146-
sink.setup(ctx)
165+
# Each sink sees the redactor resolved for its own surface: the
166+
# per-surface override, else the cross-cutting one. Metrics carry
167+
# no payloads, so their ctx never advertises a redactor.
168+
sink.setup(replace(ctx, redactor=self._redactor_for(concern)))
147169
self._active.append((concern, sink))
148170
setattr(self, f"_{concern}", sink)
149171
logger.info(
@@ -177,6 +199,12 @@ def shutdown(self) -> None:
177199
self._logging = NullLoggingSink()
178200
self._configured = False
179201

202+
def _redactor_for(self, concern: str) -> Redactor | None:
203+
if concern == "metrics":
204+
return None
205+
override = self._surface_redactors.get(concern)
206+
return override if override is not None else self._redactor
207+
180208
def _build_setup_context(self, settings: BaseServiceSettingsProtocol, service_name: str) -> ObsSetupContext:
181209
environment = getattr(settings, "environment", None)
182210
if not environment:

0 commit comments

Comments
 (0)