Skip to content

fix(ingest/masking): mask logged exceptions without rebuilding them - #21406

Merged
rajatoss merged 14 commits into
masterfrom
fix/masking-exception-rebuild
Nov 27, 2026
Merged

rajatoss merged 14 commits into
masterfrom
fix/masking-exception-rebuild

Conversation

@rajatoss

@rajatoss rajatoss commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Problem

  • SecretMaskingFilter._mask_exception rebuilt every logged exception with type(exc_value)(*masked_args). It did this whether or not the exception held a secret.
  • That only works when the constructor accepts exactly args. Other classes raise TypeError. Examples: botocore ClientError(error_response, operation_name), SQLAlchemy DBAPIError(statement, params, orig), or any custom QueryError(message, query).
  • On that failure, the filter replaced the exception with RuntimeError: [MASKING_ERROR - OUTPUT_SUPPRESSED_FOR_SECURITY] and no traceback. The real type, message, chained causes and frames were lost. With Sentry enabled, all of these errors collapse into one issue.
  • The failure was reported with exc_info=True on the masking-internal logger, which writes to the raw stderr without masking. When the log call is made inside an except block, Python chains the logged exception onto the TypeError, so the original exception is printed unmasked. _mask_args had the same shape.
  • Rebuilding only masked args. An attribute-built __str__, an OSError filename, __notes__ and ExceptionGroup members were not covered.

Two symptoms, one cause

With Sentry enabled, this bug shows up as two separate, high-volume issues. Both come from the same failed rebuild, once per logged exception:

  1. TypeError: <Class>.__init__() missing N required positional argument(s), reported by the diagnostic CRITICAL: Secret masking failed in exception: ….
  2. RuntimeError: [MASKING_ERROR - OUTPUT_SUPPRESSED_FOR_SECURITY] with no stack trace. This is the original log record, after the filter swapped in the placeholder. Every affected error lands in this one issue, whatever the real error was.

What happens for one logger.exception(...) call that carries a QueryError(message, query):

  1. The filter masks the message, then calls QueryError(masked_message) to rebuild the exception.
  2. The constructor also requires query, so it raises TypeError.
  3. The filter's except branch logs the CRITICAL diagnostic. That is symptom 1.
  4. It then replaces the record's exception with RuntimeError(MASKING_ERROR) and no traceback. Every handler and Sentry receive that instead of the real error. That is symptom 2.

The volume comes from two things. The rebuild ran for every logged exception, not only those holding a secret. And jobs that fail the same way on every run log the same exception each time, so every such failure produces both events.

Fix

One rule for every exception class. The exception is never rebuilt and never modified.

  1. The traceback text is set once. If record.exc_text is unset, it is set to the masked output of Formatter.formatException: the full traceback with its chain.
    • Formatters that print exc_text, such as the standard logging.Formatter, print this text.
    • So do handlers that format later, such as MemoryHandler.
  2. The exception's own texts are checked. These are its traceback summary line (traceback.format_exception_only, which includes its notes), repr, message and detail, for the exception and for every exception linked to it by __cause__, __context__ or group membership. The walk is iterative and stops on cycles. If rendering any of these raises, the record is handled as an internal failure (step 5).
  3. No secret in those texts: exc_info stays the caller's tuple, so Sentry and other exc_info readers get the real exception.
    • A registered value that appears only in a file path or source line is masked in exc_text, but it does not replace the exception.
  4. A secret in those texts: each exception in the chain is replaced in exc_info by a stand-in.
    • The stand-in is a MaskedException subclass with the original class's name and module, created once per class, so formatters and Sentry show the original type.
    • It carries the original traceback and is linked to the other stand-ins as the originals are (__cause__, __context__, __suppress_context__). An exception group keeps its members as stand-ins.
    • It holds only the masked message and notes. No other attribute is copied.
    • exc_text still has the full masked traceback.
  5. Internal failures: exc_info becomes MaskedException("[MASKING_ERROR - OUTPUT_SUPPRESSED_FOR_SECURITY]").
    • The diagnostics name only the exception type and carry no exc_info.
    • The filter() stderr warning also prints only the type name.

_mask_exception is private. It now takes the record instead of returning a new tuple, and filter() is its only caller.

Sentry events

The CLI started Sentry with the SDK defaults. Every frame's local variables were sent, and registered secrets were sent unmasked wherever the logging filter never saw them: capture_exception, the excepthook, and breadcrumbs from records below a handler's level. _init_sentry in telemetry.py now:

  • turns off include_local_variables;
  • masks each event in a global event processor, which runs before the SDK truncates long strings (1,024 characters on sentry-sdk 1.x, 100,000 on 2.x), so a secret cut at the limit can't leave its first characters behind;
  • masks it again in before_send, after object values become strings;
  • drops the event while the registry fails closed.

Formatted log output

