Generated banner for Secret Serialization
Generated logo for Secret Serialization

Secret Serialization

SentryOfficialPublished by Sentry

  • Skill
  • Review and audit
  • Security
  • Apache-2.0
  • No issues found

From the author

Finds secrets, tokens, passwords, and API keys that can leak through generated serialization: Python dataclass repr and asdict, attrs, pydantic model_dump, NamedTuple, JavaScript JSON.stringify and util.inspect, structured logs, tracing spans, and error reports. Use when asked to "check for secret serialization", "credential in repr", "repr=False audit", "secret in spans", "token in logs", or when a change adds a credential field to a dataclass, model, or config object, or adds code that stringifies whole objects or every kwarg into telemetry.
— the description by Sentry

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a systematic process for identifying and mitigating credential leaks that occur when sensitive data is stored in objects that are subsequently serialized by automated systems. Leaks often arise from the combination of a 'holder' (a class or data structure that stores a credential and provides a default serialization method) and a 'sink' (a logging, tracing, or reporting utility that serializes the entire object). Because these components are often developed independently, this skill emphasizes searching the entire repository for potential sinks rather than focusing solely on the changed code.

What it does

  • Identifies credential-bearing fields in data structures like dataclasses, Pydantic models, and JavaScript objects.
  • Maps generated serialization paths such as repr, asdict, model_dump, and JSON.stringify.
  • Detects wholesale serialization sinks that inadvertently capture sensitive object attributes.
  • Evaluates the effectiveness of field-level exclusion mechanisms against various serialization methods.
  • Provides guidance on remediating leaks through redaction, allowlisting, or structural changes.
  • Distinguishes between generated serialization paths and raw attribute access sinks.

When to use it

  • When reviewing changes that add credential fields to data models or configuration objects.
  • When auditing telemetry, logging, or error-reporting code that serializes entire objects or kwargs.
  • When responding to requests to check for secret serialization, credential exposure in repr, or token leaks in logs.
  • When a refactor moves a credential from a secure scope (like a closure) onto an object field.

Advantages

  • Prevents common, high-impact security vulnerabilities caused by indirect data exposure.
  • Provides a clear framework for evaluating the security of different serialization mechanisms.
  • Encourages a holistic view of the codebase by tracing the lifecycle of sensitive objects.
  • Offers actionable, concrete fix guidance for both holders and sinks.

Usage examples

“Check for secret serialization in the new UserConfig dataclass.”
The agent will inspect the dataclass for credential fields, verify if they are excluded from repr/asdict, and search the repository for any logging or tracing sinks that might serialize the UserConfig instance.
“Audit the new telemetry sink for credential leaks.”
The agent will analyze the sink's implementation to see if it performs wholesale serialization of objects and check if any credential-bearing objects are passed to it by callers.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/getsentry/secret-serialization/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip secret-serialization.zip -d .agents/skills

Documentation by Sentry

Secret Serialization Review

Find credentials that can leak because a type serializes itself and something upstream serializes whole objects.

A leak usually needs two changes that each look safe alone:

  1. Holder: a credential is stored as a field on a type with generated repr, str, asdict, model_dump, toJSON, or property enumeration.

  2. Sink: logging, tracing, error reporting, caching, or a response serializes whole objects or every kwarg (str(value), span.set_data(key, obj), logger.info("%s", obj), JSON.stringify(args)).

The two sides are often written months apart by different authors. Report either side on its own. Always search the existing tree for the other side, because it is frequently already on the default branch and absent from the diff.

Boundary

  • This skill covers indirect leaks through generated serialization and wholesale sinks.

  • Direct leaks, such as interpolating a token into a log message, belong to security-review. Report them here only when they come from a changed wholesale sink.

  • Hardcoded secret literals and committed .env files are out of scope.

References

ReferenceRead When
references/python.mdReviewing Python dataclasses, attrs, pydantic, NamedTuple, msgspec, logging, Sentry SDK, or OpenTelemetry code
references/javascript-typescript.mdReviewing JavaScript or TypeScript classes, config objects, JSON.stringify, util.inspect, pino or winston, or Sentry and OpenTelemetry spans

Credential Fields

