Skip to content

fix(security): confine export/import paths to the store (#24) - #145

Merged
abogartz merged 2 commits into
mainfrom
fix/24-export-import-containment
Oct 27, 2026
Merged

abogartz merged 2 commits into
mainfrom
fix/24-export-import-containment

Conversation

@abogartz

@abogartz abogartz commented Oct 27, 2026 •

Copy link
Copy Markdown
Owner

Closes #24

What was wrong

Both model-facing path arguments went straight to the filesystem:

  • src/portable.ts — Bun.write(path, …) with path = opts.file ?? <default>
  • src/portable.ts — Bun.file(path) with no check at all

So a session holding only memory_export / memory_import had an arbitrary write and an arbitrary read on the host. Reproduced on main (61e01b0, Bun 1.4.3, macOS):

probe on main
memory_export { file: "<tmp>/victim.jsonl" } wrote it
memory_export { file: "<tmp>/.gitconfig" } clobbered the dotfile
memory_import { file: "<tmp>/outside.jsonl" } read it, rows reached the gate
memory_export { file: "~/.osi-probe.jsonl" } nothing expands ~ — created a literal ~ directory
memory_export { file: "link/x.jsonl" } wrote into the host process's cwd, not the store

That last row is a second bug hiding in the same line: a relative file was 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:

  1. Trim, then reject control characters and any leading ~ component. ~/~/… are expanded so they are judged for what they point at; a ~user form we cannot resolve portably is refused instead of creating a literal ~nobody directory. Trimming first is safe because trim() removes nothing but whitespace — NUL and the non-whitespace C0/C1 controls that actually matter survive it, and the test list pins that.
  2. Resolve against a root the plugin chose, never the process cwd, and require a strict descendant: . is refused, because accepting the root would create a regular file named exports and disable every later export (verified on the pre-fix code).
  3. 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.
  4. Also check against the memory root, not just exports/: an exports/ that is itself a symlink elsewhere satisfied every per-root check and still wrote outside the store. This is the two-level check undo.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.
  5. If the final component exists it must be a regular file, decided with lstat: a stat() passes an in-root link to an in-root file and clobbers the target.
  6. Traversal failures (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-fix file: "." bug left behind.

Applied as:

  • export → confined to <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 opened O_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.
  • import → confined to <memory-root>, and to a .jsonl name. The extension rule closes a real leak, not a theoretical one: importing a day file on main returned skipped: 11 for an 11-line file.

Also: memory_export reports a refusal as a soft tool message, matching memory_import; undo.ts's private isWithin now 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:

Export my memories                        # -> <memory-root>/exports/<stamp>.jsonl
# …copy that file to the other machine's <memory-root>/…
Import <memory-root>/memories.jsonl

OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS=1 restores 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 in src/ ever assigns process.env; plugin options come only from ctx.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

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, symlinked exports/, directory target, neutral error wording, escape hatch), plus both boundaries through exportMemories / importMemories and through the registered tools, plus the writer's O_NOFOLLOW, its 0600 on create and on replace, and its failure wording.

Twenty-two mutants, nineteen killed:

mutant result
export uses opts.file directly (the pre-fix line) killed ×12
import skips containment (the pre-fix line) killed ×4
default destination skips containment killed ×2
drop the realpath containment check killed ×2
drop the final-component lstat block killed ×3
lstat → stat at the final component killed ×1
lstat → stat in the ancestor walk killed ×1
drop the control-character floor killed ×2
no trim before the control-character check killed ×4
drop home expansion killed ×1
drop the strict-descendant check killed ×1
drop the memory-root (outerRoot) check killed ×1
drop the root-is-not-a-directory cause killed ×1
rethrow raw fs errors instead of neutral wording killed ×1
rethrow raw runtime text on a failed write killed ×1
drop the ~user rejection killed ×1
remove O_NOFOLLOW from the export open killed ×1
drop the chmod (0600 only at creation) killed ×1
drop .trim() killed ×3
move the destination check after the store read survived — no black-box observable; consequence bounded by O_NOFOLLOW
check .jsonl on the raw argument instead of the target survived — that mutant is stricter, not weaker
drop the non-ENOENT arm of the final-component lstat survived — unreachable: realAncestor() sees that errno first, so no caller can

The first two rows are the red-on-main evidence: they reproduce main's exact behavior and fail the new boundary tests.

Full local merge gate (bun run gate, green on the pushed commit): typecheck clean · biome lint 0 errors (362 warnings on main, 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), the 0600 mode on create and on replace (Windows reports every writable file 0666), the raw-ENOTDIR/ELOOP wrapping (Windows turns those into ENOENT, 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 of isWithin cannot be exercised from this host.

Second commit: a test-isolation bug this PR stepped on

test/capture-sid-race.test.ts clears setRepoScope / resetSessionScopes / resetState in beforeEach and restores none of it in afterEach. bySession is module state shared with every other test file in the process, and repoScopeFor() prefers a session entry over the ambient scope — so the leaked ses-other → <tmp>/repo-b silently 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):

$ bun test ./test/capture-sid-race.test.ts ./test/repo-scope.test.ts   # → 9 failures, all of repo-scope
$ bun test ./test/repo-scope.test.ts ./test/capture-sid-race.test.ts   # → 15 pass

Adding test/containment.test.ts reshuffled bun's directory enumeration on the Linux runner and put repo-scope.test.ts after capture-sid-race.test.ts, which is why this PR's required test check failed 2/2 with repo=<hash of /tmp/osi-capture-sid-…/repo-b> 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. Filed as #146, which also raises the wider question of whether these registries should expose one resetAllForTests() 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 unpinned lstat, 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 symlinked exports/ (so the README sentence I had just written was false), that 0600 was 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.

@abogartz
abogartz force-pushed the fix/24-export-import-containment branch 2 times, most recently from a59ad45 to 84ed4ab Compare October 27, 2026 15:02
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
abogartz force-pushed the fix/24-export-import-containment branch from bac5d1f to 9a9cb71 Compare October 27, 2026 19:26
@abogartz
abogartz merged commit f6782e3 into main Oct 27, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.14.11 🎉

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.

memory_export/memory_import accept arbitrary paths outside the memory root

1 participant