Skip to content

Sentry (secrets out of the event)

You turn Sentry on, a 500 happens, and the event lands in the dashboard with the user's JWT in clear text. This recipe shows why that happens even with Sentry's scrubber on, and how to close the hole with one line.

Installation

No extra. The SDK does not depend on sentry-sdk: the callback only knows the shape of the event, a dict. Install sentry-sdk in your service as you already would (uv add sentry-sdk).

The leak

Sentry's EventScrubber hides a value by the name of its key: password, authorization... A secret without a key of its own goes straight through.

The case every FastAPI service hits: Sentry collects the local variables of every traceback frame (the default in sentry-sdk 2.x and 3.x), and the ASGI scope is one of them. There the headers are a list of pairs of bytes, [(b"authorization", b"Bearer eyJ...")]. There is no authorization key to match, only a position in a list.

Measured with sentry-sdk 2.0.0 and 3.0.2, sentry_sdk.init with nothing but the DSN, and a handler that fails with headers and token as local variables. The frame variables that reached the transport:

token:   '[Filtered]'                                  (2.0.0)
token:   "'abc'"                                       (3.0.2)
headers: [["b'host'", "b'api.example.com'"],
          ["b'authorization'", "b'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln'"]]

The JWT went out whole in both versions. The variable named token was filtered only on 2.0.0.

The fix: redact by value

make_sentry_before_send() builds a before_send that runs every string of the event through a RedactionPolicy — the same one as log redaction — at any depth:

import sentry_sdk

from tempest_fastapi_sdk import make_sentry_before_send

sentry_sdk.init(
    dsn="https://public@sentry.example.com/1",
    before_send=make_sentry_before_send(),
)

The same error, now:

message: 'Stripe recusou [Filtered]'
token:   '[Filtered]'
headers: [["b'host'", "b'api.example.com'"],
          ["b'authorization'", "b'Bearer [Filtered]'"]]

Same on 2.0.0 and 3.0.2. The header name and the host stay: you still see that there was an Authorization, just not the token.

What the callback's default policy hides:

  • By value, in every string: JWT, Bearer <credential>, e-mail, the token of the SDK's capability routes (/password-reset/<token>...) and SECRET_KEY_PATTERN — a third-party secret key written sk_... / rk_... (RevenueCat, Stripe sk_live_/sk_test_/rk_live_/rk_test_).
  • By key, in every dict: the same sensitive keys as log redaction (token, password, secret, authorization, cookie, email...), plus key=value inside text.
  • Everything written as [Filtered] (SENTRY_FILTERED), the EventScrubber's own marker, so a value filtered by Sentry and one filtered by the SDK read the same in the dashboard.

The callback adds to Sentry's scrubber, it does not replace it, and it never drops the event: it returns the same dict it received.

By value errs on the side of hiding

Bearer matches regardless of length, so the phrase "bearer of news" becomes "[Filtered] news". And a key with token in its name goes whole — token_type included. That is the deliberate trade: a less readable field, never a secret in the dashboard.

The event keeps its shape

Sentry expects a structured event: a dict where there was a dict, a list where there was a list. That is why the callback does not use RedactionPolicy.redact_value (what log redaction uses), which returns a flattened copy: from the eighth level of nesting the node becomes its str, a tuple becomes a list and bytes becomes "b'...'". In an event, exception.values[0].stacktrace.frames[i].vars.<variable> is already at the eighth level.

It uses RedactionPolicy.redact_in_place:

  • No depth limit. Dicts, lists and sets are walked with an explicit stack, so not even nesting deeper than Python's recursion limit blows up. A container seen twice (a cycle, or one object in two places) is walked once.
  • In place. Dicts and lists are changed where they stand and come back as the same object.
  • Types kept. A tuple (a named tuple too) and a frozenset come back as the same type; bytes is decoded as UTF-8 with surrogateescape, redacted and encoded back, so any byte sequence round-trips.
  • Other objects are left as they are. A number, None, an arbitrary object: nothing becomes a str.

You can use it outside Sentry, on any payload that must leave without secrets and without changing shape:

from tempest_fastapi_sdk import RedactionPolicy

payload: dict[str, object] = {
    "headers": [(b"host", b"api.example.com"), (b"x-auth", b"Bearer abc123")],
}
RedactionPolicy().redact_in_place(payload)
print(payload)
{'headers': [(b'host', b'api.example.com'), (b'x-auth', b'[REDACTED]')]}

What Sentry actually hands to before_send

Measured on 2.0.0 and 3.0.2: sentry-sdk serializes the event before calling before_send. So in the event the callback receives, bytes already arrives as the text "b'...'", a tuple as a list, and past a certain depth of the variables Sentry itself already hands the node over as text. Keeping tuples and bytes matters for redact_in_place used outside Sentry; inside it, what matters is the depth.

Your own policy

Pass a RedactionPolicy to change what is hidden. It replaces the default whole, so bring along what you want to keep — here, the secret key and Sentry's marker:

import sentry_sdk

from tempest_fastapi_sdk import (
    SECRET_KEY_PATTERN,
    SENTRY_FILTERED,
    RedactionPolicy,
    make_sentry_before_send,
)

policy: RedactionPolicy = RedactionPolicy(
    extra_keys={"cpf"},
    extra_patterns=(SECRET_KEY_PATTERN,),
    replacement=SENTRY_FILTERED,
)
sentry_sdk.init(
    dsn="https://public@sentry.example.com/1",
    before_send=make_sentry_before_send(policy),
)

Typing

The callback is generic in the event type, so sentry_sdk.init accepts it without a cast — checked with mypy --strict and basedpyright against the sentry-sdk 2.0.0 and 3.0.2 stubs. A hand-written def before_send(event: dict[str, object], hint: object) -> dict[str, object] is rejected by both, because Sentry types the event as a TypedDict.

_meta is left out

sentry-sdk 2.x annotates trimmed values in event["_meta"], keyed by the value's path: a trimmed variable token becomes _meta...vars.token = {"": {"rem": [...]}}. That is not event data, and redacting it by key would turn the annotation into a string. The callback skips the top-level _meta key (SENTRY_META_KEY).

Recap

  • Sentry's EventScrubber filters by key name; the Authorization header inside the ASGI scope is a list of pairs and goes straight through — measured on sentry-sdk 2.0.0 and 3.0.2.
  • sentry_sdk.init(before_send=make_sentry_before_send()) redacts by value (JWT, Bearer, e-mail, sk_...) and by key, writing [Filtered].
  • The event is changed in place, with no depth limit, and the same object comes back — never None.
  • RedactionPolicy.redact_in_place is the piece underneath, and works for any payload that must keep tuples, bytes and nesting.
  • A policy of your own replaces the default: bring SECRET_KEY_PATTERN and SENTRY_FILTERED along if you want to keep them.