Skip to content

fix: mask secrets in long strings and dict keys in code variables - #988

Merged
ablaszkiewicz merged 4 commits into
mainfrom
fix/mask-long-strings-and-dict-keys
Sep 29, 2026
Merged

ablaszkiewicz merged 4 commits into
mainfrom
fix/mask-long-strings-and-dict-keys

Conversation

@ablaszkiewicz

@ablaszkiewicz ablaszkiewicz commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

  • With code variables capture on, exceptions can send credentials in cleartext through two paths the masker misses.
  • Long strings: known key formats (AWS, Stripe, OpenAI and others) are searched only up to 200 characters. A SQL query with an inlined AWS key pair is usually longer.
  • Dict keys: a matching key redacts its value, but the key text goes out as-is. A non-string key goes out as its repr, so aiohttp's ConnectionKey(..., proxy_auth=BasicAuth(..., password=...)) leaks proxy credentials.

Changes

  • The known-format search now covers strings up to 2,048 characters, the cap the other pattern checks use.
  • A dict key becomes $$_posthog_redacted_key_<n>_$$ when its text could hold a secret: a mask match that is not a plain field name, a secret-looking key, a non-string key with parts that need masking, an unreadable key, or a key too long to scan.
  • Field names such as password keep their key, and only the value is redacted, as before.
  • URL credentials are removed from string keys, and keys that end up with the same text keep separate entries.
  • Checking a key's parts stays inside the traversal's node budget and cycle guard.
Input main This PR
SQL string over 200 characters with an AWS key pair Sent as-is Redacted
Pool keyed by ConnectionKey(..., password=...) Key leaks the password Key replaced
Dict keyed by ("admin", "<random token>") Key leaks the token Key replaced
{"password": "hunter2"} {"password": <REDACTED>} Unchanged

Warning

Behavior change: {("db", "password"): "x"} now masks to {"$$_posthog_redacted_key_0_$$": <REDACTED>}.

Note

The sk- patterns stay unanchored, so words such as disk-usage-… are over-redacted in longer strings too. A word boundary would miss %3Dsk-… in URLs.

Performance: median ms per capture, local benchmark (not committed), default configuration.

Case main This PR
Real payload A 0.12 0.19
Synthetic realistic 0.38–0.41 0.54–0.64
Synthetic large 0.86–0.88 1.16–1.19
Synthetic huge 0.74 0.77–0.79

💚 How did you test it?

  • 17 new or changed test cases fail on main and pass here, one or more for each leak above.
  • Guard cases pass on both: field-name keys stay, and a sk- key after %3D stays redacted.
  • Not done: make prep_local inside the PostHog app.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

  • Claude Code with Claude Opus 5.5 (claude-opus-5-5). Skills: qa-swarm, writing-tests, writing-code-comments, writing-pr-descriptions.
  • Later commits address a QA-swarm review and the Greptile and PostHog Review comments.
  • Reverted: a word boundary before sk- (495e712), because it missed keys in percent-encoded URLs.
  • The changeset was written by hand in the sampo add format, because the CLI is not installed locally.
  • Earlier session: https://claude.ai/code/session_01GaMtfy4QuhjzpquxM9p4fN

🤖 Generated with Claude Code

https://claude.ai/code/session_01NHmek81fkmrddpN8MqWmCz

Search strings up to the 2,048-character pattern-match cap for known
credential formats, instead of stopping at 200 characters, so a key
inside a longer string such as an inlined SQL query is redacted.