Treat a field as credential-bearing when its name, type, or source says so:

  • Names containing secret, token, password, passwd, pwd, api_key, apikey, access_key, private_key, signing_key, client_secret, bearer, credential, authorization, auth_header, cookie, session_key, dsn, connection_string, webhook_secret, hmac, or refresh_token.

  • Types such as SecretStr, SecretBytes, or wrappers around them.

  • Values assigned from environment variables, a secrets manager, or a constructor argument named like the above.

Explicit Exclusion

Separate two kinds of path:

  • Generated paths are produced by the type itself: __repr__ and __str__, asdict, model_dump, toJSON, and own-enumerable-property walks (JSON.stringify, util.inspect, spread). They are the holder's responsibility.

  • Raw attribute access reads the stored value directly: vars(obj), obj.__dict__, pickle, json.dumps(obj, default=vars). Every stored attribute is exposed this way, whatever flags the field has. Treat these only as sinks: report them when a sink in the repository applies one to a credential-bearing instance.

A field is fully excluded when every generated path its type has is blocked, whether by one mechanism or several together. A field is partially excluded when at least one generated path still includes it. No field-level mechanism defeats raw attribute access. Only not storing the value does, so fix raw attribute findings at the sink.

MechanismBlocksStill includes the field
dataclasses.field(repr=False), attrs.field(repr=False)__repr__, __str__asdict, astuple, raw access
Pydantic Field(repr=False)__repr__, __str__model_dump, model_dump_json, response serialization, raw access
Pydantic Field(exclude=True)model_dump, model_dump_json, response serialization__repr__, __str__, raw access
Pydantic Field(repr=False, exclude=True)Every generated pathRaw access
JavaScript #private fieldEvery generated pathNothing outside the class body
Object.defineProperty(..., { enumerable: false })Every generated pathExplicit property reads, Object.getOwnPropertyNames
Hand-written __repr__, __str__, toJSON, or [util.inspect.custom] that omits the fieldOnly the path it overrides (a __repr__ also serves str() when there is no __str__)Every other generated path, raw access
Redacting wrapper: SecretStr, SecretBytes, a project Redacted[T]Every generated pathpickle and recursive __dict__ walks such as default=vars, which reach the value stored inside the wrapper
Not stored on the object: read inside the method, or held in a closureEverythingNothing

Do not treat underscore naming, TypeScript private, __slots__, type annotations, comments, dataclass(init=False), or a custom __init__ that still assigns the field as blocking any path.

