Repository navigation
fix(security): finish entry-point breadth — session-scoped export + ownership-checked undo (#143 #153) - #156
Conversation
…z#143 abogartz#153) memory_export dumps every repo's private rows into a plaintext JSONL with no visibility filter; memory_undo(force) rewrites a shared day file wholesale, so a session in repo A drops or rewinds repo B's rows it can neither recall nor merge. Both red at 91f7a56: export leak + fail-closed pin red; undo force-drop leak + force-rewind-of-foreign-supersession red. Green pins: admin/ambient export breadth (the entry-point property), default-mode refuse, merge-mode foreign survival, same-repo force rollback still works.
…abogartz#153) memory_export: ExportOptions.sessionID threads readerFromSid + isVisibleTo through the export filter, the same pattern eight other entry points already use. A session exports its repo plus global; '?' or absent resolves the AMBIENT reader, so viewer/CLI keep full breadth - breadth stays a property of the entry point, never of a missing session. The tool description no longer promises a full-store backup from a plugin session. memory_undo: restoreSnapshot takes a Reader (default ADMIN_READER, so the viewer's whole-file restore is byte-identical to before). In every mode, foreign live rows are re-emitted untouched and foreign snapshot lines are never revived or rewound; the deletion audit and MERGE replay consider only the caller's own rows. CHECK keeps its documented conservatism - any divergence of the shared file, foreign included, refuses until merge/force is said on purpose - but the refusal no longer claims foreign rows would be clobbered, because they are not. memory.ts: lineVisibleTo, the day-file twin of isVisibleTo for whole-file paths (raw logfmt lines, rows' no-stamp-is-legacy rule); isVisibleTo's parameter widens to Pick<Memory, repo | repoPath> so the two share one predicate and cannot drift.
|
@abogartz Fresh review of fce47d6, including a local trial merge with current main ed5ecde (#157 / v0.14.14). One remaining P2 finding for #143: the default export artifact can become another repository's data. Please address before closing #143. The row filter works, but default destinations still use a shared second-resolution timestamp and Reproduced at this exact head and with current main trial-merged, on Windows/Bun 1.4.4: Fix: give each implicit destination a unique suffix and create it exclusively, so normal default exports cannot overwrite each other's artifacts. Keep intentional explicit-file replacement semantics separate. The local patch below does that and flips the reproduction green; merely adding milliseconds still permits collisions. The rest of this review:
No additional blocker found in the undo ownership changes. The already tracked #154/#155 are separate from this PR. Local trial edits and merge were reverted; nothing was pushed to this branch. Runnable export-collision regressionSave as import { afterEach, beforeEach, expect, test, setSystemTime } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { loadPlugin, type LoadedPlugin } from "./test/harness.ts";
import { appendMemory, loadAll, snapshotFiles } from "./src/memory.ts";
import { restoreSnapshot } from "./src/undo.ts";
import { deleteMemory } from "./src/viewer/mutate.ts";
import { rememberSessionDir, resetSessionScopes, resolveRepo, setRepoScope } from "./src/repokey.ts";
import { resetState } from "./src/state.ts";
let root: string, a: string, b: string;
let plugins: LoadedPlugin[];
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "osi-review156-"));
a = join(root, "a"); b = join(root, "b"); mkdirSync(a); mkdirSync(b);
process.env.OPENCODE_MEMORY_DIR = join(root, "memory");
process.env.OPENCODE_COMMANDS_DIR = join(root, "commands");
resetState(); resetSessionScopes(); setRepoScope(null); plugins = [];
});
afterEach(async () => {
setSystemTime();
for (const p of plugins) await p.cleanup();
resetState(); resetSessionScopes(); setRepoScope(null);
delete process.env.OPENCODE_MEMORY_DIR; delete process.env.OPENCODE_COMMANDS_DIR;
if (dirname(resolve(root)) !== resolve(tmpdir()) || !basename(root).startsWith("osi-review156-")) throw new Error("Unexpected cleanup target");
rmSync(root, {recursive: true, force: true, maxRetries: 5, retryDelay: 20});
});
async function plugin(dir: string | null) { const p = await loadPlugin(dir); plugins.push(p); return p; }
async function seed(dir: string, content: string) { const s = resolveRepo(dir); return appendMemory({type:"context",scope:"review",content,repo:s.key,repoPath:s.path}); }
const ctx = (sessionID: string) => ({sessionID,id:"review"});
const pathFrom = (content: string) => { expect(content).toContain("Exported"); return content.split(" -> ").pop()!; };
test("exports within one second must not replace another session's scoped artifact", async () => {
const pa = await plugin(a), pb = await plugin(b);
await seed(a, "PRIVATE_ALPHA_MARKER"); await seed(b, "PRIVATE_BETA_MARKER");
setSystemTime(new Date("2026-10-28T12:34:56.100Z"));
const outA = await pa.tools.memory_export.execute({}, ctx("a"));
const pathA = pathFrom(outA.content);
expect(readFileSync(pathA,"utf8")).toContain("PRIVATE_ALPHA_MARKER");
expect(readFileSync(pathA,"utf8")).not.toContain("PRIVATE_BETA_MARKER");
const outB = await pb.tools.memory_export.execute({}, ctx("b"));
const pathB = pathFrom(outB.content);
console.log("default-export-collision", JSON.stringify({pathA,pathB,readFromAsReturnedPath:readFileSync(pathA,"utf8")}));
expect(readFileSync(pathA,"utf8")).not.toContain("PRIVATE_BETA_MARKER");
});Locally verified patch (against the trial-merged tree; same changes apply to this PR)diff --git a/src/portable.ts b/src/portable.ts
index c98950f..12d4f11 100644
--- a/src/portable.ts
+++ b/src/portable.ts
@@ -4,6 +4,7 @@
// runWriteGate), so moving memories between machines cannot bypass the 4-gate
// moat. Decay is supersede-not-delete and snapshot-first, mirroring prune.
import { constants } from "node:fs";
+import { randomUUID } from "node:crypto";
import { mkdir, open } from "node:fs/promises";
import { dirname, join } from "node:path";
import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
@@ -56,9 +57,9 @@ export interface ExportResult {
count: number;
}
-// Filesystem-safe YYYY-MM-DDTHHMMSS (no colons).
+// Filesystem-safe timestamp plus a unique suffix for each default export.
function stamp(d: Date = new Date()): string {
- return d.toISOString().slice(0, 19).replace(/:/g, "");
+ return `${d.toISOString().slice(0, 19).replace(/:/g, "")}-${randomUUID()}`;
}
// An export is a full copy of the live store, so it may only be written inside
@@ -99,10 +100,11 @@ async function resolveExportTarget(file: string | undefined): Promise<string> {
// Exported so the flag itself can be pinned: the containment layer refuses an
// existing link long before this runs, so the only way to test O_NOFOLLOW
// without racing is to call the writer directly.
-export async function writeExport(path: string, text: string): Promise<void> {
+export async function writeExport(path: string, text: string, exclusive = false): Promise<void> {
await mkdir(dirname(path), { recursive: true });
const flags =
- constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0);
+ constants.O_WRONLY | constants.O_CREAT |
+ (exclusive ? constants.O_EXCL : constants.O_TRUNC) | (constants.O_NOFOLLOW ?? 0);
const handle = await open(path, flags, 0o600);
try {
await handle.writeFile(text, "utf8");
@@ -157,7 +159,7 @@ export async function exportMemories(opts: ExportOptions = {}): Promise<ExportRe
}),
);
try {
- await writeExport(path, `${[header, ...lines].join("\n")}\n`);
+ await writeExport(path, `${[header, ...lines].join("\n")}\n`, opts.file === undefined);
} catch (err) {
// Past containment, so this is not an existence oracle: `path` is one the
// plugin chose or already validated. The errno stays, because it is the |
Brings in abogartz#152's write-identity rule (writeTarget / UnresolvedWriterError at the appendMemory choke point) plus the release commit. No textual conflicts. Verified semantically after the merge, not just textually: the full gate is green (tsc, biome, unit 608 pass / 12 skip / 0 fail, e2e smoke+BDD 11 pass), and this PR's own abogartz#143/abogartz#153 probes stay green — restoreSnapshot publishes through writeAtomic, so abogartz#152's appendMemory refusal is not on the undo path.
abogartz
left a comment
There was a problem hiding this comment.
Verdict: CHANGES_REQUESTED
The security work itself is correct and I verified it independently — both leaks close, in every mode, with the admin path untouched. What must land before merge is two documentation/contract defects (F1, F2), both small, neither structural.
I merged main (v0.14.14, which is #157's write-identity rule) into this branch as 956b990 to clear the BEHIND state. No textual conflicts, and I checked the merge semantically rather than trusting that: restoreSnapshot publishes through writeAtomic, not appendMemory, so #152's new UnresolvedWriterError is not on the undo path.
What I verified myself (not from the body)
1. Red-at-base, reproduced. With src/ from origin/main and your tests: exactly the four claimed reds fire — force undo from A must preserve a private B row, force undo must not rewind a foreign row's supersession, an export run by repo A's session omits repo B's private rows, an unbound session's export carries no foreign rows. With your src/: 8/8 green. The tests genuinely die without the fix.
2. Post-merge gate, run on the merged tree: tsc clean, biome lint exit 0, unit 608 pass / 12 skip / 0 fail, e2e smoke + BDD 11 pass. merge gate: all green.
3. Nine independent probes (written from scratch against the merged branch, run, then deleted — not committed):
| Probe | Result |
|---|---|
header count equals the rows that actually landed |
✅ 2 of 3 rows, not 3 — no cross-repo count leak |
scope filter composes with visibility |
✅ a shared scope name does not smuggle B |
| scoped export with nothing to export | ✅ header-only file, Exported 0 |
| export → import round-trip (the documented workflow) | ✅ own rows re-import clean, blocked: 0 |
| FORCE: foreign line bytes | ✅ byte-identical, and the tool reports Left 1 row(s)… |
| ADMIN restore in a mixed store | ✅ still the whole-file rollback, foreignPreserved: 0 |
unbound session (global-only) force undo |
✅ touches no stamped row, does not throw |
| foreign row that B deleted itself | ✅ stays deleted — never resurrected from A's snapshot |
#89's since fileIdentity anchor |
✅ still passed to writeAtomic |
lineVisibleTo being isVisibleTo widened to Pick<Memory,"repo"|"repoPath"> is the right call — one predicate, no second filter to drift.
F1 — the new export description points at an admin route that does not exist
the full-store export is the standalone viewer/CLI path
The viewer serves /, /api/data, /api/edit, /api/delete, /api/block, /api/unblock, /api/restore-entry, /api/restore. There is no export route, and scripts/ holds only merge-gate.ts and test-sweep.ts. After this PR the only full-breadth caller is exportMemories() invoked out-of-plugin (library / bun -e) — which is fine, but is not what the sentence tells the model to promise.
The README has the same drift: README.md:201 still says "memory_export writes the live store as JSONL", and README.md:206 shows Export my memories # -> <memory-root>/exports/<stamp>.jsonl as the way to back a store up or move it between machines — now a repo-scoped export.
Ask: (a) reword the tool description to name the caller that really has full breadth (a session-less call outside the plugin), and (b) update README.md §"Export and move between machines" for the new scoping (own repo + global from a session; full store only from a session-less caller). Precedent: #103 was held for a missing README row on a behavior change.
F2 — "never restored, rewound, or dropped in any mode" has an unstated exception: global rows
isVisibleTo makes a repo=global row visible to every reader, so it lands in curOwn, not curForeign. Measured (probe P6): a global row appended after A's snapshot is dropped by A's force undo.
I am not asking for a behavior change — it follows #131's "act on exactly what you may read", and memory_forget already deletes global rows by scope. But Rows belonging to other repositories are never restored, rewound, or dropped in any mode is what a reader will take as the contract, and a global row written by B is somebody else's prose being deleted by A.
Ask: one clause in undo.ts's header comment and in the tool description (global rows are visible everywhere, therefore in scope for any repository's rollback), plus a pinned test asserting the drop so the next reader inherits the decision instead of rediscovering it.
Nits (non-blocking)
- N1
out = out.concat(curForeign)moves foreign lines to the end of the day file. Content identical, position not — "byte-identical" is true per line and a reader may take it per position. One clause settles it. - N2
lineVisibleTois called twice per live line (own filter + foreign filter), so a whole-file restore parses every line twice extra. A single partition pass would avoid it. - N3
foreignPreservedis computed on the CHECK-refusal path but the tool never surfaces it there.
Nothing here is a reason to redesign: the reader threading, the every-mode rule, the audit/divergence exclusion for foreign rows, and the admin default are all right. Fix F1/F2 and I expect to approve on sight of the diff.
…bogartz#143 review) Red at e6cc6d6: two sessions exporting in the same second get the SAME path (second-granularity stamp), and the second export's O_TRUNC replaces the first's artifact - reading the first export's own returned path yields the other repo's private rows. The abogartz#143 scoping fix leaks through the file name.
abogartz#143 review) stamp() gains a randomUUID suffix and writeExport gains an exclusive-create mode used exactly when no file was named: two sessions exporting in the same second previously got the same path, and the second's O_TRUNC replaced the first's artifact AND its returned path - the scoping fix leaking through the file name. Explicit-file callers keep the historical replace semantics backups rely on. Descriptions (tool, schema, boundaries fixture) now promise the unique default.
…review (F1, F2, N1-N3) F1: the export description named an admin route that does not exist - full-store breadth belongs to a session-less call made outside the plugin, not to a viewer export (there is none). README 'Export and move between machines' now states the scoping (own repo + global from a session; full breadth only session-less) and the unique default name. F2: the ownership rule's unstated exception is now stated - global rows are visible to EVERY reader, therefore in every repository's rollback scope; a force restore may drop a global line appended after the snapshot. Pinned by a contract test so the decision is inherited, not rediscovered. N1: 'byte-identical' was per-line, not per-position - foreign lines are carried verbatim, appended at the end; the undo.ts comments, the foreignPreserved field comment, and the tool description now say so. N2: one partition pass over the live lines instead of three lineVisibleTo filters. N3: the CHECK refusal surfaces the foreignPreserved count.
|
All findings addressed on top of your F1 — description + README. The tool description now names the caller that really has full breadth: "full-store breadth belongs to a session-less call made outside the plugin, the library route; the viewer has no export route". README §"Export and move between machines" states the scoping (own repo + global from a session; full store only from a session-less caller) and the unique default name — so the F2 — the global-row exception is now stated where a reader meets the rule: Export collision (the earlier review comment) — probes first: Nits: N1 — "byte-identical" is now per-line-per-position-honest in all three places (header, Verification at |
abogartz
left a comment
There was a problem hiding this comment.
Verdict: APPROVED
Both asks are met, the three nits are addressed, and the destination-collision fix you found yourself is correct. Re-verified against the tree at 834ccba, not against the commit messages.
F1 — export breadth description ✅
The description now names the caller that actually has full breadth ("a session-less call made outside the plugin, the library route; the viewer has no export route"), README.md §"Export and move between machines" states the scoping in prose and in the copy block, and test/boundaries.test.ts's wire fixture was updated with the schema description rather than left to drift. I re-checked the claim itself: the viewer still serves only /, /api/data, /api/edit, /api/delete, /api/block, /api/unblock, /api/restore-entry, /api/restore — the sentence is now true.
F2 — the global-row exception ✅
Stated in undo.ts's header, in RestoreResult, and in the tool description ("Global rows are visible to every repository, so they are in every repository's rollback scope"), and pinned by a contract test that asserts the drop rather than describing it. Your test pins the legacy unstamped twin; I probed the explicit repo:"global" twin separately and it behaves identically (dropped by A's force undo) — same branch of isVisibleTo, so nothing is missing, but a second row in that test would make the pair explicit. Not a blocker.
N1 / N2 / N3 ✅
Position-vs-content is now said in all three places; the live lines are partitioned in one pass; the CHECK refusal surfaces the count. I re-ran the four ownership probes against the refactored partition to confirm it is exactly equivalent: foreign line byte-identical and appended last, admin restore still the whole-file rollback with foreignPreserved: 0, an unbound session touches no stamped row, and a foreign row B deleted itself stays deleted.
The new destination fix — reviewed as new code
stamp() + randomUUID, O_EXCL applied only when the caller named no file. Verified:
- Red without it: reverting
src/portable.tsto5b9c43cfails exactlytwo sessions exporting in the same second keep separate artifacts, passes the other three. stamp()has only the two default-destination call sites — the UUID cannot leak into any other filename;exportedAtis a separate ISO value.- Default exports in one tick get distinct paths, both artifacts intact, mode
0600, name matching^\d{4}-\d{2}-\d{2}T\d{6}-[0-9a-f-]{36}\.jsonl$, still underexports/. writeExport(p, _, true)twice → second throwsEEXISTand the first file is untouched, so exclusivity is real and not just a naming convention.- Explicit
file:keeps replace (a repeatedfile: "backup.jsonl"returns the same path and rewrites it), and theOPENCODE_MEMORY_ALLOW_OUTSIDE_PATHSdefault still gets a unique destination. memory_importaccepts a unique-named export (skipped: 0) — no filename-grammar regression.
One residual, deliberately not a blocker: an explicit file: destination is still a shared namespace — a session in B can write exports/backup.jsonl that a session in A later reads, and get B's scoped content. That is outside this boundary (#24 confines to the store, not per repository, and A could read B's day file directly with the host's read tool), and replace-on-explicit-name is the documented backup workflow, so keeping it is the right call. Worth an issue so the decision is on record rather than implicit.
Evidence
bun scripts/merge-gate.tson the merged head: tsc clean, biome clean, unit 610 pass / 12 skip / 0 fail (622 tests), e2e smoke + BDD 11 pass —merge gate: all green.- CI on
834ccba:lint,test,smoke,test-windowsall pass; branch is an ancestor-descendant oforigin/main(ed5ecde), so no BEHIND at merge time. - Twelve independent probes (written for this round, run, deleted — not committed): the four ownership-equivalence probes above, the explicit-global contract, header
count= filtered rows,scopecomposing with visibility, empty export as a header-only file, export→import round-trip, and the five destination probes. - Final diff is 9 files, +466/−29, no stray debug or TODO markers.
Merging is yours. My earlier CHANGES_REQUESTED is superseded by this review.
|
Thanks for the re-verification depth — and for reviewing the destination fix as new code rather than trusting the probe that came with it. Two operational notes:
|
|
@abogartz Independent final recheck of 834ccba: my export-collision objection is cleared, and I recommend merging this head. On Windows/Bun 1.4.4, the four export/undo/portable suites plus our seven independent probes pass 54/54. In particular, our original same-second two-repository export reproduction now keeps separate paths and intact contents. I reviewed the UUID/exclusive-create change, the clarified global-row rollback contract, and the partition refactor; no additional blocker found. Your approval is on this same head and all four CI checks are green. The explicit-name shared-namespace decision remains the accepted non-blocking follow-up in #159. Duplicate #161 has been consolidated and closed. No branch changes were made by this review. |
|
🎉 This PR is included in version 0.14.15 🎉 The release is available on: Your semantic-release bot 📦🚀 |
What this is
The last two model-facing surfaces that bypass the entry-point reader #133 established. One principle, two probes, one review:
memory_export(read side, #143) dumped every repository's private rows into a plaintext JSONL, andmemory_undo(write side, #153) rewrote shared day files wholesale so a force rollback from repo A silently deleted or rewound repo B's rows A can neither recall nor merge. Both probes are verified red on91f7a56(0.14.13); the probes' file lands first, the fix second.#143 — export threads the caller's reader
ExportOptionsgainssessionID;exportMemoriesapplies the samereaderFromSid+isVisibleTofilter eight sibling entry points already use. A plugin session exports its repo + global rows."?"/absent resolves the ambient reader exactly as elsewhere: the viewer, CLI maintenance, and library callers keep full-store breadth — breadth stays a property of the entry point, never of a missing session. The tool description no longer promises a full-store backup from inside a session (the full-store route is named instead).#153 — undo respects row ownership in every mode
restoreSnapshottakes aReader(defaultADMIN_READER— the viewer's whole-file restore stays byte-identical to today's). The rule is the issue's acceptance criterion: foreign live rows survive in every mode; foreign snapshot lines are never revived or replaced in any mode. Concretely:merge/forceon purpose — but the refusal message no longer claims foreign rows would be clobbered, because they aren't anymore.Left N row(s) belonging to other repositories untouched.when it applied the rule.One new primitive
lineVisibleToinmemory.ts: the day-file twin ofisVisibleTofor whole-file paths that see raw logfmt lines instead of parsed rows (restore). It isisVisibleTo— the predicate widened toPick<Memory, "repo" | "repoPath">so there is still exactly one filter, per the comment that started with #127. It deliberately carries the rows' rule (no stamp = legacy/global), not the evidence lines' private-unstamped rule — that difference is the reason the twins exist.Deliberate boundaries
allRepos: truefrom the issue's suggestion: skipped. The ambient path already is the admin route; a model-facing flag would add a bypass surface for nothing. Easy to add on request.Evidence
91f7a56: export leak + unbound fail-closed pin red; undo force-drop leak + force-rewind red (test/export-visibility.test.ts2/3 red,test/undo-ownership.test.ts2/5 red) — including the issue-P1: memory_undo force rollback lets one repository remove another repository's private rows #153 probe verbatim (adapted only to relative test/ imports).containment.test.tssymlink EPERMs, this machine's unprivileged-Windows environment per test/containment.test.ts: 2 of 7 symlink tests miss the file's win32 skip guard and EPERM on unprivileged Windows #147 (unrelated files, untouched code; ubuntu CI runs them green).tsc --noEmitclean;biome lint(the CI gate) 0 errors.Related: #127 (reader machinery), #131 (id-is-not-authority), #152 (the write-side twin of the binding story — separate branch), #145/#74 (export boundaries).