Repository navigation
fix(ingest/masking): mask logged exceptions without rebuilding them - #21406
Conversation
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>
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Connector Tests ResultsConnector tests failed for commit To skip connector tests, add the 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>
PR SummaryOverview Sentry and custom logging: Telemetry initializes Sentry with no frame locals, masks events via a global processor and Tests cover exception chains, Reviewed by Cursor Bugbot for commit e6b2637. Bugbot is set up for automated code reviews on this repo. Configure here. |
|
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 problemThe filter decides on the exception's text, but when the text is clean it keeps the real traceback in Master already behaves this way when the rebuild succeeds. With this PR the multi-argument classes ( ReproRuns against this branch with only 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): The leaked frame in the event looks like The same happens for exceptions Sentry captures without any log call ( Suggested fixIn 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,
)
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 tracebackOnce locals are off, there is no reason left to drop the traceback from the replaced It also reports every such error to Sentry as 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_inI tried this shape against this branch with a
Notes and exception group members would need the same treatment, and a |
|
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 That holds for formatters that print This is easy to hit, because ReproRuns against this branch with 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): Why not drop the traceback hereReplacing the exception whenever masking changes the rendered traceback would close this, but with a value like Suggested fixMask the formatted output at the handler, which is the one place that sees whatever any formatter rendered. In original_format = handler.format
handler.format = lambda record: masking_filter.mask_text(original_format(record))With that added to the repro, both lines print It needs the same care as the filter attachment:
Every handler we construct goes through Two escaped forms the registry does not matchMasking 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:
|
|
Could you also document Proposed change to 1. A bullet in the environment variable list, after - `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:
|
…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>
Smart test selectionpytest smoke testsMode: shadow. The selection below is computed but not applied; this PR still runs the default matrix (
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)
Add the commit |
… 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>
|
Done in 243083b, with one addition to your suggestion:
|
|
Done in 6d89525.
|
|
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 |
skrydal
left a comment
There was a problem hiding this comment.
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
MaskedExceptionwith 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
MaskedExceptionsubclass 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,.messageor.detailmust 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.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>
|
Stand-in keeps type, frames and chain (a4a6e74)
Sentry grouping
sentry-sdk 3.0 note (f9105de) |
skrydal
left a comment
There was a problem hiding this comment.
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>
|
Fixing chain-length finding. Fixed in e6b2637.
- 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 |
|
Excellent! |
Problem
SecretMaskingFilter._mask_exceptionrebuilt every logged exception withtype(exc_value)(*masked_args). It did this whether or not the exception held a secret.args. Other classes raiseTypeError. Examples: botocoreClientError(error_response, operation_name), SQLAlchemyDBAPIError(statement, params, orig), or any customQueryError(message, query).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.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.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 aQueryError(message, query):QueryError(masked_message)to rebuild the exception.query, so it raisesTypeError.exceptbranch logs the CRITICAL diagnostic. That is symptom 1.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.
record.exc_textis unset, it is set to the masked output ofFormatter.formatException: the full traceback with its chain.exc_text, such as the standardlogging.Formatter, print this text.MemoryHandler.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).exc_infostays the caller's tuple, so Sentry and otherexc_inforeaders get the real exception.exc_text, but it does not replace the exception.exc_infoby a stand-in.MaskedExceptionsubclass with the original class's name and module, created once per class, so formatters and Sentry show the original type.__cause__,__context__,__suppress_context__). An exception group keeps its members as stand-ins.exc_textstill has the full masked traceback.exc_infobecomesMaskedException("[MASKING_ERROR - OUTPUT_SUPPRESSED_FOR_SECURITY]").exc_info.filter()stderr warning also prints only the type name._mask_exceptionis private. It now takes the record instead of returning a new tuple, andfilter()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_sentryintelemetry.pynow:include_local_variables;before_send, after object values become strings;Formatted log output
A formatter that renders
record.exc_infoand extra fields itself, such aspython-json-logger(used throughDATAHUB_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.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 ingestwith asqlalchemysource whose SQLite file can't be opened (no secret involved).Before:
After:
A registered secret in the message of
QueryError(message, query), raisedfrom ConnectionError.RuntimeErrorline, and the CRITICAL diagnostic printed the secret to stderr.QueryError: login failed for ***REDACTED:DB_PASSWORD***.Testing
TestExceptionMaskingtests.record.exc_infodirectly (JSON-formatter style).sentry_sdk.utils.exceptions_from_error_tuple(record.exc_info), which is what Sentry's logging integration uses.exc_textand in the standard handler's output.__cause__(no__context__), only in__context__, a context cycle, an attribute-built__str__, anOSErrorfilename,.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.exc_infoof(None, None, None)is unchanged.__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.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.FileHandlerwrites neither a registered value found only in traceback paths nor a JSON-escaped secret in an extra field. The traceback is still written.format()wrapper is added once, restored on uninstall, and withholds the line when masking raises.Checklist
docs/cli.mddocumentsDATAHUB_LOG_CONFIG_FILEand where secret masking applies🤖 Generated with Claude Code
Summary by cubic
Fixes the exception masking filter so logged exceptions are no longer rebuilt. The filter sets
exc_textto the masked formatted traceback and only replaces an exception whose own texts hold a secret, with aMaskedExceptionsubclass named after the original class that keeps the traceback and mirrors cause, context and group membership.Behavior changes
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.repr,messageanddetailare rendered directly, so checking a long chain stays linear instead of quadratic.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.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.Written for commit e6b2637. Summary will update on new commits.