Skip to content

fix: restrict durable store permissions on POSIX - #244

Merged
abogartz merged 4 commits into
abogartz:mainfrom
WhollyMindless:fix/store-permissions-218
Nov 2, 2026
Merged

abogartz merged 4 commits into
abogartz:mainfrom
WhollyMindless:fix/store-permissions-218

Conversation

@WhollyMindless

@WhollyMindless WhollyMindless commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Closes #218.

With a permissive umask, durable memory and its auxiliary files could be created readable by other local users. This change creates POSIX store directories with 0700 and files with 0600, including locks, atomic replacement temps, snapshots, append-only ledgers, and status files. Existing store roots are tightened when resolved, including on reads, when directory chmod is supported and permitted; existing append/status files and written directories lose group/other permissions without adding owner permissions. Atomic replacement and O_APPEND behavior are retained.

Existing ancestors outside the store are not chmodded, and old descendants are not recursively migrated: a successfully tightened root is the traversal barrier. Directory fchmod failures EPERM/EROFS/EOPNOTSUPP/ENOSYS preserve readable access with existing modes; owner-only traversal is not guaranteed in that case. Open-time symlink/ENOTDIR refusals and unexpected chmod errors still propagate. Final-component root symlinks and append/status file symlinks are refused before permission changes; a symlinked store root must be configured using its real directory. This is not comprehensive intermediate-symlink/race hardening, nor does it revoke already-open handles or protect outside hard links. Windows ACLs are unchanged. README describes the contract and compatibility implications.

Status retains its best-effort behavior even when root resolution fails. Three mutation catalog patterns are re-anchored to the changed opens/append call; their intended mutations are unchanged.

Updated after #247/#248 merged: permission handling and tests now use the domain layout, with the helper in src/core/permissions.ts. This remains a separate permissions change.

Validation at 895ba93 (Bun 1.4.4):

  • Windows full merge gate: typecheck/lint, 843 unit tests passed / 24 skipped, all 30 real-host E2E tests passed. The thirteen POSIX cases intentionally skip on Windows.
  • Linux/WSL full unit suite: 855 passed / 12 skipped / 0 failed. Thirteen permission regressions exercise permissive umask, existing stores, private pre-write temps/snapshots/status files, lock creation, restrictive owner permissions, final-component symlink refusal, supported directory-chmod fallbacks, and unexpected-error propagation.
  • Original pre-refactor negative control against base 2a2cb92: supplying only the new helper and regression test while retaining original call sites gives 7 failures / 1 pass. The passing case tests the supplied helper directly; the seven failing cases pin integration behavior.
  • All 45 mutation patterns validate. The full mutation sweep was not run.

Please feel free to request a different scope, defer, or close this if it does not fit the project's direction. Merge remains your call.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Updated in b2f2929 after #247/#248 merged, bringing in main at 279df73 and moving the permissions integration to the domain modules. The helper now lives in src/core/permissions.ts; status handling spans payload.ts and write.ts; test imports and all three affected mutation anchors follow the new layout. The permission behavior and scope remain unchanged.

Validation: Windows full merge gate passed (typecheck/lint, 843 unit pass / 19 skip, 30 real-host E2E pass); Linux unit suite passed (850 pass / 12 skip), including all eight permission regressions. All 45 mutation patterns validate. Hosted CI is pending; full mutation sweep not run.

This remains separate from the refactor. Please feel free to defer or reject it if it does not fit the direction you want; merge is your call.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Pushed a175eda to address the Ubuntu failure on b2f2929. This is a test-fixture lifetime fix; no production change or timeout increase.

The failed job starts with an evidence-file ENOENT in lock-partial-outcomes, then cascades into other tests. LOCK_WRITE/LOCK_RESTORE launch audit records without awaiting them, while the fixture removes its temporary store after the awaited lock/tool work ends. The lock operation finishing does not mean that its audit append finished.

Reproduction: an external probe delays the real evidence filesystem write by 80ms (open in this branch; appendFile on the refactor base). The original fixture gives 3 pass / 6 fail / 2 unhandled errors on both this branch and 9e736da without the permissions change. With the fixture tracking real record promises and draining them before store removal, the delayed-open probe gives 9 pass / 0 fail. Actual evidence errors are collected and asserted empty, not silently swallowed. Existing partial-write assertions and the 40ms lock budget are unchanged. This supports the original Ubuntu residual in #245; the Windows timeout fix addresses a different trigger.

Validation after the correction: full Windows gate passed (typecheck/lint, 843 unit pass / 19 skip, 30 host E2E pass); Linux unit suite 850 pass / 12 skip / 0 fail, including the eight permission regressions; mutation catalog validation passed. Hosted CI on the new commit still needs to run. The delay probe is an external diagnostic, not a permanent sleep in the suite.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Verdict: APPROVE (one minor finding, one residual, one nit — none block merge)

Adversarial re-verification at head a175eda against base main 279df73 (macOS, Bun 1.4.3). Every body claim was checked against the tree and re-measured, not trusted.

Claims verified against the tree

  • Negative control reproduced exactly: with only src/core/permissions.ts + test/store-permissions.test.ts copied onto base main and original call sites intact, the suite gives 7 fail / 1 pass — identical to the body's claim (the pass is the direct-helper test; the seven pin integration).
  • New tests are red-on-base and green-on-head; full unit suite 880 pass / 12 skip / 0 fail vs base main 872 / 12 / 0 — delta is exactly the +8 permission tests. e2e 30 / 0 on this host. Typecheck clean. bun run lint rc=0.
  • All three re-anchored mutation find strings occur exactly once in their files (lock.ts wx+0o600, publish.ts handle.appendFile, snapshots.ts wx+0o600), so the sweep cannot silently no-op on them.
  • Windows skip is real: describe.skipIf(process.platform === "win32").
  • CI: all four legs pass at head; mergeStateStatus CLEAN.

Independent behavior probes (fresh temp stores, umask 0): new store dir lands 0700 and appended file 0600; existing 0755 root tightens to 0700 on memoryRoot(); a deliberate 0500 root is left untouched (no owner bits added); a symlinked root is refused before any chmod and the outside target keeps its mode; an append-target symlink is refused (ELOOP) with the victim file byte-intact; writeAtomic final file is 0600 under umask 0; preparePrivateFile tightens an existing 0644 status file to 0600 without truncating it and refuses a symlinked status target; writeStatus/readStatus degrade to no-op/null on a refused root; ancestors outside the store are not chmodded. One correction to expectations, not to the code: on macOS a symlinked root throws ENOTDIR (from O_DIRECTORY|O_NOFOLLOW), not ELOOP — refusal holds either way.

Test-fixture fix (a175eda) is real, not vacuous. pendingEvidence is only populated through the spyOn(evidence, "record") mock, so I added a temporary guard that fails unless interception occurs; all 9 tests pass with it and the guard trips when interception is suppressed — the spy genuinely rewires the cross-module record calls. The added expect(evidenceErrors).toEqual([]) makes the drain assert rather than hide: an insufficient drain would now fail loudly.

Minor finding (not a blocker). blockedRecent() resolves evidenceDir() → memoryRoot(), which now throws synchronously on a refused root (symlink, ENOTDIR path component, or EPERM). readStatus was wrapped, but blockedRecent was not, and src/tui/panel.tsx refresh() calls it via void refresh() with no catch — on a refused-but-configured root the panel produces an unhandled rejection per poll/watch event, where pre-PR it degraded to an empty list. The refused state is a misconfiguration the README tells the user to fix, so this is polish: wrap blockedRecent in the same try/catch as readStatus (return []), or catch in refresh().

