Skip to content

fix(sanitizer): linear KEY=value redaction — the #1661 CPU spin is the regex, not the pipe - #1670

Merged
obasilakis merged 2 commits into
devfrom
feature/1661-leaked-reader-thread-spin
Jul 17, 2026
Merged

obasilakis merged 2 commits into
devfrom
feature/1661-leaked-reader-thread-spin

Conversation

@dolho

@dolho dolho commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Fixes #1661. The spinning thread was never blocked on a pipe — it was computing. That is why the #728 and #1502 pipe fixes are present in the affected image and do not cover this path.

Related to #1661

Root cause

The sanitizers' patterns describe variable names (.*TOKEN.* = "a name containing TOKEN"), but stage 3 composed each one into a line-scanning regex:

(.*TOKEN.*)=(["\']?)([^\s"\']+)\2

Two unbounded .* around a literal, re-scanned from every offset of the line. Measured on this branch:

line size sanitize_text (before)
1 KB 45 ms
2 KB 274 ms
4 KB 1 501 ms
8 KB 8 572 ms

~5.7× per 2× input (≈ n^2.5) → ~10 CPU-minutes for the 44 KB tool-result line named in the report. .*TOKEN.* alone accounts for 6.8s of the 8 KB figure.

The headless reader calls sanitize_dict(raw_msg) on every parsed message (headless_executor.py:610), so one 44 KB tool result puts the reader thread into a ~10-minute C-level regex burn. That single fact explains every observation in the report:

Reported symptom Explanation
100% of one core, R, wchan=0, no syscall, memory flat a regex in C, not I/O
"Reader thread(s) still busy after process exit" busy, literally — computing
kill group → 30s wait → 90s budget → "leaked" (#728/#1502) those make a blocked reader EOF; this one was never blocked
"Result event lost (stdout pipe race) → soft success" the result line wasn't lost — the reader hadn't reached it yet
spin persists with no active task, then self-clears the regex finishes
recurs on the next large-output task; docker restart clears it next big line, same burn

Fix

One linear pass: find key=value pairs with a delimiter-bounded key, then test the (short) key against the name patterns.

line size before after
8 KB 8 572 ms 0.4 ms
44 KB ~10 min 1.2 ms
500 KB — 18 ms
200 KB single unbroken token — 11.7 ms

The reader's actual per-message call, sanitize_dict on a 44 KB tool_result: 1.6 ms.

It also fixes a security bug

The greedy .* spans to the last = on the line, so on a multi-pair line the old code redacted the wrong pair and left the real credential in place:

GH_TOKEN=supersecret PLAIN=harmless
  old -> GH_TOKEN=supersecret PLAIN=***REDACTED***      # leaks the token
  new -> GH_TOKEN=***REDACTED*** PLAIN=harmless

env: ANTHROPIC_API_KEY=sk-ant-realkey123456 LOG_LEVEL=debug
  old -> ... ANTHROPIC_API_KEY=sk-ant-realkey123456 LOG_LEVEL=***REDACTED***
  new -> ... ANTHROPIC_API_KEY=***REDACTED*** LOG_LEVEL=debug

Stages 1–2 (known env values; value-shaped patterns like sk-ant-[…]{20,}) mask this for many real keys, which is why it went unnoticed — the exposure is a credential whose value matches nothing known, on a line with 2+ pairs.

Suffix matching is preserved deliberately. The old regex could start matching mid-token, so ANTHROPIC_.* redacts MY_ANTHROPIC_KEY=x. A fullmatch rewrite would quietly redact less — a leak, not a speedup — so the key test is anchored with \Z to reproduce the old reach exactly.

Scope

  • Both copies fixed. The backend layer has the identical flaw and sanitizes execution logs before DB write, so it burned backend CPU on the same input.
  • Pattern lists untouched. They differ (agent-side is a superset: DB_.*, REDIS_.*, …), so MY_DB_PASS=x is redacted agent-side but not backend-side. That asymmetry predates this issue and is now pinned by a test — widening a list changes what gets redacted and belongs in its own change.
  • Not addressed (the upstream trigger, which the report itself suggests isolating): the stdio MCP child interleaving on claude's stdout pipe. This fix removes the CPU burn and the drain/leak/soft-success cascade; the interleave remains its own fault.

Verification

31 new tests (tests/unit/test_1661_sanitizer_linear.py) covering both copies: 44 KB budget, a shape assertion that 8× input isn't ~300× time (the old curve), the giant-unbroken-token case, multi-pair redaction, and the single-pair behaviour contract captured from the pre-fix implementation. 510 passing across the sanitizer/executor suites; the 117 existing sanitizer tests pass unchanged.

Along the way I also reproduced the safe_close_pipes ↔ readline() deadlock the log line mentions (close() never returns while a reader is mid-readline) — real, but it leaves the reader blocked at 0% CPU, so it is not the spin. Noting it as a separate latent issue rather than folding it in.

🤖 Generated with Claude Code

… regex, not the pipe (#1661)

The spinning thread was never blocked on a pipe. It was computing.

The sanitizers' name patterns describe VARIABLE NAMES (`.*TOKEN.*` = "a name
containing TOKEN"), but stage 3 composed each one into a LINE-scanning regex:

    (.*TOKEN.*)=(["\']?)([^\s"\']+)\2

Two unbounded `.*` around a literal, re-scanned from every offset of the line.
Measured cost on this branch: ~6.8s for `.*TOKEN.*` alone on an 8 KB line, and
~n^2.5 growth — about 10 CPU-minutes on the 44 KB tool-result lines named in the
report.

The headless reader calls `sanitize_dict(raw_msg)` on every parsed message
(headless_executor.py:610), so ONE 44 KB tool result put the reader thread into
a ~10-minute C-level regex burn. That single fact explains every symptom:

- 100% of one core, R state, `wchan=0`, no syscall, memory flat — a regex, not I/O.
- "Reader thread(s) still busy after process exit" — busy, literally: computing.
- Drain kills the group, waits 30s, blows the 90s budget, declares the reader
  leaked (#728/#1502) — those fixes make a BLOCKED reader EOF, and this reader
  was never blocked, which is why the spin survived them.
- "Result event lost (stdout pipe race) — recovering as soft success": the
  result line was not lost, the reader had not reached it yet.
- Spin persists with no active task, then "self-clears": the regex finishes.
- Recurs on the next large-output task; `docker restart` clears it.

Fix: one linear pass. Find `key=value` pairs with a delimiter-bounded key, then
test the (short) key against the name patterns. 8 KB: 8572ms -> 0.4ms. 44 KB:
~10min -> 1.2ms. 500 KB: 18ms. A 200 KB unbroken token stays linear too (the
lookbehind stops the engine retrying every offset inside it).

It also fixes a SECURITY bug the greedy `.*` caused: spanning to the LAST `=` on
the line, the old code redacted the WRONG pair on a multi-pair line and left the
real credential in place —

    GH_TOKEN=supersecret PLAIN=harmless
    old -> GH_TOKEN=supersecret PLAIN=***REDACTED***      # leaks the token
    new -> GH_TOKEN=***REDACTED*** PLAIN=harmless

Stages 1-2 (known values, value-shaped patterns) mask this for many real keys,
which is why it went unnoticed. Suffix matching is preserved deliberately: the
old regex could start matching mid-token, so `ANTHROPIC_.*` redacts
`MY_ANTHROPIC_KEY=x`; a `fullmatch` rewrite would silently redact LESS, which is
a leak rather than a speedup.

Both copies carry the flaw and both are fixed (the backend layer sanitizes
execution logs before DB write, so it burned backend CPU on the same input).
Their pattern lists differ (agent-side is a superset) — untouched here and
pinned by a test, since widening one changes what gets redacted.

Not addressed (upstream trigger, worth isolating separately per the report): the
stdio MCP child interleaving on claude's stdout pipe.

Related to #1661

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…1661)

CodeQL flags `py/polynomial-redos` on `_KV_LINE_RE`: its model does not
account for the lookbehind, so it assumes the key can be retried at every
offset inside a long non-matching run — which would indeed be quadratic.

Measured across 11 adversarial shapes (both strings CodeQL names, unterminated
quotes, trailing '=', missing values, all-'='): every one is linear, 4x input ->
~4x time, worst case 7.4ms at 32 KB. The two CodeQL strings run in ~1ms at 64 KB.

Rather than dismiss the alert on assertion, the adversarial cases are now tests,
and the code says why the lookbehind is load-bearing — a later 'simplification'
of it would reintroduce exactly the pathology this issue fixed, and now fails CI
instead.

Related to #1661

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@dolho

dolho commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

CodeQL py/polynomial-redos (#237) — investigated, not waved through

CodeQL flagged the new _KV_LINE_RE as a high-severity ReDoS. Given this PR exists because of a regex complexity pathology, that got a real investigation rather than a dismissal.

It is a false positive in effect, and here is why: the lookbehind (?<![^\s"'=]) means the key can only start after a delimiter, so the engine cannot retry ([^\s"'=]+)= at every offset inside a long non-matching run — which is the quadratic shape CodeQL assumes. Its model does not account for lookbehinds.

Measured, both strings CodeQL names plus 9 more adversarial shapes:

input 2 KB 8 KB 32 KB
!*n (CodeQL) 0.0 ms 0.1 ms 0.6 ms
!= + !=!*n (CodeQL) 0.0 ms 0.0 ms 0.1 ms
unterminated quote K="+x*n 0.1 ms 0.3 ms 1.0 ms
trailing =, missing values, all-=, quoted pairs, huge value — — ≤ 7.4 ms

Every shape: 4× input → ~4× time. Worst case 7.4 ms at 32 KB (vs 8 572 ms for an 8 KB line before this PR).

What I did instead of just dismissing it:

  1. The adversarial cases — including CodeQL's two strings — are now tests (test_adversarial_inputs_stay_linear, 64 KB budget). If someone later "simplifies away" the lookbehind, they reintroduce the exact pathology this issue is about and CI fails instead of a reviewer having to remember this thread.
  2. The code says the lookbehind is load-bearing and why.
  3. Only then dismissed alert bug: Slack file download fails — get_bot_token called with wrong argument #237 as a false positive, citing the tests.

Happy to restructure the regex instead if a reviewer prefers a shape the analyser can prove — the trade is a less faithful match extent (the quote handling needs a backreference or an alternation) for a green analyser, and I judged the executable proof the better deal.

@obasilakis obasilakis 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.

Verified the diagnosis independently rather than taking the numbers on trust — it holds.

Reproduced the old cost curve from scratch: 8 KB = 8533 ms (PR claims 8572 ms), growth ~6.8x per 2x input, so the 44 KB tool-result line is genuinely CPU-minutes. New path at 44 KB = 1.2 ms (PR claims 1.2 ms). Confirmed sanitize_dict(raw_msg) runs inside the reader loop (headless_executor.py:610, same shape in claude_code.py:358), which is what puts the burn on the reader thread and explains every observation in the report — state R, wchan=0, no syscall, memory flat, self-clears, recurs on the next big output. The re-diagnosis is correct and #1661's own suggested area was a red herring.

Also confirmed the lookbehind is load-bearing rather than folklore: removing it takes 64 KB from 1.8 ms to 23404 ms (cleanly quadratic). The 'do not simplify away' comment is earned and should stay.

Two non-blocking notes:

  1. The comment 'Anchoring with \Z reproduces exactly that' overclaims. \Z preserves reach within a token, but the old .* also spanned spaces and quotes across tokens. A differential run over a realistic corpus shows 9/19 lines redact less. Most of that is accidental over-redaction worth losing (the old net only ever hit the LAST pair on the line, so it was never a real property). But "GH_TOKEN"=v and GH_TOKEN ="v" are genuinely-sensitive key names the old code reliably redacted and the new one never will. Rare formats, not worth blocking — but the comment asserts an exactness that doesn't hold, and the next maintainer will trust it. Worth softening to state the actual boundary (delimiter-bounded key).

  2. The two copies now share ~50 lines of scan logic with no parity guard. test_the_two_copies_carry_different_pattern_lists pins the list asymmetry nicely, but nothing pins that _KV_LINE_RE / _is_sensitive_kv_key / _redact_kv_match stay in sync — and this bug existed identically in both copies precisely because they drift silently.

On the declined residuals: agreed on both calls. Post-fix the interleave degrades to a parse warning and the safe_close_pipes deadlock parks a thread at 0% CPU — neither reproduces the P1 symptom. Leaving them in the PR body rather than inflating the backlog; the interleave will re-surface on its own with better evidence than we could write today.

158 tests pass locally (31 new + 127 existing unchanged).

@obasilakis
obasilakis merged commit 7670d6e into dev Jul 17, 2026
20 checks passed
dolho added a commit that referenced this pull request Aug 26, 2026
…1670 fix (#2398)

py-spy caught this 14 times across three agents (cmo, copywriter, cornelius),
every dump on the same stack:

    <genexpr> (credential_sanitizer.py)      <- the any(...) in this function
    _is_sensitive_kv_key
    _redact_kv_match -> sanitize_text -> sanitize_dict (recursive)
    sanitize_subprocess_line -> read_stdout (headless_executor)

#1670 made the LINE scan linear (#1661) and left the KEY test quadratic:
re.search(r'(?:.*TOKEN.*)\Z', key) retries the leading .* from every offset,
O(n^2) in key length. Measured on 3.13: 4 KB = 0.32s, 44 KB = 40s — for ONE
key, per match, per line, on a thread holding the GIL. That is the pegged core.

What made a quadratic test look harmless was a wrong docstring. It called the
key "a short KEY= name". It is not: the key is whatever preceded an "=" in
_KV_LINE_RE's unbounded capture — and the stack above reaches it from
stream-json tool RESULTS via recursive sanitize_dict, so multi-KB "keys" are
the normal case rather than an adversarial one.

Every pattern is ".*LITERAL.*" or "LITERAL.*", and under .search() with a
trailing \Z both mean exactly "the key CONTAINS this literal" — so the test is
substring containment. Linear, C-level, no backtracking.

VERDICTS ARE UNCHANGED, and that is the part that mattered to get right: a
faster check that redacts LESS is a credential leak. Pinned against the old
implementation as an oracle — 5,420 keys on the backend copy, 9,607 on the
agent copy, zero disagreements — including the deliberate #1670 suffix
semantics (DB_ still redacts MY_DB_PASSWORD).

The literals are DERIVED from the patterns, and the derivation REFUSES anything
that is not a plain literal, so a future pattern needing real regex fails loudly
at import rather than being silently reduced to a check that redacts less.

BOTH copies (Invariant #5). The two are vendored in shape, not byte-identically
— the agent list is SENSITIVE_VAR_PATTERNS with 30 entries to the backend's 13
— and every py-spy dump was taken in the AGENT copy, so a backend-only fix
would have left all 14 burns exactly where they were.

  backend copy:      44 KB key  40s -> 0.00035s  (112,000x)
  agent-server copy: 44 KB key  44s -> 0.00066s  ( 67,000x)

727 passed across the sanitizer, #1661 and #1670 suites.

Related to #2398

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Aug 26, 2026
…f-review)

Two findings from reviewing my own diff.

[C1] The derivation guard used `re.escape(body) != body` to mean "is this a
plain literal". `re.escape` also escapes `-`, which is NOT a metacharacter
outside a character class — so adding a perfectly literal pattern like
`.*API-KEY.*` (or `X-AUTH-TOKEN.*`, a header-shaped name) would have raised at
import. This module is imported everywhere, so that is a boot crash for the
whole platform on a benign pattern addition. Loud, but "loud" there means
"nothing starts".

Replaced with an explicit safe set, [A-Za-z0-9_-]+, which accepts every current
pattern and any plausible env-var or header name while still refusing real
metacharacters: `A.B` and `TOKEN+` remain rejected, pinned by tests.

[I2] `_sensitive_key_re` in the backend copy compiled the very regexes this
change stopped using, and nothing referenced it any more. Dead code is a style
note anywhere else; here it is the specific artifact that let this bug survive
#1670 — a module-level name that looks like the live check and is not, sitting
next to the one that is. Removed, with a test asserting neither it nor
_SENSITIVE_KEY_SUFFIX_RE comes back.

Also verified during the review, and worth recording as NOT findings: the agent
copy's other two uses of the pattern list (`_sensitive_var_re` in
`get_credential_values`) run `.match()` against ENV VAR NAMES — anchored at
offset 0 and genuinely short — so they are not a third instance of the
`.search`-every-offset shape. And the old/new verdicts were re-checked for
Unicode divergence (ligatures, dotless i); none observed.

706 passed. Equivalence re-run after the change: 7,566 backend + 9,606 agent
keys, zero disagreements.

Related to #2398

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Aug 26, 2026
…f-review)

Two findings from reviewing my own diff.

[C1] The derivation guard used `re.escape(body) != body` to mean "is this a
plain literal". `re.escape` also escapes `-`, which is NOT a metacharacter
outside a character class — so adding a perfectly literal pattern like
`.*API-KEY.*` (or `X-AUTH-TOKEN.*`, a header-shaped name) would have raised at
import. This module is imported everywhere, so that is a boot crash for the
whole platform on a benign pattern addition. Loud, but "loud" there means
"nothing starts".

Replaced with an explicit safe set, [A-Za-z0-9_-]+, which accepts every current
pattern and any plausible env-var or header name while still refusing real
metacharacters: `A.B` and `TOKEN+` remain rejected, pinned by tests.

[I2] `_sensitive_key_re` in the backend copy compiled the very regexes this
change stopped using, and nothing referenced it any more. Dead code is a style
note anywhere else; here it is the specific artifact that let this bug survive
#1670 — a module-level name that looks like the live check and is not, sitting
next to the one that is. Removed, with a test asserting neither it nor
_SENSITIVE_KEY_SUFFIX_RE comes back.

Also verified during the review, and worth recording as NOT findings: the agent
copy's other two uses of the pattern list (`_sensitive_var_re` in
`get_credential_values`) run `.match()` against ENV VAR NAMES — anchored at
offset 0 and genuinely short — so they are not a third instance of the
`.search`-every-offset shape. And the old/new verdicts were re-checked for
Unicode divergence (ligatures, dotless i); none observed.

706 passed. Equivalence re-run after the change: 7,566 backend + 9,606 agent
keys, zero disagreements.

Related to #2398

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Aug 26, 2026
hotfix(sanitizer): the key test was still quadratic — one call below the #1670 fix (#2398)
pull Bot pushed a commit to bryanwills/trinity that referenced this pull request Aug 26, 2026
…bilityai#1670 fix (Abilityai#2398)

HOTFIX ONTO MAIN: the burn is happening on client instances, which run main.
Both sanitizer copies on main carry the vulnerable code, and the agent copy's
_is_sensitive_kv_key sits at line 150 — exactly the line in every py-spy dump.

A py-spy watchdog caught this 14 times across three agents (cmo, copywriter,
cornelius), every dump on the same stack:

    <genexpr> (credential_sanitizer.py)      <- the any(...) in this function
    _is_sensitive_kv_key
    _redact_kv_match -> sanitize_text -> sanitize_dict (recursive)
    sanitize_subprocess_line -> read_stdout (headless_executor)

Abilityai#1670 made the LINE scan linear (Abilityai#1661) and left the KEY test quadratic:
re.search(r'(?:.*TOKEN.*)\Z', key) retries the leading .* from every offset,
O(n^2) in key length. Measured on main's tree, Python 3.13:

    backend copy (13 patterns):      44 KB key  40.9s -> 0.00035s  (116,000x)
    agent-server copy (30 patterns): 44 KB key  44.4s -> 0.00072s  ( 62,000x)

Forty seconds of CPU for ONE key, per match, per line, on a thread holding the
GIL. That is the pegged core, and why the event loop stopped accepting.

What made a quadratic test look harmless was a wrong docstring. It called the
key "a short KEY= name". It is not: the key is whatever preceded an "=" in
_KV_LINE_RE's unbounded capture — and the dumps show it arriving from
stream-json tool RESULTS through recursive sanitize_dict, so multi-KB "keys"
are the normal case rather than an adversarial one.

Every pattern is ".*LITERAL.*" or "LITERAL.*", and under .search() with a
trailing \Z both mean exactly "the key CONTAINS this literal" — so the test is
substring containment. Linear, C-level, no backtracking.

VERDICTS ARE UNCHANGED, which is the half that mattered: a faster check that
redacts LESS is a credential leak. Pinned against the old implementation as an
oracle over 17,172 keys across both copies (7,566 + 9,606), zero disagreements,
including the deliberate Abilityai#1670 suffix semantics (DB_ still redacts
MY_DB_PASSWORD).

The literals are DERIVED from the patterns, and the derivation REFUSES anything
that is not a plain literal, so a future pattern needing real regex fails loudly
at import rather than being silently reduced to a check that redacts less.

BOTH copies (Invariant #5) — vendored in shape, not byte-identically: the agent
list is SENSITIVE_VAR_PATTERNS with 30 entries to the backend's 13. Every dump
was taken in the AGENT copy, so a backend-only fix would have left all 14 burns
exactly where they were. Existing agents need a base-image rebuild.

704 passed across the sanitizer, Abilityai#1661 and Abilityai#1670 suites on main.

Related to Abilityai#2398

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Sep 2, 2026
…edge (#2455)

#1661/#1670 made the LINE scan linear and said so. Neither bounded the KEY
that scan hands to _is_sensitive_kv_key. `_KV_LINE_RE`'s key group is
`[^\s"'=]+` — unbounded — and base64 pads with `=`, so a 37 KB base64 run
inside a tool_result arrives here AS A KEY. Each of the nine `.*X.*` patterns
is then `.search()`ed over it, and because `search` retries at every offset
while `.*` re-scans forward from each, the cost is O(n^2).

Measured on the pre-fix code, both copies:

    18 KB line ->  5.6 s        40 KB -> 35.3 s
    37 KB line -> 28.3 s        (the #2455 09-02 transcript's longest
                                 line was exactly 37 KB)

`re` never releases the GIL mid-call, so those are not "slow", they are the
whole process STOPPED. That is the wedge, and it explains the parts of #2455
that three previous fixes could not:

  - the event loop going dark ~10 min BEFORE claude finished: the reader
    thread holds the GIL through each line (measured 1.4 s of loop stall
    from ONE 16 KB line);
  - the loop's own asyncio timeouts not firing while it was frozen, so the
    run was only killed at the outer timeout hours later;
  - `claude` staying alive an hour after its final message: the reader
    stops draining the pipe, the 64 KB buffer fills, and claude blocks in
    write() and cannot exit;
  - the CPU flip between the two occurrences — reader-side (08-31) is the
    per-line pass, main-thread-side (09-02) is _finalize_headless_result,
    which re-sanitizes the whole transcript ON the event loop thread;
  - fleet-wide blast radius: the backend copy is identical and its
    `sanitize_execution_log` runs on the FastAPI loop inside
    `apply_result`, so ONE agent's big line stalls every agent and user.

The bound belongs on the key rather than in the pattern list because it holds
for any pattern added later: an environment-variable name is short, so
anything this long cannot be a credential NAME. Nothing stops being redacted —
a secret in that text is still caught by VALUE (the sk-/ghp_/xoxb-/Bearer
patterns and the known-credential replacement both scan the full text
independently); only the name heuristic, which could never have matched, is
skipped. Pinned by a test.

After, both copies, every input class linear (ratio ~4 for 4x input):

    37 KB line: 28.3 s -> 0.4 ms      800 KB: ~hours -> 7.7 ms
    worst case across 10 adversarial shapes: 11.2 ms

170 existing sanitizer tests unchanged and green, so no redaction semantics
moved. Full unit suite: 6510 passed (the one IPv6-origin failure is
pre-existing on unmodified dev).

Related to #2455.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01NLfHNPtB5UCMk4LonZiJux
vybe pushed a commit that referenced this pull request Oct 8, 2026
… sensitive word (#3311)

Merge-train finding on #3335: walking the KEY=value chain put keys under
the containment key rule (`.*AUTH.*`, `.*TOKEN.*`, ...) that dev never
examined, because they sat inside a harmless pair's value. Everyday query
parameters were redacted, and since a sensitive value runs to whitespace
each one took the rest of the URL with it:

  .../issues?q=is:open&author=bob&page=2
  ?page=2&tokens_used=10&model=x
  ?sort=asc&passwordless=true&lang=en

AC1 says the harmless pairs are kept.

For a chained key only, a closed list of harmless words is blanked out
before the same containment test: AUTHOR... (not authoriz/authoris),
PASSWORDLESS, SECRETARY/-IES/-IAT, TOKENIZ/TOKENIS, and the token-count
names (max/total/input/output/prompt/completion_tokens,
token(s)_used/_count/_limit/_usage). A word list rather than a
word-boundary rule, because a boundary rule leaks an open class
(secretkey, authkey, tokenvalue, passwords, credentials, authorization);
with the list, the remainder is still tested, so author_token and
max_tokens_secret still redact.

"Chained" means the key sits inside what #1670 consumed as a harmless
pair's value: after `=`, `&`, `;` or `,`, with only value characters back
to the previous `KEY=`. Every key dev already tested - one starting its
run, following a bare word, or following a redacted pair - keeps plain
containment, so this never redacts less than dev did. The gap check scans
only the text between two consecutive keys, so the walk stays linear.

Both copies (backend and agent-server) carry the identical change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vybe pushed a commit that referenced this pull request Oct 8, 2026
… pair (#3311) (#3335)

* fix(sanitizer): redact a sensitive KEY=value chained after a harmless pair (#3311)

#1670's single KEY=value regex took the key up to the first `=` and the value
up to whitespace, so in `user=a&password=X` the harmless `user` pair consumed
`a&password=X` and the sensitive pair was never examined (same for
`?client=me&access_token=X` and `--env=GITHUB_TOKEN=X`). The pre-#1661 regex
redacted all of these.

_KV_LINE_RE now matches only `KEY=` (the key also stops at `&`, `;` and `,`),
and _redact_kv_pairs walks the keys in order. A harmless key consumes nothing,
so the next key in the chain is still checked. Only a sensitive key takes its
value, in the old up-to-whitespace shape, so a secret containing a separator
is never split and partly leaked, and the Google consent-link exemption still
sees the whole URL. The search only moves forward and the lookbehind is kept,
so the pass stays linear. Applied identically to the agent-server copy.

Red with the fix reverted: TestChainedPairs (both copies) and
test_ec_input_hardening_edges::TestSanitizerBoundaries::
test_a_sensitive_pair_chained_after_a_harmless_one_is_redacted (xfail removed).

Fixes #3311

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(sanitizer): keep harmless chained pairs whose key only contains a sensitive word (#3311)

Merge-train finding on #3335: walking the KEY=value chain put keys under
the containment key rule (`.*AUTH.*`, `.*TOKEN.*`, ...) that dev never
examined, because they sat inside a harmless pair's value. Everyday query
parameters were redacted, and since a sensitive value runs to whitespace
each one took the rest of the URL with it:

  .../issues?q=is:open&author=bob&page=2
  ?page=2&tokens_used=10&model=x
  ?sort=asc&passwordless=true&lang=en

AC1 says the harmless pairs are kept.

For a chained key only, a closed list of harmless words is blanked out
before the same containment test: AUTHOR... (not authoriz/authoris),
PASSWORDLESS, SECRETARY/-IES/-IAT, TOKENIZ/TOKENIS, and the token-count
names (max/total/input/output/prompt/completion_tokens,
token(s)_used/_count/_limit/_usage). A word list rather than a
word-boundary rule, because a boundary rule leaks an open class
(secretkey, authkey, tokenvalue, passwords, credentials, authorization);
with the list, the remainder is still tested, so author_token and
max_tokens_secret still redact.

"Chained" means the key sits inside what #1670 consumed as a harmless
pair's value: after `=`, `&`, `;` or `,`, with only value characters back
to the previous `KEY=`. Every key dev already tested - one starting its
run, following a bare word, or following a redacted pair - keeps plain
containment, so this never redacts less than dev did. The gap check scans
only the text between two consecutive keys, so the walk stays linear.

Both copies (backend and agent-server) carry the identical change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: trinity-ability <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

3 participants