Repository navigation
fix(security): confine export/import paths to the store (#24) - #145
Merged
Merged
Conversation
abogartz
force-pushed
the
fix/24-export-import-containment
branch
2 times, most recently
from
October 27, 2026 15:02
a59ad45 to
84ed4ab
Compare
abogartz
added a commit
that referenced
this pull request
Oct 27, 2026
The file clears setRepoScope / resetSessionScopes / resetState in beforeEach and restores none of it in afterEach, so bySession keeps "ses-other" -> <tmp>/repo-b and repoScopeFor() prefers a session entry over the ambient scope. Whichever file the runner schedules next stamps its rows with this file's repo key: on unmodified main, `bun test ./test/capture-sid-race.test.ts ./test/repo-scope.test.ts` fails all 9 of repo-scope, and the same two files in the reverse order pass. Adding test/containment.test.ts reshuffled bun's directory enumeration on the Linux runner and put repo-scope after capture-sid-race, so #145's required `test` check failed 2/2 with someone else's repo key while every local run was green. Teardown now mirrors setup, the way the sibling repo-scope-session.test.ts (the only other caller of rememberSessionDir) already does. Verified against all 50 files in the CI job's exact order: 9 failures before, 0 after.
memory_export's `file` went straight to Bun.write and memory_import's straight to Bun.file, so a session holding only plugin tools had an arbitrary write and an arbitrary read on the host: `file: "~/.gitconfig"` clobbered the dotfile, `../x.jsonl` walked out of the root, and a bare relative name wrote into whatever directory the opencode process happened to run in. Both destinations now go through src/containment.ts: trim then reject control characters and `~` forms, resolve against a root the plugin chose (never the process cwd), require a strict descendant, re-check the REAL path via the nearest existing ancestor so a symlink cannot carry the request out, and check the destination against the memory root as well as exports/ — undo.ts's restore already makes that two-level check. A destination that exists must be a regular file, decided with lstat so an in-root link to an in-root file is refused rather than clobbered. Traversal failures (ENOTDIR, ELOOP, ENAMETOOLONG) collapse into one neutral rejection: verbatim they are an existence oracle and a raw Bun error in a model-facing result. A root that exists as a non-directory is the exception and names its cause, because the neutral wording there sends the caller to a default that fails identically — the state the pre-fix `file: "."` bug left behind. The argument-free default destination goes through the same check as a named one. Skipping it was enough to write the whole store outside the store: an exports/ that is a symlink satisfied every per-root check. Exports are confined to <memory-root>/exports (an export is a copy of the store, so it is store data), written 0600 — chmod'd, not just created so, since open()'s mode is ignored for a file that already existed — and opened O_NOFOLLOW: the check and the open are separate syscalls and the gap is the whole store read. Imports are confined to <memory-root> and to a .jsonl name, because the `skipped: N` tally would otherwise leak line counts of day files, snapshots and the blocklist. A write that fails after containment keeps its errno, in our sentence rather than the runtime's. OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS=1 restores anywhere-on-disk for operator-run migrations. It is read from the plugin process's own environment, so a model cannot grant it to itself; it appears in the README only, never in a refusal or a tool description. Tests: 40 scenarios in test/containment.test.ts. Twenty-two mutants were run; nineteen are killed, including the two pre-fix lines themselves. Three survive and are recorded as such: moving the destination check after the store read (no black-box observable, consequence bounded by O_NOFOLLOW), checking the .jsonl suffix on the raw argument (a stricter mutant, not a weaker one), and the non-ENOENT arm of the final-component lstat, which no caller can reach because realAncestor() sees that errno first. The Windows cross-drive guard in isWithin cannot be exercised from this host. Also: memory_export reports a refusal as a soft tool message like memory_import, undo.ts's private isWithin comes from the shared module, and the wire-contract capture in boundaries.test.ts tracks the two changed argument descriptions.
The file clears setRepoScope / resetSessionScopes / resetState in beforeEach and restores none of it in afterEach, so bySession keeps "ses-other" -> <tmp>/repo-b and repoScopeFor() prefers a session entry over the ambient scope. Whichever file the runner schedules next stamps its rows with this file's repo key: on unmodified main, `bun test ./test/capture-sid-race.test.ts ./test/repo-scope.test.ts` fails all 9 of repo-scope, and the same two files in the reverse order pass. Adding test/containment.test.ts reshuffled bun's directory enumeration on the Linux runner and put repo-scope after capture-sid-race, so #145's required `test` check failed 2/2 with someone else's repo key while every local run was green. Teardown now mirrors setup, the way the sibling repo-scope-session.test.ts (the only other caller of rememberSessionDir) already does. Verified against all 50 files in the CI job's exact order: 9 failures before, 0 after.
abogartz
force-pushed
the
fix/24-export-import-containment
branch
from
October 27, 2026 19:26
bac5d1f to
9a9cb71
Compare
|
🎉 This PR is included in version 0.14.11 🎉 The release is available on: Your semantic-release bot 📦🚀 |
This was referenced Oct 27, 2026
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #24
What was wrong
Both model-facing path arguments went straight to the filesystem:
src/portable.ts—Bun.write(path, …)withpath = opts.file ?? <default>src/portable.ts—Bun.file(path)with no check at allSo a session holding only
memory_export/memory_importhad an arbitrary write and an arbitrary read on the host. Reproduced onmain(61e01b0, Bun 1.4.3, macOS):mainmemory_export { file: "<tmp>/victim.jsonl" }memory_export { file: "<tmp>/.gitconfig" }memory_import { file: "<tmp>/outside.jsonl" }memory_export { file: "~/.osi-probe.jsonl" }~— created a literal~directorymemory_export { file: "link/x.jsonl" }That last row is a second bug hiding in the same line: a relative
filewas never resolved against the store, so the destination depended on wherever opencode happened to be started.The boundary
New
src/containment.ts, applied before anything touches the filesystem:~component.~/~/…are expanded so they are judged for what they point at; a~userform we cannot resolve portably is refused instead of creating a literal~nobodydirectory. Trimming first is safe becausetrim()removes nothing but whitespace — NUL and the non-whitespace C0/C1 controls that actually matter survive it, and the test list pins that..is refused, because accepting the root would create a regular file namedexportsand disable every later export (verified on the pre-fix code).realpath()the nearest existing ancestor (lstat, so a dangling link is seen for what it is) and re-join the missing remainder, then require the real path to stay inside the real root — so a destination that does not exist yet is still checked, and a symlink cannot carry the request out.exports/: anexports/that is itself a symlink elsewhere satisfied every per-root check and still wrote outside the store. This is the two-level checkundo.ts's restore already makes — and it now covers the argument-free default, which is the call a model makes without knowing anything about the layout.lstat: astat()passes an in-root link to an in-root file and clobbers the target.ENOTDIR,ELOOP,ENAMETOOLONG) become one neutral rejection. Verbatim they were both an existence oracle and a raw Bun error in a model-facing tool result. One exception: a root that exists as a non-directory names its cause, because the neutral wording there tells the caller to "omit file for the default" and the default then fails for exactly the same reason — which is precisely the state the pre-fixfile: "."bug left behind.Applied as:
<memory-root>/exports, resolved before the store is read, written 0600 (chmod'd, not merely created that way —open()'s mode is ignored for a file that already existed) and openedO_NOFOLLOW. A write that fails after containment keeps its errno, in our sentence rather than the runtime's: the path is confined by then, so the errno is not an oracle, it is the operator's only diagnostic.<memory-root>, and to a.jsonlname. The extension rule closes a real leak, not a theoretical one: importing a day file onmainreturnedskipped: 11for an 11-line file.Also:
memory_exportreports a refusal as a soft tool message, matchingmemory_import;undo.ts's privateisWithinnow comes from the shared module so the two boundaries cannot drift;boundaries.test.ts's wire-contract capture tracks the two changed argument descriptions.Behavior change, and the way out
The README documented the vulnerability as a feature (
Export my memories to ~/memories.jsonl). The workflow survives with one copy step, which is what moving a file between machines already involves:OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS=1restores anywhere-on-disk for an operator running a one-off migration. It is read from the plugin process's own environment, so a model cannot grant it to itself through a tool argument (verified: nothing insrc/ever assignsprocess.env; plugin options come only fromctx.options). It appears in the README only — a swept pass over every registered tool name, description, argument description and 22 hostile tool results found 64 model-facing strings, none naming it. The refusal text is returned to the model, and naming the variable there is an instruction it can relay.Known limits, stated rather than papered over
O_NOFOLLOWcloses the final-component swap on POSIX only, and the test pins it deterministically rather than by racing:writeExportthrough a planted link givesELOOPwith the victim intact on this commit, and clobbers it with the flag removed. I measured a 37-of-60 win rate for that attack on this host before the flag; a second pass could not reproduce a rate, so the claim here is demonstrated possible, not measured universal. An intermediate component swapped inside the window is not caught on any platform; that needsopenat-relative traversal, which neithernode:fsnor Bun exposes.exports/shares an inode with its target and a write through it truncates that target. No path check sees this; it needs an owner or device policy.memory_exportstill writes every repository's rows into the file. That is memory_export has no repo-visibility filter — any session can export every repository's rows #143, which needs theReaderplumbing from fix(security): session-scoped reads, evidence credential scrub, viewer origin preservation (#127 #128 #129) #133 and is deliberately not folded in here.memory_evidence'sdatetraversal (security: memory_evidence date allows traversal outside the evidence directory (medium) #130) andmemory_merge_review's missing ownership check (security: memory_merge_review can supersede another repository's rows (medium) #131) are separate boundaries, already covered by draft PR fix(security): date-shaped evidence reads, ownership-checked merges, redact-before-crop capture (#130 #131 #132) #135. Confirmed still exploitable on this branch and out of scope here.<memory-root>/exportswith no rotation. Pre-existing, but confining them there makes it more visible; worth a prune story of its own.memory_undohas returned an absolute target since viewer /api/restore joins raw body.name — files outside the store can be promoted into memory #21) and the path is plugin-chosen rather than attacker-selected, but it is now unconditional.Test evidence
test/containment.test.ts— 40 scenarios: the helper directly (relative-resolves-to-root, nested creation, absolute/traversal/~/~user, empty and control chars, whitespace trimming, the root itself, a root that is not a directory, symlinked parent, dangling link in the path, in-root file link, symlinkedexports/, directory target, neutral error wording, escape hatch), plus both boundaries throughexportMemories/importMemoriesand through the registered tools, plus the writer'sO_NOFOLLOW, its0600on create and on replace, and its failure wording.Twenty-two mutants, nineteen killed:
opts.filedirectly (the pre-fix line)lstatblocklstat→statat the final componentlstat→statin the ancestor walkouterRoot) check~userrejectionO_NOFOLLOWfrom the export openchmod(0600 only at creation).trim()O_NOFOLLOW.jsonlon the raw argument instead of the targetlstatrealAncestor()sees that errno first, so no caller canThe first two rows are the red-on-
mainevidence: they reproducemain's exact behavior and fail the new boundary tests.Full local merge gate (
bun run gate, green on the pushed commit): typecheck clean ·biome lint0 errors (362 warnings onmain, 362 here; 113 infos → 112) · 561 pass / 12 skip / 0 fail · e2e 11 pass. Tests leave no residue and never touch a real~/.config/opencode/memory(verified by a 337-entry name+mtime snapshot of the live store around a full run).Five
test.skipIf(win32)sites cover four guarantees, each with its reason stated at the site:O_NOFOLLOW(libuv follows the link on Windows), the0600mode on create and on replace (Windows reports every writable file0666), the raw-ENOTDIR/ELOOPwrapping (Windows turns those intoENOENT, so there is no error to wrap), and a file symlink as the final component (needs elevation, and a junction cannot stand in — the in-root junction test does exercise that branch cross-platform). The Windows cross-drive arm ofisWithincannot be exercised from this host.Second commit: a test-isolation bug this PR stepped on
test/capture-sid-race.test.tsclearssetRepoScope/resetSessionScopes/resetStateinbeforeEachand restores none of it inafterEach.bySessionis module state shared with every other test file in the process, andrepoScopeFor()prefers a session entry over the ambient scope — so the leakedses-other → <tmp>/repo-bsilently overrides whatever the next file sets, and that file's rows come out stamped with someone else's repo key.This reproduces on unmodified
main(61e01b0):Adding
test/containment.test.tsreshuffled bun's directory enumeration on the Linux runner and putrepo-scope.test.tsaftercapture-sid-race.test.ts, which is why this PR's requiredtestcheck failed 2/2 withrepo=<hash of /tmp/osi-capture-sid-…/repo-b>while every local run was green. Teardown now mirrors setup — the way the siblingrepo-scope-session.test.ts, the only other caller ofrememberSessionDir, already does. Verified against all 50 files in the CI job's exact order: 9 failures before, 0 after. Filed as #146, which also raises the wider question of whether these registries should expose oneresetAllForTests()instead of each file remembering the globals it happens to know about.Process
Two adversarial review passes against this branch. The first found the
file: "."self-DoS, the symlinked-exports/escape, the raw-error existence oracle, the unpinnedlstat, the winnable TOCTOU race, and the hatch name leaking into model-facing text. The second found that the argument-free default skipped the very check added for the symlinkedexports/(so the README sentence I had just written was false), that0600was a claim rather than a guarantee on replace, that the neutral wording could hide an undiagnosable bricked store, and two unpinned guards. All are fixed in the pushed commit; the limits above are the ones that survived both passes.Not merged, per instruction.