Investigation Process

  1. Read the changed hunk. Find new or modified credential fields on auto-serializing types, and new or modified code that serializes objects or kwargs into logs, spans, error context, caches, queues, or responses.

  2. For each credential field, read the full class, decorators, base classes, and model config. List every generated path and check which ones the field's mechanisms block, using the table above.

  3. Grep for where instances are constructed and passed. Instances handed to decorators, **kwargs, tool call arguments, task payloads, or middleware reach generic sinks.

  4. Grep the whole repository for sinks that can see those instances, not only the diff. Useful patterns: str(value), repr(, asdict(, model_dump(, set_data(, set_attribute(, set_context(, set_extra(, JSON.stringify(, util.inspect(, loggers called with objects, and raw attribute access (vars(, __dict__, pickle.dumps(, default=vars).

  5. For each changed sink, check for a key allowlist, redaction keyed on credential names, or a filter that replaces objects with their type name. Then grep for callers that pass credential-bearing objects into it.

  6. Look at tests only to see whether one asserts the credential is absent from the serialized form. A missing test is fix guidance, not a finding.

  7. Confirm the code ships. Skip fixtures, examples, generated code, and test-only helpers.

What To Report

CategoryReport When
Unexcluded credential fieldA credential field is added or moved onto a type with generated serialization, and no mechanism blocks any of its generated paths.
Partial exclusionAt least one generated path still includes the field, and a sink in the repository uses that path on instances of the type.
Raw attribute sinkA sink applies vars, __dict__, pickle, or default=vars to an instance that stores a credential, even if the field is fully excluded or wrapped.
Credential moved onto a holderA refactor moves a credential from a lazy read or closure onto an object field.
Wholesale serialization sinkNew or changed telemetry, logging, error-context, cache, or response code serializes every kwarg, every attribute, or whole objects without an allowlist or redaction.
Sink loses its filterA change removes or weakens redaction, an allowlist, or object-to-type-name replacement in an existing sink.
Object passed to telemetryA client, config, or settings object is passed to a span, log, or error-context call that stringifies it.

Severity

LevelUse For
highThe credential reaches a sink anywhere in the repository: log line, span attribute, error event, cache entry, persisted row, queue payload, or API response. The other side may predate the diff. Also a new wholesale sink whose existing callers pass credential-bearing objects.
mediumAn unexcluded credential field whose instances leave the constructing module, after a repository search found no sink. Also a wholesale sink with no allowlist and no traced credential-bearing caller.
lowAn unexcluded credential field whose instances never leave the constructing scope.
  • Do not downgrade because the sink or the holder is outside the diff. That is the normal shape of this bug.

  • Choose the lower severity when reachability depends on unproven preconditions.

What Not To Report

  • Fully excluded fields, unless a raw attribute sink receives the instance.

  • Partial exclusions when no sink in the repository uses the unblocked path.

  • Credentials read inside a method and never stored on the instance.

  • Placeholder or fake values in tests, fixtures, or examples.

  • Types with no generated serialization and no __dict__ or enumeration sink.

  • Sinks that already allowlist scalar keys, redact by credential name, or replace objects with a type name.

  • Pre-existing fields and sinks the diff does not touch, unless the diff connects them.

  • Style, naming, or missing-test-only observations.

Fix Guidance

Include one concrete fix per finding:

  • Holder: block every generated path, wrap the value in a redacting type, or stop storing it on the object.

  • Raw attribute sink: serialize an explicit allowlisted dict instead of the instance, or stop storing the credential on it. A field flag or wrapper does not fix it.

  • Sink: allowlist scalar keys, redact keys matching credential names, and record type(value).__name__ instead of str(value) for non-scalar values.

  • Regression test: serialize an instance with the same serializer the sink uses (for example sentry_sdk.serializer.serialize, json.dumps(asdict(obj)), JSON.stringify(obj), util.inspect(obj)) and assert the credential string is absent.

Finding Format

  • Title: name the field or sink and the leak path, for example "_shared_secret included in RpcClient dataclass repr".

  • Description: one or two sentences naming the generated path that exposes the credential, where instances travel, and the fix.

  • Evidence: 2 to 5 bullets naming the class, decorator, generated paths checked, the exclusion looked for, and every sink or caller traced, including those outside the diff.

Files

SOURCES.md

Secret Serialization Skill Sources

Source Inventory

SourceTrust tierConfidenceUsage constraintsDecisions
Internal Sentry incident: an RPC client's shared secret reached tracing spansInternal incidentHighMechanism only. No repository names, PR links, secrets, or span data in this public repo.Two-sided threat model; report each side alone; search the repository for the other side; require exclusion on every generated path; recommend a serializer-based regression test.
Python dataclasses, attrs, pydantic, and functools.cached_property documentation, checked against Pydantic 2.11Official docs and runtimeHighSummarize as tables.repr=False covers repr only; asdict has no field exclusion; cached_property writes to __dict__; SecretStr redacts repr, str, and model_dump, but pickle and a recursive default=vars walk reach its raw value. Pydantic Field(exclude=True) leaves the raw value in __repr__ and __str__. Field(repr=False) leaves it in model_dump. Both flags together block every generated path and still leave the value in __dict__ and pickle.
Sentry Python SDK serializer and include_local_variables behaviorOfficial docs and SDK sourceHighTreat as a sink, not an SDK bug.Exception frames are a sink for any credential holder in scope. The serializer renders unknown objects with safe_repr, not a __dict__ walk, so it follows generated repr exclusions.
Node util.inspect, JSON.stringify, and #private field semanticsOfficial docsHighSummarize as tables.TypeScript private is not an exclusion; #private is; toJSON alone is partial when inspect or logger sinks exist.
security-review skill in this repoLocal prior artHighAvoid overlap.Direct secret logging stays in security-review; this skill covers generated serialization and wholesale sinks.

Incident Mechanism

  1. A tool-tracing decorator recorded every tool kwarg with str(value) into a span attribute. It was harmless while no kwarg object held a secret.

  2. Much later, a refactor moved the shared secret from a lazy environment read onto a dataclass field of the RPC client, without field(repr=False). The client was passed to tools as a kwarg.

  3. The generated __repr__ included the secret, and the decorator wrote it into spans.

  4. The fix added field(repr=False) to the credential fields and a test that runs sentry_sdk.serializer.serialize over the client and asserts the secret is absent.

Neither change looked dangerous in its own diff, and the sink was already on the default branch when the field was added.

Source-Backed Decisions

  1. Report the holder without a proven sink.

    • Reason: the sink predated the field and lived in another module.

    • Decision: an unexcluded credential field is medium when instances leave the module and no sink is found, and high when a sink is found anywhere in the repository.

  2. Report the sink without a proven credential input.

    • Reason: the wholesale str(value) sink was harmless until an unrelated change.

    • Decision: a wholesale sink without an allowlist is medium on its own.

  3. Search beyond the diff and do not downgrade for it.

    • Reason: diff-only review marked each half safe, and consumers commonly publish only high findings.

    • Decision: the investigation greps the repository for the other side, and severity follows what it finds.

  4. Treat partial exclusion as a finding.

    • Reason: repr=False is the reflexive fix and does not cover asdict, __dict__, or pickle.

    • Decision: severity follows the unblocked path.

  5. Name the sink's serializer in the regression test.

    • Reason: a repr check alone misses __dict__-based serializers.

  6. Do not treat a single Pydantic field flag as exclusion.

    • Reason: a review treated Field(exclude=True) as complete. On Pydantic 2.11, str(model) and repr(model) still contain that field, which is the span path this skill targets. Field(repr=False) still appears in model_dump. Setting both flags covers those paths and does not clear __dict__.

    • Decision: accept Field(repr=False, exclude=True) together, or SecretStr / SecretBytes, as fully excluding generated paths. Report either flag alone at the severity of the unblocked path.

  7. Treat raw attribute access as a sink, not as a generated path.

    • Reason: a follow-up review found the skill both accepted Field(repr=False, exclude=True) and called a leftover __dict__ path partial. Every stored attribute is in __dict__, so counting it as a generated path would make every field-level mechanism, including the incident's repr=False fix, fail.

    • Decision: judge holders by generated paths only. Report vars, __dict__, pickle, and default=vars as a raw attribute sink finding when they receive a credential-bearing instance, whatever its field flags or wrapper.

  8. Report a partial exclusion only when a sink uses the unblocked path.

    • Reason: the report table required a sink while the severity table also listed a sinkless low partial exclusion. The incident eval expects no findings for repr=False fields with only a repr-based sink.

    • Decision: drop the sinkless low case.

Evaluation Runs

Warden pi runtime, openrouter/x-ai/grok-4.5, effort high, against the original internal repository.

CaseExpectedResult
Incident diff: two credential fields added to dataclass RPC clients, str(value) kwarg sink already on the default branchHigh findings naming both fields and the sinkPass, twice. 3 and 4 high findings; every finding traced tool kwarg, tracing decorator, str(value), span attribute.
Same diff with field(repr=False) on both fieldsNo findingsPass. No findings.
Unrelated diff adding seven *_tokens usage-count fields to an LLM proxy modelNo findingsPass. No findings across 22 hunks.

Observations:

  1. With comma-delimited allowed-tools, the same incident run produced only 2 medium findings: the agent had no read or grep, so it could not trace the sink. Fixed by switching to space-delimited tools.

  2. Call-site hunks that pass a credential into the constructor produce extra findings for the same field. Warden analyzes hunks independently, so a per-hunk dedupe instruction did not help and was removed. These are duplicates, not false positives.

  3. Substring name matching did not cause false positives on LLM token counters in this run, so the name list was left unchanged.

Open Gaps

  • Sample size is one positive and two negative cases on one model. Add more negative diffs, such as OAuth request models that legitimately serialize a token into an outbound request body, before relying on precision.

  • Not yet run on Claude models.

  • Add Go, Java, or Rust references only if findings in those languages recur.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Needs an API key, Needs Python

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Sentry
Publisher
Sentry (Official)
Source
getsentry/skills · skills/secret-serialization · commit e94f222
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Sentry.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download secret-serialization.zip