A formatter that renders record.exc_info and extra fields itself, such as python-json-logger (used through DATAHUB_LOG_CONFIG_FILE), wrote traceback paths, source lines and extras unmasked. On stdout/stderr the stream wrapper caught them; on a file handler nothing did.

  • install_masking_filter wraps each covered handler's format(), so whatever it returns is masked. It does this once per handler, and uninstall_masking_filter restores it. If masking raises, the line becomes the masking-error marker.
  • The registry also matches a secret as written inside a JSON string (pa\"ss, p\u00e4ss), with ' escaped as \', and after two levels of repr/JSON escaping (a list's repr inside a JSON log line).
  • docs/cli.md documents DATAHUB_LOG_CONFIG_FILE and the handlers and formatters masking supports with it.

Before and after

A datahub ingest with a sqlalchemy source whose SQLite file can't be opened (no secret involved).

Before:

[datahub.masking.masking_filter] ERROR: CRITICAL: Secret masking failed in exception: DBAPIError.__init__() missing 2 required positional arguments: 'params' and 'orig'
Traceback (most recent call last):
  ...
TypeError: DBAPIError.__init__() missing 2 required positional arguments: 'params' and 'orig'
ERROR    {datahub.ingestion.run.pipeline:781} - Ingestion pipeline threw an uncaught exception: (sqlite3.OperationalError) unable to open database file
RuntimeError: [MASKING_ERROR - OUTPUT_SUPPRESSED_FOR_SECURITY]

After:

ERROR    {datahub.ingestion.run.pipeline:781} - Ingestion pipeline threw an uncaught exception: (sqlite3.OperationalError) unable to open database file
Traceback (most recent call last):
  ...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file

A registered secret in the message of QueryError(message, query), raised from ConnectionError.

  • Before: the same RuntimeError line, and the CRITICAL diagnostic printed the secret to stderr.
  • After: the full chained traceback, ending in QueryError: login failed for ***REDACTED:DB_PASSWORD***.

Testing

  • New TestExceptionMasking tests.
    • Setup: they log through a real logger with two formatters, the standard one and one that renders record.exc_info directly (JSON-formatter style).
    • Sentry check: they also call sentry_sdk.utils.exceptions_from_error_tuple(record.exc_info), which is what Sentry's logging integration uses.
    • Cases:
      • No secret: output is identical to unmasked logging, and Sentry gets the real types.
      • A registered value only in a file path: the exception and frames are kept, and the path is masked in exc_text and in the standard handler's output.
      • A secret anywhere in the exception: in the message, only in __cause__ (no __context__), only in __context__, a context cycle, an attribute-built __str__, an OSError filename, .message, .detail, raise ... from None, a note on group member Fix bugs, Reenforce log, ReFormat, Add missing DDL #18 (3.11+), or notes stored as a tuple (3.11+). Each is masked everywhere, and the replacement keeps the original type name, frames and links.
      • A replaced exception: both formatters print the full masked chain, Sentry gets the original types and frames, and the caller's exception is unchanged.
      • A replaced group still renders as a group, with the member's note masked.
      • Filtering a replaced record again changes nothing.
      • Deferred handler: changing the exception after the log call does not change the output.
      • Edge records: an exc_info of (None, None, None) is unchanged.
      • Diagnostics: a __str__ that raises ends in the internal-failure stand-in, repeated internal failures do not open the circuit breaker, and diagnostics carry type names only.
  • Sentry (tests/unit/telemetry/test_sentry_masking.py): an error captured through _init_sentry, with a secret in a breadcrumb, an extra, a frame local and a message cut at the SDK's length limit, plus an unregistered value in a frame local. None of them reaches the transport. While masking fails closed, the event is dropped.
  • Formatted output:
    • A JSON formatter on a FileHandler writes neither a registered value found only in traceback paths nor a JSON-escaped secret in an extra field. The traceback is still written.
    • Secrets after repr and JSON escaping, one and two levels deep, are masked.
    • The format() wrapper is added once, restored on uninstall, and withholds the line when masking raises.

Checklist

  • The PR conforms to DataHub's Contributing Guideline (particularly PR Title Format)
  • Links to related issues: none
  • Tests for the changes have been added/updated
  • Docs: docs/cli.md documents DATAHUB_LOG_CONFIG_FILE and where secret masking applies
  • Breaking changes: none

🤖 Generated with Claude Code


Summary by cubic

Fixes the exception masking filter so logged exceptions are no longer rebuilt. The filter sets exc_text to the masked formatted traceback and only replaces an exception whose own texts hold a secret, with a MaskedException subclass named after the original class that keeps the traceback and mirrors cause, context and group membership.

Behavior changes

  • Exceptions without secrets pass to exc_info readers (Sentry, JSON formatters) unchanged; a secret anywhere in the chain (message, __str__, OSError filename, cause, context, notes, group members) triggers the masked stand-in.
  • Each linked exception's summary line, notes, repr, message and detail are rendered directly, so checking a long chain stays linear instead of quadratic.
  • Diagnostics carry exception type names only and no longer count toward the circuit breaker.
  • Sentry captures no frame locals and masks registered secrets via a global event processor plus before_send; events are dropped while masking fails closed. The include_local_variables option keeps sentry-sdk pinned below 3.0.
  • install_masking_filter wraps every covered handler's format() so output is masked even when a formatter renders exc_info and extras itself; a line whose masking raises is replaced by the masking-error marker.
  • exc_text is now set by the filter, so a handler's custom formatException is no longer used.
  • Documents DATAHUB_LOG_CONFIG_FILE, which replaces the CLI's logging setup with a fileConfig file; masking is only guaranteed for standard-library stream and file handlers using the standard logging.Formatter or python-json-logger.

Written for commit e6b2637. Summary will update on new commits.

View guided diff Turn on auto-fix

The masking filter rebuilt every logged exception as
type(exc)(*masked_args). Classes whose constructor takes more than args
raised TypeError, so the exception was replaced by
RuntimeError([MASKING_ERROR]) without a traceback, and the failure
diagnostic printed the original exception unmasked to raw stderr.

The filter now sets exc_text to the masked formatted traceback, keeps
the caller's exception when its own texts hold no secret, and otherwise
replaces it with a MaskedException carrying the masked summary and no
traceback. Diagnostics carry type names only and do not count toward
the circuit breaker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the ingestion PR or Issue related to the ingestion of metadata label Nov 18, 2026
@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.75182% with 25 lines in your changes missing coverage. Please review.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
...ta-ingestion/src/datahub/masking/masking_filter.py 81.73% 21 Missing ⚠️
...a-ingestion/src/datahub/masking/secret_registry.py 66.66% 3 Missing ⚠️
...adata-ingestion/src/datahub/telemetry/telemetry.py 92.30% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@datahub-connector-tests

datahub-connector-tests Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Connector Tests Results

Connector tests failed for commit e6b2637

View full test logs →

To skip connector tests, add the skip-connector-tests label (org members only).

Autogenerated by the connector-tests CI pipeline.

…erer

Render each linked exception with traceback.format_exception_only instead
of str() plus list-of-str notes, so the secret check sees exactly what
tracebacks print, including notes stored as a tuple or as non-str objects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Render exc_text with logging.Formatter.formatException instead of a copy
  of its logic.
- Drop the per-render guard in _linked_exception_texts; a render that
  fails now fails closed through the outer handler and its diagnostic.
- Tests: a cause-only chain (no __context__), a .detail attribute, the
  stdlib handler output in the file-path case, and split the replaced-
  exception test into chain/caller-object and re-filter stability.
- Note the logging behaviour change in docs/how/breaking-changes.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rajatoss
rajatoss marked this pull request as ready for review November 19, 2026 10:56
@rajatoss rajatoss self-assigned this Nov 19, 2026
@rajatoss
rajatoss requested a review from skrydal November 19, 2026 10:56
@cursor

cursor Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

PR Summary

Overview
Stops rebuilding exceptions in SecretMaskingFilter (which broke multi-arg types like DBAPIError and leaked secrets in diagnostics). Logged failures now get a masked exc_text traceback; only when a registered secret appears in the exception’s own rendered texts does the filter swap in MaskedException stand-ins that keep type name, frames, and cause/context/group links without mutating the caller’s objects.

Sentry and custom logging: Telemetry initializes Sentry with no frame locals, masks events via a global processor and before_send, and drops events when masking fails closed. install_masking_filter wraps each handler’s format() so JSON/custom formatters still redact secrets; the registry also matches repr/JSON-escaped secret forms. docs/cli.md documents DATAHUB_LOG_CONFIG_FILE and which handlers/formatters masking guarantees.

Tests cover exception chains, ExceptionGroup, Sentry transport, and JSON file output.

Reviewed by Cursor Bugbot for commit e6b2637. Bugbot is set up for automated code reviews on this repo. Configure here.

@skrydal

skrydal commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Secrets can still reach Sentry through frame locals, and this PR sends more tracebacks there than master does. Could you close that in this PR?

The problem

The filter decides on the exception's text, but when the text is clean it keeps the real traceback in exc_info, and Sentry serializes the local variables of every frame. Sentry's own scrubber only filters by variable name (password, token, ...), so the same value under url, dsn, config or self goes through.

Master already behaves this way when the rebuild succeeds. With this PR the multi-argument classes (ClientError, DBAPIError, ...) also keep their traceback, where master replaced them with a traceback-less RuntimeError.

Repro

Runs against this branch with only sentry-sdk installed; nothing is sent, before_send captures the event and drops it.

import io
import logging

import sentry_sdk

from datahub.masking.masking_filter import SecretMaskingFilter
from datahub.masking.secret_registry import SecretRegistry

SECRET = "s3cr3t-test-value"
SecretRegistry.get_instance().register_secret("DB_PASSWORD", SECRET)
masking_filter = SecretMaskingFilter()

handler = logging.StreamHandler(io.StringIO())
handler.addFilter(masking_filter)
log = logging.getLogger("repro")
log.addHandler(handler)

events = []


def run(**init_options):
    events.clear()
    hook = init_options.pop("mask", None)

    def capture(event, hint):
        events.append(hook(event) if hook else event)
        return None

    sentry_sdk.init(
        dsn="https://key@example.invalid/1", before_send=capture, **init_options
    )

    def connect(url):
        raise ConnectionError("unable to connect")

    try:
        connect(f"postgresql://user:{SECRET}@host/db")
    except ConnectionError:
        log.exception("ingestion failed")
    return SECRET in repr(events)


print("log output masked:      ", SECRET not in handler.stream.getvalue())
print("as on this branch leaks:", run())
print("locals off leaks:       ", run(include_local_variables=False))
print("event masked leaks:     ", run(mask=masking_filter.mask_structure))

Output (sentry-sdk 2.75.0, Python 3.11):

log output masked:       True
as on this branch leaks: True
locals off leaks:        False
event masked leaks:      False

The leaked frame in the event looks like "vars": {"url": "'postgresql://user:s3cr3t-test-value@host/db'"}.

The same happens for exceptions Sentry captures without any log call (capture_exception, the excepthook), which the logging filter never sees. So the fix belongs in the Sentry init, not in the filter.

Suggested fix

In metadata-ingestion/src/datahub/telemetry/telemetry.py, where sentry_sdk.init is called:

def _mask_sentry_event(event, hint):
    return SecretMaskingFilter().mask_structure(event)


sentry_sdk.init(
    dsn=SENTRY_DSN,
    environment=SENTRY_ENVIRONMENT,
    release=__version__,
    include_local_variables=False,
    before_send=_mask_sentry_event,
)
  • include_local_variables=False covers secrets that were never registered.
  • before_send covers registered secrets everywhere else in the event (messages, breadcrumbs, context).

Please add a test that pushes an event with a secret in a frame local and in a breadcrumb through the real init options.

Follow-on: the stand-in can then keep its traceback

Once locals are off, there is no reason left to drop the traceback from the replaced exc_info. Today a secret-bearing exception reaches exc_info readers as one line. With python-json-logger (the DATAHUB_LOG_CONFIG_FILE path) the whole log entry becomes:

"exc_info": "datahub.masking.masking_filter.MaskedException: ValueError: login failed for ***REDACTED:DB_PASSWORD***"

It also reports every such error to Sentry as type MaskedException, so they cannot be told apart by type.

Building one stand-in per linked exception, each carrying the original traceback object and the original type's name, keeps frames, chain and type without touching the caller's exception:

_STAND_IN_TYPES: Dict[type, type] = {}


def _stand_in_type(exc_type: type) -> type:
    """A MaskedException subclass that renders under the original type's name."""
    if exc_type not in _STAND_IN_TYPES:
        _STAND_IN_TYPES[exc_type] = type(
            exc_type.__name__,
            (MaskedException,),
            {"__module__": exc_type.__module__, "__qualname__": exc_type.__qualname__},
        )
    return _STAND_IN_TYPES[exc_type]


def _stand_in_for(self, exc, seen):
    if id(exc) in seen:
        return seen[id(exc)]
    stand_in = _stand_in_type(type(exc))(self.mask_text(str(exc))).with_traceback(
        exc.__traceback__
    )
    seen[id(exc)] = stand_in
    if exc.__cause__ is not None:
        stand_in.__cause__ = self._stand_in_for(exc.__cause__, seen)
    if exc.__context__ is not None:
        stand_in.__context__ = self._stand_in_for(exc.__context__, seen)
    stand_in.__suppress_context__ = exc.__suppress_context__
    return stand_in

I tried this shape against this branch with a QueryError(message, query) raised from a ConnectionError, both holding the secret:

  • The standard and JSON formatters print the full chained traceback, ending in QueryError: login failed for ***REDACTED:DB_PASSWORD***.
  • Sentry receives two exceptions typed ConnectionError and QueryError, with their frames and masked values.
  • isinstance(stand_in, MaskedException) still holds, so a replaced exception stays recognisable.

Notes and exception group members would need the same treatment, and a __str__ that raises still has to take the internal-failure path.

@skrydal

skrydal commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

One case from the PR description is still open, and I'd like it handled in this PR: "A registered value that appears only in a file path or source line is masked in exc_text, but it does not replace the exception."

That holds for formatters that print exc_text. A formatter that renders record.exc_info itself (python-json-logger, so the DATAHUB_LOG_CONFIG_FILE path) reads paths and source lines from the real traceback and writes the value unmasked. On stdout/stderr the stream wrapper catches it afterwards; on a file handler nothing does.

This is easy to hit, because config_loader registers every ${VAR} a recipe references, from 3 characters up. A recipe with username: ${DB_USER} and a user called datahub registers a value that is in every site-packages/datahub/... frame.

Repro

Runs against this branch with python-json-logger installed. It reports booleans because install_masking_filter wraps stdout, which would mask the evidence if printed.

import logging
import os
import tempfile

from pythonjsonlogger import jsonlogger

from datahub.masking.masking_filter import install_masking_filter
from datahub.masking.secret_registry import SecretRegistry

# A registered value that also occurs in a traceback path, e.g. `username: ${DB_USER}`.
VALUE = os.path.splitext(os.path.basename(__file__))[0]
registry = SecretRegistry.get_instance()
registry.register_secret("DB_USER", VALUE)

log_path = os.path.join(tempfile.mkdtemp(), "ingestion.log")
handlers = {
    "json file": logging.FileHandler(log_path),
    "plain file": logging.FileHandler(log_path + ".txt"),
}
handlers["json file"].setFormatter(jsonlogger.JsonFormatter("%(message)s"))
for handler in handlers.values():
    logging.getLogger().addHandler(handler)

masking_filter = install_masking_filter(registry)

try:
    raise ValueError("query failed")
except ValueError:
    logging.getLogger("repro").exception("ingestion failed")

for name, handler in handlers.items():
    handler.flush()
    with open(handler.baseFilename) as f:
        text = f.read()
    print(f"{name}: value written unmasked = {VALUE in text}")

Output (Python 3.11, python-json-logger 4.2.0):

json file: value written unmasked = True
plain file: value written unmasked = False

Why not drop the traceback here

Replacing the exception whenever masking changes the rendered traceback would close this, but with a value like datahub registered it would strip the traceback from every logged exception for Sentry and JSON logs. Keeping the exception, as the PR does, is the right call for exc_info.

Suggested fix

Mask the formatted output at the handler, which is the one place that sees whatever any formatter rendered. In install_masking_filter, next to handler.addFilter(masking_filter):

original_format = handler.format
handler.format = lambda record: masking_filter.mask_text(original_format(record))

With that added to the repro, both lines print False and both files still contain the full traceback.

It needs the same care as the filter attachment:

  • apply it once per handler, so repeated install_masking_filter calls do not stack wrappers
  • restore the original format in uninstall_masking_filter
  • add a test with a formatter that renders exc_info directly and writes to a file, for a value that occurs only in a path

Every handler we construct goes through self.format, so the wrapper covers them all. At this PR's head, metadata-ingestion/src, datahub-actions/src and metadata-ingestion-modules/*/src only build StreamHandler, _ResilientStreamHandler, _BufferLogHandler and NullHandler (plus masking's own diagnostic handler, which is deliberately unmasked). A handler class brought in through DATAHUB_LOG_CONFIG_FILE that builds its output another way would stay uncovered.

