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