Skip to content

fix(#740): strip haiku from every document of an untrusted project config - #744

Merged
fdaviddpt merged 4 commits into
mainfrom
fix/740
Sep 25, 2026
Merged

fdaviddpt merged 4 commits into
mainfrom
fix/740

Conversation

@fdaviddpt

@fdaviddpt fdaviddpt commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Closes #740.

Found by the release auditor on v0.33.0..HEAD, ranked discloses, and blocking v0.34.0.

Problem

#726 stripped the untrusted project layer's haiku block with jq -s '(.[-1] |= del(.haiku)) | ...'. -s flattens every document from every source into one array, so .[-1] only reached the last document. A project .remember/config.json holding two whitespace-concatenated JSON documents, with haiku.oauth_token / haiku.anthropic_api_key in the first, kept that block and passed it to the nested summarizer.

Fix

  • jq path: when the project layer is untrusted, it is first sanitized by a separate plain call, jq -c 'del(.haiku)' "$_project_cfg" > <tmp>. That call applies to each document, so it covers multi-document and empty files. The original jq -s reduce, back to its pre-security(scan-20260918): repo-local .remember/config.json selects summarizer credential and key-stripping policy #726 shape, then merges bundled + user + the sanitized temp file. No path comparison, no --slurpfile, no /dev/null: both calls use only plain file arguments, the form already proven on Windows.
  • Fail closed: if sanitizing fails (mktemp, unreadable file, malformed JSON, or a non-object document), only the project layer is dropped. Bundled + user still merge.
  • no-jq Python fallback: parses every document of the untrusted file (raw_decode loop) and strips haiku from each one. An unreadable project file is skipped instead of crashing the whole merge.
  • Corrected the overclaims in changelog.d/726.fixed.md and docs/git-backup-security.md §5. Added changelog.d/740.security.md. Updated the byte-pin and divergence tuples in tests/test_case_divergence_298.py. The spawn measurement goes 17 → 18: one extra jq call, only when an untrusted project config is present.

History on this PR

  • efb45b3 used --slurpfile + /dev/null. It failed on all 4 Windows legs: the jq call errored and fell back to bundled-only, so every Windows user would have lost their project and user config with no error. Caught by test_config_flatten_cache_668.py:645.
  • An earlier intermediate design matched input_filename against the last document's file. It was rejected because an empty project config makes it strip a trusted layer's haiku, and a test pins that case.

Tests (red first)

tests/test_untrusted_project_haiku_config_726.py:

  • haiku in the first of two project documents: red before, green after
  • haiku in the second document: regression guard
  • project dir reached through a symlink
  • empty project config: the user layer's haiku survives
  • no-jq fallback with a multi-document project config
  • sanitize failure (chmod 000 project config), on the jq and no-jq paths: the trusted layer's key still merges, and haiku never appears

Full suite on macOS: 2606 passed, 59 skipped, 0 failed. CI: 16/16 legs green at efc446d, Windows included.

Platform

Observed: macOS locally, and CI green on Linux, macOS and Windows. These haiku-strip test modules carry the repo's blanket win32 skip, so Windows CI proves the config merge still works there (the #668 test) but not the strip itself. That part is reasoned, from the same plain jq FILE form.

🤖 Generated with Claude Code

[AI-generated]

…t config

The #726 fix stripped an untrusted project layer's `haiku` block by
targeting `.[-1]` of a `jq -s` slurp -- the LAST element of the LAST
source file, on the (undocumented) assumption of exactly one JSON
document per file. `-s`/slurp has no file-boundary information, so a
project `.remember/config.json` shipping two whitespace-concatenated
JSON documents had its FIRST document's `haiku` block survive
untouched, one array element before the position `.[-1]` ever looked
at -- the same #726 credential-choice/strip attack, reachable through
one extra document.

The merge now runs as `jq -n` with `inputs`/`input_filename`, tagging
each document with the file it actually came from, so every document
the untrusted project file contributes is stripped, however many
there are -- not a position that assumed exactly one.

Also updates the two places this pin's exact jq invocation was
asserted verbatim (the #298 byte-pin's sanctioned-divergence tuple and
its own #440 unit tests, and #663's spawn-log substring), and corrects
the #726 changelog fragment and docs/git-backup-security.md §5's
"Fixed" claim, which did not hold for the multi-document case.

Closes #740.

Co-Authored-By: Max <noreply>
…ayer directly

The first #740 fix (jq -n/inputs/input_filename, comparing every
document's source file against a shell-supplied `--arg proj` path)
removed the multi-document leak but still depended on jq's own view of
a path string agreeing with the shell's -- reasoned to be safe (both
sides derive from the identical bash variable) but unverifiable on a
platform where jq's own path handling could diverge (a Windows-native
jq.exe, this repo's CI skips every bash-subprocess test on win32,
#79), and it also introduced a real regression: comparing every
document against the LAST document's own file breaks the moment the
untrusted project config exists but is EMPTY (0 documents) -- its
"last document" then belongs to a TRUSTED file, stripping that layer's
own legitimate `haiku` by mistake.

`jq --slurpfile proj "$_project_cfg"` removes the comparison entirely:
jq opens the untrusted file directly, by its own single file argument,
so there is no filename string left to diverge on any platform, and no
"assume the project file is last" ambiguity when it happens to be
empty (an empty file just slurps to `[]`).

Also fixes the same class of gap in the no-jq Python fallback: a
project config with more than one JSON document raised
`json.JSONDecodeError`, uncaught, taking the WHOLE merge down with it
(falling back to bundled defaults, dropping the user-global layer's
own overrides too) rather than stripping `haiku` from each of the
untrusted file's own documents and keeping everything else. Parses
multiple whitespace-concatenated documents from the untrusted file
specifically, mirroring the jq path.

New tests: a symlinked project directory and an empty-but-present
project config (the regression the rejected `input_filename` design
introduced), plus the no-jq multi-document fix with its own positive
control. Updates the #298 byte-pin's sanctioned-divergence tuples for
both the jq and Python sites, and the now-permanently-stale
pre-#726 Python tuple is dropped (same reasoning #734 already applied
to a different site on this file: once a transitional commit has
landed, real origin/main can never again be at the state before it).

