@exulu/backend 5.12.0 → 5.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Behaviour of a real (direct-exec) session sandbox around `project/`: S3 is
3
+ * mocked, the SRT wrapper passes commands through unchanged, files land in a
4
+ * real /tmp/exulu-sessions/<unique id> directory that is removed afterwards.
5
+ */
6
+ jest.mock("@anthropic-ai/sandbox-runtime", () => ({
7
+ SandboxManager: {
8
+ initialize: jest.fn(async () => {}),
9
+ wrapWithSandbox: jest.fn(async (cmd: string) => cmd),
10
+ reset: jest.fn(async () => {}),
11
+ },
12
+ }));
13
+ jest.mock("@SRC/uppy/index.ts", () => ({
14
+ listS3ObjectsByPrefix: jest.fn(async () => []),
15
+ getS3ObjectBytes: jest.fn(),
16
+ uploadFile: jest.fn(async (_c: Buffer, key: string) => `bucket/user_7/${key}`),
17
+ getPresignedUrl: jest.fn(async () => "https://signed"),
18
+ }));
19
+ jest.mock("@SRC/postgres/client", () => ({
20
+ postgresClient: jest.fn(async () => ({ db: { from: () => ({ select: async () => [] }) } })),
21
+ }));
22
+ jest.mock("@SRC/exulu/system-dependencies.ts", () => ({ getNpmGlobalRoot: jest.fn(async () => null) }));
23
+ jest.mock("@SRC/utils/python-setup.ts", () => ({ getPythonVenvPath: () => undefined }));
24
+
25
+ import { existsSync } from "node:fs";
26
+ import { readFile } from "node:fs/promises";
27
+ import { join } from "node:path";
28
+ import { listS3ObjectsByPrefix, getS3ObjectBytes, uploadFile } from "@SRC/uppy/index.ts";
29
+ import { createSessionSandbox } from "./create-sandbox";
30
+
31
+ const list = listS3ObjectsByPrefix as jest.Mock;
32
+ const bytes = getS3ObjectBytes as jest.Mock;
33
+ const upload = uploadFile as jest.Mock;
34
+ const config = { fileUploads: { s3Bucket: "bucket" } } as any;
35
+
36
+ const uploadedKeys = () => upload.mock.calls.map((c) => c[1] as string);
37
+
38
+ // Project files come from the project prefix; the session prefix is empty.
39
+ const remote = (files: Record<string, string>) => {
40
+ list.mockImplementation(async (prefix: string) =>
41
+ prefix.startsWith("projects/")
42
+ ? Object.entries(files).map(([name, body]) => ({ key: `${prefix}${name}`, size: body.length, lastModified: new Date() }))
43
+ : [],
44
+ );
45
+ bytes.mockImplementation(async (key: string) => Buffer.from(files[key.split("/").pop()!] ?? ""));
46
+ };
47
+
48
+ let handles: Array<{ cleanup: () => Promise<void> }> = [];
49
+ const open = async (sid: string, projectId: string | null) => {
50
+ const h = await createSessionSandbox(sid, [], config, 7, undefined, { projectId });
51
+ handles.push(h);
52
+ return h;
53
+ };
54
+ const sid = () => `jest-project-${process.pid}-${Math.random().toString(36).slice(2)}`;
55
+
56
+ beforeEach(() => {
57
+ upload.mockClear();
58
+ list.mockClear();
59
+ remote({});
60
+ jest.spyOn(console, "warn").mockImplementation(() => {});
61
+ jest.spyOn(console, "log").mockImplementation(() => {});
62
+ });
63
+ afterEach(async () => {
64
+ for (const h of handles) await h.cleanup();
65
+ handles = [];
66
+ jest.restoreAllMocks();
67
+ });
68
+
69
+ const run = (h: any, command: string) => h.tools.bash.execute({ command }, { toolCallId: "t", messages: [] });
70
+ const write = (h: any, path: string, content: string) =>
71
+ h.tools.writeFile.execute({ path, content }, { toolCallId: "t", messages: [] });
72
+
73
+ describe("session sandbox with a project", () => {
74
+ it("materialises project files under project/ and never writes them back", async () => {
75
+ remote({ "brief.txt": "shared" });
76
+ const id = sid();
77
+ const h = await open(id, "p1");
78
+ expect(await readFile(join(h.sessionDir, "project", "brief.txt"), "utf8")).toBe("shared");
79
+
80
+ const w = await write(h, "project/mine.txt", "x");
81
+ expect(w.key).toBeUndefined();
82
+ await run(h, "echo y > project/bash.txt && echo z > out.txt");
83
+
84
+ expect(uploadedKeys()).toEqual([`sessions/${id}/out.txt`]);
85
+ expect(upload.mock.calls[0][3]).toEqual({ metadata: { "exulu-origin": "agent" } });
86
+ });
87
+
88
+ it("the next turn replaces agent edits and drops files gone from the project", async () => {
89
+ remote({ "a.txt": "aaa", "b.txt": "bb" });
90
+ const id = sid();
91
+ const h = await open(id, "p1");
92
+ await run(h, "echo changed-content > project/a.txt && echo extra > project/extra.txt");
93
+
94
+ remote({ "a.txt": "aaa" });
95
+ await open(id, "p1"); // cache hit
96
+ expect(await readFile(join(h.sessionDir, "project", "a.txt"), "utf8")).toBe("aaa");
97
+ expect(existsSync(join(h.sessionDir, "project", "b.txt"))).toBe(false);
98
+ expect(existsSync(join(h.sessionDir, "project", "extra.txt"))).toBe(false);
99
+ });
100
+
101
+ it("detaching on a cached sandbox removes project/ and makes the name ordinary again", async () => {
102
+ remote({ "a.txt": "aaa" });
103
+ const id = sid();
104
+ const h = await open(id, "p1");
105
+ expect(existsSync(join(h.sessionDir, "project", "a.txt"))).toBe(true);
106
+
107
+ await open(id, null); // same cached sandbox, project gone
108
+ expect(existsSync(join(h.sessionDir, "project"))).toBe(false);
109
+
110
+ upload.mockClear();
111
+ await run(h, "mkdir -p project && echo y > project/x.txt");
112
+ expect(uploadedKeys()).toEqual([`sessions/${id}/project/x.txt`]);
113
+ });
114
+
115
+ it("attaching a project to a cached sandbox makes project/ read-only from that turn", async () => {
116
+ const id = sid();
117
+ const h = await open(id, null);
118
+ remote({ "a.txt": "aaa" });
119
+ await open(id, "p1");
120
+ expect(await readFile(join(h.sessionDir, "project", "a.txt"), "utf8")).toBe("aaa");
121
+ await run(h, "echo y > project/new.txt");
122
+ expect(existsSync(join(h.sessionDir, "project", "new.txt"))).toBe(true);
123
+ expect(uploadedKeys()).toEqual([]);
124
+ });
125
+ });
126
+
127
+ describe("project flag is fixed for the duration of one bash command", () => {
128
+ it("a detach that lands mid-command does not upload the project copy as agent files", async () => {
129
+ remote({ "brief.txt": "shared" });
130
+ const id = sid();
131
+ const h = await open(id, "p1");
132
+ upload.mockClear();
133
+
134
+ // The detach turn's session restore hangs until we let it go: by then it has
135
+ // already flipped the project state, but its sync has not removed project/ yet.
136
+ let release!: () => void;
137
+ const gate = new Promise<void>((r) => (release = r));
138
+ list.mockImplementation(async (prefix: string) => {
139
+ if (!prefix.startsWith("projects/")) await gate;
140
+ return [];
141
+ });
142
+
143
+ const bash = run(h, "sleep 0.4 && echo z > out.txt");
144
+ await new Promise((r) => setTimeout(r, 100)); // before-snapshot taken
145
+ const detach = open(id, null);
146
+ await bash;
147
+ release();
148
+ await detach;
149
+
150
+ expect(uploadedKeys()).toEqual([`sessions/${id}/out.txt`]);
151
+ });
152
+ });
153
+
154
+ describe("an attach that lands mid-command", () => {
155
+ it("does not upload the freshly synced project copy as agent files", async () => {
156
+ const id = sid();
157
+ const h = await open(id, null);
158
+ upload.mockClear();
159
+ remote({ "brief.txt": "shared" });
160
+
161
+ const bash = run(h, "sleep 0.4 && echo z > out.txt");
162
+ await new Promise((r) => setTimeout(r, 100)); // before-snapshot taken without a project
163
+ await open(id, "p1"); // attach: sync writes project/brief.txt during the command
164
+ expect(existsSync(join(h.sessionDir, "project", "brief.txt"))).toBe(true);
165
+ await bash;
166
+
167
+ expect(uploadedKeys()).toEqual([`sessions/${id}/out.txt`]);
168
+ });
169
+ });
170
+
171
+ describe("session sandbox without a project", () => {
172
+ it("project/ is an ordinary folder whose files are uploaded to the session", async () => {
173
+ const id = sid();
174
+ const h = await open(id, null);
175
+ const w = await write(h, "project/x.txt", "x");
176
+ expect(w.key).toBe(`bucket/user_7/sessions/${id}/project/x.txt`);
177
+ await run(h, "echo y > project/y.txt");
178
+ expect(uploadedKeys()).toEqual([`sessions/${id}/project/x.txt`, `sessions/${id}/project/y.txt`]);
179
+ // and the next turn leaves it alone
180
+ await open(id, null);
181
+ expect(await readFile(join(h.sessionDir, "project", "y.txt"), "utf8")).toBe("y\n");
182
+ expect(list.mock.calls.some((c) => String(c[0]).startsWith("projects/"))).toBe(false);
183
+ });
184
+ });
@@ -0,0 +1,47 @@
1
+ jest.mock("@SRC/uppy/index.ts", () => ({
2
+ listS3ObjectsByPrefix: jest.fn(),
3
+ getS3ObjectBytes: jest.fn(),
4
+ uploadFile: jest.fn(async () => "bucket/pre/user_7/sessions/s1/out.txt"),
5
+ getPresignedUrl: jest.fn(),
6
+ }));
7
+ jest.mock("@SRC/postgres/client", () => ({ postgresClient: jest.fn() }));
8
+
9
+ import { uploadFile } from "@SRC/uppy/index.ts";
10
+ import { isArtifactPath, uploadAgentArtifact } from "./create-sandbox";
11
+
12
+ const sessionDir = "/tmp/exulu-sessions/s1";
13
+
14
+ describe("isArtifactPath and project/", () => {
15
+ it("project/ is not an artifact in a project session", () => {
16
+ expect(isArtifactPath(`${sessionDir}/project/a.pdf`, sessionDir, { hasProject: true })).toBe(false);
17
+ expect(isArtifactPath(`${sessionDir}/project`, sessionDir, { hasProject: true })).toBe(false);
18
+ });
19
+
20
+ it("project/ is an ordinary artifact in a session without a project", () => {
21
+ expect(isArtifactPath(`${sessionDir}/project/a.pdf`, sessionDir, { hasProject: false })).toBe(true);
22
+ expect(isArtifactPath(`${sessionDir}/project/a.pdf`, sessionDir)).toBe(true);
23
+ });
24
+
25
+ it("other paths are unaffected by the project flag", () => {
26
+ expect(isArtifactPath(`${sessionDir}/projects/a.pdf`, sessionDir, { hasProject: true })).toBe(true);
27
+ expect(isArtifactPath(`${sessionDir}/out/a.pdf`, sessionDir, { hasProject: true })).toBe(true);
28
+ expect(isArtifactPath(`${sessionDir}/skills/x/SKILL.md`, sessionDir, { hasProject: true })).toBe(false);
29
+ expect(isArtifactPath(`/tmp/elsewhere/a.pdf`, sessionDir, { hasProject: false })).toBe(false);
30
+ });
31
+ });
32
+
33
+ describe("uploadAgentArtifact", () => {
34
+ it("marks the upload as written by the agent", async () => {
35
+ const content = Buffer.from("x");
36
+ const config = { fileUploads: { s3Bucket: "bucket" } } as any;
37
+ const key = await uploadAgentArtifact(content, "sessions/s1/out.txt", config, 7);
38
+ expect(key).toBe("bucket/pre/user_7/sessions/s1/out.txt");
39
+ expect(uploadFile).toHaveBeenCalledWith(
40
+ content,
41
+ "sessions/s1/out.txt",
42
+ config,
43
+ { metadata: { "exulu-origin": "agent" } },
44
+ 7,
45
+ );
46
+ });
47
+ });
@@ -0,0 +1,296 @@
1
+ /**
2
+ * The backend must not follow links the agent plants in its session directory:
3
+ * reads (artifact mirroring after bash) and writes (restore, upload sync, skills)
4
+ * run with the backend's rights, not the sandbox's. Real (direct-exec) sandbox,
5
+ * S3 mocked, as in create-sandbox.project-session.test.ts.
6
+ */
7
+ jest.mock("@anthropic-ai/sandbox-runtime", () => ({
8
+ SandboxManager: {
9
+ initialize: jest.fn(async () => {}),
10
+ wrapWithSandbox: jest.fn(async (cmd: string) => cmd),
11
+ reset: jest.fn(async () => {}),
12
+ },
13
+ }));
14
+ jest.mock("@SRC/uppy/index.ts", () => ({
15
+ listS3ObjectsByPrefix: jest.fn(async () => []),
16
+ getS3ObjectBytes: jest.fn(),
17
+ uploadFile: jest.fn(async (_c: Buffer, key: string) => `bucket/user_7/${key}`),
18
+ getPresignedUrl: jest.fn(async () => "https://signed"),
19
+ }));
20
+ jest.mock("@SRC/postgres/client", () => ({
21
+ postgresClient: jest.fn(async () => ({ db: { from: () => ({ select: async () => [] }) } })),
22
+ }));
23
+ jest.mock("@SRC/exulu/system-dependencies.ts", () => ({ getNpmGlobalRoot: jest.fn(async () => null) }));
24
+ jest.mock("@SRC/utils/python-setup.ts", () => ({ getPythonVenvPath: () => undefined }));
25
+ // node:fs/promises cannot be spied on (non-configurable exports); route `stat`
26
+ // through a hook the tests can set instead.
27
+ let mockStatHook: ((path: string) => Promise<void>) | null = null;
28
+ jest.mock("node:fs/promises", () => {
29
+ const actual = jest.requireActual("node:fs/promises");
30
+ return {
31
+ ...actual,
32
+ stat: async (p: any, ...rest: any[]) => {
33
+ const st = await actual.stat(p, ...rest);
34
+ if (mockStatHook) await mockStatHook(String(p));
35
+ return st;
36
+ },
37
+ };
38
+ });
39
+
40
+ import { mkdtemp, readFile, rm, symlink, unlink, writeFile, mkdir, lstat } from "node:fs/promises";
41
+ import { tmpdir } from "node:os";
42
+ import { join } from "node:path";
43
+ import { existsSync } from "node:fs";
44
+ import { uploadFile, listS3ObjectsByPrefix, getS3ObjectBytes } from "@SRC/uppy/index.ts";
45
+ import { createSessionSandbox, downloadKeyIntoSandbox, refreshSessionSkills } from "./create-sandbox";
46
+ import { readRegularFileInside, writeFileInside } from "./safe-fs";
47
+
48
+ const upload = uploadFile as jest.Mock;
49
+ const list = listS3ObjectsByPrefix as jest.Mock;
50
+ const bytes = getS3ObjectBytes as jest.Mock;
51
+ const config = { fileUploads: { s3Bucket: "bucket" } } as any;
52
+ const uploadedKeys = () => upload.mock.calls.map((c) => c[1] as string);
53
+ const uploadedBodies = () => upload.mock.calls.map((c) => String(c[0]));
54
+
55
+ let handles: Array<{ cleanup: () => Promise<void> }> = [];
56
+ let victimDir: string;
57
+ const sid = () => `jest-symlink-${process.pid}-${Math.random().toString(36).slice(2)}`;
58
+ const open = async (id: string) => {
59
+ const h = await createSessionSandbox(id, [], config, 7, undefined, { projectId: null });
60
+ handles.push(h);
61
+ return h;
62
+ };
63
+ const run = (h: any, command: string) => h.tools.bash.execute({ command }, { toolCallId: "t", messages: [] });
64
+
65
+ beforeEach(async () => {
66
+ upload.mockClear();
67
+ list.mockReset();
68
+ list.mockImplementation(async () => []);
69
+ bytes.mockReset();
70
+ victimDir = await mkdtemp(join(tmpdir(), "exulu-victim-"));
71
+ await writeFile(join(victimDir, "secret.txt"), "TOP SECRET");
72
+ jest.spyOn(console, "warn").mockImplementation(() => {});
73
+ jest.spyOn(console, "log").mockImplementation(() => {});
74
+ });
75
+ afterEach(async () => {
76
+ for (const h of handles) await h.cleanup();
77
+ handles = [];
78
+ jest.restoreAllMocks();
79
+ mockStatHook = null;
80
+ await rm(victimDir, { recursive: true, force: true });
81
+ });
82
+
83
+ /**
84
+ * Swap `relPath` for a link right after the after-command snapshot stats it —
85
+ * what a process the agent left running could do between snapshot and read.
86
+ */
87
+ function swapAfterSnapshot(sessionDir: string, relPath: string, makeLink: () => Promise<void>) {
88
+ const target = join(sessionDir, relPath);
89
+ let seen = 0;
90
+ mockStatHook = async (p) => {
91
+ if (p !== target) return;
92
+ seen++;
93
+ // 1st stat: before-snapshot; 2nd: after-snapshot — swap right after it.
94
+ if (seen === 2) await makeLink();
95
+ };
96
+ }
97
+
98
+ describe("bash artifact mirroring does not follow agent-planted links", () => {
99
+ it("a changed file replaced by a symlink to a victim file is not uploaded", async () => {
100
+ const h = await open(sid());
101
+ await run(h, "echo old > out.txt");
102
+ upload.mockClear();
103
+ swapAfterSnapshot(h.sessionDir, "out.txt", async () => {
104
+ await unlink(join(h.sessionDir, "out.txt"));
105
+ await symlink(join(victimDir, "secret.txt"), join(h.sessionDir, "out.txt"));
106
+ });
107
+ await run(h, "sleep 0.05 && echo new > out.txt");
108
+ expect(uploadedKeys()).not.toContain(expect.stringContaining("out.txt"));
109
+ expect(uploadedBodies().join("")).not.toContain("TOP SECRET");
110
+ });
111
+
112
+ it("a file whose parent directory was swapped for a link to a victim dir is not uploaded", async () => {
113
+ const h = await open(sid());
114
+ await run(h, "mkdir -p d && echo old > d/secret.txt");
115
+ upload.mockClear();
116
+ swapAfterSnapshot(h.sessionDir, "d/secret.txt", async () => {
117
+ await rm(join(h.sessionDir, "d"), { recursive: true, force: true });
118
+ await symlink(victimDir, join(h.sessionDir, "d"));
119
+ });
120
+ await run(h, "sleep 0.05 && echo new > d/secret.txt");
121
+ expect(uploadedBodies().join("")).not.toContain("TOP SECRET");
122
+ });
123
+
124
+ it("ordinary changed files are still uploaded", async () => {
125
+ const h = await open(sid());
126
+ await run(h, "mkdir -p out && echo hi > out/a.txt");
127
+ expect(uploadedKeys()).toEqual([expect.stringMatching(/\/out\/a\.txt$/)]);
128
+ expect(uploadedBodies()).toEqual(["hi\n"]);
129
+ });
130
+ });
131
+
132
+ describe("readRegularFileInside", () => {
133
+ let dir: string;
134
+ beforeEach(async () => {
135
+ dir = await mkdtemp(join(tmpdir(), "exulu-session-"));
136
+ });
137
+ afterEach(async () => {
138
+ await rm(dir, { recursive: true, force: true });
139
+ });
140
+
141
+ it("reads a regular file inside the session directory", async () => {
142
+ await mkdir(join(dir, "a"));
143
+ await writeFile(join(dir, "a", "f.txt"), "ok");
144
+ expect(String(await readRegularFileInside(dir, join(dir, "a", "f.txt")))).toBe("ok");
145
+ });
146
+
147
+ it("returns null for a symlink, a symlinked parent, a directory and a missing file", async () => {
148
+ await symlink(join(victimDir, "secret.txt"), join(dir, "link.txt"));
149
+ await symlink(victimDir, join(dir, "linkdir"));
150
+ await mkdir(join(dir, "sub"));
151
+ expect(await readRegularFileInside(dir, join(dir, "link.txt"))).toBeNull();
152
+ expect(await readRegularFileInside(dir, join(dir, "linkdir", "secret.txt"))).toBeNull();
153
+ expect(await readRegularFileInside(dir, join(dir, "sub"))).toBeNull();
154
+ expect(await readRegularFileInside(dir, join(dir, "missing.txt"))).toBeNull();
155
+ expect((await lstat(join(victimDir, "secret.txt"))).isFile()).toBe(true);
156
+ expect(await readFile(join(victimDir, "secret.txt"), "utf8")).toBe("TOP SECRET");
157
+ });
158
+ });
159
+
160
+ /** S3 holds `files` (name -> body) under the session prefix and `skills` under skill prefixes. */
161
+ function s3(id: string, files: Record<string, string>, skills: Record<string, string> = {}) {
162
+ const sessionPrefix = `user_7/sessions/${id}/`;
163
+ const all: Record<string, string> = {};
164
+ for (const [n, b] of Object.entries(files)) all[`${sessionPrefix}${n}`] = b;
165
+ for (const [k, b] of Object.entries(skills)) all[k] = b;
166
+ list.mockImplementation(async (prefix: string) =>
167
+ Object.entries(all)
168
+ .filter(([k]) => k.startsWith(prefix))
169
+ .map(([key, body]) => ({ key, size: body.length, lastModified: new Date() })),
170
+ );
171
+ bytes.mockImplementation(async (key: string) => Buffer.from(all[key] ?? ""));
172
+ }
173
+
174
+ const victim = () => readFile(join(victimDir, "secret.txt"), "utf8");
175
+
176
+ describe("session restore does not write through agent-planted links", () => {
177
+ it("a symlink planted at the destination is replaced, the victim untouched", async () => {
178
+ const id = sid();
179
+ const h = await open(id);
180
+ await symlink(join(victimDir, "secret.txt"), join(h.sessionDir, "doc.txt"));
181
+ s3(id, { "doc.txt": "uploaded by the user" });
182
+ await open(id); // cache hit: re-sync of missing session files
183
+ expect(await victim()).toBe("TOP SECRET");
184
+ expect((await lstat(join(h.sessionDir, "doc.txt"))).isFile()).toBe(true);
185
+ expect(await readFile(join(h.sessionDir, "doc.txt"), "utf8")).toBe("uploaded by the user");
186
+ });
187
+
188
+ it("a symlinked parent directory is not written through", async () => {
189
+ const id = sid();
190
+ const h = await open(id);
191
+ await symlink(victimDir, join(h.sessionDir, "sub"));
192
+ s3(id, { "sub/secret.txt": "overwritten!", "sub/new.txt": "planted" });
193
+ await open(id);
194
+ expect(await victim()).toBe("TOP SECRET");
195
+ expect(existsSync(join(victimDir, "new.txt"))).toBe(false);
196
+ });
197
+
198
+ it("without links, restore behaves as before", async () => {
199
+ const id = sid();
200
+ const h = await open(id);
201
+ s3(id, { "a/b/c.txt": "deep", "top.txt": "top" });
202
+ await open(id);
203
+ expect(await readFile(join(h.sessionDir, "a", "b", "c.txt"), "utf8")).toBe("deep");
204
+ expect(await readFile(join(h.sessionDir, "top.txt"), "utf8")).toBe("top");
205
+ });
206
+ });
207
+
208
+ describe("downloadKeyIntoSandbox", () => {
209
+ it("refuses a key suffix containing .. and writes nothing outside", async () => {
210
+ const id = sid();
211
+ const h = await open(id);
212
+ const escape = `../${id}-escaped.txt`;
213
+ bytes.mockResolvedValue(Buffer.from("x"));
214
+ await expect(
215
+ downloadKeyIntoSandbox({ sessionId: id, userId: 7, fullS3Key: `bkt/user_7/sessions/${id}/${escape}`, config }),
216
+ ).rejects.toThrow(/\.\./);
217
+ expect(existsSync(join(h.sessionDir, escape))).toBe(false);
218
+ });
219
+
220
+ it("does not write through a symlinked parent or a planted destination link", async () => {
221
+ const id = sid();
222
+ const h = await open(id);
223
+ await symlink(victimDir, join(h.sessionDir, "sub"));
224
+ await symlink(join(victimDir, "secret.txt"), join(h.sessionDir, "f.txt"));
225
+ bytes.mockResolvedValue(Buffer.from("overwritten!"));
226
+ await expect(
227
+ downloadKeyIntoSandbox({ sessionId: id, userId: 7, fullS3Key: `bkt/user_7/sessions/${id}/sub/secret.txt`, config }),
228
+ ).rejects.toThrow();
229
+ const ok = await downloadKeyIntoSandbox({ sessionId: id, userId: 7, fullS3Key: `bkt/user_7/sessions/${id}/f.txt`, config });
230
+ expect(ok.written).toBe(true);
231
+ expect(await victim()).toBe("TOP SECRET");
232
+ expect((await lstat(join(h.sessionDir, "f.txt"))).isFile()).toBe(true);
233
+ });
234
+ });
235
+
236
+ describe("skills/ replaced by a link", () => {
237
+ const skill = (v: number) => ({ id: "sk1", name: "Review", current_version: v }) as any;
238
+ const skillFiles = (v: number) => ({ [`skills/sk1/v${v}/SKILL.md`]: `v${v}` });
239
+
240
+ it("an upgrade leaves the victim directory untouched and recreates skills/", async () => {
241
+ const id = sid();
242
+ s3(id, {}, skillFiles(1));
243
+ const h = await createSessionSandbox(id, [skill(1)], config, 7, undefined, { projectId: null });
244
+ handles.push(h);
245
+ expect(await readFile(join(h.sessionDir, "skills", "Review", "SKILL.md"), "utf8")).toBe("v1");
246
+
247
+ await mkdir(join(victimDir, "Review"));
248
+ await writeFile(join(victimDir, "Review", "keep.txt"), "keep");
249
+ await rm(join(h.sessionDir, "skills"), { recursive: true, force: true });
250
+ await symlink(victimDir, join(h.sessionDir, "skills"));
251
+
252
+ s3(id, {}, skillFiles(2));
253
+ await createSessionSandbox(id, [skill(2)], config, 7, undefined, { projectId: null });
254
+ expect(await readFile(join(victimDir, "Review", "keep.txt"), "utf8")).toBe("keep");
255
+ expect(existsSync(join(victimDir, "Review", "SKILL.md"))).toBe(false);
256
+ expect((await lstat(join(h.sessionDir, "skills"))).isDirectory()).toBe(true);
257
+ expect(await readFile(join(h.sessionDir, "skills", "Review", "SKILL.md"), "utf8")).toBe("v2");
258
+ });
259
+
260
+ it("a reload with skills/<name> replaced by a link removes only the link", async () => {
261
+ const id = sid();
262
+ s3(id, {}, skillFiles(1));
263
+ const h = await createSessionSandbox(id, [skill(1)], config, 7, undefined, { projectId: null });
264
+ handles.push(h);
265
+ await mkdir(join(victimDir, "inner"));
266
+ await writeFile(join(victimDir, "inner", "keep.txt"), "keep");
267
+ await rm(join(h.sessionDir, "skills", "Review"), { recursive: true, force: true });
268
+ await symlink(join(victimDir, "inner"), join(h.sessionDir, "skills", "Review"));
269
+
270
+ await refreshSessionSkills(id, [skill(1)], config);
271
+ expect(await readFile(join(victimDir, "inner", "keep.txt"), "utf8")).toBe("keep");
272
+ expect(existsSync(join(victimDir, "inner", "SKILL.md"))).toBe(false);
273
+ expect((await lstat(join(h.sessionDir, "skills", "Review"))).isDirectory()).toBe(true);
274
+ expect(await readFile(join(h.sessionDir, "skills", "Review", "SKILL.md"), "utf8")).toBe("v1");
275
+ });
276
+ });
277
+
278
+ describe("writeFileInside", () => {
279
+ let dir: string;
280
+ beforeEach(async () => {
281
+ dir = await mkdtemp(join(tmpdir(), "exulu-session-"));
282
+ });
283
+ afterEach(async () => {
284
+ await rm(dir, { recursive: true, force: true });
285
+ });
286
+
287
+ it.each(["../x", "a/../../x", "/etc/x", "", "a/.."])("refuses %p", async (p) => {
288
+ await expect(writeFileInside(dir, p, "x")).rejects.toThrow();
289
+ });
290
+
291
+ it("creates parents and replaces an existing regular file", async () => {
292
+ await writeFileInside(dir, "a/b/c.txt", "one");
293
+ await writeFileInside(dir, "a/b/c.txt", "two");
294
+ expect(await readFile(join(dir, "a", "b", "c.txt"), "utf8")).toBe("two");
295
+ });
296
+ });