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 nodeScript =
152 "#!/opt/python-tools/bin/node --conditions=python\nconsole.log('hello')\n";
153 yield* writeTextFile(cwd, "run-node", nodeScript);
154 const envNodeScript =
155 "#!/usr/bin/env -S LABEL='python script' node --conditions=python\nconsole.log('hello')\n";
156 yield* writeTextFile(cwd, "run-env-node", envNodeScript);
157 const envSplitStringScript = "#!/usr/bin/env --split-string=node\nconsole.log('hello')\n";
158 yield* writeTextFile(cwd, "run-env-split-string", envSplitStringScript);
159 const envUnsetScript = "#!/usr/bin/env -u FOO node\nconsole.log('hello')\n";
160 yield* writeTextFile(cwd, "run-env-unset", envUnsetScript);
161 const envGroupedUnsetScript =
162 "#!/usr/bin/env -S -iu PYTHONPATH node\nconsole.log('hello')\n";
163 yield* writeTextFile(cwd, "run-env-grouped-unset", envGroupedUnsetScript);
164 const envArgv0Script = "#!/usr/bin/env -a myapp node\nconsole.log('hello')\n";
165 yield* writeTextFile(cwd, "run-env-argv0", envArgv0Script);
166 const envLongArgv0Script = "#!/usr/bin/env --argv0 myapp node\nconsole.log('hello')\n";
167 yield* writeTextFile(cwd, "run-env-long-argv0", envLongArgv0Script);
168 const image = path.join(cwd, "image");
169 yield* fs.writeFile(
170 image,
171 new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
172 );
173 const archive = path.join(cwd, "archive");
174 const emptyZip = new Uint8Array(22);
175 emptyZip.set([0x50, 0x4b, 0x05, 0x06]);
176 yield* fs.writeFile(archive, emptyZip);
177 expect(
178 (yield* service.getMetadata({
179 paths: [
180 path.join(cwd, "run"),
181 path.join(cwd, "run-node"),
182 path.join(cwd, "run-env-node"),
183 path.join(cwd, "run-env-split-string"),
184 path.join(cwd, "run-env-unset"),
185 path.join(cwd, "run-env-grouped-unset"),
186 path.join(cwd, "run-env-argv0"),
187 path.join(cwd, "run-env-long-argv0"),
188 image,
189 archive,
190 ],
191 })).entries,
192 ).toEqual([
193 { kind: "file", byteLength: script.length, mimeType: "text/x-python" },
194 { kind: "file", byteLength: nodeScript.length, mimeType: "text/javascript" },
195 { kind: "file", byteLength: envNodeScript.length, mimeType: "text/javascript" },
196 { kind: "file", byteLength: envSplitStringScript.length, mimeType: "text/javascript" },
197 { kind: "file", byteLength: envUnsetScript.length, mimeType: "text/javascript" },
198 { kind: "file", byteLength: envGroupedUnsetScript.length, mimeType: "text/javascript" },
199 { kind: "file", byteLength: envArgv0Script.length, mimeType: "text/javascript" },
200 { kind: "file", byteLength: envLongArgv0Script.length, mimeType: "text/javascript" },
201 { kind: "file", byteLength: 8, mimeType: "image/png" },
202 { kind: "file", byteLength: 22, mimeType: "application/zip" },
203 ]);
204 }),
205 );
206
207 // A file chip for `file://attacker.test/s/a.ts` in an agent's message sent
208 // the Windows user's NTLM credentials to attacker.test as it rendered.
209 it.effect("never stats a network path", () =>
210 Effect.gen(function* () {
211 const fs = yield* FileSystem.FileSystem;
212 const statted: Array<string> = [];
213 const service = yield* WorkspaceFileSystem.make.pipe(
214 Effect.provideService(
215 FileSystem.FileSystem,
216 FileSystem.FileSystem.of({
217 ...fs,
218 stat: (requestedPath) => {
219 statted.push(requestedPath);
220 return fs.stat(requestedPath);
221 },
222 }),
223 ),
224 Effect.provide(layerKnownWorkspacesTest),
225 );
226 const paths = [
227 "\\\\attacker.test\\s\\a.ts",
228 "//attacker.test/s/a.ts",
229 "/\\attacker.test\\s",
230 ];
231 expect((yield* service.getMetadata({ paths })).entries).toEqual([null, null, null]);
232 expect(statted).toEqual([]);
233 }),
234 );
235
236 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
237 "reports a Windows drive path under WSL as the file it maps to",
238 () =>
239 Effect.gen(function* () {
240 const { mountRoot, service, underWsl } = yield* makeWslHost;
241 yield* writeTextFile(mountRoot, "c/Users/me/Documents/notes.md", "# Notes\n");
242
243 const { entries } = yield* underWsl(
244 service.getMetadata({
245 paths: [
246 "C:\\Users\\me\\Documents\\notes.md",
247 "C:/Users/me/Documents/notes.md",
248 "C:/Users/me/Documents/notes\u0000.md",
249 ],
250 }),
251 );
252
253 expect(entries).toEqual([
254 { kind: "file", byteLength: 8 },
255 { kind: "file", byteLength: 8 },
256 null,
257 ]);
258 }),
259 );
260 });
261
262 describe("readFile", () => {
263 it.effect("reads UTF-8 files relative to the workspace root", () =>
264 Effect.gen(function* () {
265 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
266 const cwd = yield* makeTempDir;
267 yield* writeTextFile(cwd, "src/index.ts", "export const answer = 42;\n");
268
269 const result = yield* workspaceFileSystem.readFile({
270 cwd,
271 relativePath: "src/index.ts",
272 });
273
274 expect(result).toEqual({
275 relativePath: "src/index.ts",
276 contents: "export const answer = 42;\n",
277 byteLength: 26,
278 truncated: false,
279 });
280
281 const bomContents = "\uFEFFexport const answer = 42;\n";
282 yield* writeTextFile(cwd, "bom.ts", bomContents);
283 const bomRead = yield* workspaceFileSystem.readFile({ cwd, relativePath: "bom.ts" });
284 yield* workspaceFileSystem.writeFile({
285 cwd,
286 relativePath: "bom.ts",
287 contents: bomRead.contents.replace("42", "43"),
288 });
289 const fs = yield* FileSystem.FileSystem;
290 const saved = yield* fs.readFile(`${cwd}/bom.ts`);
291 expect([...saved]).toEqual([...new TextEncoder().encode(bomContents.replace("42", "43"))]);
292
293 yield* writeTextFile(cwd, "report.txt", "ordinary file");
294 for (const relativePath of whitespaceFilePaths) {
295 yield* writeTextFile(cwd, relativePath, "whitespace file");
296 const read = yield* workspaceFileSystem.readFile({ cwd, relativePath });
297 expect(read.contents).toBe("whitespace file");
298 expect(read.relativePath).toBe(relativePath);
299 }
300 }),
301 );
302
303 it.effect("reports an optional file as absent when the workspace root was removed", () =>
304 Effect.gen(function* () {
305 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
306 const path = yield* Path.Path;
307 const cwd = path.join(yield* makeTempDir, "removed-worktree");
308
309 const result = yield* workspaceFileSystem.readFile({
310 cwd,
311 relativePath: "t3.json",
312 allowMissing: true,
313 });
314 expect(result).toEqual({
315 relativePath: "t3.json",
316 contents: "",
317 byteLength: 0,
318 truncated: false,
319 exists: false,
320 });
321
322 const error = yield* workspaceFileSystem
323 .readFile({ cwd, relativePath: "t3.json" })
324 .pipe(Effect.flip);
325 expect(error).toMatchObject({ operation: "realpath-workspace-root" });
326 }),
327 );
328
329 it.effect("finishes short reads before decoding UTF-8 text", () =>
330 Effect.gen(function* () {
331 const files = yield* WorkspaceFileSystem.WorkspaceFileSystem;
332 const fs = yield* FileSystem.FileSystem;
333 const cwd = yield* makeTempDir;
334 const contents = "A café 🐈\n";
335 yield* writeTextFile(cwd, "short.txt", contents);
336 const target = yield* fs.realPath(`${cwd}/short.txt`);
337 yield* injectShortReads(target);
338 expect(yield* files.readFile({ cwd, relativePath: "short.txt" })).toEqual({
339 relativePath: "short.txt",
340 contents,
341 byteLength: Buffer.byteLength(contents),
342 truncated: false,
343 });
344 }),
345 );
346
347 it.effect("rejects binary bytes delivered after an initial short read", () =>
348 Effect.gen(function* () {
349 const files = yield* WorkspaceFileSystem.WorkspaceFileSystem;
350 const fs = yield* FileSystem.FileSystem;
351 const cwd = yield* makeTempDir;
352 yield* writeTextFile(cwd, "short.txt", "ab\0cd");
353 const target = yield* fs.realPath(`${cwd}/short.txt`);
354 yield* injectShortReads(target);
355 const error = yield* files.readFile({ cwd, relativePath: "short.txt" }).pipe(Effect.flip);
356 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
357 }),
358 );
359
360 it.effect("reads host files outside the workspace root by absolute path", () =>
361 Effect.gen(function* () {
362 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
363 const path = yield* Path.Path;
364 const cwd = yield* makeTempDir;
365 const outsideDir = yield* makeTempDir;
366 yield* writeTextFile(outsideDir, "cleanup-report.md", "# Report\n");
367 const absolutePath = path.join(outsideDir, "cleanup-report.md");
368
369 const result = yield* workspaceFileSystem.readFile({
370 cwd,
371 relativePath: absolutePath,
372 });
373
374 expect(result).toEqual({
375 relativePath: absolutePath,
376 contents: "# Report\n",
377 byteLength: 9,
378 truncated: false,
379 });
380
381 for (const relativePath of whitespaceFilePaths) {
382 yield* writeTextFile(outsideDir, relativePath, "whitespace file");
383 const requestedPath = path.join(outsideDir, relativePath);
384 const read = yield* workspaceFileSystem.readFile({ cwd, relativePath: requestedPath });
385 expect(read.contents).toBe("whitespace file");
386 expect(read.relativePath).toBe(requestedPath);
387 }
388 }),
389 );
390
391 it.effect("reads files whose native realpath fails, as on rclone WinFsp drives", () =>
392 Effect.gen(function* () {
393 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
394 const path = yield* Path.Path;
395 const cwd = yield* makeTempDir;
396 const outsideDir = yield* makeTempDir;
397 yield* writeTextFile(cwd, "notes.md", "# Notes\n");
398 yield* writeTextFile(outsideDir, "report.md", "# Report\n");
399 const native = yield* Effect.promise(() =>
400 vi.importActual<typeof NodeFSP>("node:fs/promises"),
401 );
402 const realpath = vi
403 .mocked(NodeFSP.realpath)
404 .mockClear()
405 .mockRejectedValue(
406 Object.assign(new Error("UNKNOWN: unknown error, realpath"), { code: "UNKNOWN" }),
407 );
408 yield* Effect.addFinalizer(() =>
409 Effect.sync(() => realpath.mockImplementation(native.realpath)),
410 );
411
412 const relative = yield* workspaceFileSystem.readFile({ cwd, relativePath: "notes.md" });
413 const absolute = yield* workspaceFileSystem.readFile({
414 cwd,
415 relativePath: path.join(outsideDir, "report.md"),
416 });
417
418 expect(relative.contents).toBe("# Notes\n");
419 expect(absolute.contents).toBe("# Report\n");
420 expect(realpath).toHaveBeenCalled();
421 }),
422 );
423
424 it.effect.each(["~/.claude/CLAUDE.md", "~\\.claude/CLAUDE.md"])(
425 "reads %s from the server home outside the workspace",
426 (relativePath) =>
427 Effect.gen(function* () {
428 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
429 const cwd = yield* makeTempDir;
430 const home = yield* makeTempDir;
431 yield* writeTextFile(home, ".claude/CLAUDE.md", "# Notes\n");
432 yield* writeTextFile(cwd, "~/.claude/CLAUDE.md", "Workspace decoy\n");
433
434 const result = yield* workspaceFileSystem
435 .readFile({ cwd, relativePath })
436 .pipe(Effect.provideService(HostProcess.HomeDirectory, home));
437
438 expect(result).toEqual({
439 relativePath,
440 contents: "# Notes\n",
441 byteLength: 8,
442 truncated: false,
443 });
444 }),
445 );
446
447 it.effect("does not read server state files", () =>
448 Effect.gen(function* () {
449 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
450 const config = yield* ServerConfig.ServerConfig;
451 const path = yield* Path.Path;
452 const cwd = yield* makeTempDir;
453 yield* writeTextFile(config.secretsDir, "example.bin", "example\n");
454 yield* writeTextFile(config.stateDir, "statev2.sqlite", "example\n");
455
456 for (const input of [
457 { cwd, relativePath: path.join(config.secretsDir, "example.bin") },
458 { cwd: config.stateDir, relativePath: "statev2.sqlite" },
459 ]) {
460 const error = yield* workspaceFileSystem.readFile(input).pipe(Effect.flip);
461 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
462 }
463 const metadata = yield* workspaceFileSystem.getMetadata({
464 paths: [
465 path.join(config.secretsDir, "example.bin"),
466 path.join(config.stateDir, "statev2.sqlite"),
467 config.stateDir,
468 ],
469 });
470 expect(metadata.entries).toEqual([null, null, { kind: "directory" }]);
471 }),
472 );
473
474 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
475 "rejects a FIFO without blocking on open",
476 () =>
477 Effect.gen(function* () {
478 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
479 const path = yield* Path.Path;
480 const cwd = yield* makeTempDir;
481 const outsideDir = yield* makeTempDir;
482 const fifoPath = path.join(outsideDir, "pipe");
483 yield* Effect.promise(
484 () =>
485 new Promise<void>((resolve, reject) =>
486 NodeChildProcess.execFile("mkfifo", [fifoPath], (error) =>
487 error ? reject(error) : resolve(),
488 ),
489 ),
490 );
491
492 const error = yield* workspaceFileSystem
493 .readFile({ cwd, relativePath: fifoPath })
494 .pipe(Effect.flip);
495
496 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
497 expect((yield* workspaceFileSystem.getMetadata({ paths: [fifoPath] })).entries).toEqual([
498 { kind: "other" },
499 ]);
500 }),
501 );
502
503 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
504 "reads a Windows drive path under WSL from where wslpath mounts it",
505 () =>
506 Effect.gen(function* () {
507 const { mountRoot, service, underWsl } = yield* makeWslHost;
508 const cwd = yield* makeTempDir;
509 yield* writeTextFile(mountRoot, "c/Users/me/Documents/notes.md", "# Notes\n");
510
511 for (const relativePath of [
512 "C:\\Users\\me\\Documents\\notes.md",
513 "C:/Users/me/Documents/notes.md",
514 ]) {
515 const result = yield* underWsl(service.readFile({ cwd, relativePath }));
516 expect(result).toMatchObject({ contents: "# Notes\n", truncated: false });
517 }
518 }),
519 );
520
521 // Agents on Windows copy paths from Git Bash, which prints `C:\x` as `/c/x`.
522 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
523 "reads a Git Bash drive path on Windows",
524 () =>
525 Effect.gen(function* () {
526 const service = yield* WorkspaceFileSystem.WorkspaceFileSystem;
527 const fs = yield* FileSystem.FileSystem;
528 const path = yield* Path.Path;
529 const cwd = yield* makeTempDir;
530 const filePath = path.join(yield* fs.realPath(yield* makeTempDir), "notes.md");
531 yield* fs.writeFileString(filePath, "# Notes\n");
532 const gitBashPath = `/${filePath[0]!.toLowerCase()}${filePath.slice(2).replaceAll("\\", "/")}`;
533
534 expect((yield* service.getMetadata({ paths: [gitBashPath] })).entries).toEqual([
535 { kind: "file", byteLength: 8 },
536 ]);
537 const result = yield* service.readFile({ cwd, relativePath: gitBashPath });
538 expect(result).toMatchObject({ contents: "# Notes\n", truncated: false });
539 }),
540 );
541
542 it.effect("refuses a network path outside the workspace", () =>
543 Effect.gen(function* () {
544 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
545
546 const error = yield* workspaceFileSystem
547 .readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" })
548 .pipe(Effect.flip);
549
550 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
551 }),
552 );
553
554 // This resolves inside the project, but Windows reads `\\?\` paths as
555 // written, so realpath on the raw string signed in to attacker.test.
556 it.effect("reads the network path it checked", () =>
557 Effect.gen(function* () {
558 const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe(
559 Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)),
560 );
561 // Rejects without touching the filesystem, so a Windows runner never looks the share up.
562 const realpath = vi
563 .mocked(NodeFSP.realpath)
564 .mockClear()
565 .mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
566
567 yield* workspaceFileSystem
568 .readFile({
569 cwd: "\\\\?\\UNC\\nas.test\\share\\project",
570 relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md",
571 })
572 .pipe(Effect.exit);
573
574 expect(realpath.mock.calls.map(([target]) => target)).toEqual([
575 "\\\\?\\UNC\\nas.test\\share\\project\\a.md",
576 ]);
577 }),
578 );
579
580 // Resolving `..` before realpath would read beside the link instead of its target.
581 // Windows collapses `..` before the filesystem sees a path, so it has no such reads.
582 it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")(
583 "reads `..` after a link from the link's target",
584 () =>
585 Effect.gen(function* () {
586 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
587 const fs = yield* FileSystem.FileSystem;
588 const path = yield* Path.Path;
589 const root = yield* makeTempDir;
590 yield* writeTextFile(root, "target/parent.md", "beside the target\n");
591 yield* writeTextFile(root, "parent.md", "beside the link\n");
592 yield* fs.makeDirectory(path.join(root, "target", "child"));
593 yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link"));
594
595 const result = yield* workspaceFileSystem.readFile({
596 cwd: root,
597 relativePath: `${root}/link/../parent.md`,
598 });
599
600 expect(result.contents).toBe("beside the target\n");
601 }),
602 );
603
604 it.effect.skipIf(!symlinksSupported)(
605 "reads through symlinks that resolve outside the workspace root as read-only",
606 () =>
607 Effect.gen(function* () {
608 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
609 const fileSystem = yield* FileSystem.FileSystem;
610 const path = yield* Path.Path;
611 const cwd = yield* makeTempDir;
612 const outsideDir = yield* makeTempDir;
613 yield* writeTextFile(outsideDir, "specs/design.md", "outside\n");
614 yield* writeTextFile(cwd, "inside.md", "inside\n");
615 yield* fileSystem.symlink(outsideDir, path.join(cwd, "_files"));
616
617 const result = yield* workspaceFileSystem.readFile({
618 cwd,
619 relativePath: "_files/specs/design.md",
620 });
621 expect(result).toMatchObject({
622 relativePath: "_files/specs/design.md",
623 contents: "outside\n",
624 readOnly: true,
625 });
626
627 const inside = yield* workspaceFileSystem.readFile({ cwd, relativePath: "inside.md" });
628 expect(inside.readOnly).toBeUndefined();
629
630 const missing = yield* workspaceFileSystem.readFile({
631 cwd,
632 relativePath: "_files/missing/t3.json",
633 allowMissing: true,
634 });
635 expect(missing.exists).toBe(false);
636 }),
637 );
638
639 it.effect("drops a multibyte character split by the read limit", () =>
640 Effect.gen(function* () {
641 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
642 const fileSystem = yield* FileSystem.FileSystem;
643 const path = yield* Path.Path;
644 const cwd = yield* makeTempDir;
645 const limit = 1024 * 1024;
646 const euro = new TextEncoder().encode("€");
647 const bytes = new Uint8Array(limit - 1 + euro.length).fill(0x61);
648 bytes.set(euro, limit - 1);
649 yield* fileSystem.writeFile(path.join(cwd, "large.txt"), bytes);
650
651 const result = yield* workspaceFileSystem.readFile({ cwd, relativePath: "large.txt" });
652
653 expect(result.truncated).toBe(true);
654 expect(result.byteLength).toBe(bytes.length);
655 expect(result.contents).toBe("a".repeat(limit - 1));
656 }),
657 );
658
659 it.effect.each([
660 { name: "a NUL byte", bytes: [0x61, 0, 0x62] },
661 { name: "invalid UTF-8", bytes: [0x63, 0x61, 0x66, 0xe9] },
662 ])("rejects files with $name without leaking their contents", ({ bytes }) =>
663 Effect.gen(function* () {
664 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
665 const fileSystem = yield* FileSystem.FileSystem;
666 const path = yield* Path.Path;
667 const cwd = yield* makeTempDir;
668 const absolutePath = path.join(cwd, "asset.bin");
669 yield* fileSystem.writeFile(absolutePath, Uint8Array.from(bytes));
670
671 const error = yield* workspaceFileSystem
672 .readFile({ cwd, relativePath: "asset.bin" })
673 .pipe(Effect.flip);
674 const resolvedPath = yield* fileSystem.realPath(absolutePath);
675
676 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
677 expect(error).toMatchObject({
678 workspaceRoot: cwd,
679 relativePath: "asset.bin",
680 resolvedPath,
681 });
682 expect("cause" in error).toBe(false);
683 expect("contents" in error).toBe(false);
684 }),
685 );
686 });
687
688 describe("writeFile", () => {
689 it.effect("rejects writes outside a known workspace", () =>
690 Effect.gen(function* () {
691 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
692 const fileSystem = yield* FileSystem.FileSystem;
693 const cwd = yield* fileSystem.makeTempDirectoryScoped({
694 prefix: UNKNOWN_WORKSPACE_PREFIX,
695 });
696
697 const error = yield* workspaceFileSystem
698 .writeFile({ cwd, relativePath: "plan.md", contents: "# nope\n" })
699 .pipe(Effect.flip);
700
701 expect(error).toBeInstanceOf(KnownWorkspaces.UnknownWorkspaceError);
702 expect(yield* fileSystem.readDirectory(cwd)).toEqual([]);
703 }),
704 );
705
706 it.effect("rejects writes by absolute path", () =>
707 Effect.gen(function* () {
708 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
709 const path = yield* Path.Path;
710 const cwd = yield* makeTempDir;
711 const outsideDir = yield* makeTempDir;
712 const absolutePath = path.join(outsideDir, "cleanup-report.md");
713
714 const error = yield* workspaceFileSystem
715 .writeFile({ cwd, relativePath: absolutePath, contents: "# Edited\n" })
716 .pipe(Effect.flip);
717
718 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
719 }),
720 );
721
722 it.effect("invalidates workspace entry search cache after writes", () =>
723 Effect.gen(function* () {
724 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
725 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
726 const cwd = yield* makeTempDir;
727 yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
728
729 const beforeWrite = yield* workspaceEntries.list({ cwd });
730 expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
731 false,
732 );
733
734 yield* workspaceFileSystem.writeFile({
735 cwd,
736 relativePath: "plans/effect-rpc.md",
737 contents: "# Plan\n",
738 });
739
740 const afterWrite = yield* workspaceEntries.list({ cwd });
741 expect(afterWrite.entries).toEqual(
742 expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
743 );
744 expect(afterWrite.truncated).toBe(false);
745 }),
746 );
747
748 it.effect("saves over an existing file without rescanning the workspace", () =>
749 Effect.gen(function* () {
750 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
751 const fileSystem = yield* FileSystem.FileSystem;
752 const path = yield* Path.Path;
753 const cwd = yield* makeTempDir;
754 yield* writeTextFile(cwd, "src/main.ts", "export {};\n");
755
756 yield* workspaceFileSystem.writeFile({
757 cwd,
758 relativePath: "src/main.ts",
759 contents: "export const edited = true;\n",
760 });
761
762 expect(yield* fileSystem.readFileString(path.join(cwd, "src/main.ts"))).toBe(
763 "export const edited = true;\n",
764 );
765
766 yield* writeTextFile(cwd, "report.txt", "ordinary file");
767 for (const relativePath of whitespaceFilePaths) {
768 yield* writeTextFile(cwd, relativePath, "whitespace file");
769 const written = yield* workspaceFileSystem.writeFile({
770 cwd,
771 relativePath,
772 contents: "edited",
773 });
774 expect(yield* fileSystem.readFileString(path.join(cwd, "report.txt"))).toBe(
775 "ordinary file",
776 );
777 expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("edited");
778 expect(written.relativePath).toBe(relativePath);
779 }
780 }).pipe(
781 Effect.provide(
782 Layer.fresh(WorkspaceFileSystem.layer).pipe(
783 Layer.provide(layerKnownWorkspacesTest),
784 Layer.provide(WorkspacePaths.layer),
785 Layer.provide(
786 Layer.mock(WorkspaceEntries.WorkspaceEntries)({
787 refresh: () => Effect.die("An overwrite rescanned the workspace."),
788 }),
789 ),
790 ),
791 ),
792 ),
793 );
794
795 it.effect("rejects writes outside the workspace root", () =>
796 Effect.gen(function* () {
797 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
798 const cwd = yield* makeTempDir;
799 const path = yield* Path.Path;
800 const fileSystem = yield* FileSystem.FileSystem;
801
802 for (const relativePath of ["../escape.md", "../escape.md ", " folder/../../escape.md"]) {
803 const error = yield* workspaceFileSystem
804 .writeFile({ cwd, relativePath, contents: "# nope\n" })
805 .pipe(Effect.flip);
806
807 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
808 }
809
810 const escapedPath = path.resolve(cwd, "..", "escape.md");
811 const escapedStat = yield* fileSystem
812 .stat(escapedPath)
813 .pipe(Effect.orElseSucceed(() => null));
814 expect(escapedStat).toBeNull();
815 }),
816 );
817
818 it.effect.skipIf(!symlinksSupported)(
819 "rejects writes through symlinks that resolve outside the workspace root",
820 () =>
821 Effect.gen(function* () {
822 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
823 const fileSystem = yield* FileSystem.FileSystem;
824 const path = yield* Path.Path;
825 const cwd = yield* makeTempDir;
826 const outsideDir = yield* makeTempDir;
827 yield* writeTextFile(outsideDir, "existing.md", "outside\n");
828 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
829 yield* fileSystem.symlink(
830 path.join(outsideDir, "existing.md"),
831 path.join(cwd, "linked-file.md"),
832 );
833 yield* fileSystem.symlink(
834 path.join(outsideDir, "missing.md"),
835 path.join(cwd, "dangling.md"),
836 );
837
838 for (const relativePath of [
839 "linked-dir/new.md",
840 "linked-dir/nested/new.md",
841 "linked-file.md",
842 ]) {
843 const error = yield* workspaceFileSystem
844 .writeFile({ cwd, relativePath, contents: "# nope\n" })
845 .pipe(Effect.flip);
846 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
847 }
848 const danglingError = yield* workspaceFileSystem
849 .writeFile({ cwd, relativePath: "dangling.md", contents: "# nope\n" })
850 .pipe(Effect.flip);
851 expect(danglingError).toBeInstanceOf(
852 WorkspaceFileSystem.WorkspaceFileSystemOperationError,
853 );
854 expect(danglingError).toMatchObject({ operation: "realpath-target" });
855
856 expect((yield* fileSystem.readDirectory(outsideDir)).toSorted()).toEqual(["existing.md"]);
857 expect(yield* fileSystem.readFileString(path.join(outsideDir, "existing.md"))).toBe(
858 "outside\n",
859 );
860 }),
861 );
862
863 it.effect.skipIf(!symlinksSupported)(
864 "writes through symlinks that stay inside the workspace root",
865 () =>
866 Effect.gen(function* () {
867 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
868 const fileSystem = yield* FileSystem.FileSystem;
869 const path = yield* Path.Path;
870 const parentDir = yield* makeTempDir;
871 const cwd = path.join(parentDir, "workspace");
872 const cwdAlias = path.join(parentDir, "workspace-alias");
873 yield* writeTextFile(cwd, "docs/README.md", "old\n");
874 yield* fileSystem.symlink(path.join(cwd, "docs"), path.join(cwd, "docs-alias"));
875 yield* fileSystem.symlink("docs/README.md", path.join(cwd, "README.md"));
876 yield* fileSystem.symlink(cwd, cwdAlias);
877
878 yield* workspaceFileSystem.writeFile({
879 cwd,
880 relativePath: "docs-alias/plans/plan.md",
881 contents: "# Plan\n",
882 });
883 yield* workspaceFileSystem.writeFile({
884 cwd,
885 relativePath: "README.md",
886 contents: "new\n",
887 });
888 yield* workspaceFileSystem.writeFile({
889 cwd: cwdAlias,
890 relativePath: "notes.md",
891 contents: "notes\n",
892 });
893 // `..` after a link in cwd is resolved by name, as for the relative path.
894 yield* fileSystem.symlink(path.join(cwd, "docs/plans"), path.join(cwd, "plans-alias"));
895 yield* workspaceFileSystem.writeFile({
896 cwd: `${path.join(cwd, "plans-alias")}${path.sep}..`,
897 relativePath: "dotdot.md",
898 contents: "dotdot\n",
899 });
900
901 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/plans/plan.md"))).toBe(
902 "# Plan\n",
903 );
904 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/README.md"))).toBe("new\n");
905 expect(yield* fileSystem.readLink(path.join(cwd, "README.md"))).toBe("docs/README.md");
906 expect(yield* fileSystem.readFileString(path.join(cwd, "notes.md"))).toBe("notes\n");
907 expect(yield* fileSystem.readFileString(path.join(cwd, "dotdot.md"))).toBe("dotdot\n");
908 }),
909 );
910
911 // On Windows `\` is a separator, so the name cannot exist there.
912 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
913 "keeps a backslash in a file name as part of the name",
914 () =>
915 Effect.gen(function* () {
916 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
917 const fileSystem = yield* FileSystem.FileSystem;
918 const cwd = yield* makeTempDir;
919 yield* writeTextFile(cwd, "a\\b.md", "old\n");
920
921 yield* workspaceFileSystem.writeFile({ cwd, relativePath: "a\\b.md", contents: "new\n" });
922
923 expect(
924 (yield* workspaceFileSystem.readFile({ cwd, relativePath: "a\\b.md" })).contents,
925 ).toBe("new\n");
926 expect(yield* fileSystem.readDirectory(cwd)).toEqual(["a\\b.md"]);
927 }),
928 );
929
930 it.effect("refuses writes into git's own folders", () =>
931 Effect.gen(function* () {
932 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
933 const fileSystem = yield* FileSystem.FileSystem;
934 const path = yield* Path.Path;
935 const cwd = yield* makeTempDir;
936 yield* writeTextFile(cwd, ".git/config", "[core]\n");
937 yield* writeTextFile(cwd, ".bare/HEAD", "ref: refs/heads/main\n");
938 yield* writeTextFile(cwd, ".bare/objects/info/packs");
939 yield* writeTextFile(cwd, ".bare/refs/heads/main");
940 yield* writeTextFile(cwd, ".bare/hooks/pre-push.sample");
941 // Only a linked worktree's `.git` file ends the upward check, not any `.git` folder.
942 yield* fileSystem.makeDirectory(path.join(cwd, ".bare/hooks/.git"));
943 yield* writeTextFile(cwd, ".bare/worktrees/main/HEAD", "ref: refs/heads/main\n");
944 yield* writeTextFile(cwd, ".bare/worktrees/main/commondir", "../..\n");
945 if (symlinksSupported) yield* fileSystem.symlink(".git", path.join(cwd, "docs"));
946
947 for (const [folder, relativePath] of [
948 [cwd, ".git/config"],
949 [cwd, ".git/hooks/pre-commit"],
950 [cwd, "sub/.git"],
951 [cwd, ".GIT/config"],
952 [cwd, ".gıt/config"],
953 [cwd, ".git. /config"],
954 [cwd, ".git::$INDEX_ALLOCATION/config"],
955 [cwd, "GIT~1/config"],
956 [path.join(cwd, ".git"), "config"],
957 [cwd, ".bare/config"],
958 [path.join(cwd, ".bare"), "hooks/post-checkout"],
959 [path.join(cwd, ".bare/hooks"), "post-checkout"],
960 [path.join(cwd, ".bare/worktrees/main"), "commondir"],
961 ...(symlinksSupported ? [[cwd, "docs/config"] as const] : []),
962 ] as const) {
963 const error = yield* workspaceFileSystem
964 .writeFile({ cwd: folder, relativePath, contents: "[core]\n\tfsmonitor = x\n" })
965 .pipe(Effect.flip);
966 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
967 }
968
969 expect(yield* fileSystem.readFileString(path.join(cwd, ".git/config"))).toBe("[core]\n");
970 expect(yield* fileSystem.exists(path.join(cwd, ".bare/config"))).toBe(false);
971 expect((yield* fileSystem.readDirectory(path.join(cwd, ".bare/hooks"))).toSorted()).toEqual(
972 [".git", "pre-push.sample"],
973 );
974 expect(yield* fileSystem.exists(path.join(cwd, "sub"))).toBe(false);
975 expect(
976 yield* fileSystem.readFileString(path.join(cwd, ".bare/worktrees/main/commondir")),
977 ).toBe("../..\n");
978 }),
979 );
980
981 it.effect.skipIf(!symlinksSupported)(
982 "refuses writes through a git config that links to a file outside git's folders",
983 () =>
984 Effect.gen(function* () {
985 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
986 const fileSystem = yield* FileSystem.FileSystem;
987 const path = yield* Path.Path;
988 const cwd = yield* makeTempDir;
989 yield* writeTextFile(cwd, "shared/config", "[core]\n");
990 yield* fileSystem.makeDirectory(path.join(cwd, ".git"));
991 yield* fileSystem.symlink("../shared/config", path.join(cwd, ".git/config"));
992
993 const error = yield* workspaceFileSystem
994 .writeFile({ cwd, relativePath: ".git/config", contents: "[core]\n\tfsmonitor = x\n" })
995 .pipe(Effect.flip);
996
997 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
998 expect(yield* fileSystem.readFileString(path.join(cwd, "shared/config"))).toBe(
999 "[core]\n",
1000 );
1001 }),
1002 );
1003
1004 it.effect("writes files that sit beside git's folders", () =>
1005 Effect.gen(function* () {
1006 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
1007 const fileSystem = yield* FileSystem.FileSystem;
1008 const path = yield* Path.Path;
1009 const parentDir = yield* makeTempDir;
1010 const bare = path.join(parentDir, "repo.git");
1011 yield* writeTextFile(bare, "HEAD", "ref: refs/heads/main\n");
1012 yield* writeTextFile(bare, "objects/info/packs");
1013 yield* writeTextFile(bare, "refs/heads/main");
1014 yield* writeTextFile(bare, "main/.git", `gitdir: ${path.join(bare, "worktrees/main")}\n`);
1015
1016 for (const [cwd, relativePath] of [
1017 [path.join(bare, "main"), ".gitignore"],
1018 [path.join(bare, "main"), ".gitattributes"],
1019 [path.join(bare, "main"), ".github/workflows/ci.yml"],
1020 [path.join(bare, "main"), "vendor/lib.git/README.md"],
1021 [path.join(bare, "main/.github"), "CODEOWNERS"],
1022 [bare, "main/plan.md"],
1023 ] as const) {
1024 yield* workspaceFileSystem.writeFile({ cwd, relativePath, contents: "ok\n" });
1025 expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("ok\n");
1026 }
1027 }),
1028 );
1029 });
1030});