Public: anyone can read this; the crew can change it.

An imported session is deleted through the API by its owner who sends its exact title #18390

opened this

Merged 1h 50m ago, live in production

scout/forge:scout/18388-an-imported-session-is-deleted-through-t → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/18388-an-imported-session-is-deleted-through-t was merged into main as 2c0a8b8.

Review

Sign in to review this change.
9 files changed +239 −5
docs/features/traces.md +3 −1
@@ -56,7 +56,9 @@ For Codex, point the same command at a rollout: `--data-binary @"$(ls -t ~/.code
5656
5757 `POST /api/v1/traces/import` takes the session JSONL (Claude Code or Codex) as the raw body, at most 32 MiB (a plain 413 past it; `traceImport` in `src/kernel/body_caps.ts`). The file is read by the reader of its source (`src/trace/claude_code.ts`, `src/trace/codex.ts`), stored gzipped as `traces/imported/<id>.jsonl.gz` under the data directory, and indexed as a trace of kind `imported`, attributed to the caller and private to them: `GET /api/v1/traces?kind=imported` lists it for them and for no one else. The id comes from the caller and the session's own id, so sending the same session again answers 200 and replaces its trace; a first send answers 201. A file that is not UTF-8, is empty, holds no session records or carries no usable `sessionId` is a 422 (`invalid_session`) that says which. An account keeps at most 256 MiB of imported sessions (compressed, as stored; `IMPORT_QUOTA_BYTES` in `src/trace/import.ts`): an import that would pass it is a 413 (`quota_exceeded`), and re-sending a session replaces its own copy in the count. A person's imported files are deleted with their account. A session caller's cross-origin request is a 403.
5858
59 A new source is one file implementing `ImportAdapter` (`src/trace/import_adapter.ts`, see `import_claude_code.ts`) and one line in `ADAPTERS`; Codex rollouts are taken the same way (`import_codex.ts`). Not yet: deleting one.
59 A new source is one file implementing `ImportAdapter` (`src/trace/import_adapter.ts`, see `import_claude_code.ts`) and one line in `ADAPTERS`; Codex rollouts are taken the same way (`import_codex.ts`).
60
61 `DELETE /api/v1/traces/<id>` (#18388) deletes one imported session, with `{ "confirm": "<the session's title>" }` as its body (at most 4 KiB; `traceDelete` in `src/kernel/body_caps.ts`). Nothing is removed unless the title is sent exactly: a wrong or missing one is a 422 (`name_mismatch`) and the file and rows stay. Only the importer may: another person's or an unknown id is a 404, a crew run or Talk turn is a 403 (`record_kept`, its record is kept), a session caller's cross-origin request is a 403, and a session with a live share link is a 409 (`shared`: stop sharing first). A right name removes `traces/imported/<id>.jsonl.gz`, the index row and its touched tools and files (`deleteImported` in `src/trace/import.ts`), frees the quota, and answers `{ removed, title, bytes }`. Not yet: a button on the page and a terminal screen.
6062
6163 `/traces/<id>` of an imported trace (#18357) is the same tree and strip a crew run has, read from the stored file (`src/trace/imported_read.ts`, `src/web/pages/trace_imported.ts`), with `#step-N` permalinks and each step's raw lines (the file's lines that name it) on demand at `/traces/<id>/steps/<n>`. Only the importer reads it; anyone else gets the not-found an unknown id gets. Each step line shows the tokens its file held for it (`5 in, 7 cached, 9 out`; a reply split across records is counted once) and the total is their sum; a session holds no cost, and sometimes no tokens: the page says "not recorded in this file" rather than zero. Steps are capped at 20,000. `GET /api/v1/traces/<id>` answers the same tree for an imported id.
6264 ## One trace as a tree (#18022)
scripts/unused-exports-allow.json +1 −2
@@ -180,6 +180,5 @@
180180 "src/spawn/machines.ts forgetMachines",
181181 "src/spawn/machines.ts registerMachine",
182182 "src/spawn/routes.ts forgetRoutes",
183 "src/maintain/lockfiles.ts lockfileDependencies",
184 "src/trace/import.ts readImported"
183 "src/maintain/lockfiles.ts lockfileDependencies"
185184 ]
src/contract/openapi/routes/deleteApiV1TracesId.ts added +16
@@ -0,0 +1,16 @@
1 import { bool, int, obj, str } from "../schema_kit.ts";
2 import type { Route } from "../shared.ts";
3
4 export const route: Route = {
5 method: "delete",
6 path: "/api/v1/traces/{id}",
7 summary: "Delete one of your imported sessions",
8 detail:
9 "Body { confirm }: the session's exact title; nothing is removed without it. Removes the stored file, the index row and its touched tools and files, and frees the quota. Another person's or an unknown id is a 404 not_found; a crew run or Talk turn is a 403 record_kept; a session with a live share link is a 409 shared. A session caller's cross-origin request is refused (403). Answers { removed, title, bytes }",
10 auth: true,
11 role: "member",
12 body: { confirm: "string" },
13 response: obj({ removed: bool, title: str, bytes: int }),
14 errorStatus: { 409: "shared: stop sharing first", 422: "name_mismatch: confirm is not the session's exact title" },
15 refuses: [401, 403, 404],
16 };
src/contract/openapi/routes/index.ts +1
@@ -44,6 +44,7 @@ export { route as deleteApiV1SecretsScopeName } from "./deleteApiV1SecretsScopeN
4444 export { route as deleteApiV1Sessions } from "./deleteApiV1Sessions.ts";
4545 export { route as deleteApiV1TimersKey } from "./deleteApiV1TimersKey.ts";
4646 export { route as deleteApiV1TokensId } from "./deleteApiV1TokensId.ts";
47 export { route as deleteApiV1TracesId } from "./deleteApiV1TracesId.ts";
4748 export { route as deleteApiV1TracesSavedId } from "./deleteApiV1TracesSavedId.ts";
4849 export { route as deleteApiV1UserDevicesId } from "./deleteApiV1UserDevicesId.ts";
4950 export { route as deleteApiV1UserKeysId } from "./deleteApiV1UserKeysId.ts";
src/http/api/traces.ts +36 −2
@@ -11,8 +11,8 @@ import { getRun } from "../../core/runs.ts";
1111 import { compareViews, sameIssue } from "../../trace/compare.ts";
1212 import { readTrace, type TraceView } from "../../trace/read.ts";
1313 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
14 import { importSession } from "../../trace/import.ts";
15 import { LIST_PARAMETERS, listSeenTraces, readListAsk, TRACE_ID, traceTree } from "../../trace/tree.ts";
14 import { deleteImported, IMPORTED_ID, importSession } from "../../trace/import.ts";
15 import { LIST_PARAMETERS, listSeenTraces, readListAsk, seenTraceRow, TRACE_ID, traceTree } from "../../trace/tree.ts";
1616 import { cleanName, MAX_SAVED, openedSaved, openSaved, removeSaved, SAVE_WORDS, saveSearch, type OpenedSearch } from "../../trace/saved.ts";
1717 import { MAX_LIMIT } from "../../trace/index_table.ts";
1818 import type { Handler } from "../context.ts";
@@ -57,6 +57,39 @@ export const importTrace: Handler = async (ctx) => {
5757 return json({ ...done.row, session: done.session, source: done.source, updated: done.updated }, done.updated ? 200 : 201);
5858 };
5959
60 /**
61 * DELETE /api/v1/traces/:id (#18388): `{ "confirm": "<the title>" }` removes the caller's own
62 * imported session, its file and rows, and answers `{ removed, title, bytes }`. Nothing is removed
63 * without the person naming it; a crew run or Talk turn is kept (403), a live share link is a 409.
64 */
65 export const deleteTrace: Handler = async (ctx) => {
66 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
67 const denied = requireScope(ctx, "rw");
68 if (denied) return denied;
69 const id = ctx.params.id ?? "";
70 const row = seenTraceRow(ctx.app, ctx.auth.user!, id);
71 if (row === undefined) return apiError("not_found", 404, "no such trace");
72 if (row.kind !== "imported") return apiError("record_kept", 403, "a crew run's or a Talk turn's record is kept; only an imported session is deleted");
outdated

Medium: !IMPORTED_ID.test(id) shares this branch with the kind check, so an imported row with an odd id answers 403 record_kept, which is not true of it. Validate the id shape first and answer 404 for it, before seenTraceRow. Keep this branch for the kind only.

73 // An imported row's id is 32 hex digits; any other shape is not one this route builds a path
74 // from.
75 if (!IMPORTED_ID.test(id)) return apiError("not_found", 404, "no such trace");
76 const raw = await readBounded(ctx.request, BODY_CAPS.traceDelete.bytes);
77 if (raw === "too_large") return apiError("too_large", 413, `the confirmation is at most ${BODY_CAPS.traceDelete.bytes / 1024} KiB`);
78 let confirm: unknown;
79 try {
80 confirm = (JSON.parse(new TextDecoder().decode(raw)) as { confirm?: unknown } | null)?.confirm;
81 } catch {
82 confirm = undefined;
83 }
84 const done = deleteImported(ctx.app.db, ctx.app.config.dataDir, ctx.auth.user!.id, id, confirm);
85 if (!done.ok) {
86 return done.error === "shared"
87 ? apiError("shared", 409, "this session has a live share link: stop sharing it first")
88 : apiError("name_mismatch", 422, "send { \"confirm\": <the session's exact title> } to delete it");
89 }
90 return json({ removed: true, title: done.title, bytes: done.bytes });
91 };
92
6093 /**
6194 * GET /api/v1/traces/:id (#18022): the thread, its turns and their steps as one tree, rebuilt from
6295 * the raw log with `parseRunLog` (a Talk turn's log is a run log). A trace the caller may not see
@@ -150,5 +183,6 @@ export function traceRoutes(router: Router<Handler>): void {
150183 router.add("DELETE", "/api/v1/traces/saved/:id", removeSavedTrace);
151184 router.add("GET", "/api/v1/traces/compare", compareTraces);
152185 router.add("GET", "/api/v1/traces/:id", readTraceTree);
186 router.add("DELETE", "/api/v1/traces/:id", deleteTrace);
153187 router.add("GET", "/api/v1/traces", listTraces);
154188 }
src/http/lazy_lists.ts +1
@@ -1547,6 +1547,7 @@ export const API_ROUTES = [
15471547 ["DELETE", "/api/v1/traces/saved/:id"],
15481548 ["GET", "/api/v1/traces/compare"],
15491549 ["GET", "/api/v1/traces/:id"],
1550 ["DELETE", "/api/v1/traces/:id"],
15501551 ["GET", "/api/v1/traces"],
15511552 ["POST", "/api/v1/builds"],
15521553 ["GET", "/api/v1/conversations/:id/build"],
src/kernel/body_caps.ts +4
@@ -149,6 +149,10 @@ export const BODY_CAPS = {
149149 bytes: 32 * MIB,
150150 reason: "one agent session file sent to be kept as a trace: a long Claude Code session runs to a few MiB, read whole to check it before anything is kept",
151151 },
152 traceDelete: {
153 bytes: 4 * KIB,
154 reason: "the confirmation that deletes an imported session: its title (cut to 120 characters) in a small JSON object",
155 },
152156 printRaster: {
153157 bytes: 80 * MIB,
154158 reason: "PWG raster sent to a printer: uncompressed pages run large; every page is walked before anything is sent",
src/trace/import.ts +26
@@ -60,6 +60,32 @@ export function removeImported(dataDir: string, ids: readonly string[]): void {
6060 for (const id of ids) rmSync(fileOf(dataDir, id), { force: true });
6161 }
6262
63 /** What a removal answers: the session's title and the stored bytes it frees. */
64 export type Removal =
65 | { readonly ok: true; readonly title: string; readonly bytes: number }
66 | { readonly ok: false; readonly error: "name_mismatch" | "shared" };
67
68 /** An imported id as `importedId` makes it: the only shape a path is ever built from. */
69 export const IMPORTED_ID = /^[0-9a-f]{32}$/;
70
71 /**
72 * Remove one imported session of `owner` (its row, its touches, its file) when `confirm` is its
73 * exact title and no share link is live. The caller has already checked the row is the owner's.
74 */
75 export function deleteImported(db: Database, dataDir: string, owner: string, id: string, confirm: unknown): Removal {
76 const row = IMPORTED_ID.test(id) ? db.query<{ title: string }, [string, string]>("SELECT title FROM trace_index WHERE id = ?1 AND owner = ?2").get(id, owner) : null;
77 if (row === null) return { ok: false, error: "name_mismatch" };
78 if (typeof confirm !== "string" || confirm !== row.title) return { ok: false, error: "name_mismatch" };
79 if (db.query("SELECT 1 FROM trace_share WHERE run_id = ?1 AND revoked_at IS NULL").get(id) !== null) return { ok: false, error: "shared" };
80 const bytes = sizeOf(fileOf(dataDir, id));
81 db.transaction(() => {
82 db.query("DELETE FROM trace_touch WHERE trace_id = ?1").run(id);
83 db.query("DELETE FROM trace_index WHERE id = ?1 AND owner = ?2").run(id, owner);
84 })();
85 removeImported(dataDir, [id]);
86 return { ok: true, title: row.title, bytes };
87 }
88
6389 /** What the stored file is now (size and mtime), so a re-import, which replaces it, is seen. */
6490 export function stampOf(dataDir: string, id: string): string | undefined {
6591 try {
test/traces-delete.test.ts added +151
@@ -0,0 +1,151 @@
1 /**
2 * DELETE /api/v1/traces/:id (#18388): an imported session goes only to its owner who sends its
3 * exact title; the file, the row and the touches go together and the quota is freed.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { existsSync, readdirSync, statSync } from "node:fs";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { newConversation } from "../src/core/conversations.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { importedIdsOf } from "../src/trace/import.ts";
17 import { indexTalkTurn, putTraceRow } from "../src/trace/index_table.ts";
18 import { seedAdmin } from "./helpers/admin.ts";
19
20 const rec = (o: object): string => JSON.stringify({ sessionId: "sess-d", cwd: "/w", ...o });
21 const SESSION = [
22 rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "fix the login bug" } }),
23 rec({ type: "assistant", timestamp: "2026-12-01T09:00:01Z", message: { id: "m1", model: "claude-x", role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Edit", input: { file_path: "a.ts", old_string: "a", new_string: "b" } }], usage: { input_tokens: 5, output_tokens: 9 } } }),
24 ].join("\n");
25
26 let dir = "";
27 let app: App;
28 let servers: Servers;
29 let alice = "";
30 let aliceUser: User;
31 let bob = "";
32 let id = "";
33
34 const file = (i: string): string => join(dir, "traces", "imported", `${i}.jsonl.gz`);
35 const del = (token: string, i: string, body?: unknown, headers: Record<string, string> = {}): Promise<Response> =>
36 fetch(`${servers.url}/api/v1/traces/${i}`, { method: "DELETE", headers: { authorization: `Bearer ${token}`, ...headers }, body: body === undefined ? undefined : JSON.stringify(body) });
37 const mine = async (token: string): Promise<any[]> =>
38 ((await (await fetch(`${servers.url}/api/v1/traces?kind=imported`, { headers: { authorization: `Bearer ${token}` } })).json()) as any).items;
39 const touches = (i: string): number => app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM trace_touch WHERE trace_id = ?1").get(i)!.n;
40 const upload = async (): Promise<string> => {
41 const res = await fetch(`${servers.url}/api/v1/traces/import`, { method: "POST", headers: { authorization: `Bearer ${alice}` }, body: SESSION });
42 return ((await res.json()) as any).id;
43 };
44
45 beforeAll(async () => {
46 dir = await mkdtemp(join(tmpdir(), "forge-traces-delete-"));
47 app = createApp({ dataDir: dir, port: 0 });
48 servers = await serve(app);
49 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
50 if (!a.ok) throw new Error(a.error);
51 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
52 if (!b.ok) throw new Error(b.error);
53 aliceUser = a.value;
54 alice = createToken(app.db, a.value.id, "t", "rw").token;
55 bob = createToken(app.db, b.value.id, "t", "rw").token;
56 id = await upload();
57 }, 30_000);
58
59 afterAll(async () => {
60 await servers.stop();
61 await rm(dir, { recursive: true, force: true });
62 });
63
64 test("a wrong, missing or malformed confirm is a 422 and keeps the file and the row", async () => {
65 expect(touches(id)).toBeGreaterThan(0);
66 for (const body of [{ confirm: "fix the login" }, {}, { confirm: 7 }, undefined]) {
67 const res = await del(alice, id, body);
68 expect(res.status).toBe(422);
69 expect(((await res.json()) as any).error).toBe("name_mismatch");
70 }
71 expect(existsSync(file(id))).toBe(true);
72 expect((await mine(alice)).map((r) => r.id)).toEqual([id]);
73 expect(touches(id)).toBeGreaterThan(0);
74 });
75
76 test("another person's session is a 404 and stays; a malformed or unknown id is refused", async () => {
77 expect((await del(bob, id, { confirm: "fix the login bug" })).status).toBe(404);
78 expect((await del(alice, "nope0000000000000000000000000000", { confirm: "x" })).status).toBe(404);
79 expect((await del(alice, "..%2F..%2Fsecret", { confirm: "x" })).status).toBe(404);
80 expect(existsSync(file(id))).toBe(true);
81 expect(await mine(alice)).toHaveLength(1);
82 });
83
outdated

Medium: if the login gives no cookie, the whole block is skipped and the test passes without asserting the 403. Require the cookie (expect(cookie).not.toBe("")) and assert 403 unconditionally. Add a same-origin success case so the test fails if the check is removed.

84 test("a cross-site session request is a 403 and removes nothing; the same session without that Origin passes", async () => {
85 const login = await fetch(`${servers.url}/signin`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url }, body: new URLSearchParams({ username: "alice", password: "correct-horse-battery" }) });
86 expect(login.status).toBeLessThan(400);
87 const cookie = (login.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
88 expect(cookie).not.toBe("");
89 const send = (headers: Record<string, string>, confirm: string) =>
90 fetch(`${servers.url}/api/v1/traces/${id}`, { method: "DELETE", headers: { cookie, ...headers }, body: JSON.stringify({ confirm }) });
91 const evil = await send({ origin: "https://evil.example" }, "fix the login bug");
92 expect(evil.status).toBe(403);
93 expect(existsSync(file(id))).toBe(true);
outdated

Medium: [403, 404] passes when the route 404s, so the record_kept behaviour is untested. Seed the row so seenTraceRow finds it for alice, then expect exactly 403 and the record_kept error code.

94 // Same cookie, own origin: it gets past the Origin check (a wrong title is the 422 after it).
95 expect((await send({ origin: servers.url }, "wrong")).status).toBe(422);
96 expect((await send({}, "wrong")).status).toBe(422);
97 expect(existsSync(file(id))).toBe(true);
98 });
99
100 test("a crew run's and a Talk turn's record is kept: exactly 403 record_kept", async () => {
101 const user = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!.id;
102 const repo = await createRepo(app, aliceUser, { name: "kept", visibility: "public", description: "" });
103 if (!repo.ok) throw new Error(String(repo.error));
104 app.db.query("INSERT INTO run (id, repo_id, kind, state, summary, model, actor_id, cost_usd, created_at, finished_at) VALUES ('run0001', ?1, 'agent', 'ok', 'a run', 'm', ?2, 0, ?3, ?3)").run(repo.value.id, user, "2026-12-01T09:00:00.000Z");
105 putTraceRow(app.db, { id: "run0001", kind: "run", repository: repo.value.id, title: "a run", model: "", account: "", steps: 0, errors: 0, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, outcome: "ok", started: "2026-12-01T09:00:00.000Z", ended: "2026-12-01T09:00:01.000Z" });
106 const convo = newConversation(app.db, user);
107 app.db.query("INSERT INTO conversation_run (id, conversation_id, user_id, state, prompt, started_at, finished_at, model) VALUES ('talk0001', ?1, ?2, 'ok', 'a turn', '2026-12-04T13:00:00.000Z', '2026-12-04T13:00:01.000Z', 'm')").run(convo.id, user);
108 indexTalkTurn(app.db, dir, "talk0001");
109 for (const [rid, title] of [["run0001", "a run"], ["talk0001", "a turn"]] as const) {
110 const res = await del(alice, rid, { confirm: title });
111 expect(res.status).toBe(403);
112 expect(((await res.json()) as any).error).toBe("record_kept");
113 expect(app.db.query("SELECT 1 FROM trace_index WHERE id = ?1").get(rid)).not.toBeNull();
114 }
115 });
116
117 test("an imported row whose id is not 32 hex is a 404, not a false record_kept", async () => {
118 const user = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!.id;
119 putTraceRow(app.db, { id: "imp1", kind: "imported", repository: "", title: "odd", model: "", account: "", steps: 0, errors: 0, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, outcome: "ok", started: "2026-12-01T09:00:00.000Z", ended: "2026-12-01T09:00:01.000Z" }, user);
120 const res = await del(alice, "imp1", { confirm: "odd" });
121 expect(res.status).toBe(404);
122 expect(app.db.query("SELECT 1 FROM trace_index WHERE id = 'imp1'").get()).not.toBeNull();
123 app.db.query("DELETE FROM trace_index WHERE id = 'imp1'").run();
124 });
125
126 test("a session with a live share link is a 409 until it is stopped", async () => {
127 app.db.query("INSERT INTO trace_share (id, run_id, token_hash, created_by, created_at) VALUES ('s1', ?1, 'h1', 'u', 'now')").run(id);
128 const res = await del(alice, id, { confirm: "fix the login bug" });
129 expect(res.status).toBe(409);
130 expect(existsSync(file(id))).toBe(true);
131 app.db.query("UPDATE trace_share SET revoked_at = 'now' WHERE id = 's1'").run();
132 });
133
134 test("the exact title removes the file, the row and the touches, frees the quota and answers a receipt", async () => {
135 const size = Bun.file(file(id)).size;
136 const stored = (): number => readdirSync(join(dir, "traces", "imported")).reduce((n, f) => n + statSync(join(dir, "traces", "imported", f)).size, 0);
137 const before = stored();
138 const res = await del(alice, id, { confirm: "fix the login bug" });
139 expect(res.status).toBe(200);
140 expect(await res.json()).toEqual({ removed: true, title: "fix the login bug", bytes: size });
141 expect(size).toBeGreaterThan(0);
142 expect(existsSync(file(id))).toBe(false);
143 expect(await mine(alice)).toEqual([]);
144 expect(touches(id)).toBe(0);
145 expect(importedIdsOf(app.db, app.db.query<{ id: string }, []>("SELECT id FROM user LIMIT 1").get()!.id)).toEqual([]);
146 expect((await del(alice, id, { confirm: "fix the login bug" })).status).toBe(404);
147 // The quota counts stored bytes: they drop by the receipt's `bytes`.
148 expect(stored()).toBe(before - size);
149 // And the same session imports as new.
150 expect(await upload()).toBe(id);
151 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs