Skip to content

fix: mask authorization credentials and signed urls in code variables - #1015

Merged
ablaszkiewicz merged 4 commits into
mainfrom
ab/fix/mask-auth-header-code-variables
Oct 6, 2026
Merged

ablaszkiewicz merged 4 commits into
mainfrom
ab/fix/mask-auth-header-code-variables

Conversation

@ablaszkiewicz

@ablaszkiewicz ablaszkiewicz commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

With code variables on, an HTTP Bearer or Basic credential reaches error tracking unmasked whenever it is not stored under a header-name key.

  • A header pair list or an ASGI scope (every FastAPI and Starlette request) holds headers as (name, value) tuples.
  • The name authorization matches the auth pattern and gets redacted. The value next to it stays.
  • A credential in a local with a neutral name also passes, because the entropy check skips any value that contains a space.
  • A signed URL, such as an Azure SAS URL, carries its signature in a sig query parameter that no rule matches.

Changes:

  • Bearer <credential> and Basic <credential> become Bearer $$_posthog_redacted_based_on_masking_rules_$$ in every string, repr and mapping key the SDK emits. The scheme stays for context.
  • The rule also matches a colon or an opening quote after the scheme, as in Bearer: <token>.
  • The rule runs whenever masking runs. It adds no option, so the public API keeps its shape.
  • Prose stays unchanged: the rule skips a credential shorter than 8 characters, such as "Bearer token", and a lowercase word of up to 15 letters, such as "bearer transportation". It also requires a separator, so basicConfig stays.
  • URL credentials are scrubbed before Authorization values, so Bearer postgresql://user:pass@host cannot hide the URL from the URL pass.
  • A Basic credential of any length is redacted when it decodes to user:password, so Basic YTpi (a:b) is caught while "basic auth" stays.
  • The default mask patterns gain (?i)[?&]sig=. A bare sig would redact any value that contains "design" or "signal", because mask patterns also match values.
  • Mechanical: the API snapshot records the new default pattern list. It also gains posthog.mcp.get_tool_input_properties, which feat(mcp): record safe tool input names #989 added without a snapshot update, so make public_api_check fails on main without it.

💚 How did you test it?

  • New tests cover a header pair list, an ASGI scope with byte headers, a neutral local, a short Basic credential, a lowercase-only token, colon and quote separators, and an Azure SAS URL. All of them fail on main.
  • Guard tests keep prose, basicConfig(level=10), design, signal_handler and /signup?step=2 unchanged.
  • Not checked: a running FastAPI app. The tests build the same scope shape by hand.

Performance

The new check adds one regex pass to every string and key the masker emits. Only exceptions captured with code variables pay it.

Median time per operation, main (2273c7a) against this branch (5819111):

Case main This PR Change
Short plain string 1.59 µs 2.03 µs +0.44 µs (+27%)
2 KB plain string 123.1 µs 141.9 µs +18.8 µs (+15%)
Header pair list 4.27 µs 5.65 µs +1.38 µs (+32%)
ASGI scope, 10 headers 108.7 µs 116.0 µs +7.4 µs (+7%)
Dict with 40 string keys 28.3 µs 44.6 µs +16.3 µs (+58%)
Frame with 11 locals 41.6 µs 50.9 µs +9.4 µs (+23%)
capture_exception, 6 frames 203.3 µs 219.7 µs +16.4 µs (+8%)
  • A regex pass with no match costs about 200 ns on a short string and 100 ns on a short key.
  • The dict case grows most because the check now runs on each key as well as each value.
  • A substring pre-check for bearer/basic would cost about 50 ns, so it could cut the added cost about 4x. This PR does not include it.
Method and script

Apple M4 Pro, macOS 26.7.1, Python 3.14.7. The same interpreter imports each checkout through PYTHONPATH. Three alternating runs per version, 7 repeats per case each, median per operation. Minimums give the same changes within 3 percentage points.

"""Time code-variable masking for one posthog-python checkout (picked by PYTHONPATH).

Prints JSON: {case: [per-op seconds for each repeat]}. Fake values only.
"""

import dataclasses
import json
import sys
import timeit

import posthog
from posthog import Posthog
from posthog.exception_utils import (
    DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS,
    DEFAULT_CODE_VARIABLES_MASK_PATTERNS,
    VariableSizeLimiter,
    _MaskingConfig,
    _mask_value,
    _serialize_frame_variables,
)

CONFIG = _MaskingConfig.build(
    DEFAULT_CODE_VARIABLES_MASK_PATTERNS,
    DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS,
    mask_url_credentials=True,
)

TOKEN = "tok_" + "Zx81Qm7Lp2Vb9Nc4Rt6Yh3Kd"
PROSE = "Request to the upstream service failed after 3 retries, giving up now. "


