Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install secret-serialization@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin secret-serialization v1.0.0 follows the Agent Plugins spec.
gh skills-hub install secret-serialization Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/secret-serialization/ Extract the ZIP to .github/skills/ in your repo. The folder name must match secret-serialization for Copilot to auto-discover it.
Skill Files (5)
SKILL.md 10.2 KB
---
name: secret-serialization
description: '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.'
allowed-tools: Read Grep Glob
---
# 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
| Reference | Read When |
|-----------|-----------|
| `references/python.md` | Reviewing Python dataclasses, attrs, pydantic, NamedTuple, msgspec, logging, Sentry SDK, or OpenTelemetry code |
| `references/javascript-typescript.md` | Reviewing 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.
| Mechanism | Blocks | Still 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 path | Raw access |
| JavaScript `#private` field | Every generated path | Nothing outside the class body |
| `Object.defineProperty(..., { enumerable: false })` | Every generated path | Explicit property reads, `Object.getOwnPropertyNames` |
| Hand-written `__repr__`, `__str__`, `toJSON`, or `[util.inspect.custom]` that omits the field | Only 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 path | `pickle` 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 closure | Everything | Nothing |
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
| Category | Report When |
|----------|-------------|
| Unexcluded credential field | A credential field is added or moved onto a type with generated serialization, and no mechanism blocks any of its generated paths. |
| Partial exclusion | At least one generated path still includes the field, and a sink in the repository uses that path on instances of the type. |
| Raw attribute sink | A 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 holder | A refactor moves a credential from a lazy read or closure onto an object field. |
| Wholesale serialization sink | New 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 filter | A change removes or weakens redaction, an allowlist, or object-to-type-name replacement in an existing sink. |
| Object passed to telemetry | A client, config, or settings object is passed to a span, log, or error-context call that stringifies it. |
## Severity
| Level | Use For |
|-------|---------|
| high | The 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. |
| medium | An 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. |
| low | An 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.
SOURCES.md 6.8 KB
# Secret Serialization Skill Sources
## Source Inventory
| Source | Trust tier | Confidence | Usage constraints | Decisions |
|--------|------------|------------|-------------------|-----------|
| Internal Sentry incident: an RPC client's shared secret reached tracing spans | Internal incident | High | Mechanism 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.11 | Official docs and runtime | High | Summarize 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` behavior | Official docs and SDK source | High | Treat 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 semantics | Official docs | High | Summarize 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 repo | Local prior art | High | Avoid 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.
| Case | Expected | Result |
|------|----------|--------|
| Incident diff: two credential fields added to dataclass RPC clients, `str(value)` kwarg sink already on the default branch | High findings naming both fields and the sink | Pass, 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 fields | No findings | Pass. No findings. |
| Unrelated diff adding seven `*_tokens` usage-count fields to an LLM proxy model | No findings | Pass. 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.
SPEC.md 5.1 KB
# Secret Serialization Skill Specification
## Intent
`secret-serialization` catches credentials that leak through generated serialization. The leak needs a holder (a credential field on a type with generated `repr`, `asdict`, `model_dump`, or property enumeration) and a sink (code that serializes whole objects or every kwarg into logs, spans, errors, caches, or responses). The two sides are usually added separately, and each looks safe in its own diff.
The skill reports either side alone and searches the whole repository for the other side, so a leak is caught whichever half lands second.
## Scope
In scope:
- Credential fields on auto-serializing types in Python and JavaScript/TypeScript.
- Partial exclusions, where one generated path is blocked and another is not.
- New or changed wholesale serialization sinks and weakened sink filters.
Out of scope:
- Direct interpolation of a secret into a log or response. `security-review` covers that.
- Hardcoded secret literals and committed `.env` files. Secret scanners cover those.
- Secrets-manager architecture advice with no changed field or sink.
- Missing tests as a standalone finding.
## Users And Trigger Context
- Primary users: Warden runs in repositories that keep credentials on client, config, or settings objects, added with `remote = "getsentry/skills"`, and engineers reviewing such changes locally.
- Should trigger for: "secret serialization", "credential in repr", "repr=False", "SecretStr", "token in logs", "secret in spans", "dataclass secret field", "kwargs stringified into telemetry", "asdict leaks", "JSON.stringify config".
- Should not trigger for: general security review, hardcoded-secret scanning, or dataclass refactors with no credential fields.
This is opt-in and specialized. It reports an unexcluded credential field before a sink is proven, which is too noisy for a default review of every repository.
## Runtime Contract
- Required first actions: find changed credential fields and changed sinks in the diff, then read the full class or sink and enumerate generated paths.
- Required evidence per finding: the field or sink, the generated path or serialization call, the exclusion looked for, and where instances travel or what the sink receives, including code outside the diff.
- Constraints:
- Keep `allowed-tools` space-delimited (`Read Grep Glob`). Warden drops comma-suffixed tokens such as `Read,`, which leaves the agent with only `find` and `ls` and caps every finding at medium because no sink can be traced.
- Do not downgrade because the other side predates the diff.
- Judge holders by generated paths only (`__repr__`, `asdict`, `model_dump`, `toJSON`, enumeration). A field is fully excluded when its mechanisms together block all of them.
- Treat raw attribute access (`vars`, `__dict__`, `pickle`, `default=vars`) as a sink category. No field flag or wrapper defeats it, so it never makes a fully excluded holder partial.
- Do not treat underscore naming, TypeScript `private`, `__slots__`, or a custom `__init__` as blocking any path. Pydantic `Field(exclude=True)` or `Field(repr=False)` alone is partial.
- Keep language-specific tables and examples in `references/`.
## Source And Evidence Model
See `SOURCES.md`. Do not store secrets, customer data, span payloads, or internal repository identifiers in this skill.
## Reference Architecture
- `SKILL.md`: threat model, boundary with `security-review`, credential heuristics, exclusion rules, investigation steps, report table, severity, exclusions, fix guidance, finding format.
- `references/python.md`: generated paths and exclusions per Python type, sink table, report and do-not-report examples, regression test shape.
- `references/javascript-typescript.md`: the same for JavaScript and TypeScript.
## Validation
- Run `uv run scripts/quick_validate.py ../secret-serialization` from `skills/skill-writer`.
- Manual check against the incident shape: a diff that adds an unexcluded credential field to a dataclass, with a pre-existing `str(value)` kwarg sink elsewhere in the repository, should produce a high finding naming both.
- Precision checks: `SecretStr`, `#private`, a lazily read `property`, a filtered sink, and `Field(repr=False, exclude=True)` with only repr or `model_dump` sinks should produce no finding.
- Recall checks: `Field(exclude=True)` alone on a model passed to `str()` should produce a partial-exclusion finding. Any credential-bearing instance, including a fully excluded or `SecretStr` one, passed to `pickle` or `default=vars` should produce a raw attribute sink finding.
## Known Limitations
- Credential detection depends on names, types, and sources. Oddly named credential fields are missed unless their source is an obvious secret read.
- Behavior of third-party serializers is limited to what the references document.
- Go, Java, and Rust are not covered by references. The core contract still applies.
## Maintenance Notes
- Update `SKILL.md` when exclusion rules, severity, or the report table change.
- Update `references/` when a new serializer or sink causes a real leak or a repeated false positive.
- Record each incident or review outcome that changes a decision in `SOURCES.md`.
javascript-typescript.md 5.1 KB
# JavaScript and TypeScript Secret Serialization Notes
Use this when reviewing JavaScript or TypeScript code. These notes refine the core skill; they do not add reporting scope.
## Generated Serialization Paths
| Shape | Paths that include every own enumerable property | Exclusion |
|-------|--------------------------------------------------|-----------|
| Plain object or class instance | `JSON.stringify`, `util.inspect` / `console.log`, spread `{...obj}`, `Object.entries`, `structuredClone` | `#private` fields (excluded from all of these), `Object.defineProperty(obj, k, { enumerable: false })`, a `toJSON()` returning an allowlisted object, `[util.inspect.custom]()` for inspect only |
| Class with TypeScript `private` or `protected` | Same as a plain class. The modifier is compile-time only. | Not an exclusion. Use `#private`. |
| Zod or Valibot parsed config object | Plain object; `JSON.stringify` and loggers see every key | Split secrets into a separate object, or redact at the sink |
| Value held in a closure | Not reachable by serialization | Preferred for client credentials |
| `WeakMap` keyed by instance | Not reachable by `JSON.stringify` or `util.inspect` of the instance | Acceptable for credentials attached to instances |
A `toJSON()` covers `JSON.stringify` only. `console.log`, `util.inspect`, pino, and the Sentry normalizer walk own enumerable properties and ignore `toJSON`. Treat a `toJSON`-only block as partial when an inspect or logger sink exists.
## High-Signal Sinks
| Sink | Why it leaks | Safe form |
|------|--------------|-----------|
| `logger.info({ ...config })`, `logger.info('msg', client)` in pino, winston, or bunyan | Serializes own enumerable properties | Log identifiers. Logger `redact` paths are defense in depth, not the fix. |
| `console.log(obj)` / `util.inspect(obj)` in shipped code | Walks properties, including TypeScript `private` ones | Remove, or log a summary |
| `Sentry.setContext('client', obj)`, `setExtra`, `captureException(err, { extra: { client } })` | The normalizer walks properties | Pass explicit scalar fields |
| `span.setAttribute(key, JSON.stringify(obj))`, `span.setAttributes(obj)` | Stringifies whole objects | Allowlist scalar attributes |
| Logging an HTTP client error with its request config (for example axios `error.config.headers`) | The attached request carries `Authorization` | Strip headers before logging |
| `res.json(obj)`, `Response.json(obj)`, a Server Action return value | Serializes a config or client object into a response | Return a DTO |
| `for (const [k, v] of Object.entries(args)) attrs[k] = String(v)` | Stringifies arbitrary argument objects into telemetry | Allowlist keys; record `v.constructor.name` for objects; redact credential-named keys |
## Examples
**Report (high): token property on a client that instrumentation serializes**
```ts
export class ApiClient {
constructor(
public readonly baseUrl: string,
private readonly token: string, // compile-time private only
) {}
}
```
```ts
// instrumentation.ts, already on the default branch
span.setAttribute('tool.args', JSON.stringify(args)); // args.client is an ApiClient
```
Evidence: `private` does not affect `JSON.stringify`, so `args.client` serializes with `token`. Fix: `readonly #token: string` or a closure, and have the sink skip object values.
**Report (medium): unexcluded credential on a shared config object**
```ts
export const config = {
region: process.env.REGION,
webhookSecret: process.env.WEBHOOK_SECRET,
};
export function createHandler(cfg: typeof config) { ... }
```
Evidence: `config` is exported and passed into handler factories. A repository search found no logger or Sentry context call on it yet. Fix: split into `config` and `secrets`, or read the secret inside the function that signs.
**Report (medium): new wholesale sink**
```ts
export function traced<T extends (...a: any[]) => any>(fn: T) {
return (...args: Parameters<T>) =>
Sentry.startSpan({ name: fn.name, attributes: { args: JSON.stringify(args) } }, () => fn(...args));
}
```
Evidence: every argument is stringified into span attributes with no filter. Fix: record primitive arguments and a type name for objects.
**Do not report: `#private` field**
```ts
export class ApiClient {
readonly #token: string;
constructor(readonly baseUrl: string, token: string) { this.#token = token; }
}
```
`#private` fields are not own enumerable properties. `JSON.stringify`, `util.inspect`, spread, and the Sentry normalizer do not see them.
**Do not report: allowlisted `toJSON` with no inspect or logger sink**
```ts
toJSON() { return { baseUrl: this.baseUrl }; }
```
This is enough when the only sinks are `JSON.stringify` or `res.json`. It becomes a partial exclusion if the instance is also passed to `console.log` or a logger.
## Regression Test Shape
```ts
it('does not serialize the token', () => {
const client = new ApiClient('https://example.invalid', 'token-value');
expect(JSON.stringify(client)).not.toContain('token-value');
expect(util.inspect(client)).not.toContain('token-value');
});
```
Assert against every serializer a sink in the repository uses.
python.md 9.9 KB
# Python Secret Serialization Notes
Use this when reviewing Python code. These notes refine the core skill; they do not add reporting scope. "Generated paths" and "raw attribute access" have the meanings defined in `SKILL.md` under Explicit Exclusion.
## Generated Serialization Paths
| Type | Generated paths that include every field by default | What blocks them |
|------|------------------------------------------------------|------------------|
| `@dataclasses.dataclass` | `__repr__` (so `str()`, f-strings, `%s`, `%r`), `dataclasses.asdict`, `dataclasses.astuple` | `field(repr=False)` blocks repr only. Nothing blocks `asdict`; wrap the value or keep it off the instance. |
| `attrs` `@define` / `@attr.s` | `__repr__`, `attrs.asdict`, `attrs.astuple` | `field(repr=False)` blocks repr only. `asdict` still includes the field unless the call passes `filter=`. |
| `pydantic.BaseModel` | `__repr__`, `__str__`, `model_dump`, `model_dump_json`, `.dict()`, `.json()`, FastAPI response serialization | `SecretStr` / `SecretBytes` redact all of these (`**********`). `Field(repr=False)` blocks `__repr__` and `__str__`. `Field(exclude=True)` blocks dump, JSON, and response serialization. A plain field is fully excluded only with both flags. |
| `pydantic_settings.BaseSettings` | Same as `BaseModel`; often logged wholesale at startup | `SecretStr` for every credential setting. Plain fields follow the `BaseModel` flag rules. |
| `typing.NamedTuple` | `__repr__`, `_asdict`, iteration and unpacking | None. Do not hold credentials on a NamedTuple. |
| `TypedDict` / `dict` | `repr`, `json.dumps`, iteration | None. Redact at the sink. |
| `msgspec.Struct` | `__repr__`, `msgspec.to_builtins`, encoders | `field(repr=False)` on newer versions blocks repr only. |
| Plain class | None. The default repr is `<Class object at 0x...>`. | Nothing to block. A hand-written `__repr__` that prints fields creates a generated path. |
Every stored attribute on these types, including one with `repr=False`, `exclude=True`, or both, is still visible through raw attribute access. `SecretStr` hides the value from `repr`-based rendering of `vars(obj)`, but `pickle` and a recursive `default=vars` walk still reach the raw string stored inside the wrapper.
`dataclass(init=False)` with a hand-written `__init__` still generates `__repr__` and still registers annotated fields with `asdict`. A custom constructor blocks nothing.
`functools.cached_property` stores its result in `instance.__dict__` after first access. It does not appear in the generated `__repr__` or in `asdict`, so it matters only when a raw attribute sink receives the instance.
The Sentry SDK serializer, used for span data, `set_context`, `set_extra`, and exception frame locals, renders unknown objects with `repr()`. It does not walk `__dict__`. A fully excluded field does not reach Sentry through that serializer.
## High-Signal Sinks
| Sink | Why it leaks | Safe form |
|------|--------------|-----------|
| `safe_kwargs[key] = str(value)` over `**kwargs` | Stringifies client and config objects passed as tool or task arguments | Allowlist scalar keys; record `type(value).__name__` for objects; redact keys matching credential names |
| `span.set_data(key, obj)`, `set_context(name, obj)`, `set_extra` | The Sentry serializer renders objects with `repr()` | Pass explicit scalar fields only |
| `span.set_attribute(key, str(obj))` in OpenTelemetry | OpenTelemetry drops non-primitive values, so callers stringify with `str()` or `json.dumps` first | Pass explicit scalar fields only |
| `logger.info("... %s", obj)`, `{obj}` in f-strings, `logger.exception(...)` | Interpolates `__repr__`; Sentry `include_local_variables=True` (the default) captures frame locals by repr on exceptions | Log identifiers, not objects; exclude credential fields from repr |
| `json.dumps(obj, default=str)`, `default=repr` | Falls back to repr for unknown objects | An explicit `to_dict()` with an allowlist |
| `json.dumps(obj, default=vars)`, `vars(obj)`, `obj.__dict__` into a log, span, or payload | Raw attribute access, including fully excluded fields, cached properties, and the value inside a `SecretStr` when the walk recurses | An explicit `to_dict()` with an allowlist |
| `dataclasses.asdict(obj)` / `model.model_dump()` into a response, cache, or queue | Includes every field regardless of `repr=False` | `exclude={...}` or a separate public DTO |
| `pickle.dumps(obj)` into Redis or a task queue | Raw attribute access: serializes `__dict__`, including fully excluded fields and cached properties | Rebuild clients from config at the consumer |
| `pprint`, `print(obj)` in shipped code | repr | Remove, or log identifiers |
| `rich.inspect(obj)` in shipped code | Raw attribute access: lists attribute values | Remove |
## Examples
**Report (high): credential field added to a dataclass that existing instrumentation stringifies**
```python
@dataclasses.dataclass(init=False)
class RpcClient:
referrer: str
_base_url: str | None
_shared_secret: str | None # new field, no repr=False
def __init__(self, referrer, *, base_url=None, shared_secret=None):
self.referrer = referrer
self._base_url = base_url
self._shared_secret = shared_secret
```
```python
# tracing.py, already on the default branch, not in this diff
for key, value in kwargs.items():
safe_kwargs[key] = str(value) # rpc_client=RpcClient(...) lands here
span.set_data("gen_ai.tool.call.arguments", safe_kwargs)
```
Evidence: `str(rpc_client)` renders `RpcClient(referrer=..., _base_url=..., _shared_secret='...')`. The tool-tracing decorator passes every kwarg through `str()` into a span attribute, and tools receive `rpc_client` as a kwarg. Fix: `_shared_secret: str | None = dataclasses.field(repr=False)`, and have the sink record `type(value).__name__` for non-scalar values.
**Report (medium): unexcluded field, instances travel, no sink found**
```python
@dataclass
class WebhookConfig:
url: str
signing_secret: str
def register(config: WebhookConfig) -> None:
dispatcher.enqueue("register_webhook", config=config)
```
Evidence: `WebhookConfig.__repr__` includes `signing_secret`, and instances are enqueued as task kwargs. A repository search found no task instrumentation that serializes kwargs. Fix: `signing_secret: str = field(repr=False)`, or pass `config.url` and read the secret inside the task.
**Report (high): partial exclusion with a sink on the unblocked path**
```python
@dataclass
class Settings:
api_key: str = field(repr=False)
cache.set("settings", json.dumps(asdict(settings)))
```
Evidence: `repr=False` does not affect `asdict`, and the cache write serializes the key. Fix: build an explicit dict of non-secret fields for the cache.
**Report (medium): new wholesale sink with no filter**
```python
def trace_call(func):
def wrapper(*args, **kwargs):
with start_span() as span:
span.set_data("call.kwargs", {k: str(v) for k, v in kwargs.items()})
return func(*args, **kwargs)
return wrapper
```
Evidence: every kwarg is stringified into span data with no allowlist or type filter, and no credential-bearing caller was traced yet. Fix: record `int`, `float`, `bool`, and short `str` values; record `type(v).__name__` for everything else; redact keys matching credential names.
**Do not report: credential never stored on the instance**
```python
@dataclass
class RpcClient:
referrer: str
@property
def shared_secret(self) -> str:
return os.environ["RPC_SHARED_SECRET"]
```
A plain `property` is not a dataclass field and does not write to `__dict__`. Switching it to `cached_property` would make `vars(obj)` leak after first access.
**Report (high): `Field(exclude=True)` with a `str()` sink**
```python
class Settings(BaseModel):
service: str
api_key: str = Field(exclude=True)
span.set_data("settings", str(settings))
```
Evidence: `exclude=True` omits `api_key` from `model_dump` and response serialization. `str(settings)` and `repr(settings)` still contain the raw key, and the span records `str(settings)`. Fix: `api_key: str = Field(repr=False, exclude=True)`, or use `SecretStr`. `repr=False` alone still leaks through `model_dump`.
**Report (high): fully excluded field with a raw attribute sink**
```python
class Settings(BaseModel):
service: str
api_key: str = Field(repr=False, exclude=True)
redis.set("settings", pickle.dumps(settings))
```
Evidence: both flags block every generated path, but `pickle` serializes `__dict__`, which holds the raw key, into a cache entry. `SecretStr` would not help, because it pickles its raw value. Fix: cache `settings.model_dump()` and read the key from the secret source at the consumer.
**Do not report: fully excluded field with only generated-path sinks**
```python
class Settings(BaseModel):
service: str
api_key: str = Field(repr=False, exclude=True)
logger.info("loaded %s", settings)
return settings.model_dump()
```
`repr`, `str`, and `model_dump` all omit `api_key`, and no sink reads `__dict__`.
**Do not report: pydantic `SecretStr`**
```python
class Settings(BaseSettings):
database_password: SecretStr
```
`repr`, `str`, and `model_dump` render `**********`. Report only if a changed call site passes `get_secret_value()` to a sink, or a raw attribute sink such as `pickle` receives the instance.
**Do not report: sink already filters**
```python
SCALARS = (str, int, float, bool, type(None))
safe_kwargs = {
k: (v if isinstance(v, SCALARS) and not is_credential_key(k) else type(v).__name__)
for k, v in kwargs.items()
}
```
## Regression Test Shape
```python
from sentry_sdk.serializer import serialize
def test_client_serialization_excludes_secret():
client = RpcClient(referrer="test", shared_secret="shared-secret-value")
assert "shared-secret-value" not in json.dumps(serialize({"client": client}))
assert "shared-secret-value" not in repr(client)
```
Use the serializer the real sink uses. A `repr` check alone misses the `asdict` and `__dict__` paths.
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/getsentry/skills/blob/main/LICENSE