Two escaped forms the registry does not match

Masking already-serialized JSON only works if the registry knows the escaped form of the value. I ran seven shapes of secret through a JSON formatter with the wrapper in place, in a field only the wrapper can catch:

Secret contains Result
plain text, backslash, newline, tab, / + = masked
a double quote (pa"ss) written as pa\"ss, not masked
non-ASCII (pässwörd), with the formatter's default ensure_ascii written as pässwörd, not masked

_escaped_rendering uses repr, which leaves both of those unchanged. Adding the JSON forms (json.dumps(value)[1:-1], with and without ensure_ascii) to maskable_renderings should close it. The stdout/stderr stream wrapper has the same gap for JSON logs, since it runs the same mask_text over the same text.

@skrydal

skrydal commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Could you also document DATAHUB_LOG_CONFIG_FILE in this PR, including which configurations secret masking supports? The variable is not documented anywhere today, and a config file can bring in any handler class, including ones that build their output without Handler.format() and so bypass the masking of formatted output.

Proposed change to docs/cli.md.

1. A bullet in the environment variable list, after DATAHUB_DEBUG:

- `DATAHUB_LOG_CONFIG_FILE` (default unset) - Path to a Python [`logging.config.fileConfig`](https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig) file. When set, it replaces the CLI's default logging setup, for example to emit JSON logs. Secret masking is only supported for some configurations; see [Custom logging configuration](#custom-logging-configuration).

2. A new subsection below the list:

### Custom logging configuration

Set `DATAHUB_LOG_CONFIG_FILE` to the path of a `fileConfig` file to replace the CLI's default logging setup. The example below writes JSON logs to stderr using `python-json-logger`, which is installed with the CLI:

```ini
[loggers]
keys = root

[handlers]
keys = console

[formatters]
keys = json

[logger_root]
level = INFO
handlers = console

[handler_console]
class = StreamHandler
formatter = json
args = (sys.stderr,)

[formatter_json]
class = pythonjsonlogger.jsonlogger.JsonFormatter
format = %(asctime)s %(name)s %(levelname)s %(message)s
```

#### Secret masking with a custom configuration

DataHub masks registered secrets (recipe secrets and every `${VAR}` a recipe references) in log output. With a custom configuration, masking is supported only for:

- **Handlers** that write formatted text: `StreamHandler`, `FileHandler` and the rotating file handlers from the Python standard library.
- **Formatters**: the standard `logging.Formatter` and `python-json-logger`.

Other handler classes, such as ones that send log records over a socket, HTTP or to a third-party service, are not supported. They may work, but DataHub does not guarantee that secrets are masked in what they send.

Notes:

  • I loaded the example config with fileConfig and installed the masking filter; a logged secret came out as ***REDACTED:DB_PASSWORD*** in the JSON line.
  • pythonjsonlogger.jsonlogger emits a deprecation warning on python-json-logger 4.x. I kept it because it is the import path that exists across the whole pinned range (>=2.0.0,<5.0.0).
  • The supported list assumes the two changes from my previous comment: the handler.format wrapper, and the JSON-escaped forms in maskable_renderings. If the second one is left out, the section needs one more line: a secret containing a double quote or non-ASCII characters is not masked in JSON output.

…lure

The test patched traceback.format_exception, which the exception path no
longer calls, so no failure happened. Patch the formatter the filter uses
and assert each record was replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The CLI's Sentry init used the SDK defaults, so every frame's local
variables were sent, and registered secrets in messages, breadcrumbs and
extras were sent unmasked whenever the logging filter did not see them
(capture_exception, the excepthook, records below a handler's level).

- Turn off include_local_variables.
- Run the masking registry over each event in a global event processor,
  before the SDK truncates long strings, and again in before_send, after
  object values become strings.
- Drop the event while the registry fails closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Smart test selection

pytest smoke tests

Mode: shadow. The selection below is computed but not applied; this PR still runs the default matrix (p0).

  • Selection: smart: tests for the tagged features, plus always-run modules, this PR's changed tests, and the plumbing sample if the PR changes the pytest harness
  • Size: 127 of 846 tests in 1 batch, predicted longest batch ~3 min
  • Tags: change-type: docs; feature-dev: authentication, system-metadata; technical-layer: cli
  • Confidence: MEDIUM (8 changed files)
  • Classifier reasoning: Changes add Sentry event masking and a custom logging config path in the Python CLI with tests and docs; masking maps to no clear feature tag, so feature-dev and feature-user picks are weak and the telemetry/masking area is only loosely covered by the taxonomy.

Medium confidence: a wrong tag means tests are skipped, so check the tags above against what this PR touches.

Selected scopes (15 files or classes, 127 tests)
  • tests/e2e/authorization/test_self_entity_auth.py
  • tests/e2e/frontend/test_static_asset_encodings.py
  • tests/e2e/mcp/mcp_test.py
  • tests/e2e/openapi/v1/test_tracking.py
  • tests/e2e/platform_resources/test_platform_resource.py
  • tests/e2e/read_only/test_services_up.py
  • tests/e2e/search/test_search_projection.py::TestSearchProjection
  • tests/e2e/service_accounts/test_service_accounts.py
  • tests/e2e/status/test_lifecycle_state.py::TestLifecycleStageAPIs
  • tests/e2e/telemetry/telemetry_test.py
  • tests/e2e/test_authentication_e2e.py
  • tests/e2e/test_e2e.py
  • tests/e2e/tokens/revokable_access_token_test.py
  • tests/e2e/tokens/session_access_token_test.py
  • tests/e2e/trace/test_api_trace.py

Add the run-all-tests:pytest label to run the full pytest suite on this PR.

commit e6b2637 · workflow run

rajatoss and others added 2 commits November 23, 2026 15:50
… secrets

A formatter that renders record.exc_info and extra fields itself, such as
python-json-logger, wrote traceback paths, source lines and extras
unmasked. stdout/stderr are masked by the stream wrapper; file handlers
were not.

- install_masking_filter wraps each covered handler's format() so its
  output is masked, once per handler; uninstall restores the original.
  If masking raises, the line is replaced by the masking-error marker.
- The registry also matches a secret as written inside a JSON string
  (escaped quotes, \uXXXX), with ' escaped as \', and after two levels of
  repr/JSON escaping (a list's repr inside a JSON log line).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…applies

The variable replaces the CLI's logging setup with a fileConfig file but
was not documented. List the handlers and formatters secret masking
supports with a custom configuration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rajatoss

Copy link
Copy Markdown
Member Author

Re #21406 (comment)

Done in 243083b, with one addition to your suggestion:

  • include_local_variables=False and the masking before_send, as proposed.
  • The same masking also runs as a global event processor. The SDK truncates long strings before before_send runs (1,024 characters on sentry-sdk 1.x, 100,000 on 2.x), so a secret cut at the limit kept its first characters. The processor runs before truncation; before_send still catches objects that only become strings during serialization.
  • The event is dropped while the registry fails closed. Otherwise masking renames every key, and the SDK fails inside capture_event.
  • Test: tests/unit/telemetry/test_sentry_masking.py sends an error through _init_sentry with a secret in a breadcrumb, an extra, a frame local and a message at the length limit, plus an unregistered value in a frame local.

@rajatoss

Copy link
Copy Markdown
Member Author

Re #21406 (comment)

Done in 6d89525.

  • install_masking_filter wraps each covered handler's format(), once per handler, and uninstall_masking_filter restores it. If masking raises, the line becomes the masking-error marker. Your repro now prints False for both files.
  • The JSON forms are in maskable_renderings, plus two cases from testing that your table didn't include: a secret escaped twice (a list's repr, or a JSON string, inside a JSON log line), and ' escaped as \' in a repr that holds both kinds of quote. Renderings now cover repr/JSON escaping up to two levels deep. Plain values still have one rendering.
  • I also tried wrapping the Formatter, the stream and the whole handler. They break on a later setFormatter, on rotation and delay=True, and on removeHandler, so format() is the right place.
  • Not covered: MemoryHandler targets, and handlers that don't call format() (socket, HTTP, queue listeners). The docs list neither as supported.
  • Test: a JSON formatter on a FileHandler, with a value found only in traceback paths and a JSON-escaped secret in an extra field.

@rajatoss

Copy link
Copy Markdown
Member Author

Re #21406 (comment)

Done in 9964565, using your text as proposed. The extra caveat isn't needed, since the JSON-escaped forms are in. I loaded the example config through DATAHUB_LOG_CONFIG_FILE and the CLI's logging setup. Every line was valid JSON, and a secret with " and ö came out as ***REDACTED:DB_PASSWORD*** in both the message and an extra field.

@skrydal skrydal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the four points are addressed. I re-ran my repros against 9964565357:

  • Sentry (sentry-sdk 2.x): no registered secret and no frame locals in the events, for a logged exception and for a directly captured one. The truncation case you added was a gap I had only guessed at.
  • JSON formatter on a FileHandler: the path-only value is masked, and so are secrets with a double quote, non-ASCII characters, both kinds of quote, and a backslash.
  • The docs match what I proposed.

One item is left. It was the "Follow-on" section of #21406 (comment), and _mask_exception is unchanged.

A secret-bearing exception still loses its traceback and its type

On 9964565357, a ValueError with a registered secret in its message, raised from a ConnectionError, reaches exc_info readers as:

  • JSON log: "exc_info": "datahub.masking.masking_filter.MaskedException: ValueError: login failed for ***REDACTED:DB_PASSWORD***", with no frames and no chain
  • Sentry: one exception of type MaskedException with 0 frames

So every error whose message holds a secret is reported to Sentry under the same type and can only be grouped by message. That is a smaller version of the single RuntimeError issue this PR set out to remove.

The reason given for dropping the traceback was that Sentry serializes frame locals. With include_local_variables=False that reason is gone, and paths and source lines are now masked downstream in both formatted output and Sentry events.

Requested change

Keep the stand-in, but give it the frames, the chain and the type name of what it replaces:

  • one stand-in per linked exception, not one for the whole chain
  • each built with .with_traceback(exc.__traceback__), so it carries the original frames without touching the caller's exception
  • __cause__, __context__ and __suppress_context__ set to mirror the original links
  • each an instance of a MaskedException subclass named after the original class (same __name__, __qualname__ and __module__), created once per class and cached, with the masked message only

The sketch is in the comment linked above. I tried it against this branch before your changes: the JSON formatter printed the full chained traceback ending in QueryError: login failed for ***REDACTED:DB_PASSWORD***, and Sentry received ConnectionError and QueryError with their frames and masked values.

The sketch is not complete. Please also add:

  • Notes: masked __notes__ on the stand-in (3.11+), including notes stored as a tuple or as non-string objects, which the current check already handles.
  • Exception groups: members replaced by their stand-ins, so a secret in a member's message or note stays masked and the group still renders as a group.
  • A __str__ that raises: this must still end in the internal-failure path (MaskedException(MASKING_ERROR_MESSAGE), type names only in diagnostics).
  • No attribute copying: fields such as .query, .message or .detail must not be carried over, since they can hold the secret.
  • Tests: a secret-bearing chained exception keeps its frames, chain and type name in the exc_info-rendering formatter and in the Sentry event; the existing parametrized cases (cause, context, cycle, group member note, tuple notes) still pass with the traceback now present; the caller's exception is unchanged.

Please confirm how Sentry groups these

I checked the event payload only: types, frames and masked values. I did not check grouping on the Sentry side. Could you confirm, against a real project, that:

  • an error whose message holds a secret lands in the same issue as the same error without one, given the same type and frames
  • two different error types that both hold a secret no longer share an issue
  • the masked value (***REDACTED:NAME*** in place of the secret) does not split one error into several issues

If grouping does not behave that way, say what you see and we can decide whether the type name or a fingerprint needs adjusting.

Small: _init_sentry(**overrides) lets a caller switch the masking off

The overrides exist for the test, but they are merged last, so any caller can also replace before_send or include_local_variables. Could _init_sentry() take no arguments, with the test injecting what it needs by patching?

def _send_failed_connection(
    monkeypatch: pytest.MonkeyPatch, message: str = "unable to connect"
) -> bytes:
    transport = _CapturingTransport()
    real_init = sentry_sdk.init
    monkeypatch.setattr(telemetry, "SENTRY_DSN", "https://key@example.invalid/1")
    monkeypatch.setattr(
        sentry_sdk,
        "init",
        lambda **options: real_init(
            **options, transport=transport, default_integrations=False
        ),
    )
    _init_sentry()
    ...

I ran this pattern against a copy of _init_sentry without the overrides (sentry-sdk 2.x): the event was captured and masked. It works because _init_sentry looks up sentry_sdk.init and SENTRY_DSN when it is called.

Small: note the sentry-sdk 3.0 break at the pin

sentry-sdk 3.0.0 rejects include_local_variables (TypeError: Unknown option 'include_local_variables'). Telemetry.__init__ catches that and prints "Error initializing Sentry", so nothing leaks, but Sentry would be off without anyone noticing. The <3.0.0 ceiling protects us today. Could you add a line at the pin in setup.py so whoever raises it knows to check, for example:

# sentry-sdk 3.0 rejects include_local_variables, which telemetry relies on to keep
# frame locals out of events. Find its replacement before raising the ceiling.

rajatoss and others added 3 commits November 25, 2026 22:07
The test now patches sentry_sdk.init and SENTRY_DSN instead, so no caller
can replace before_send or include_local_variables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A secret-bearing exception is replaced by one stand-in per linked
exception. Each stand-in is a MaskedException subclass named after the
original class, carries the original traceback, mirrors the cause,
context and suppress-context links, and holds only the masked message
and notes. Exception groups keep their members. A __str__ that raises
still takes the internal-failure path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rajatoss

Copy link
Copy Markdown
Member Author

Re #21406 (review)

Stand-in keeps type, frames and chain (a4a6e74)

  • One stand-in per linked exception, built with .with_traceback(exc.__traceback__), with __cause__, __context__ and __suppress_context__ mirrored.
  • Each is a cached MaskedException subclass with the original's __name__, __qualname__ and __module__. Message and notes (tuple and non-string too) are masked; no attributes are copied.
  • Groups keep their members as stand-ins and render as groups. A __str__ that raises still ends in MaskedException(MASKING_ERROR_MESSAGE).
  • One change from the sketch: the stand-ins are built without recursion, so a long context chain can't hit RecursionError.
  • Tests: the parametrized cases now expect frames and the original type name, plus from None and group cases. The chain test checks the exc_info formatter output, the Sentry types, values and frames, and that the caller's exception is unchanged.

Sentry grouping
Checked on a real project: 5 errors sent through _init_sentry and install_masking_filter, before and after the change.

  • Same error with and without a secret: one issue after, grouped by in-app stack trace. Before, the masked one was a separate MaskedException issue, grouped by message.
  • KeyError and ValueError with secrets: separate issues.
  • The same error with DB_PASSWORD vs API_KEY in its message: one issue after, two before.
  • No secret value appeared in any stored event.

_init_sentry() takes no arguments (364577a)
The test patches sentry_sdk.init and SENTRY_DSN, as you suggested.

sentry-sdk 3.0 note (f9105de)
Your comment is now at the pin in setup.py.

@skrydal skrydal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for all the changes.

…hain

traceback.format_exception_only builds a TracebackException for the
whole rest of the chain, so checking every linked exception took time
quadratic in the chain length (about 1.5 s for 800 links). Each
exception's own summary line and notes are now rendered directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rajatoss

rajatoss commented Nov 27, 2026 •

Copy link
Copy Markdown
Member Author

Fixing chain-length finding. Fixed in e6b2637.

  • Cause: traceback.format_exception_only builds a TracebackException for the whole rest of the chain on every call, so checking each link was quadratic.
  • Fix: each exception's own summary line and notes are rendered directly (qualified type name, str() with the stdlib fallback text, notes), with no chain walk. The same texts are checked, and all existing cases pass on 3.10, 3.11 and 3.13.
  • Now linear: 800 links take 25 ms instead of 1.5 s, and 5,000 links 0.16 s instead of 61 s, per pass. Most of what remains is formatting the traceback once for exc_text.
  • Test: a 3,000-link chain is filtered twice in under a second (13 s before the fix).

- Real-world impact was small: across 90 days of real Sentry events, the longest chain was 7 links, which took 0.3 ms.

cc: @skrydal

@rajatoss
rajatoss merged commit c694793 into master Nov 27, 2026
95 of 96 checks passed
@rajatoss
rajatoss deleted the fix/masking-exception-rebuild branch November 27, 2026 06:17
@skrydal

skrydal commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Excellent!

This branch was successfully deployed

1 active deployment
Preview — e6b26371 Deployed Nov 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ingestion PR or Issue related to the ingestion of metadata

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants