Skip to content

fix(connect): close precondition-token TOCTOU between check and write - #1352

Merged
Dumbris merged 3 commits into
mainfrom
claude/optimistic-herschel-2d683a
Sep 24, 2026
Merged

Dumbris merged 3 commits into
mainfrom
claude/optimistic-herschel-2d683a

Conversation

@Dumbris

@Dumbris Dumbris commented Sep 23, 2026

Copy link
Copy Markdown
Member

Summary

ConnectWithPrecondition resolved pre-write state and checked the caller's precondition token against one read (preWriteState), but connectJSON/connectTOML each then performed their own independent second read of the same file before mutating it. The token was never re-validated against that second read: if the file changed between the two reads and the caller passed force=true, the write would silently commit whatever the unchecked second read contained instead of the state the token actually described — the user confirms drift against one snapshot, but a different snapshot gets destroyed.

This gap was flagged as a must-fix in round 2 of a cross-model review of #1340 (a narrower, unrelated fix), which explicitly scoped it out as pre-existing on main and asked for its own PR.

  • Threads preWriteState's single read (bytes, permission, read error) through a new preWriteResult struct into connectJSON/connectTOML via pure parseOrCreateJSON/parseOrCreateTOML helpers, so there is exactly one pre-write content read for the whole operation.
  • guardJsoncComments split the same way (guardJsoncCommentsBytes) so Preview and connectJSON share the same bytes instead of re-reading.
  • Two rounds of cross-model review (codex gpt-5.6-sol) on the refactor itself caught three regressions it would otherwise have introduced silently, all fixed:
    • A non-ENOENT stat failure produced raw=nil with no read error — indistinguishable from "file absent" — risking a silent overwrite of unreadable-but-existing content with an empty config. Now surfaced as a refusal via a recorded readErr.
    • A file vanishing between stat and read used to self-heal into a create via the write's own redundant second read; collapsing to one read broke that self-heal until preWriteState explicitly reclassifies a read-time "absent" as fileExists=false.
    • perm was captured from the same early stat used for content, widening a chmod-race window versus the pre-refactor code. Restored via a currentPerm helper that re-stats (metadata only) immediately before atomicWriteFile.
  • Round 2 review verdict: clean.

Test plan

  • New regression tests in internal/connect/token_test.go: the original race (plain JSON replace, verified RED before the fix / GREEN after), OpenCode's adopted-entry delete (the most destructive shape — deleting unrelated content repurposed under an adopted key), plus targeted tests for the three regressions above.
  • go build ./... and go build -tags server
  • go test -race ./internal/connect/... ./internal/httpapi/...
  • golangci-lint run --config .github/.golangci.yml ./internal/connect/... (bare and --build-tags server)
  • gofmt -l clean

🤖 Generated with Claude Code

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: claude/optimistic-herschel-2d683a

Available Artifacts

  • archive-darwin-amd64 (30 MB)
  • archive-darwin-arm64 (27 MB)
  • archive-linux-amd64 (18 MB)
  • archive-linux-arm64 (16 MB)
  • archive-windows-amd64 (30 MB)
  • archive-windows-arm64 (26 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (24 MB)
  • installer-dmg-darwin-arm64 (22 MB)
  • smart-mcp-proxymcpproxy-goIMQUS2.dockerbuild (0 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 35969834564 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@codecov-commenter

codecov-commenter commented Sep 23, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 96.96970% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/connect/connect.go 93.10% 1 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@Dumbris
Dumbris force-pushed the claude/optimistic-herschel-2d683a branch 2 times, most recently from 06ce43b to 829a52a Compare September 24, 2026 04:38
Dumbris and others added 3 commits September 24, 2026 10:27
ConnectWithPrecondition resolved pre-write state and checked the caller's
precondition token against ONE read (preWriteState), but connectJSON and
connectTOML each then performed their OWN independent second read of the
same file before mutating it. The token was never re-validated against
that second read: if the file changed between the two reads and the
caller passed force=true, the write would silently commit whatever the
unchecked second read contained instead of the state the token actually
described.

Thread preWriteState's single read (bytes, permission, and any read
error) through a new preWriteResult struct into connectJSON/connectTOML
via pure parseOrCreateJSON/parseOrCreateTOML helpers, so there is exactly
one pre-write content read for the whole operation. guardJsoncComments is
split the same way (guardJsoncCommentsBytes) so Preview and connectJSON
share the same bytes instead of re-reading.

Two rounds of cross-model review (codex gpt-5.6-sol) on this refactor
caught three regressions it would otherwise have introduced silently:

- A non-ENOENT stat failure produced raw=nil with no read error,
  indistinguishable from "file absent" — parseOrCreateJSON would have
  silently overwritten unreadable-but-existing content with an empty
  config. Now surfaced as a refusal via a recorded readErr.
- A file vanishing between stat and read used to self-heal into a create
  via the write's own redundant second read; collapsing to one read broke
  that self-heal until preWriteState explicitly reclassifies a read-time
  "absent" as fileExists=false.
- perm was captured from the same early stat used for content, widening a
  chmod-race window versus the pre-refactor code (which re-stat'ed right
  before the write). Restored via a currentPerm helper that re-stats
  (metadata only) immediately before atomicWriteFile.

New regression tests in token_test.go cover the original race (plain JSON
replace and OpenCode's adopted-entry delete, the most destructive shape)
plus the three fixes above.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…e file gone

preWriteState captured result.perm from stat's info.Mode() before the
subsequent read; when that read fails with ENOENT (the file vanished between
stat and read), the self-heal to fileExists=false/accessAbsent left the stale
perm in place. A freshly created config then inherited the deleted file's
mode (e.g. 0400) via currentPerm's fallback instead of the 0644 create
default.
…-heal test

TestConnectWithPrecondition_FileVanishedBetweenStatAndReadDefaultsPerm
asserted the newly created config's mode is exactly 0644, which fails on
Windows: os.Chmod there only toggles the read-only DOS attribute, so a
0644 chmod reports back as 0666 (writable) rather than the literal Unix
value. The production fix is correct on Windows too — it produces a
writable file, not the stale restrictive one — only the test's exact-value
assertion was too strict for a platform with no Unix permission bits.

On Windows, assert the file came back writable (the actual invariant the
test exists to prove) instead of the literal 0644 value; keep the exact
assertion on Unix.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@Dumbris
Dumbris force-pushed the claude/optimistic-herschel-2d683a branch 2 times, most recently from ef89552 to 36a6598 Compare September 24, 2026 07:28
@Dumbris
Dumbris merged commit 655f731 into main Sep 24, 2026
39 checks passed
Dumbris added a commit that referenced this pull request Sep 24, 2026
TestConnectJSON_CommentGuardSharesOneReadWithParse called connectJSON
directly with a stale (resolved *existingEntry) argument that PR #1352's
single-pre-write-read refactor removed; connectJSON now takes the shared
preWriteResult and no longer performs any read of its own. Route both
subtests through ConnectWithPrecondition instead, which is the only
remaining caller that resolves a preWriteResult from a config path. Read
counts are unchanged (4 for the comment-free path, 1 for the refusal path)
because ConnectWithPrecondition's own connectRefusal check stats rather than
reads the file.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Dumbris added a commit that referenced this pull request Sep 24, 2026
zcode's read-only review of the #1352/#1353 rebase resolution (round 1)
found a genuine stale comment introduced by the conflict resolution itself:
guardJsoncComments' doc claimed it is "used only by the read-only preview
path (preview.go)", but preview.go actually calls the read-free
guardJsoncCommentsBytes(cfgPath, pre.raw) — a switch #1352 made — so the
reading wrapper has zero production callers. Fix the doc to say so, note it
is kept only for its own direct test coverage and as a documented trap
against future write-path use, and correct a second, minor inaccuracy that
listed connectTOML among guardJsoncCommentsBytes' callers (a .toml path can
never match the .jsonc suffix it checks, so it never calls the guard).
Also corrects the matching false claim repeated in
TestGuardJsoncComments_SkipsReadForNonJsoncPath's doc comment.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Dumbris added a commit that referenced this pull request Sep 24, 2026
…1353)

* fix(connect): close JSONC comment-guard TOCTOU in connect/disconnect

guardJsoncComments and readOrCreateJSON each did their own independent
s.read(cfgPath), so a file that was comment-free when the guard read it
but gained comments before the parse's later read would pass the guard
on stale bytes and get silently rewritten as plain JSON, stripping the
comments the guard exists to protect (#922). disconnectJSON had the
identical shape.

Fold the check into a pure guardJsoncCommentsBytes(cfgPath, raw) run
against bytes the caller already read, so the guard and the parse/write
now always see the same snapshot. The old read-it-yourself
guardJsoncComments is kept only for the read-only preview path, which
never writes.

Flagged as a pre-existing, out-of-scope finding in cross-model review of
PR #1340. Verified with call-counting regression tests (fail against the
pre-fix code, pass against the fix) and two rounds of independent
cross-model review (codex gpt-5.6-sol, then zcode/GLM), the second of
which caught a suffix-check-ordering regression and a test coverage gap
in the first fix, both corrected here.

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

* fix(connect): correct stale TOCTOU comments and test name after review

- ConnectWithPrecondition's doc comment still described the JSONC
  comment-guard double-read as a pre-existing, out-of-scope limitation;
  this PR actually closes it via guardJsoncCommentsBytes, so update the
  comment to say so instead of contradicting the fix it sits next to.
- Fix TestConnectJSON_CommentGuardSharesOneReadWithParse's subtest name,
  which still said "2 total reads, not 3" while its assertion checks
  for 4 (the count PR #1340's extra refuseIfServersSectionRaced checks
  raised it to).

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

* fix(connect): rebase test onto #1352's pre-based connectJSON signature

TestConnectJSON_CommentGuardSharesOneReadWithParse called connectJSON
directly with a stale (resolved *existingEntry) argument that PR #1352's
single-pre-write-read refactor removed; connectJSON now takes the shared
preWriteResult and no longer performs any read of its own. Route both
subtests through ConnectWithPrecondition instead, which is the only
remaining caller that resolves a preWriteResult from a config path. Read
counts are unchanged (4 for the comment-free path, 1 for the refusal path)
because ConnectWithPrecondition's own connectRefusal check stats rather than
reads the file.

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

* fix(connect): correct guardJsoncComments doc after zcode review

zcode's read-only review of the #1352/#1353 rebase resolution (round 1)
found a genuine stale comment introduced by the conflict resolution itself:
guardJsoncComments' doc claimed it is "used only by the read-only preview
path (preview.go)", but preview.go actually calls the read-free
guardJsoncCommentsBytes(cfgPath, pre.raw) — a switch #1352 made — so the
reading wrapper has zero production callers. Fix the doc to say so, note it
is kept only for its own direct test coverage and as a documented trap
against future write-path use, and correct a second, minor inaccuracy that
listed connectTOML among guardJsoncCommentsBytes' callers (a .toml path can
never match the .jsonc suffix it checks, so it never calls the guard).
Also corrects the matching false claim repeated in
TestGuardJsoncComments_SkipsReadForNonJsoncPath's doc comment.

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

* fix(connect): correct misattributed test-coverage clause in guardJsoncComments doc

zcode round-2 re-review caught one remaining issue in the previous fix: the
doc said guardJsoncComments is kept because "guardJsoncCommentsBytes's own
tests exercise directly" — grammatically misattributing the coverage to the
wrong function. No test calls guardJsoncCommentsBytes directly; the only
direct caller is guardJsoncComments' own test,
TestGuardJsoncComments_SkipsReadForNonJsoncPath. Name it explicitly instead.

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

Development

Successfully merging this pull request may close these issues.

2 participants