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