@dataclasses.dataclass(frozen=True)
class Order:
    id: int
    customer: str
    items: list
    note: str


def make_frame():
    def handler(request_id, payload):
        user_id = 4821
        retries = 3
        status = "failed"
        url = "https://api.example.com/v1/orders/4821?expand=items"
        message = PROSE
        tags = ["checkout", "eu", "mobile", "retry", "v2"]
        order = Order(4821, "Ada Lovelace", [{"sku": "A-1", "qty": 2}], "leave at door")
        headers = [("content-type", "application/json"), ("authorization", "Bearer " + TOKEN)]
        context = {"region": "eu-west-1", "attempt": retries, "trace": "4bf92f3577b34da6"}
        raise ValueError("boom")

    try:
        handler("req-1", {"order": 4821, "items": 2})
    except ValueError:
        tb = sys.exc_info()[2]
        while tb.tb_next:
            tb = tb.tb_next
        return tb.tb_frame


FRAME = make_frame()

CASES = {
    "plain short string": lambda: _mask_value("request failed: upstream timeout", CONFIG),
    "plain 2 KB string": lambda: _mask_value((PROSE * 28)[:2000], CONFIG),
    "header pair list": lambda: _mask_value(
        [("content-type", "application/json"), ("authorization", "Bearer " + TOKEN)], CONFIG
    ),
    "ASGI scope": lambda: _mask_value(
        {
            "type": "http",
            "path": "/api/orders",
            "headers": [(b"host", b"api.example.com"), (b"accept", b"*/*"), (b"user-agent", b"bench/1.0")]
            + [(b"x-request-id", b"4bf92f3577b34da6")] * 6
            + [(b"authorization", ("Bearer " + TOKEN).encode())],
        },
        CONFIG,
    ),
    "dict with 40 string keys": lambda: _mask_value({f"field_{i}": f"value {i}" for i in range(40)}, CONFIG),
    "frame of 11 locals": lambda: _serialize_frame_variables(FRAME, VariableSizeLimiter(), CONFIG),
}

client = Posthog("phc_fake", host="http://127.0.0.1:9", capture_exception_code_variables=True)
client.capture = lambda *a, **k: None


def nested(depth):
    local_url = "postgresql://app:fake-pass@db.example.com/app"
    local_header = "Bearer " + TOKEN
    if depth == 0:
        raise RuntimeError("deep failure")
    nested(depth - 1)


def capture_e2e():
    try:
        nested(4)
    except RuntimeError as e:
        client.capture_exception(e)


CASES["capture_exception, 6 frames"] = capture_e2e

NUMBERS = {"capture_exception, 6 frames": 300, "frame of 11 locals": 2000}

out = {"_posthog_file": posthog.__file__}
for name, fn in CASES.items():
    number = NUMBERS.get(name, 5000)
    fn()  # warm caches, e.g. compiled patterns
    times = timeit.repeat(fn, repeat=7, number=number)
    out[name] = [t / number for t in times]
print(json.dumps(out))

📝 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

The changeset was written by hand in the sampo add format: .sampo/changesets/mask-authorization-credentials.md.

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

  • Claude Code with Claude Opus 5.5 (claude-opus-5-5). Skills: writing-pr-descriptions.

  • The scope is limited on purpose to Bearer/Basic and sig. Hex-only keys and Discord webhook URLs also pass the current rules, and stay out of this PR.

  • Credentials are matched by value, not by teaching the list walker about (name, value) pairs. The value rule also covers neutral locals and reprs, and a pair rule would not.

  • A synthetic harness replayed each shape through released SDK versions with generated fake values. It found these gaps in 7.63.0 and confirmed this branch masks them.

  • Review round: a local QA pass and the Greptile P1 thread found lowercase-only, separator and short Basic credentials passing through. All three are fixed. A second bot round found a pass-order bypass and prose loss. Both are fixed: URLs go first, and lowercase words of up to 15 letters count as prose. Wider signed-URL parameters (X-Amz-Signature, Signature) stay out of scope.

🤖 Generated with Claude Code

https://claude.ai/code/session_01MxaTpjkJ3QxjaCSrYxXFHW

@ablaszkiewicz ablaszkiewicz self-assigned this Oct 6, 2026
@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-06T12:57:56.274120+00:00
Duration: 259876ms

