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