Mask dict keys, not only their values. A non-string key is rendered as
a repr, which can embed field values, so a pattern match now replaces
the key with a numbered placeholder. Keys that look like secrets or are
too long to scan get the same placeholder, and URL credentials are
removed from string keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GaMtfy4QuhjzpquxM9p4fN
@ablaszkiewicz ablaszkiewicz self-assigned this Sep 29, 2026
@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-29T16:03:29.285013+00:00
Duration: 259274ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 514ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 508ms
Required Headers.Has Authorization Bearer Header ✅ 508ms
Required Headers.Has Content Type Json ✅ 509ms
Required Headers.Has Posthog Sdk Info Format ✅ 508ms
Required Headers.Has Posthog Attempt Header ✅ 508ms
Required Headers.Has Posthog Request Id ✅ 509ms
Required Headers.Has Posthog Request Timestamp ✅ 508ms
Required Headers.Has User Agent ✅ 507ms
Body Format.Body Has Created At And Batch ✅ 508ms
Body Format.No Api Key In Body ✅ 507ms
Body Format.No Sent At In Body ✅ 507ms
Event Format.Event Has Required Root Fields ✅ 508ms
Event Format.Event Uuid Is Valid ✅ 507ms
Event Format.Event Timestamp Is Rfc3339 ✅ 507ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 513ms
Event Format.Distinct Id Is String ✅ 507ms
Event Format.Distinct Id At Root Not Properties ✅ 508ms
Event Format.Custom Properties Preserved ✅ 508ms
Event Format.Set Properties Preserved ✅ 508ms
Event Format.Set Once Properties Preserved ✅ 508ms
Event Format.Groups Properties Preserved ✅ 507ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 508ms
Event Format.Event Has Required Root Fields Batch ✅ 509ms
Event Format.Event Uuid Is Valid Batch ✅ 511ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 510ms
Event Format.Distinct Id Is String Batch ✅ 510ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 509ms
Event Format.Custom Properties Preserved Batch ✅ 512ms
Event Format.Set Properties Preserved Batch ✅ 511ms
Event Format.Set Once Properties Preserved Batch ✅ 511ms
Event Format.Groups Properties Preserved Batch ✅ 512ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 510ms
Batch Behavior.Multiple Events In Single Batch ✅ 513ms
Batch Behavior.Batch Envelope Smoke ✅ 511ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 506ms
Batch Behavior.Flush At Triggers Batch ✅ 1009ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 509ms
Deduplication.Generates Unique Uuids ✅ 514ms
Deduplication.Different Events Same Content Different Uuids ✅ 512ms
Deduplication.Preserves Uuid On Retry ✅ 6517ms
Deduplication.Preserves Timestamp On Retry ✅ 6517ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6516ms
Deduplication.No Duplicate Events In Batch ✅ 513ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 508ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13514ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6517ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3017ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6517ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 508ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 511ms
Response Format Validation.Success No Retry After When All Ok ✅ 510ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1512ms
Response Format Validation.Success No Retry After When Drop Only ✅ 511ms
Response Format Validation.Response Echoes Request Id ✅ 509ms
Retry Behavior.Retries On 408 ✅ 6514ms
Retry Behavior.Retries On 500 ✅ 6514ms
Retry Behavior.Retries On 503 ✅ 8519ms
Retry Behavior.Retries On 504 ✅ 6518ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3515ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11542ms
Retry Behavior.Does Not Retry On 400 ✅ 2511ms
Retry Behavior.Does Not Retry On 401 ✅ 2511ms
Retry Behavior.Does Not Retry On 402 ✅ 2511ms
Retry Behavior.Does Not Retry On 413 ✅ 2510ms
Retry Behavior.Does Not Retry On 415 ✅ 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2511ms
Retry Behavior.Implements Backoff ✅ 22524ms
Retry Behavior.Max Retries Respected ✅ 22532ms
Partial Batch Handling.Handles 200 Full Success ✅ 2511ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3515ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3514ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3514ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6518ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6518ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6520ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6515ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6519ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6514ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8518ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3513ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3515ms
Compression.Sends Gzip Content Encoding ✅ 509ms
Compression.No Content Encoding When Disabled ✅ 509ms
Compression.Compressed Body Is Decompressible ✅ 508ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2510ms
Event Options.Cookieless Mode Override ✅ 509ms
Event Options.Disable Skew Correction Override ✅ 509ms
Event Options.Process Person Profile Override ✅ 509ms
Event Options.Product Tour Id Override ✅ 508ms
Event Options.Unset Options Omitted ✅ 509ms
Event Options.Options Override In Batch ✅ 510ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 508ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 508ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 508ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 508ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 508ms
Identity.Capture Ai Event Has Uuid ✅ 508ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 508ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 508ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 9ms
Request Payload.Flags Request Uses V2 Query Param ✅ 6ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 6ms
Request Payload.Flags Request Omits Authorization Header ✅ 6ms
Request Payload.Token In Flags Body Matches Init ✅ 7ms
Request Payload.Groups Round Trip ✅ 6ms
Request Payload.Groups Default To Empty Object ✅ 6ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 6ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 6ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 6ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 506ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 11ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 6ms
Retry Behavior.Retries Flags On 502 ✅ 310ms
Retry Behavior.Retries Flags On 504 ✅ 310ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 509ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 46ms
Versioned Boolean Matching.Matching Version 1 ✅ 43ms
Versioned Boolean Matching.Matching Version 2 ✅ 43ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 23ms

