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