Residual. A store root owned by another uid (container uid-mapping setups) used to be readable; fchmodSync now throws EPERM through memoryRoot() and every caller fails, including read-only ones. Consistent with the "tighten on resolve" contract, but worth a README sentence or an EPERM-specific carve-out later.

Nit. One new advisory biome warning vs base (499 vs 498): test/store-permissions.test.ts:11 useImportType — the whole import { type StatusPayload } line should be import type. Warnings are advisory and CI lint passes.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Reviewed adversarially at a175eda. Verdict: REQUEST CHANGES — one finding (a hard-fail path introduced by resolving-with-tighten), two nits. Everything else verified; this is close.

What I verified against the tree, not the body

  • Diff shape: helper lives at src/core/permissions.ts; call sites are exactly the opens/appends the body names — appendLog (O_APPEND|O_CREAT|O_NOFOLLOW, 0600, tighten-without-adding), writeAtomic (pre-claim temp wx 0600, claimed flag so an EEXIST open failure no longer unlinks a temp that was never ours), holdFileLock and claimSnapshot (wx 0600), ensureDir (mkdir mode 0700 + tighten), status via preparePrivateFile before Bun.write, export mkdir 0700 (the export file itself was already 0600+chmod from #156). Writers audit: grep over src for Bun.write|writeFile|appendFile|open( finds no store writer outside the covered set; command/ensure.ts writes the commands mirror outside the store and is not sensitive.
  • Tests red without the fix: disabling the append chmod and the memoryRoot tighten together turns exactly 3 of the 8 new tests red (root protection, ledger privacy, status-root); the helper-direct test stays green — consistent with your 7f/1p negative control.
  • Mutation catalog: bun scripts/test-sweep.ts --validate → every pattern applies to exactly one site, including the three re-anchored ones (find strings match the new sources byte-for-byte).
  • The third commit is not vacuous: I probed the load-bearing assumption — spyOn(evidence, "record") does intercept the direct ESM binding lock.ts holds (forced a timeout event under contention; the spy fired). Without that, pendingEvidence would stay empty and the drain would be a no-op.
  • Counts reconcile exactly: local macOS branch 892 run (880 pass / 12 skip / 0 fail) = base main 884 + the 8 new tests; your 862-run unit figure + the 30 real-host E2E files = 892. tsc clean; biome rc 0; test-windows green with the 8 POSIX tests skipping.
  • Symlink refusal: pinned by your test (root symlink throws, outside target untouched; append symlink throws, target bytes unchanged). O_NOFOLLOW guards the final component only, as disclosed.

Finding: memoryRoot() now hard-fails every operation when fchmod is not permitted

tightenDirectory catches only ENOENT from the open; fchmodSync has no error handling, so any chmod failure propagates out of memoryRoot() — which every tool, and injection, calls first. Reproduced on this base with an immutable store root (chflags uchg, so chmod fails EPERM for the owner):

memoryRoot THREW: EPERM: operation not permitted, fchmod

Realistic triggers: a store previously touched by sudo (root-owned root, later used as the normal user), an operator lock flag, or OPENCODE_MEMORY_DIR on a mount without POSIX chmod (SMB/FUSE). Before this PR all of those still served reads — your own comment says the tighten exists to "protect old stores even on read-only use", but the foreign-owned store is precisely the read-only case that now throws before any read. writeStatus/readStatus are wrapped; the 20 other memoryRoot() sites are not, so recall/injection would break outright.

Ask: make the fchmod best-effort — catch EPERM/EROFS/EOPNOTSUPP/ENOSYS around fchmodSync and continue (the traversal barrier is then simply not achieved, which is the honest ceiling when we cannot chmod). Keep the open-time refusals (ELOOP/ENOTDIR) exactly as they are — those are policy, this is capability. ensureDir inherits the fix through the same helper. A test pinning "unmodifiable-but-readable root still resolves" would lock it in.

Nits

  1. New lint warning: test/store-permissions.test.ts:11 useImportType (import { type StatusPayload } → import type { StatusPayload }). Base is 498 warnings, branch 499; this is the only new one.
  2. README: whatever you decide about the finding, the contract sentence should say what happens when the root cannot be chmod'ed — right now the README implies tightening always happens on access.

Otherwise the design holds up under probing: the claimed flag is a real fix (an EEXIST temp collision previously invited unlinking someone else's temp), status publication prepares before Bun.write so bytes never exist at 0644, and the fail-closed O_NOFOLLOW refusals are pinned rather than asserted.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Addressed both reviews in 895ba93.

  • Directory fchmod is now best-effort for exactly EPERM/EROFS/EOPNOTSUPP/ENOSYS, as requested. The catch is around fchmod only: open-time symlink/ENOTDIR refusals remain unchanged, and unexpected errors still propagate. File chmod behavior on write is unchanged.
  • Four error-injection cases assert that memoryRoot, ensureDir, and actual loadAll reads remain usable while the root keeps its original mode; the spy assertion proves the chmod failure path was exercised. An EIO control asserts unexpected failures still throw. Existing symlink and restrictive-owner-mode tests remain green.
  • blockedRecent now returns an empty list when root resolution fails, matching the status surface's best-effort contract. The invalid-root regression pins this alongside readStatus/writeStatus.
  • README documents the capability fallback and the absence of a guaranteed private traversal barrier when chmod cannot succeed. Fixed the new import-type warning.

Red/green: before the source fix, the focused Linux tests gave five failures (the four capability errors and invalid-root blockedRecent); after it, the full Linux suite passed 855 / 12 skip / 0 fail. Windows full gate passed: typecheck/lint, 843 unit pass / 24 skip, 30 real-host E2E pass. All mutation anchors validate. The immutable-root condition is simulated at fchmod; I did not run a live macOS chflags probe here. Hosted CI on 895ba93 is pending.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

APPROVE with one follow-up (see F1)

Adversarial review at a175eda against base 279df73. Every body claim checked against the tree and re-measured locally (Bun 1.4.3, macOS).

What I verified independently

  • Red/green. test/store-permissions.test.ts: 8 pass / 43 asserts on head; on base the file cannot even load (src/core/permissions.ts absent), and the body's stronger negative control (helper + test on old call sites at 2a2cb92: 7 fail / 1 pass) matches what the call-site diff implies. The 8 tests are real: permissive umask(0), parent-mode assertions, content-preservation asserts, and Bun.write spies that assert mode before the real write runs — that is the "private before sensitive bytes" claim pinned, not test theater.
  • Suite arithmetic. Head: 892 tests / 90 files / 12 skip / 0 fail. Base 279df73 measured on the same machine: 884 / 89 / 12 / 0. Delta is exactly the +8 new tests plus the 2 added status assertions inside an existing test. Typecheck clean.
  • Lint. biome lint summary: head 499 vs base 498 warnings. The +1 is test/store-permissions.test.ts:11:8 lint/style/useImportType (advisory; see N1). With --max-diagnostics raised, the src/ test/ scripts/ warning sets are otherwise identical modulo line shifts.
  • Mutation catalog. bun scripts/test-sweep.ts --validate on head: every pattern applies to exactly one site. I additionally checked kill power of the three re-anchored mutants by hand: lock-noexcl-mutex → test/lock.test.ts 2 fail; append-truncate-regression → logfmt + store-permissions 2 fail; snapshot-overwrite → undo + store-permissions 1 fail. All three killed; tree reverted clean.
  • Mechanism probes (outside the test suite):
    • Existing 0755 store root → memoryRoot() leaves it 0700, parent stays 0755, old descendant files untouched — matches the README contract exactly.
    • Append onto an existing 0644 ledger tightens it to 0600 and preserves content ("one\ntwo\n").
    • Symlinked root refused: memoryRoot() throws (ENOTDIR on macOS with O_DIRECTORY|O_NOFOLLOW); the outside target is untouched.
    • Writer completeness: every store-adjacent open/mkdir in src/ now carries a private mode (appendLog 0600, writeAtomic temp wx 0600, lock wx 0600, snapshot claim wx 0600, all mkdir 0700). The only unmodified ones are src/command/ensure.ts (commands dir — outside the store, outside #218).
    • writeAtomic's claimed guard is a real fix: the old unconditional unlink(tmp) could delete a file the failed open never created.
    • record() does not swallow write errors, so the new expect(evidenceErrors).toEqual([]) in lock-partial-outcomes is meaningful, not vacuous.
    • No import cycle from store/lock.ts → core/logfmt/publish.ts → core/permissions.ts.
    • Windows guards are consistent (win32 early-return, IS_WINDOWS chmod guard, O_NOFOLLOW ?? 0 matching the export.ts precedent); the Windows CI leg is green.

Findings

F1 (follow-up, not a blocker): a store root owned by another user now fails every call with EPERM, and neither README nor a test says so. tightenDirectory only tolerates ENOENT; any other fchmodSync failure propagates out of memoryRoot(), which is on every path helper. Probe against a root-owned 0777 directory (/Users/Shared): memoryRoot() throws EPERM, mode unchanged. Before this PR such a store was at least readable; after it, every tool, the viewer, and the status reader fail with an opaque EPERM (status is caught and degrades to "no data" — the tools are not). Fail-closed on a store you cannot protect is consistent with the project's posture, so I am not requesting a behavior change — but the contract should be stated and pinned: one README sentence next to the symlink line ("a store root you do not own is refused"), plus a test that the refusal leaves the outside mode untouched. Alternatively, deliberately downgrade EPERM to best-effort; either is fine, silence is not. Filed as a follow-up issue.

N1 (nit). test/store-permissions.test.ts:11 — import { type StatusPayload } trips useImportType; use import type.

N2 (nit). The mutation catalog gained no pattern for the new invariant itself (e.g., tightenDirectory body no-op, or 0o600 → 0o644 on the new opens). The 8 tests pin it; a catalog entry would keep it pinned after test edits. Consistent with "full sweep not run" being disclosed.

N3. The third commit (evidence drain in lock-partial-outcomes) fixes a latent fixture-lifetime race: 8/8 idle runs pass on both trees locally, so it is contention-only, matching the known CI flake family. Fine as test hygiene bundled here.

Intermediate-symlink and open-handle residuals are disclosed in the body and README; the protected-root-as-barrier argument holds given 0700 on the root.

@abogartz
abogartz dismissed their stale review November 1, 2026 23:51

Resolved at 895ba93: fchmodSync in tightenDirectory is now wrapped catching EPERM/EROFS/EOPNOTSUPP/ENOSYS and continues, so a readable-but-unmodifiable store root still resolves; open-time symlink/ENOTDIR refusals preserved; test/store-permissions.test.ts:118 pins the four-code fallback and :131 pins unexpected errors still propagate.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Verdict: APPROVE (with nits; none blocking)

Verified against the tree at head a175edaa, not the PR body. Local host: macOS, Bun 1.4.3.

Body claims I independently confirmed

  • Negative control reproduces exactly. src/ reverted to base 279df73, test/store-permissions.test.ts kept: 7 fail / 1 pass — matches the body's stated control, and the single pass is the direct-helper case as claimed. The seven failures pin integration behavior, so the tests are not test theater.
  • Suite deltas match. Base 279df73: 842 pass / 12 skip / 0 fail. Head: 850 / 12 / 0 — exactly +8, the eight new POSIX tests. e2e: 30 pass / 0 fail locally.
  • Lint and types unchanged. bun run lint: 499 warnings on both base and head — no new diagnostics. tsc --noEmit clean.
  • Mutation anchors intact. --validate passes: all 45 patterns (44 mutants + calibration plant) apply to exactly one site; I also independently verified each find string occurs exactly once in its target file. The three re-anchored mutants (lock-noexcl-mutex, append-truncate-regression, snapshot-overwrite) are all killable on the new code.
  • a175edaa fixes a real CI failure, not a phantom. At b2f2929 the Linux test leg failed with Unhandled error between tests — ENOENT …/osi-partial-lock-*/memory/evidence/2026-01-01.logfmt and …/snapshots/…: fire-and-forget lock telemetry landing after afterEach deleted the fixture root, poisoning sibling tests. At a175edaa the same log contains zero unhandled errors. The drain is load-bearing.
  • The spy in that fix is not vacuous. I probed spyOn(evidence, "record") against a forced lock-timeout: it does intercept the direct ESM import lock.ts holds (calls > 0), so the drain actually observes the writes it claims to drain.
  • Write-site coverage is complete. Every store write funnels through appendLog/writeAtomic/claimSnapshot/preparePrivateFile (checked hits/ledger.ts, store/blocklist.ts, evidence/record.ts, store/files/append.ts, store/lock.ts, portable/export.ts). No raw Bun.write/appendFile site inside the store escapes the mode handling.
  • Intermediate-dir modes hold. mkdir(…, {recursive:true, mode:0o700}) under umask(0) gives 0700 at every created level (probe), so the root barrier is real, not just the leaf.
  • Refusal is fail-safe, not crash-prone. With a symlinked or file-valued OPENCODE_MEMORY_DIR, every plugin hook is wrapped by guarded() — the CI log shows the fail-closed robustness test passing with warnings only.

Behavior change worth stating plainly (documented, so not blocking)

A symlinked store root worked on main (loadAll() returned rows through it) and now throws on every read (ENOTDIR in my probe; ELOOP on some platforms). The README states the contract, and the plugin degrades to warnings + no injection rather than a crash, so this is a disclosed breaking change, not a defect. Calling it out because "refused" in the body understates that previously-working configurations stop working.

Nits (optional)

  1. Opaque refusal error. tightenDirectory rethrows the raw ENOTDIR/ELOOP from openSync. A named error — "OPENCODE_MEMORY_DIR must be a real directory, not a symlink: configure <target>" — would make the breaking change self-explaining.
  2. Viewer 500s on a refused root. src/viewer/server.ts:208 calls memoryRoot() inside the route; the catch at line 187 turns it into a 500 carrying the raw errno. Same fix as nit 1 covers it.
  3. snapshot-overwrite kill is timing-flaky — pre-existing, not introduced by the re-anchor. Measured kill rate 2/3 on the PR head and 0/3 on base with the old anchor: the kill depends on two Date.now() snapshot stamps landing in the same millisecond. The re-anchor itself is correct (it applies cleanly and does get killed); the flake is in undo.test.ts's detection and predates this PR. A deterministic variant would call claimSnapshot twice with a stubbed clock.
  4. TOCTOU window on existing loose files. Between open() and fchmod() on an already-world-readable file the permissive mode briefly persists. The body already discloses that this is not comprehensive race hardening — fine as scoped.
  5. Windows validation numbers don't match CI at the cited commit. Body cites "843 passed / 19 skipped" at b2f2929; the test-windows job at that exact SHA reports 845 pass / 17 skip / 0 fail (and the same at head a175edaa). Totals agree — 862 either way — so this is two capability-gated tests that skipped in your local Windows run but ran on the hosted runner, not a miscount of the suite. Both runs are 0-fail, so nothing hides behind it; restating the numbers from the CI job would make the claim reproducible for the next reader.

Merge is your call.

@abogartz
abogartz merged commit 3b77073 into abogartz:main Nov 2, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.15.6 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Store dirs and files are created with the process umask - durable memory is group/world-readable

2 participants