@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Retrigger

[Medium risk] Expands secret masking to longer strings and dictionary keys.

The PR appears safe to merge, though key probing can reduce the usefulness of captured exception variables.

Reviews (2) · Last reviewed commit: "fix: bound key probes and fail closed on..."

Comment thread posthog/exception_utils.py
- Replace a string key that matches a mask pattern unless it is shaped like
  a field name, so `password=...` or SQL text used as a key cannot leak.
- Replace a non-string key when masking its parts redacts anything; its repr
  defeats the entropy check.
- Give a key a placeholder when its str() raises, instead of aborting the
  whole variable into the repr fallback.
- Keep both entries when two keys end up with the same text, e.g. URLs that
  differ only in credentials, or a literal key equal to a placeholder.
- Stop the OpenAI/Anthropic `sk-` patterns matching inside words like `disk-`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GaMtfy4QuhjzpquxM9p4fN
@posthog

posthog Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🦔 PostHog Review reviewed this pull request

Found 2 must fix, 2 should fix, 0 consider.

Published 4 findings (view the review).

@posthog

posthog Bot commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

PostHog Review alpha 🦔 If you find any issues helpful - please reply "valid", "invalid", etc., for evaluation purposes 🙏

@posthog posthog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PostHog Review

Found 2 must fix, 2 should fix.

Comment thread posthog/exception_utils.py Outdated
Comment thread posthog/exception_utils.py Outdated
Comment thread posthog/exception_utils.py Outdated
Comment thread posthog/exception_utils.py Outdated
- Share the traversal's `seen` set with key probes, so probes count against
  the node budget and cycle guard. A probe that reaches an already visited
  object replaces the key, because that part of its repr went unchecked.
- Replace the key when its probe raises, instead of falling back to the
  repr of the whole variable.
- Redact the value of a key whose str() raises, because nothing shows
  whether the key names a secret.
- Remove the `sk-` word-boundary lookbehind: a key often follows a letter or
  digit, e.g. `%3Dsk-...` in a URL, and the lookbehind let it through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NHmek81fkmrddpN8MqWmCz
@ablaszkiewicz
ablaszkiewicz marked this pull request as ready for review September 29, 2026 15:45
@ablaszkiewicz
ablaszkiewicz requested a review from a team as a code owner September 29, 2026 15:45
Comment thread posthog/exception_utils.py Outdated
A key probe recorded its visits in the traversal's `seen` set, so an object
that a key shares with a value rendered as `<circular ref>` in the value.
Probes now record visits under a separate tag. They still stop at every
visited object and count against the same node budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NHmek81fkmrddpN8MqWmCz

@dustinbyrne dustinbyrne left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the expanded masking window, dictionary-key collisions, unreadable keys and shared traversal budget, including the MCP detector caller. The earlier review findings are addressed. No issues found.

Validation: static source review and existing CI; no tests or device runs executed for this review.

Human-driven, agent-assisted review.

@ablaszkiewicz
ablaszkiewicz merged commit 3f94e80 into main Sep 29, 2026
44 checks passed
@ablaszkiewicz
ablaszkiewicz deleted the fix/mask-long-strings-and-dict-keys branch September 29, 2026 21:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants