Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorkspaceFileSystem.test.ts

944 lines38.1 KB

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