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 "rejects symlinks that resolve outside the workspace root",
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, "secret.txt", "outside\n");
544 yield* fileSystem.symlink(
545 path.join(outsideDir, "secret.txt"),
546 path.join(cwd, "linked-secret.txt"),
547 );
548
549 const error = yield* workspaceFileSystem
550 .readFile({ cwd, relativePath: "linked-secret.txt" })
551 .pipe(Effect.flip);
552 const resolvedWorkspaceRoot = yield* fileSystem.realPath(cwd);
553 const resolvedPath = yield* fileSystem.realPath(path.join(outsideDir, "secret.txt"));
554
555 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
556 expect(error).toMatchObject({
557 workspaceRoot: cwd,
558 relativePath: "linked-secret.txt",
559 resolvedWorkspaceRoot,
560 resolvedPath,
561 });
562 expect("cause" in error).toBe(false);
563
564 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
565 const missingChildError = yield* workspaceFileSystem
566 .readFile(
567 Object.assign(
568 { cwd, relativePath: "linked-dir/missing/t3.json" },
569 { allowMissing: true },
570 ),
571 )
572 .pipe(Effect.flip);
573 expect(missingChildError).toBeInstanceOf(
574 WorkspaceFileSystem.WorkspaceFilePathEscapeError,
575 );
576 }),
577 );
578
579 it.effect("drops a multibyte character split by the read limit", () =>
580 Effect.gen(function* () {
581 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
582 const fileSystem = yield* FileSystem.FileSystem;
583 const path = yield* Path.Path;
584 const cwd = yield* makeTempDir;
585 const limit = 1024 * 1024;
586 const euro = new TextEncoder().encode("€");
587 const bytes = new Uint8Array(limit - 1 + euro.length).fill(0x61);
588 bytes.set(euro, limit - 1);
589 yield* fileSystem.writeFile(path.join(cwd, "large.txt"), bytes);
590
591 const result = yield* workspaceFileSystem.readFile({ cwd, relativePath: "large.txt" });
592
593 expect(result.truncated).toBe(true);
594 expect(result.byteLength).toBe(bytes.length);
595 expect(result.contents).toBe("a".repeat(limit - 1));
596 }),
597 );
598
599 it.effect.each([
600 { name: "a NUL byte", bytes: [0x61, 0, 0x62] },
601 { name: "invalid UTF-8", bytes: [0x63, 0x61, 0x66, 0xe9] },
602 ])("rejects files with $name without leaking their contents", ({ bytes }) =>
603 Effect.gen(function* () {
604 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
605 const fileSystem = yield* FileSystem.FileSystem;
606 const path = yield* Path.Path;
607 const cwd = yield* makeTempDir;
608 const absolutePath = path.join(cwd, "asset.bin");
609 yield* fileSystem.writeFile(absolutePath, Uint8Array.from(bytes));
610
611 const error = yield* workspaceFileSystem
612 .readFile({ cwd, relativePath: "asset.bin" })
613 .pipe(Effect.flip);
614 const resolvedPath = yield* fileSystem.realPath(absolutePath);
615
616 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
617 expect(error).toMatchObject({
618 workspaceRoot: cwd,
619 relativePath: "asset.bin",
620 resolvedPath,
621 });
622 expect("cause" in error).toBe(false);
623 expect("contents" in error).toBe(false);
624 }),
625 );
626 });
627
628 describe("writeFile", () => {
629 it.effect("rejects writes outside a known workspace", () =>
630 Effect.gen(function* () {
631 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
632 const fileSystem = yield* FileSystem.FileSystem;
633 const cwd = yield* fileSystem.makeTempDirectoryScoped({
634 prefix: UNKNOWN_WORKSPACE_PREFIX,
635 });
636
637 const error = yield* workspaceFileSystem
638 .writeFile({ cwd, relativePath: "plan.md", contents: "# nope\n" })
639 .pipe(Effect.flip);
640
641 expect(error).toBeInstanceOf(KnownWorkspaces.UnknownWorkspaceError);
642 expect(yield* fileSystem.readDirectory(cwd)).toEqual([]);
643 }),
644 );
645
646 it.effect("rejects writes by absolute path", () =>
647 Effect.gen(function* () {
648 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
649 const path = yield* Path.Path;
650 const cwd = yield* makeTempDir;
651 const outsideDir = yield* makeTempDir;
652 const absolutePath = path.join(outsideDir, "cleanup-report.md");
653
654 const error = yield* workspaceFileSystem
655 .writeFile({ cwd, relativePath: absolutePath, contents: "# Edited\n" })
656 .pipe(Effect.flip);
657
658 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
659 }),
660 );
661
662 it.effect("invalidates workspace entry search cache after writes", () =>
663 Effect.gen(function* () {
664 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
665 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
666 const cwd = yield* makeTempDir;
667 yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
668
669 const beforeWrite = yield* workspaceEntries.list({ cwd });
670 expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
671 false,
672 );
673
674 yield* workspaceFileSystem.writeFile({
675 cwd,
676 relativePath: "plans/effect-rpc.md",
677 contents: "# Plan\n",
678 });
679
680 const afterWrite = yield* workspaceEntries.list({ cwd });
681 expect(afterWrite.entries).toEqual(
682 expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
683 );
684 expect(afterWrite.truncated).toBe(false);
685 }),
686 );
687
688 it.effect("saves over an existing file without rescanning the workspace", () =>
689 Effect.gen(function* () {
690 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
691 const fileSystem = yield* FileSystem.FileSystem;
692 const path = yield* Path.Path;
693 const cwd = yield* makeTempDir;
694 yield* writeTextFile(cwd, "src/main.ts", "export {};\n");
695
696 yield* workspaceFileSystem.writeFile({
697 cwd,
698 relativePath: "src/main.ts",
699 contents: "export const edited = true;\n",
700 });
701
702 expect(yield* fileSystem.readFileString(path.join(cwd, "src/main.ts"))).toBe(
703 "export const edited = true;\n",
704 );
705
706 yield* writeTextFile(cwd, "report.txt", "ordinary file");
707 for (const relativePath of whitespaceFilePaths) {
708 yield* writeTextFile(cwd, relativePath, "whitespace file");
709 const written = yield* workspaceFileSystem.writeFile({
710 cwd,
711 relativePath,
712 contents: "edited",
713 });
714 expect(yield* fileSystem.readFileString(path.join(cwd, "report.txt"))).toBe(
715 "ordinary file",
716 );
717 expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("edited");
718 expect(written.relativePath).toBe(relativePath);
719 }
720 }).pipe(
721 Effect.provide(
722 Layer.fresh(WorkspaceFileSystem.layer).pipe(
723 Layer.provide(layerKnownWorkspacesTest),
724 Layer.provide(WorkspacePaths.layer),
725 Layer.provide(
726 Layer.mock(WorkspaceEntries.WorkspaceEntries)({
727 refresh: () => Effect.die("An overwrite rescanned the workspace."),
728 }),
729 ),
730 ),
731 ),
732 ),
733 );
734
735 it.effect("rejects writes outside the workspace root", () =>
736 Effect.gen(function* () {
737 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
738 const cwd = yield* makeTempDir;
739 const path = yield* Path.Path;
740 const fileSystem = yield* FileSystem.FileSystem;
741
742 for (const relativePath of ["../escape.md", "../escape.md ", " folder/../../escape.md"]) {
743 const error = yield* workspaceFileSystem
744 .writeFile({ cwd, relativePath, contents: "# nope\n" })
745 .pipe(Effect.flip);
746
747 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
748 }
749
750 const escapedPath = path.resolve(cwd, "..", "escape.md");
751 const escapedStat = yield* fileSystem
752 .stat(escapedPath)
753 .pipe(Effect.orElseSucceed(() => null));
754 expect(escapedStat).toBeNull();
755 }),
756 );
757
758 it.effect.skipIf(!symlinksSupported)(
759 "rejects writes through symlinks that resolve outside the workspace root",
760 () =>
761 Effect.gen(function* () {
762 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
763 const fileSystem = yield* FileSystem.FileSystem;
764 const path = yield* Path.Path;
765 const cwd = yield* makeTempDir;
766 const outsideDir = yield* makeTempDir;
767 yield* writeTextFile(outsideDir, "existing.md", "outside\n");
768 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
769 yield* fileSystem.symlink(
770 path.join(outsideDir, "existing.md"),
771 path.join(cwd, "linked-file.md"),
772 );
773 yield* fileSystem.symlink(
774 path.join(outsideDir, "missing.md"),
775 path.join(cwd, "dangling.md"),
776 );
777
778 for (const relativePath of [
779 "linked-dir/new.md",
780 "linked-dir/nested/new.md",
781 "linked-file.md",
782 ]) {
783 const error = yield* workspaceFileSystem
784 .writeFile({ cwd, relativePath, contents: "# nope\n" })
785 .pipe(Effect.flip);
786 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
787 }
788 const danglingError = yield* workspaceFileSystem
789 .writeFile({ cwd, relativePath: "dangling.md", contents: "# nope\n" })
790 .pipe(Effect.flip);
791 expect(danglingError).toBeInstanceOf(
792 WorkspaceFileSystem.WorkspaceFileSystemOperationError,
793 );
794 expect(danglingError).toMatchObject({ operation: "realpath-target" });
795
796 expect((yield* fileSystem.readDirectory(outsideDir)).toSorted()).toEqual(["existing.md"]);
797 expect(yield* fileSystem.readFileString(path.join(outsideDir, "existing.md"))).toBe(
798 "outside\n",
799 );
800 }),
801 );
802
803 it.effect.skipIf(!symlinksSupported)(
804 "writes through symlinks that stay inside the workspace root",
805 () =>
806 Effect.gen(function* () {
807 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
808 const fileSystem = yield* FileSystem.FileSystem;
809 const path = yield* Path.Path;
810 const parentDir = yield* makeTempDir;
811 const cwd = path.join(parentDir, "workspace");
812 const cwdAlias = path.join(parentDir, "workspace-alias");
813 yield* writeTextFile(cwd, "docs/README.md", "old\n");
814 yield* fileSystem.symlink(path.join(cwd, "docs"), path.join(cwd, "docs-alias"));
815 yield* fileSystem.symlink("docs/README.md", path.join(cwd, "README.md"));
816 yield* fileSystem.symlink(cwd, cwdAlias);
817
818 yield* workspaceFileSystem.writeFile({
819 cwd,
820 relativePath: "docs-alias/plans/plan.md",
821 contents: "# Plan\n",
822 });
823 yield* workspaceFileSystem.writeFile({
824 cwd,
825 relativePath: "README.md",
826 contents: "new\n",
827 });
828 yield* workspaceFileSystem.writeFile({
829 cwd: cwdAlias,
830 relativePath: "notes.md",
831 contents: "notes\n",
832 });
833 // `..` after a link in cwd is resolved by name, as for the relative path.
834 yield* fileSystem.symlink(path.join(cwd, "docs/plans"), path.join(cwd, "plans-alias"));
835 yield* workspaceFileSystem.writeFile({
836 cwd: `${path.join(cwd, "plans-alias")}${path.sep}..`,
837 relativePath: "dotdot.md",
838 contents: "dotdot\n",
839 });
840
841 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/plans/plan.md"))).toBe(
842 "# Plan\n",
843 );
844 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/README.md"))).toBe("new\n");
845 expect(yield* fileSystem.readLink(path.join(cwd, "README.md"))).toBe("docs/README.md");
846 expect(yield* fileSystem.readFileString(path.join(cwd, "notes.md"))).toBe("notes\n");
847 expect(yield* fileSystem.readFileString(path.join(cwd, "dotdot.md"))).toBe("dotdot\n");
848 }),
849 );
850
851 // On Windows `\` is a separator, so the name cannot exist there.
852 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
853 "keeps a backslash in a file name as part of the name",
854 () =>
855 Effect.gen(function* () {
856 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
857 const fileSystem = yield* FileSystem.FileSystem;
858 const cwd = yield* makeTempDir;
859 yield* writeTextFile(cwd, "a\\b.md", "old\n");
860
861 yield* workspaceFileSystem.writeFile({ cwd, relativePath: "a\\b.md", contents: "new\n" });
862
863 expect(
864 (yield* workspaceFileSystem.readFile({ cwd, relativePath: "a\\b.md" })).contents,
865 ).toBe("new\n");
866 expect(yield* fileSystem.readDirectory(cwd)).toEqual(["a\\b.md"]);
867 }),
868 );
869
870 it.effect("refuses writes into git's own folders", () =>
871 Effect.gen(function* () {
872 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
873 const fileSystem = yield* FileSystem.FileSystem;
874 const path = yield* Path.Path;
875 const cwd = yield* makeTempDir;
876 yield* writeTextFile(cwd, ".git/config", "[core]\n");
877 yield* writeTextFile(cwd, ".bare/HEAD", "ref: refs/heads/main\n");
878 yield* writeTextFile(cwd, ".bare/objects/info/packs");
879 yield* writeTextFile(cwd, ".bare/refs/heads/main");
880 yield* writeTextFile(cwd, ".bare/hooks/pre-push.sample");
881 // Only a linked worktree's `.git` file ends the upward check, not any `.git` folder.
882 yield* fileSystem.makeDirectory(path.join(cwd, ".bare/hooks/.git"));
883 yield* writeTextFile(cwd, ".bare/worktrees/main/HEAD", "ref: refs/heads/main\n");
884 yield* writeTextFile(cwd, ".bare/worktrees/main/commondir", "../..\n");
885 if (symlinksSupported) yield* fileSystem.symlink(".git", path.join(cwd, "docs"));
886
887 for (const [folder, relativePath] of [
888 [cwd, ".git/config"],
889 [cwd, ".git/hooks/pre-commit"],
890 [cwd, "sub/.git"],
891 [cwd, ".GIT/config"],
892 [cwd, ".gıt/config"],
893 [cwd, ".git. /config"],
894 [cwd, ".git::$INDEX_ALLOCATION/config"],
895 [cwd, "GIT~1/config"],
896 [path.join(cwd, ".git"), "config"],
897 [cwd, ".bare/config"],
898 [path.join(cwd, ".bare"), "hooks/post-checkout"],
899 [path.join(cwd, ".bare/hooks"), "post-checkout"],
900 [path.join(cwd, ".bare/worktrees/main"), "commondir"],
901 ...(symlinksSupported ? [[cwd, "docs/config"] as const] : []),
902 ] as const) {
903 const error = yield* workspaceFileSystem
904 .writeFile({ cwd: folder, relativePath, contents: "[core]\n\tfsmonitor = x\n" })
905 .pipe(Effect.flip);
906 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
907 }
908
909 expect(yield* fileSystem.readFileString(path.join(cwd, ".git/config"))).toBe("[core]\n");
910 expect(yield* fileSystem.exists(path.join(cwd, ".bare/config"))).toBe(false);
911 expect((yield* fileSystem.readDirectory(path.join(cwd, ".bare/hooks"))).toSorted()).toEqual(
912 [".git", "pre-push.sample"],
913 );
914 expect(yield* fileSystem.exists(path.join(cwd, "sub"))).toBe(false);
915 expect(
916 yield* fileSystem.readFileString(path.join(cwd, ".bare/worktrees/main/commondir")),
917 ).toBe("../..\n");
918 }),
919 );
920
921 it.effect.skipIf(!symlinksSupported)(
922 "refuses writes through a git config that links to a file outside git's folders",
923 () =>
924 Effect.gen(function* () {
925 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
926 const fileSystem = yield* FileSystem.FileSystem;
927 const path = yield* Path.Path;
928 const cwd = yield* makeTempDir;
929 yield* writeTextFile(cwd, "shared/config", "[core]\n");
930 yield* fileSystem.makeDirectory(path.join(cwd, ".git"));
931 yield* fileSystem.symlink("../shared/config", path.join(cwd, ".git/config"));
932
933 const error = yield* workspaceFileSystem
934 .writeFile({ cwd, relativePath: ".git/config", contents: "[core]\n\tfsmonitor = x\n" })
935 .pipe(Effect.flip);
936
937 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
938 expect(yield* fileSystem.readFileString(path.join(cwd, "shared/config"))).toBe(
939 "[core]\n",
940 );
941 }),
942 );
943
944 it.effect("writes files that sit beside git's folders", () =>
945 Effect.gen(function* () {
946 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
947 const fileSystem = yield* FileSystem.FileSystem;
948 const path = yield* Path.Path;
949 const parentDir = yield* makeTempDir;
950 const bare = path.join(parentDir, "repo.git");
951 yield* writeTextFile(bare, "HEAD", "ref: refs/heads/main\n");
952 yield* writeTextFile(bare, "objects/info/packs");
953 yield* writeTextFile(bare, "refs/heads/main");
954 yield* writeTextFile(bare, "main/.git", `gitdir: ${path.join(bare, "worktrees/main")}\n`);
955
956 for (const [cwd, relativePath] of [
957 [path.join(bare, "main"), ".gitignore"],
958 [path.join(bare, "main"), ".gitattributes"],
959 [path.join(bare, "main"), ".github/workflows/ci.yml"],
960 [path.join(bare, "main"), "vendor/lib.git/README.md"],
961 [path.join(bare, "main/.github"), "CODEOWNERS"],
962 [bare, "main/plan.md"],
963 ] as const) {
964 yield* workspaceFileSystem.writeFile({ cwd, relativePath, contents: "ok\n" });
965 expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("ok\n");
966 }
967 }),
968 );
969 });
970});