fix(ingest/masking): mask logged exceptions without rebuilding them
Problem
SecretMaskingFilter._mask_exceptionrebuilt every logged exception withtype(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 raiseTypeError. Examples: botocoreClientError(error_response, operation_name), SQLAlchemyDBAPIError(statement, params, orig), or any customQueryError(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=Trueon the masking-internal logger, which writes to the raw stderr without masking. When the log call is made inside anexceptblock, Python chains the logged exception onto theTypeError, so the original exception is printed unmasked._mask_argshad the same shape. - Rebuilding only masked
args. An attribute-built__str__, anOSErrorfilename,__notes__andExceptionGroupmembers 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:
TypeError: <Class>.__init__() missing N required positional argument(s), reported by the diagnosticCRITICAL: Secret masking failed in exception: ā¦.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):
- The filter masks the message, then calls
QueryError(masked_message)to rebuild the exception. - The constructor also requires
query, so it raisesTypeError. - The filter's
exceptbranch logs the CRITICAL diagnostic. That is symptom 1. - 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.
- The traceback text is set once. If
record.exc_textis unset, it is set to the masked output ofFormatter.formatException: the full traceback with its chain.- Formatters that print
exc_text, such as the standardlogging.Formatter, print this text. - So do handlers that format later, such as
MemoryHandler.
- Formatters that print
- The exception's own texts are checked. These are its traceback summary line (
traceback.format_exception_only, which includes its notes),repr,messageanddetail, 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). - No secret in those texts:
exc_infostays the caller's tuple, so Sentry and otherexc_inforeaders 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.
- A registered value that appears only in a file path or source line is masked in
- A secret in those texts: each exception in the chain is replaced in
exc_infoby a stand-in.- The stand-in is a
MaskedExceptionsubclass 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_textstill has the full masked traceback.
- The stand-in is a
- Internal failures:
exc_infobecomesMaskedException("[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.
- The diagnostics name only the exception type and carry no
_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_filterwraps each covered handler'sformat(), so whatever it returns is masked. It does this once per handler, anduninstall_masking_filterrestores 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.mddocumentsDATAHUB_LOG_CONFIG_FILEand 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
RuntimeErrorline, 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
TestExceptionMaskingtests.- Setup: they log through a real logger with two formatters, the standard one and one that renders
record.exc_infodirectly (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_textand 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__, anOSErrorfilename,.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_infoof(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.
- Setup: they log through a real logger with two formatters, the standard one and one that renders
- 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
FileHandlerwrites 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.
- A JSON formatter on a
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.mddocumentsDATAHUB_LOG_CONFIG_FILEand 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_inforeaders (Sentry, JSON formatters) unchanged; a secret anywhere in the chain (message,__str__,OSErrorfilename, cause, context, notes, group members) triggers the masked stand-in. - Each linked exception's summary line, notes,
repr,messageanddetailare 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. Theinclude_local_variablesoption keepssentry-sdkpinned below 3.0. install_masking_filterwraps every covered handler'sformat()so output is masked even when a formatter rendersexc_infoand extras itself; a line whose masking raises is replaced by the masking-error marker.exc_textis now set by the filter, so a handler's customformatExceptionis no longer used.- Documents
DATAHUB_LOG_CONFIG_FILE, which replaces the CLI's logging setup with afileConfigfile; masking is only guaranteed for standard-library stream and file handlers using the standardlogging.Formatterorpython-json-logger.