Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO, and reads spy on native realpath.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFSP from "node:fs/promises";
4
5import * as NodePath from "@effect/platform-node/NodePath";
6import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { it, describe, expect } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13
14import * as ServerConfig from "../config.ts";
15import { makeFakeWslHost } from "../testUtils/fakeWsl.ts";
16import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
17import * as VcsProcess from "../vcs/VcsProcess.ts";
18import * as KnownWorkspaces from "./KnownWorkspaces.ts";
19import * as WorkspaceEntries from "./WorkspaceEntries.ts";
20import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts";
21import * as WorkspacePaths from "./WorkspacePaths.ts";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
24import { vi } from "vite-plus/test";
25
26vi.mock("node:fs/promises", async (importOriginal) => {
27 const actual = await importOriginal<typeof NodeFSP>();
28 return { ...actual, realpath: vi.fn(actual.realpath), open: vi.fn(actual.open) };
29});
30
31const injectShortReads = Effect.fn("injectShortReads")(function* (target: string) {
32 const native = yield* Effect.promise(() => vi.importActual<typeof NodeFSP>("node:fs/promises"));
33 const open = vi.mocked(NodeFSP.open).mockImplementation(async (path, flags, mode) => {
34 const handle = await native.open(path, flags, mode);
35 if (path === target) {
36 const read = handle.read.bind(handle);
37 Object.defineProperty(handle, "read", {
38 value: (buffer: Uint8Array, offset: number, length: number, position: number) =>
39 read(buffer, offset, Math.min(length, 2), position),
40 });
41 }
42 return handle;
43 });
44 yield* Effect.addFinalizer(() => Effect.sync(() => open.mockImplementation(native.open)));
45});
46
47const whitespaceFilePaths =
48 HostProcess.Platform.defaultValue() === "win32"
49 ? [" report.txt"]
50 : [" report.txt", "report.txt ", "\treport.txt\t", " "];
51
52const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-";
53const layerKnownWorkspacesTest = Layer.mock(KnownWorkspaces.KnownWorkspaces)({
54 assertContains: (cwd) =>
55 cwd.includes(UNKNOWN_WORKSPACE_PREFIX)
56 ? Effect.fail(new KnownWorkspaces.UnknownWorkspaceError({ cwd }))
57 : Effect.void,
58});
59
60const layerProject = WorkspaceFileSystem.layer.pipe(
61 Layer.provide(layerKnownWorkspacesTest),
62 Layer.provide(WorkspacePaths.layer),
63 Layer.provide(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
64);
65
66const layerTest = Layer.empty.pipe(
67 Layer.provideMerge(layerProject),
68 Layer.provideMerge(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
69 Layer.provideMerge(WorkspacePaths.layer),
70 Layer.provideMerge(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))),
71 Layer.provideMerge(
72 ServerConfig.ServerConfig.layerTest(process.cwd(), {
73 prefix: "t3-workspace-files-test-",
74 }),
75 ),
76 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
77);
78
79const makeTempDir = Effect.gen(function* () {
80 const fileSystem = yield* FileSystem.FileSystem;
81 return yield* fileSystem.makeTempDirectoryScoped({
82 prefix: "t3code-workspace-files-",
83 });
84});
85
86const writeTextFile = Effect.fn("writeTextFile")(function* (
87 cwd: string,
88 relativePath: string,
89 contents = "",
90) {
91 const fileSystem = yield* FileSystem.FileSystem;
92 const path = yield* Path.Path;
93 const absolutePath = path.join(cwd, relativePath);
94 yield* fileSystem
95 .makeDirectory(path.dirname(absolutePath), { recursive: true })
96 .pipe(Effect.orDie);
97 yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
98});
99
100const makeWslHost = Effect.gen(function* () {
101 const { mountRoot, underWsl } = yield* makeFakeWslHost;
102 const service = yield* underWsl(
103 WorkspaceFileSystem.make.pipe(Effect.provide(layerKnownWorkspacesTest)),
104 );
105 return { mountRoot, service, underWsl };
106});
107
108it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (it) => {
109 describe("getMetadata", () => {
110 it.effect(
111 "reports actual kinds for extensionless files, dotfiles, and dotted directories",
112 () =>
113 Effect.gen(function* () {
114 const service = yield* WorkspaceFileSystem.WorkspaceFileSystem;
115 const fs = yield* FileSystem.FileSystem;
116 const path = yield* Path.Path;
117 const cwd = yield* makeTempDir;
118 yield* writeTextFile(cwd, "custom-name", "hello");
119 yield* writeTextFile(cwd, ".npmrc", "registry=test");
120 yield* fs.makeDirectory(path.join(cwd, "folder.ts"));
121 const file = path.join(cwd, "custom-name");
122 const result = yield* service.getMetadata({
123 paths: [
124 file,
125 path.join(cwd, ".npmrc"),
126 path.join(cwd, "folder.ts"),
127 file,
128 path.join(cwd, "missing"),
129 "relative-path",
130 ],
131 });
132 expect(result.entries).toEqual([
133 { kind: "file", byteLength: 5 },
134 { kind: "file", byteLength: 13 },
135 { kind: "directory" },
136 { kind: "file", byteLength: 5 },
137 null,
138 null,
139 ]);
140 }),
141 );
142
143 it.effect("detects an extensionless script and image without returning their contents", () =>
144 Effect.gen(function* () {
145 const service = yield* WorkspaceFileSystem.WorkspaceFileSystem;
146 const fs = yield* FileSystem.FileSystem;
147 const path = yield* Path.Path;
148 const cwd = yield* makeTempDir;
149 const script = "#!/usr/bin/env python3\nprint('hello')\n";
150 yield* writeTextFile(cwd, "run", script);
151 const image = path.join(cwd, "image");
152 yield* fs.writeFile(
153 image,
154 new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
155 );
156 expect(
157 (yield* service.getMetadata({ paths: [path.join(cwd, "run"), image] })).entries,
158 ).toEqual([
159 { kind: "file", byteLength: script.length, mimeType: "text/x-python" },
160 { kind: "file", byteLength: 8, mimeType: "image/png" },
161 ]);
162 }),
163 );
164
165 // A file chip for `file://attacker.test/s/a.ts` in an agent's message sent
166 // the Windows user's NTLM credentials to attacker.test as it rendered.
167 it.effect("never stats a network path", () =>
168 Effect.gen(function* () {
169 const fs = yield* FileSystem.FileSystem;
170 const statted: Array<string> = [];
171 const service = yield* WorkspaceFileSystem.make.pipe(
172 Effect.provideService(
173 FileSystem.FileSystem,
174 FileSystem.FileSystem.of({
175 ...fs,
176 stat: (requestedPath) => {
177 statted.push(requestedPath);
178 return fs.stat(requestedPath);
179 },
180 }),
181 ),
182 Effect.provide(layerKnownWorkspacesTest),
183 );
184 const paths = [
185 "\\\\attacker.test\\s\\a.ts",
186 "//attacker.test/s/a.ts",
187 "/\\attacker.test\\s",
188 ];
189 expect((yield* service.getMetadata({ paths })).entries).toEqual([null, null, null]);
190 expect(statted).toEqual([]);
191 }),
192 );
193
194 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
195 "reports a Windows drive path under WSL as the file it maps to",
196 () =>
197 Effect.gen(function* () {
198 const { mountRoot, service, underWsl } = yield* makeWslHost;
199 yield* writeTextFile(mountRoot, "c/Users/me/Documents/notes.md", "# Notes\n");
200
201 const { entries } = yield* underWsl(
202 service.getMetadata({
203 paths: [
204 "C:\\Users\\me\\Documents\\notes.md",
205 "C:/Users/me/Documents/notes.md",
206 "C:/Users/me/Documents/notes\u0000.md",
207 ],
208 }),
209 );
210
211 expect(entries).toEqual([
212 { kind: "file", byteLength: 8 },
213 { kind: "file", byteLength: 8 },
214 null,
215 ]);
216 }),
217 );
218 });
219
220 describe("readFile", () => {
221 it.effect("reads UTF-8 files relative to the workspace root", () =>
222 Effect.gen(function* () {
223 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
224 const cwd = yield* makeTempDir;
225 yield* writeTextFile(cwd, "src/index.ts", "export const answer = 42;\n");
226
227 const result = yield* workspaceFileSystem.readFile({
228 cwd,
229 relativePath: "src/index.ts",
230 });
231
232 expect(result).toEqual({
233 relativePath: "src/index.ts",
234 contents: "export const answer = 42;\n",
235 byteLength: 26,
236 truncated: false,
237 });
238
239 const bomContents = "\uFEFFexport const answer = 42;\n";
240 yield* writeTextFile(cwd, "bom.ts", bomContents);
241 const bomRead = yield* workspaceFileSystem.readFile({ cwd, relativePath: "bom.ts" });
242 yield* workspaceFileSystem.writeFile({
243 cwd,
244 relativePath: "bom.ts",
245 contents: bomRead.contents.replace("42", "43"),
246 });
247 const fs = yield* FileSystem.FileSystem;
248 const saved = yield* fs.readFile(`${cwd}/bom.ts`);
249 expect([...saved]).toEqual([...new TextEncoder().encode(bomContents.replace("42", "43"))]);
250
251 yield* writeTextFile(cwd, "report.txt", "ordinary file");
252 for (const relativePath of whitespaceFilePaths) {
253 yield* writeTextFile(cwd, relativePath, "whitespace file");
254 const read = yield* workspaceFileSystem.readFile({ cwd, relativePath });
255 expect(read.contents).toBe("whitespace file");
256 expect(read.relativePath).toBe(relativePath);
257 }
258 }),
259 );
260
261 it.effect("finishes short reads before decoding UTF-8 text", () =>
262 Effect.gen(function* () {
263 const files = yield* WorkspaceFileSystem.WorkspaceFileSystem;
264 const fs = yield* FileSystem.FileSystem;
265 const cwd = yield* makeTempDir;
266 const contents = "A café 🐈\n";
267 yield* writeTextFile(cwd, "short.txt", contents);
268 const target = yield* fs.realPath(`${cwd}/short.txt`);
269 yield* injectShortReads(target);
270 expect(yield* files.readFile({ cwd, relativePath: "short.txt" })).toEqual({
271 relativePath: "short.txt",
272 contents,
273 byteLength: Buffer.byteLength(contents),
274 truncated: false,
275 });
276 }),
277 );
278
279 it.effect("rejects binary bytes delivered after an initial short read", () =>
280 Effect.gen(function* () {
281 const files = yield* WorkspaceFileSystem.WorkspaceFileSystem;
282 const fs = yield* FileSystem.FileSystem;
283 const cwd = yield* makeTempDir;
284 yield* writeTextFile(cwd, "short.txt", "ab\0cd");
285 const target = yield* fs.realPath(`${cwd}/short.txt`);
286 yield* injectShortReads(target);
287 const error = yield* files.readFile({ cwd, relativePath: "short.txt" }).pipe(Effect.flip);
288 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
289 }),
290 );
291
292 it.effect("reads host files outside the workspace root by absolute path", () =>
293 Effect.gen(function* () {
294 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
295 const path = yield* Path.Path;
296 const cwd = yield* makeTempDir;
297 const outsideDir = yield* makeTempDir;
298 yield* writeTextFile(outsideDir, "cleanup-report.md", "# Report\n");
299 const absolutePath = path.join(outsideDir, "cleanup-report.md");
300
301 const result = yield* workspaceFileSystem.readFile({
302 cwd,
303 relativePath: absolutePath,
304 });
305
306 expect(result).toEqual({
307 relativePath: absolutePath,
308 contents: "# Report\n",
309 byteLength: 9,
310 truncated: false,
311 });
312
313 for (const relativePath of whitespaceFilePaths) {
314 yield* writeTextFile(outsideDir, relativePath, "whitespace file");
315 const requestedPath = path.join(outsideDir, relativePath);
316 const read = yield* workspaceFileSystem.readFile({ cwd, relativePath: requestedPath });
317 expect(read.contents).toBe("whitespace file");
318 expect(read.relativePath).toBe(requestedPath);
319 }
320 }),
321 );
322
323 it.effect.each(["~/.claude/CLAUDE.md", "~\\.claude/CLAUDE.md"])(
324 "reads %s from the server home outside the workspace",
325 (relativePath) =>
326 Effect.gen(function* () {
327 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
328 const cwd = yield* makeTempDir;
329 const home = yield* makeTempDir;
330 yield* writeTextFile(home, ".claude/CLAUDE.md", "# Notes\n");
331 yield* writeTextFile(cwd, "~/.claude/CLAUDE.md", "Workspace decoy\n");
332
333 const result = yield* workspaceFileSystem
334 .readFile({ cwd, relativePath })
335 .pipe(Effect.provideService(HostProcess.HomeDirectory, home));
336
337 expect(result).toEqual({
338 relativePath,
339 contents: "# Notes\n",
340 byteLength: 8,
341 truncated: false,
342 });
343 }),
344 );
345
346 it.effect("does not read server state files", () =>
347 Effect.gen(function* () {
348 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
349 const config = yield* ServerConfig.ServerConfig;
350 const path = yield* Path.Path;
351 const cwd = yield* makeTempDir;
352 yield* writeTextFile(config.secretsDir, "example.bin", "example\n");
353 yield* writeTextFile(config.stateDir, "statev2.sqlite", "example\n");
354
355 for (const input of [
356 { cwd, relativePath: path.join(config.secretsDir, "example.bin") },
357 { cwd: config.stateDir, relativePath: "statev2.sqlite" },
358 ]) {
359 const error = yield* workspaceFileSystem.readFile(input).pipe(Effect.flip);
360 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
361 }
362 const metadata = yield* workspaceFileSystem.getMetadata({
363 paths: [
364 path.join(config.secretsDir, "example.bin"),
365 path.join(config.stateDir, "statev2.sqlite"),
366 config.stateDir,
367 ],
368 });
369 expect(metadata.entries).toEqual([null, null, { kind: "directory" }]);
370 }),
371 );
372
373 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
374 "rejects a FIFO without blocking on open",
375 () =>
376 Effect.gen(function* () {
377 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
378 const path = yield* Path.Path;
379 const cwd = yield* makeTempDir;
380 const outsideDir = yield* makeTempDir;
381 const fifoPath = path.join(outsideDir, "pipe");
382 yield* Effect.promise(
383 () =>
384 new Promise<void>((resolve, reject) =>
385 NodeChildProcess.execFile("mkfifo", [fifoPath], (error) =>
386 error ? reject(error) : resolve(),
387 ),
388 ),
389 );
390
391 const error = yield* workspaceFileSystem
392 .readFile({ cwd, relativePath: fifoPath })
393 .pipe(Effect.flip);
394
395 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
396 expect((yield* workspaceFileSystem.getMetadata({ paths: [fifoPath] })).entries).toEqual([
397 { kind: "other" },
398 ]);
399 }),
400 );
401
402 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
403 "reads a Windows drive path under WSL from where wslpath mounts it",
404 () =>
405 Effect.gen(function* () {
406 const { mountRoot, service, underWsl } = yield* makeWslHost;
407 const cwd = yield* makeTempDir;
408 yield* writeTextFile(mountRoot, "c/Users/me/Documents/notes.md", "# Notes\n");
409
410 for (const relativePath of [
411 "C:\\Users\\me\\Documents\\notes.md",
412 "C:/Users/me/Documents/notes.md",
413 ]) {
414 const result = yield* underWsl(service.readFile({ cwd, relativePath }));
415 expect(result).toMatchObject({ contents: "# Notes\n", truncated: false });
416 }
417 }),
418 );
419
420 it.effect("refuses a network path outside the workspace", () =>
421 Effect.gen(function* () {
422 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
423
424 const error = yield* workspaceFileSystem
425 .readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" })
426 .pipe(Effect.flip);
427
428 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
429 }),
430 );
431
432 // This resolves inside the project, but Windows reads `\\?\` paths as
433 // written, so realpath on the raw string signed in to attacker.test.
434 it.effect("reads the network path it checked", () =>
435 Effect.gen(function* () {
436 const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe(
437 Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)),
438 );
439 // Rejects without touching the filesystem, so a Windows runner never looks the share up.
440 const realpath = vi
441 .mocked(NodeFSP.realpath)
442 .mockClear()
443 .mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
444
445 yield* workspaceFileSystem
446 .readFile({
447 cwd: "\\\\?\\UNC\\nas.test\\share\\project",
448 relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md",
449 })
450 .pipe(Effect.exit);
451
452 expect(realpath.mock.calls.map(([target]) => target)).toEqual([
453 "\\\\?\\UNC\\nas.test\\share\\project\\a.md",
454 ]);
455 }),
456 );
457
458 // Resolving `..` before realpath would read beside the link instead of its target.
459 // Windows collapses `..` before the filesystem sees a path, so it has no such reads.
460 it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")(
461 "reads `..` after a link from the link's target",
462 () =>
463 Effect.gen(function* () {
464 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
465 const fs = yield* FileSystem.FileSystem;
466 const path = yield* Path.Path;
467 const root = yield* makeTempDir;
468 yield* writeTextFile(root, "target/parent.md", "beside the target\n");
469 yield* writeTextFile(root, "parent.md", "beside the link\n");
470 yield* fs.makeDirectory(path.join(root, "target", "child"));
471 yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link"));
472
473 const result = yield* workspaceFileSystem.readFile({
474 cwd: root,
475 relativePath: `${root}/link/../parent.md`,
476 });
477
478 expect(result.contents).toBe("beside the target\n");
479 }),
480 );
481
482 it.effect.skipIf(!symlinksSupported)(
483 "rejects symlinks that resolve outside the workspace root",
484 () =>
485 Effect.gen(function* () {
486 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
487 const fileSystem = yield* FileSystem.FileSystem;
488 const path = yield* Path.Path;
489 const cwd = yield* makeTempDir;
490 const outsideDir = yield* makeTempDir;
491 yield* writeTextFile(outsideDir, "secret.txt", "outside\n");
492 yield* fileSystem.symlink(
493 path.join(outsideDir, "secret.txt"),
494 path.join(cwd, "linked-secret.txt"),
495 );
496
497 const error = yield* workspaceFileSystem
498 .readFile({ cwd, relativePath: "linked-secret.txt" })
499 .pipe(Effect.flip);
500 const resolvedWorkspaceRoot = yield* fileSystem.realPath(cwd);
501 const resolvedPath = yield* fileSystem.realPath(path.join(outsideDir, "secret.txt"));
502
503 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
504 expect(error).toMatchObject({
505 workspaceRoot: cwd,
506 relativePath: "linked-secret.txt",
507 resolvedWorkspaceRoot,
508 resolvedPath,
509 });
510 expect("cause" in error).toBe(false);
511
512 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
513 const missingChildError = yield* workspaceFileSystem
514 .readFile(
515 Object.assign(
516 { cwd, relativePath: "linked-dir/missing/t3.json" },
517 { allowMissing: true },
518 ),
519 )
520 .pipe(Effect.flip);
521 expect(missingChildError).toBeInstanceOf(
522 WorkspaceFileSystem.WorkspaceFilePathEscapeError,
523 );
524 }),
525 );
526
527 it.effect("drops a multibyte character split by the read limit", () =>
528 Effect.gen(function* () {
529 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
530 const fileSystem = yield* FileSystem.FileSystem;
531 const path = yield* Path.Path;
532 const cwd = yield* makeTempDir;
533 const limit = 1024 * 1024;
534 const euro = new TextEncoder().encode("€");
535 const bytes = new Uint8Array(limit - 1 + euro.length).fill(0x61);
536 bytes.set(euro, limit - 1);
537 yield* fileSystem.writeFile(path.join(cwd, "large.txt"), bytes);
538
539 const result = yield* workspaceFileSystem.readFile({ cwd, relativePath: "large.txt" });
540
541 expect(result.truncated).toBe(true);
542 expect(result.byteLength).toBe(bytes.length);
543 expect(result.contents).toBe("a".repeat(limit - 1));
544 }),
545 );
546
547 it.effect.each([
548 { name: "a NUL byte", bytes: [0x61, 0, 0x62] },
549 { name: "invalid UTF-8", bytes: [0x63, 0x61, 0x66, 0xe9] },
550 ])("rejects files with $name without leaking their contents", ({ bytes }) =>
551 Effect.gen(function* () {
552 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
553 const fileSystem = yield* FileSystem.FileSystem;
554 const path = yield* Path.Path;
555 const cwd = yield* makeTempDir;
556 const absolutePath = path.join(cwd, "asset.bin");
557 yield* fileSystem.writeFile(absolutePath, Uint8Array.from(bytes));
558
559 const error = yield* workspaceFileSystem
560 .readFile({ cwd, relativePath: "asset.bin" })
561 .pipe(Effect.flip);
562 const resolvedPath = yield* fileSystem.realPath(absolutePath);
563
564 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
565 expect(error).toMatchObject({
566 workspaceRoot: cwd,
567 relativePath: "asset.bin",
568 resolvedPath,
569 });
570 expect("cause" in error).toBe(false);
571 expect("contents" in error).toBe(false);
572 }),
573 );
574 });
575
576 describe("writeFile", () => {
577 it.effect("rejects writes outside a known workspace", () =>
578 Effect.gen(function* () {
579 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
580 const fileSystem = yield* FileSystem.FileSystem;
581 const cwd = yield* fileSystem.makeTempDirectoryScoped({
582 prefix: UNKNOWN_WORKSPACE_PREFIX,
583 });
584
585 const error = yield* workspaceFileSystem
586 .writeFile({ cwd, relativePath: "plan.md", contents: "# nope\n" })
587 .pipe(Effect.flip);
588
589 expect(error).toBeInstanceOf(KnownWorkspaces.UnknownWorkspaceError);
590 expect(yield* fileSystem.readDirectory(cwd)).toEqual([]);
591 }),
592 );
593
594 it.effect("rejects writes by absolute path", () =>
595 Effect.gen(function* () {
596 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
597 const path = yield* Path.Path;
598 const cwd = yield* makeTempDir;
599 const outsideDir = yield* makeTempDir;
600 const absolutePath = path.join(outsideDir, "cleanup-report.md");
601
602 const error = yield* workspaceFileSystem
603 .writeFile({ cwd, relativePath: absolutePath, contents: "# Edited\n" })
604 .pipe(Effect.flip);
605
606 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
607 }),
608 );
609
610 it.effect("invalidates workspace entry search cache after writes", () =>
611 Effect.gen(function* () {
612 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
613 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
614 const cwd = yield* makeTempDir;
615 yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
616
617 const beforeWrite = yield* workspaceEntries.list({ cwd });
618 expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
619 false,
620 );
621
622 yield* workspaceFileSystem.writeFile({
623 cwd,
624 relativePath: "plans/effect-rpc.md",
625 contents: "# Plan\n",
626 });
627
628 const afterWrite = yield* workspaceEntries.list({ cwd });
629 expect(afterWrite.entries).toEqual(
630 expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
631 );
632 expect(afterWrite.truncated).toBe(false);
633 }),
634 );
635
636 it.effect("saves over an existing file without rescanning the workspace", () =>
637 Effect.gen(function* () {
638 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
639 const fileSystem = yield* FileSystem.FileSystem;
640 const path = yield* Path.Path;
641 const cwd = yield* makeTempDir;
642 yield* writeTextFile(cwd, "src/main.ts", "export {};\n");
643
644 yield* workspaceFileSystem.writeFile({
645 cwd,
646 relativePath: "src/main.ts",
647 contents: "export const edited = true;\n",
648 });
649
650 expect(yield* fileSystem.readFileString(path.join(cwd, "src/main.ts"))).toBe(
651 "export const edited = true;\n",
652 );
653
654 yield* writeTextFile(cwd, "report.txt", "ordinary file");
655 for (const relativePath of whitespaceFilePaths) {
656 yield* writeTextFile(cwd, relativePath, "whitespace file");
657 const written = yield* workspaceFileSystem.writeFile({
658 cwd,
659 relativePath,
660 contents: "edited",
661 });
662 expect(yield* fileSystem.readFileString(path.join(cwd, "report.txt"))).toBe(
663 "ordinary file",
664 );
665 expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("edited");
666 expect(written.relativePath).toBe(relativePath);
667 }
668 }).pipe(
669 Effect.provide(
670 Layer.fresh(WorkspaceFileSystem.layer).pipe(
671 Layer.provide(layerKnownWorkspacesTest),
672 Layer.provide(WorkspacePaths.layer),
673 Layer.provide(
674 Layer.mock(WorkspaceEntries.WorkspaceEntries)({
675 refresh: () => Effect.die("An overwrite rescanned the workspace."),
676 }),
677 ),
678 ),
679 ),
680 ),
681 );
682
683 it.effect("rejects writes outside the workspace root", () =>
684 Effect.gen(function* () {
685 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
686 const cwd = yield* makeTempDir;
687 const path = yield* Path.Path;
688 const fileSystem = yield* FileSystem.FileSystem;
689
690 for (const relativePath of ["../escape.md", "../escape.md ", " folder/../../escape.md"]) {
691 const error = yield* workspaceFileSystem
692 .writeFile({ cwd, relativePath, contents: "# nope\n" })
693 .pipe(Effect.flip);
694
695 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
696 }
697
698 const escapedPath = path.resolve(cwd, "..", "escape.md");
699 const escapedStat = yield* fileSystem
700 .stat(escapedPath)
701 .pipe(Effect.orElseSucceed(() => null));
702 expect(escapedStat).toBeNull();
703 }),
704 );
705
706 it.effect.skipIf(!symlinksSupported)(
707 "rejects writes through symlinks that resolve outside the workspace root",
708 () =>
709 Effect.gen(function* () {
710 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
711 const fileSystem = yield* FileSystem.FileSystem;
712 const path = yield* Path.Path;
713 const cwd = yield* makeTempDir;
714 const outsideDir = yield* makeTempDir;
715 yield* writeTextFile(outsideDir, "existing.md", "outside\n");
716 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
717 yield* fileSystem.symlink(
718 path.join(outsideDir, "existing.md"),
719 path.join(cwd, "linked-file.md"),
720 );
721 yield* fileSystem.symlink(
722 path.join(outsideDir, "missing.md"),
723 path.join(cwd, "dangling.md"),
724 );
725
726 for (const relativePath of [
727 "linked-dir/new.md",
728 "linked-dir/nested/new.md",
729 "linked-file.md",
730 ]) {
731 const error = yield* workspaceFileSystem
732 .writeFile({ cwd, relativePath, contents: "# nope\n" })
733 .pipe(Effect.flip);
734 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
735 }
736 const danglingError = yield* workspaceFileSystem
737 .writeFile({ cwd, relativePath: "dangling.md", contents: "# nope\n" })
738 .pipe(Effect.flip);
739 expect(danglingError).toBeInstanceOf(
740 WorkspaceFileSystem.WorkspaceFileSystemOperationError,
741 );
742 expect(danglingError).toMatchObject({ operation: "realpath-target" });
743
744 expect((yield* fileSystem.readDirectory(outsideDir)).toSorted()).toEqual(["existing.md"]);
745 expect(yield* fileSystem.readFileString(path.join(outsideDir, "existing.md"))).toBe(
746 "outside\n",
747 );
748 }),
749 );
750
751 it.effect.skipIf(!symlinksSupported)(
752 "writes through symlinks that stay inside the workspace root",
753 () =>
754 Effect.gen(function* () {
755 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
756 const fileSystem = yield* FileSystem.FileSystem;
757 const path = yield* Path.Path;
758 const parentDir = yield* makeTempDir;
759 const cwd = path.join(parentDir, "workspace");
760 const cwdAlias = path.join(parentDir, "workspace-alias");
761 yield* writeTextFile(cwd, "docs/README.md", "old\n");
762 yield* fileSystem.symlink(path.join(cwd, "docs"), path.join(cwd, "docs-alias"));
763 yield* fileSystem.symlink("docs/README.md", path.join(cwd, "README.md"));
764 yield* fileSystem.symlink(cwd, cwdAlias);
765
766 yield* workspaceFileSystem.writeFile({
767 cwd,
768 relativePath: "docs-alias/plans/plan.md",
769 contents: "# Plan\n",
770 });
771 yield* workspaceFileSystem.writeFile({
772 cwd,
773 relativePath: "README.md",
774 contents: "new\n",
775 });
776 yield* workspaceFileSystem.writeFile({
777 cwd: cwdAlias,
778 relativePath: "notes.md",
779 contents: "notes\n",
780 });
781 // `..` after a link in cwd is resolved by name, as for the relative path.
782 yield* fileSystem.symlink(path.join(cwd, "docs/plans"), path.join(cwd, "plans-alias"));
783 yield* workspaceFileSystem.writeFile({
784 cwd: `${path.join(cwd, "plans-alias")}${path.sep}..`,
785 relativePath: "dotdot.md",
786 contents: "dotdot\n",
787 });
788
789 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/plans/plan.md"))).toBe(
790 "# Plan\n",
791 );
792 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/README.md"))).toBe("new\n");
793 expect(yield* fileSystem.readLink(path.join(cwd, "README.md"))).toBe("docs/README.md");
794 expect(yield* fileSystem.readFileString(path.join(cwd, "notes.md"))).toBe("notes\n");
795 expect(yield* fileSystem.readFileString(path.join(cwd, "dotdot.md"))).toBe("dotdot\n");
796 }),
797 );
798
799 // On Windows `\` is a separator, so the name cannot exist there.
800 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
801 "keeps a backslash in a file name as part of the name",
802 () =>
803 Effect.gen(function* () {
804 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
805 const fileSystem = yield* FileSystem.FileSystem;
806 const cwd = yield* makeTempDir;
807 yield* writeTextFile(cwd, "a\\b.md", "old\n");
808
809 yield* workspaceFileSystem.writeFile({ cwd, relativePath: "a\\b.md", contents: "new\n" });
810
811 expect(
812 (yield* workspaceFileSystem.readFile({ cwd, relativePath: "a\\b.md" })).contents,
813 ).toBe("new\n");
814 expect(yield* fileSystem.readDirectory(cwd)).toEqual(["a\\b.md"]);
815 }),
816 );
817
818 it.effect("refuses writes into git's own folders", () =>
819 Effect.gen(function* () {
820 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
821 const fileSystem = yield* FileSystem.FileSystem;
822 const path = yield* Path.Path;
823 const cwd = yield* makeTempDir;
824 yield* writeTextFile(cwd, ".git/config", "[core]\n");
825 yield* writeTextFile(cwd, ".bare/HEAD", "ref: refs/heads/main\n");
826 yield* writeTextFile(cwd, ".bare/objects/info/packs");
827 yield* writeTextFile(cwd, ".bare/refs/heads/main");
828 yield* writeTextFile(cwd, ".bare/hooks/pre-push.sample");
829 // Only a linked worktree's `.git` file ends the upward check, not any `.git` folder.
830 yield* fileSystem.makeDirectory(path.join(cwd, ".bare/hooks/.git"));
831 yield* writeTextFile(cwd, ".bare/worktrees/main/HEAD", "ref: refs/heads/main\n");
832 yield* writeTextFile(cwd, ".bare/worktrees/main/commondir", "../..\n");
833 if (symlinksSupported) yield* fileSystem.symlink(".git", path.join(cwd, "docs"));
834
835 for (const [folder, relativePath] of [
836 [cwd, ".git/config"],
837 [cwd, ".git/hooks/pre-commit"],
838 [cwd, "sub/.git"],
839 [cwd, ".GIT/config"],
840 [cwd, ".gıt/config"],
841 [cwd, ".git. /config"],
842 [cwd, ".git::$INDEX_ALLOCATION/config"],
843 [cwd, "GIT~1/config"],
844 [path.join(cwd, ".git"), "config"],
845 [cwd, ".bare/config"],
846 [path.join(cwd, ".bare"), "hooks/post-checkout"],
847 [path.join(cwd, ".bare/hooks"), "post-checkout"],
848 [path.join(cwd, ".bare/worktrees/main"), "commondir"],
849 ...(symlinksSupported ? [[cwd, "docs/config"] as const] : []),
850 ] as const) {
851 const error = yield* workspaceFileSystem
852 .writeFile({ cwd: folder, relativePath, contents: "[core]\n\tfsmonitor = x\n" })
853 .pipe(Effect.flip);
854 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
855 }
856
857 expect(yield* fileSystem.readFileString(path.join(cwd, ".git/config"))).toBe("[core]\n");
858 expect(yield* fileSystem.exists(path.join(cwd, ".bare/config"))).toBe(false);
859 expect((yield* fileSystem.readDirectory(path.join(cwd, ".bare/hooks"))).toSorted()).toEqual(
860 [".git", "pre-push.sample"],
861 );
862 expect(yield* fileSystem.exists(path.join(cwd, "sub"))).toBe(false);
863 expect(
864 yield* fileSystem.readFileString(path.join(cwd, ".bare/worktrees/main/commondir")),
865 ).toBe("../..\n");
866 }),
867 );
868
869 it.effect.skipIf(!symlinksSupported)(
870 "refuses writes through a git config that links to a file outside git's folders",
871 () =>
872 Effect.gen(function* () {
873 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
874 const fileSystem = yield* FileSystem.FileSystem;
875 const path = yield* Path.Path;
876 const cwd = yield* makeTempDir;
877 yield* writeTextFile(cwd, "shared/config", "[core]\n");
878 yield* fileSystem.makeDirectory(path.join(cwd, ".git"));
879 yield* fileSystem.symlink("../shared/config", path.join(cwd, ".git/config"));
880
881 const error = yield* workspaceFileSystem
882 .writeFile({ cwd, relativePath: ".git/config", contents: "[core]\n\tfsmonitor = x\n" })
883 .pipe(Effect.flip);
884
885 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
886 expect(yield* fileSystem.readFileString(path.join(cwd, "shared/config"))).toBe(
887 "[core]\n",
888 );
889 }),
890 );
891
892 it.effect("writes files that sit beside git's folders", () =>
893 Effect.gen(function* () {
894 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
895 const fileSystem = yield* FileSystem.FileSystem;
896 const path = yield* Path.Path;
897 const parentDir = yield* makeTempDir;
898 const bare = path.join(parentDir, "repo.git");
899 yield* writeTextFile(bare, "HEAD", "ref: refs/heads/main\n");
900 yield* writeTextFile(bare, "objects/info/packs");
901 yield* writeTextFile(bare, "refs/heads/main");
902 yield* writeTextFile(bare, "main/.git", `gitdir: ${path.join(bare, "worktrees/main")}\n`);
903
904 for (const [cwd, relativePath] of [
905 [path.join(bare, "main"), ".gitignore"],
906 [path.join(bare, "main"), ".gitattributes"],
907 [path.join(bare, "main"), ".github/workflows/ci.yml"],
908 [path.join(bare, "main"), "vendor/lib.git/README.md"],
909 [path.join(bare, "main/.github"), "CODEOWNERS"],
910 [bare, "main/plan.md"],
911 ] as const) {
912 yield* workspaceFileSystem.writeFile({ cwd, relativePath, contents: "ok\n" });
913 expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("ok\n");
914 }
915 }),
916 );
917 });
918});