✅ 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 ✅ 517ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 510ms
Required Headers.Has Authorization Bearer Header ✅ 510ms
Required Headers.Has Content Type Json ✅ 512ms
Required Headers.Has Posthog Sdk Info Format ✅ 510ms
Required Headers.Has Posthog Attempt Header ✅ 511ms
Required Headers.Has Posthog Request Id ✅ 510ms
Required Headers.Has Posthog Request Timestamp ✅ 510ms
Required Headers.Has User Agent ✅ 511ms
Body Format.Body Has Created At And Batch ✅ 510ms
Body Format.No Api Key In Body ✅ 511ms
Body Format.No Sent At In Body ✅ 511ms
Event Format.Event Has Required Root Fields ✅ 510ms
Event Format.Event Uuid Is Valid ✅ 510ms
Event Format.Event Timestamp Is Rfc3339 ✅ 510ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 517ms
Event Format.Distinct Id Is String ✅ 510ms
Event Format.Distinct Id At Root Not Properties ✅ 510ms
Event Format.Custom Properties Preserved ✅ 511ms
Event Format.Set Properties Preserved ✅ 510ms
Event Format.Set Once Properties Preserved ✅ 510ms
Event Format.Groups Properties Preserved ✅ 510ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 511ms
Event Format.Event Has Required Root Fields Batch ✅ 514ms
Event Format.Event Uuid Is Valid Batch ✅ 514ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 514ms
Event Format.Distinct Id Is String Batch ✅ 514ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 514ms
Event Format.Custom Properties Preserved Batch ✅ 513ms
Event Format.Set Properties Preserved Batch ✅ 515ms
Event Format.Set Once Properties Preserved Batch ✅ 514ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 513ms
Batch Behavior.Multiple Events In Single Batch ✅ 519ms
Batch Behavior.Batch Envelope Smoke ✅ 515ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 507ms
Batch Behavior.Flush At Triggers Batch ✅ 1011ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 510ms
Deduplication.Generates Unique Uuids ✅ 518ms
Deduplication.Different Events Same Content Different Uuids ✅ 512ms
Deduplication.Preserves Uuid On Retry ✅ 6517ms
Deduplication.Preserves Timestamp On Retry ✅ 6520ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6523ms
Deduplication.No Duplicate Events In Batch ✅ 519ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 510ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13528ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6520ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3020ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6519ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 511ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 515ms
Response Format Validation.Success No Retry After When All Ok ✅ 513ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1516ms
Response Format Validation.Success No Retry After When Drop Only ✅ 512ms
Response Format Validation.Response Echoes Request Id ✅ 511ms
Retry Behavior.Retries On 408 ✅ 6520ms
Retry Behavior.Retries On 500 ✅ 6516ms
Retry Behavior.Retries On 503 ✅ 8524ms
Retry Behavior.Retries On 504 ✅ 6519ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3517ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11521ms
Retry Behavior.Does Not Retry On 400 ✅ 2514ms
Retry Behavior.Does Not Retry On 401 ✅ 2513ms
Retry Behavior.Does Not Retry On 402 ✅ 2514ms
Retry Behavior.Does Not Retry On 413 ✅ 2514ms
Retry Behavior.Does Not Retry On 415 ✅ 2514ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2514ms
Retry Behavior.Implements Backoff ✅ 22532ms
Retry Behavior.Max Retries Respected ✅ 22535ms
Partial Batch Handling.Handles 200 Full Success ✅ 2512ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3517ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3516ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3513ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6517ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6521ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6520ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6517ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6517ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6517ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8521ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3514ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3518ms
Compression.Sends Gzip Content Encoding ✅ 511ms
Compression.No Content Encoding When Disabled ✅ 510ms
Compression.Compressed Body Is Decompressible ✅ 510ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2512ms
Event Options.Cookieless Mode Override ✅ 510ms
Event Options.Disable Skew Correction Override ✅ 511ms
Event Options.Process Person Profile Override ✅ 510ms
Event Options.Product Tour Id Override ✅ 510ms
Event Options.Unset Options Omitted ✅ 510ms
Event Options.Options Override In Batch ✅ 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 510ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 510ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 510ms

Capture_Ai Tests

✅ 5/5 tests passed

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

Feature_Flags Tests

✅ 17/17 tests passed

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

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 70ms
Versioned Boolean Matching.Matching Version 1 ✅ 67ms
Versioned Boolean Matching.Matching Version 2 ✅ 67ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 35ms

@greptile-apps

greptile-apps Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Retrigger

[Medium risk] Adds credential masking to exception reporting.

The PR appears safe to merge, though authorization matching can unnecessarily remove diagnostic prose.

Reviews (2) · Last reviewed commit: "fix: mask short basic credentials in cod..."

Comment thread posthog/exception_utils.py Outdated
@ablaszkiewicz
ablaszkiewicz marked this pull request as ready for review October 6, 2026 11:30
@ablaszkiewicz
ablaszkiewicz requested a review from a team as a code owner October 6, 2026 11:30
Comment thread posthog/exception_utils.py Outdated
Comment thread posthog/exception_utils.py Outdated
@veria-ai

veria-ai Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@ablaszkiewicz
ablaszkiewicz merged commit e3cfe17 into main Oct 6, 2026
44 checks passed
@ablaszkiewicz
ablaszkiewicz deleted the ab/fix/mask-auth-header-code-variables branch October 6, 2026 15:12
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