Full suite: 2604 passed, 59 skipped, 0 failed.

Co-Authored-By: Max <noreply>
…roven jq call

PR #744's CI showed the `--slurpfile`-based fix failing on all 4
Windows legs: the only failure was a project config's own
`cooldowns.save_seconds` not taking effect, because the merge's jq
invocation itself errored under a native jq.exe and dropped into the
`|| cp "$_bundled_cfg" ...` fallback -- silently losing EVERY layer,
project and the trusted user-global one, with no error surfaced to the
user at all. That was exactly the risk #740's own commit message
reasoned about and could not observe (no Windows box); #744 observed
it.

Rather than debug `--slurpfile`/`/dev/null` placeholder semantics
under a native jq.exe blind, this design uses nothing that was not
already proven, on every CI platform, before #740 ever touched this
file: a SEPARATE, plain `jq -c 'del(.haiku)'` call sanitizes the
untrusted project layer into its own temp file first -- no `-s`, no
`-n`, no `--slurpfile`, no path comparison of any kind -- and the
ORIGINAL `jq -s` reduce (unchanged since before #726) then runs over
that temp file in place of the untrusted one. jq's ordinary (non-slurp)
mode already treats each top-level JSON value as a separate input, so
a multi-document project config is handled the same way #740's first
fix was, and an empty one the same way its second fix was, without
either design's own platform-dependent moving part.

If sanitizing fails for any reason, the project layer is dropped
entirely (fail CLOSED) rather than merged unsanitized -- the trusted
bundled/user layers are unaffected either way, rather than the whole
merge collapsing to bundled-only. The no-jq Python fallback got the
matching hardening: an unreadable or otherwise unloadable project file
now drops just that layer instead of crashing the whole merge.

New tests: an unreadable (chmod 000) project config must drop only
that layer, on both the jq and no-jq paths, with the trusted layer's
own key as a positive control -- this is the test that would fail if
the sanitize-failure path let an unsanitized file through, or
collapsed the whole merge instead of scoping the failure.

Adds one jq spawn (the sanitize call) when the project layer is
untrusted and present, matching this repo's own spawn-budget
convention for a real, necessary, one-time security cost (same
reasoning as #429's mktemp addition): POST_TOOL_SPAWN_MEASURED 17 -> 18,
still inside the existing +2 slack. Updates the #298 byte-pin's
sanctioned-divergence tuples and #663's spawn-log substring for both
the jq and Python sites.

Full suite: 2606 passed, 59 skipped, 0 failed.

Co-Authored-By: Max <noreply>
…y source list

Two review findings on PR #744, both test-first.

1. The Python fallback's fail-closed guard around load_documents()
   caught only OSError. A malformed project config raises
   json.JSONDecodeError (from decoder.raw_decode()) or, on bad text
   encoding, UnicodeDecodeError -- both are ValueError subclasses, so
   neither was caught, and either one propagated to crash the whole
   merge down to the bundled-only fallback, taking the trusted
   user-global layer's own overrides with it. This directly
   contradicted changelog.d/740.security.md's "drops just that layer"
   claim. Now catches (OSError, ValueError). Confirmed the jq path's
   own sanitize step already scoped this failure correctly (its exit
   code already gates whether the sanitized temp file gets added to
   the merge sources) -- the new jq-path test for the same input passes
   unmodified.

2. On the jq path, if bundled and user configs are both absent AND the
   sanitize step drops the untrusted project layer, `_jq_merge_sources`
   is empty and `jq -s '...'` with zero positional file arguments falls
   back to reading STDIN -- a hook blocked on STDIN never returns.
   Guarded: an empty source array writes `{}` directly, matching the
   "no config files at all" answer the no-jq else branch already gives
   elsewhere in this file, rather than invoking jq at all.

New tests: a malformed (truncated) project config must drop only that
layer on both the jq and no-jq paths, with the trusted layer's own key
as a positive control. A constructed all-layers-absent-or-dropped case
pins the correct `{}` output and relies on the existing 30s subprocess
timeout in _run_lib_and_dump_config to fail rather than hang the suite
if stdin-blocking regresses -- this test's own subprocess did not
actually block on stdin in this harness (EOF appears immediate there),
so it does not itself prove the fix necessary, but the guard is the
right defensive shape regardless and the test pins the correct output.

Full suite: 2609 passed, 59 skipped, 0 failed.

Co-Authored-By: Max <noreply>
@fdaviddpt
fdaviddpt merged commit ba2a592 into main Sep 25, 2026
16 checks passed
@fdaviddpt
fdaviddpt deleted the fix/740 branch September 25, 2026 08:00
fdaviddpt added a commit that referenced this pull request Sep 25, 2026
main at ba2a592 fails test_case_divergence_298 on 8 legs: the pre-#726 ->
#726 pair's old AND new code are both gone from origin/main once #744
landed on top of it -- the same "neither old nor new" state #734 fixed
for #662's pair. PR CI could not see it: it compared against the old
origin/main, where the #726 form was still present. Drop the pair;
the #726 -> #740 pair below it covers the site.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
fdaviddpt added a commit that referenced this pull request Sep 25, 2026
…746)

main at ba2a592 fails test_case_divergence_298 on 8 legs: the pre-#726 ->
#726 pair's old AND new code are both gone from origin/main once #744
landed on top of it -- the same "neither old nor new" state #734 fixed
for #662's pair. PR CI could not see it: it compared against the old
origin/main, where the #726 form was still present. Drop the pair;
the #726 -> #740 pair below it covers the site.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
fdaviddpt added a commit that referenced this pull request Sep 26, 2026
* fix(#748,#759): log silent config-layer/exclusion drops

#748: when sanitizing the untrusted project config layer failed (mktemp,
an unreadable project file, or jq/the no-jq Python fallback itself), the
whole project layer was correctly dropped (fail closed) but nothing was
logged anywhere -- a project's own settings (e.g. handoff_mode) vanished
with no explanation. Both the jq path and the Python fallback now report
the drop via report_error where it is in scope, falling back to a plain
stderr line where it is not (lib-memory-dir.sh is sourced by log.sh
before log.sh defines log/report_error).

#759: a failed `mkdir -p "$BACKUP_COMMON_DIR/info"` had no else branch,
so the config.json exclusion rule in git's info/exclude was silently
never written on a read-only filesystem or permissions error, letting
`git add -- "$SLUG/"` stage config.json (which can carry a live
haiku.oauth_token) exactly as before the #719 fix, with the caller
seeing an ordinary success line either way. The mkdir failure now
reports a WARNING via report_error, matching every other failure path
in this hook.

#749 (composition of #730/#719's untrack commit with git-restore's
fast-forward) is already fixed by #741 (changelog.d/741.fixed.md) --
50-git-restore.sh already detects and restores a config.json a
fast-forward removed from tracking, logging loudly on both success and
failure. No code change needed; reported as already-shipped rather than
reopened.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* test(#748): re-derive the sanctioned-divergence allowance the review found broken

Self-review (Explore) found that the #748 fix to scripts/lib-memory-dir.sh
broke tests/test_case_divergence_298.py::test_the_per_tool_call_path_is_not_touched
-- its byte-parity guard against origin/main has no allowance for the new
lines, so the test failed against real origin/main.

Extends _SANCTIONED_DIVERGENCE's existing lib-memory-dir.sh entries in place
rather than nesting new chained pairs inside them: composing directly on top
of an already-landed pair (the #757 steady state) the same way, re-deriving
each affected pair's old_code to be that steady state rather than the
long-superseded #744/#726 forms it used to start from -- the same "fold,
don't stack a third pair" precedent the file's own #757 comments already
document for this exact site. A first attempt nesting new pairs inside the
existing ones passed the real guard test but broke
tests/test_sanctioned_divergence_state_440.py's own synthetic canary
(a chained pair's old_code duplicating verbatim inside an earlier pair's own
already-landed new_code, corrupting it under the synthetic test's naive
concatenate-then-substitute construction); re-deriving in place instead
passes both.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* chore(#748): log auditor's compound mktemp-failure finding to trap.d/

Non-blocking, ranked fails-to-preserve, "can ship behind a trap.d fragment"
per the findings table -- see the fragment for the mechanism and what would
settle it.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
fdaviddpt added a commit that referenced this pull request Sep 27, 2026
… untrusted-layer disclosure (#818)

* fix(#815): disclose a malformed TRUSTED config layer the same way #804 discloses an untrusted one

`lib-memory-dir.sh`'s no-jq Python-fallback merge loaded every TRUSTED config
source (bundled config, user-global config, or the project config when it is
not the untrusted-haiku source) with no error handling. A malformed file
there raised uncaught, exiting the subprocess with a code that is neither 0
nor 3, so the shell's own bundled-only fallback fired silently -- #804's
disclosure gate only checks the drop-marker file or `rc == 3`, neither of
which this path ever touches. A caller saw the identical "fell back to
bundled config" behaviour whether nothing but bundled config ever existed, or
a trusted file the operator actually wrote was corrupt and silently
discarded.

This is the exact gap #804's own self-review logged to trap.d/ and #815 was
filed from. Wraps the trusted-source load in the same fail-CLOSED shape the
untrusted branch already uses (skip just that layer, keep merging the rest),
and adds two new exit codes -- 4 for a trusted-only drop, 5 for both a
trusted and the untrusted layer dropping in the same run -- so the shell can
print a second, distinct WARNING without a second marker file.

Adds a paired positive/negative test (malformed user-global config warns and
drops just that layer; a well-formed one does not warn), and folds a new
`_SANCTIONED_DIVERGENCE` entry for the byte-pin guard in
tests/test_case_divergence_298.py to match.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(#815): self-review -- widen the trusted-layer WARNING and strengthen its test

Both spawned reviewers (Explore and oss:auditor) independently flagged the same
gap: the new rc-4/5 WARNING said only "bundled or user-global config," but the
branch it fires for also covers project config in external-storage mode (when
it is not the untrusted-haiku source) -- an operator on that layout debugging a
malformed project config would be pointed at the wrong two files. Widened the
message to name all three trusted sources the branch actually reaches.

Explore separately found the positive test's merged-value assertion did not
discriminate fixed from pre-fix behaviour: the bundled-config fixture and the
`_bundled_cfg` fallback target were the same file, so a value that survived
under a full wholesale fallback looked identical to one that survived under a
per-layer drop. Added a third, well-formed project-config layer read AFTER the
malformed one in merge order -- confirmed against the true pre-#815 baseline
that this addition alone goes red (asserting `extra_layer` survives) and green
against the fix, which the prior assertion did not.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(#815): correct a class docstring left stale by the second self-review commit

Both second-pass reviewers (Explore and oss:auditor) independently found the
same gap: 8df6cae added a well-formed project-config layer to the first test
in TestMalformedTrustedConfigDisclosure as a fixed-vs-broken discriminator,
but never updated the class's own docstring, which still claimed neither
test holds a project config and both go through the trusted-load branch this
class is about. Traced (as both reviewers did independently): in this file's
default legacy layout, that project layer is the untrusted-haiku source and
is processed by the pre-existing #744 branch, not the #815 trusted-load
branch -- it is there purely as an order-dependent discriminator, which the
in-method docstring already explained correctly. Corrected the class
docstring to match.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(#815): fold the #815 divergence pair into #804's, don't stack beside it

CI on PR #818 caught tests/test_sanctioned_divergence_state_440.py red on
windows-latest 3.10/3.11 -- a pure Python string-substitution bug, not a
platform flake, so it would have reproduced on every leg. My own commit
comments already cited case-divergence-pin-fold-dont-stack.md, but I only
quoted its convention rather than following it: I stacked a third tuple onto
tests/test_case_divergence_298.py's `_SANCTIONED_DIVERGENCE` list whose
old_code duplicated the existing #804 tuple's new_code, instead of folding
the transition into that tuple in place. `_apply_sanctioned_divergence` runs
substitutions in list order and stacking meant the #815 pair rewrote the
#804 pair's own output out from under it once both were live together,
exactly the "old AND new code both vanish" failure the fold-don't-stack doc
describes for #734/#746.

Replaced the separate #804 and #815 tuples with a single folded pair: old_code
is now the #804 steady state (what origin/main ships today, moved here
verbatim per the doc's own worked example), new_code is the full #815 form
including the round-2 self-review's widened warning text. No production code
changed -- scripts/lib-memory-dir.sh is untouched by this commit.

Verified genuinely red on the pre-fold (stacked) shape: temporarily restored
it via `git stash` and ran `pytest tests/test_sanctioned_divergence_state_440.py`,
which failed 3 of 4 with the "neither the old nor the new code ... is on
origin/main" / "new_code not found in result" assertions the reviewer's
report predicted. Restoring the fold: 4/4 pass, and the full targeted set
(this file + test_case_divergence_298.py + test_untrusted_project_haiku_config_726.py)
is 71 passed.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 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

1 participant