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