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

Merged
RA
14h ago
+884-54

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 #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.