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

WorkspaceFileSystem.test.ts

809 lines32.7 KB

1// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO, and reads spy on native realpath.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFSP from "node:fs/promises";
4​
5import * as NodePath from "@effect/platform-node/NodePath";
6import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { it, describe, expect } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13​
14import * as ServerConfig from "../config.ts";
15import * 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 }),
294 );
295​
296 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
297 "rejects a FIFO without blocking on open",
298 () =>
299 Effect.gen(function* () {
300 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
301 const path = yield* Path.Path;
302 const cwd = yield* makeTempDir;
303 const outsideDir = yield* makeTempDir;
304 const fifoPath = path.join(outsideDir, "pipe");
305 yield* Effect.promise(
306 () =>
307 new Promise<void>((resolve, reject) =>
308 NodeChildProcess.execFile("mkfifo", [fifoPath], (error) =>
309 error ? reject(error) : resolve(),
310 ),
311 ),
312 );
313​
314 const error = yield* workspaceFileSystem
315 .readFile({ cwd, relativePath: fifoPath })
316 .pipe(Effect.flip);
317​
318 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
319 expect((yield* workspaceFileSystem.getMetadata({ paths: [fifoPath] })).entries).toEqual([
320 { kind: "other" },
321 ]);
322 }),
323 );
324​
325 it.effect("refuses a network path outside the workspace", () =>
326 Effect.gen(function* () {
327 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
328​
329 const error = yield* workspaceFileSystem
330 .readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" })
331 .pipe(Effect.flip);
332​
333 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
334 }),
335 );
336​
337 // This resolves inside the project, but Windows reads `\\?\` paths as
338 // written, so realpath on the raw string signed in to attacker.test.
339 it.effect("reads the network path it checked", () =>
340 Effect.gen(function* () {
341 const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe(
342 Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)),
343 );
344 // Rejects without touching the filesystem, so a Windows runner never looks the share up.
345 const realpath = vi
346 .mocked(NodeFSP.realpath)
347 .mockClear()
348 .mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
349​
350 yield* workspaceFileSystem
351 .readFile({
352 cwd: "\\\\?\\UNC\\nas.test\\share\\project",
353 relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md",
354 })
355 .pipe(Effect.exit);
356​
357 expect(realpath.mock.calls.map(([target]) => target)).toEqual([
358 "\\\\?\\UNC\\nas.test\\share\\project\\a.md",
359 ]);
360 }),
361 );
362​
363 // Resolving `..` before realpath would read beside the link instead of its target.
364 // Windows collapses `..` before the filesystem sees a path, so it has no such reads.
365 it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")(
366 "reads `..` after a link from the link's target",
367 () =>
368 Effect.gen(function* () {
369 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
370 const fs = yield* FileSystem.FileSystem;
371 const path = yield* Path.Path;
372 const root = yield* makeTempDir;
373 yield* writeTextFile(root, "target/parent.md", "beside the target\n");
374 yield* writeTextFile(root, "parent.md", "beside the link\n");
375 yield* fs.makeDirectory(path.join(root, "target", "child"));
376 yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link"));
377​
378 const result = yield* workspaceFileSystem.readFile({
379 cwd: root,
380 relativePath: `${root}/link/../parent.md`,
381 });
382​
383 expect(result.contents).toBe("beside the target\n");
384 }),
385 );
386​
387 it.effect.skipIf(!symlinksSupported)(
388 "rejects symlinks that resolve outside the workspace root",
389 () =>
390 Effect.gen(function* () {
391 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
392 const fileSystem = yield* FileSystem.FileSystem;
393 const path = yield* Path.Path;
394 const cwd = yield* makeTempDir;
395 const outsideDir = yield* makeTempDir;
396 yield* writeTextFile(outsideDir, "secret.txt", "outside\n");
397 yield* fileSystem.symlink(
398 path.join(outsideDir, "secret.txt"),
399 path.join(cwd, "linked-secret.txt"),
400 );
401​
402 const error = yield* workspaceFileSystem
403 .readFile({ cwd, relativePath: "linked-secret.txt" })
404 .pipe(Effect.flip);
405 const resolvedWorkspaceRoot = yield* fileSystem.realPath(cwd);
406 const resolvedPath = yield* fileSystem.realPath(path.join(outsideDir, "secret.txt"));
407​
408 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
409 expect(error).toMatchObject({
410 workspaceRoot: cwd,
411 relativePath: "linked-secret.txt",
412 resolvedWorkspaceRoot,
413 resolvedPath,
414 });
415 expect("cause" in error).toBe(false);
416​
417 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
418 const missingChildError = yield* workspaceFileSystem
419 .readFile(
420 Object.assign(
421 { cwd, relativePath: "linked-dir/missing/t3.json" },
422 { allowMissing: true },
423 ),
424 )
425 .pipe(Effect.flip);
426 expect(missingChildError).toBeInstanceOf(
427 WorkspaceFileSystem.WorkspaceFilePathEscapeError,
428 );
429 }),
430 );
431​
432 it.effect("drops a multibyte character split by the read limit", () =>
433 Effect.gen(function* () {
434 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
435 const fileSystem = yield* FileSystem.FileSystem;
436 const path = yield* Path.Path;
437 const cwd = yield* makeTempDir;
438 const limit = 1024 * 1024;
439 const euro = new TextEncoder().encode("€");
440 const bytes = new Uint8Array(limit - 1 + euro.length).fill(0x61);
441 bytes.set(euro, limit - 1);
442 yield* fileSystem.writeFile(path.join(cwd, "large.txt"), bytes);
443​
444 const result = yield* workspaceFileSystem.readFile({ cwd, relativePath: "large.txt" });
445​
446 expect(result.truncated).toBe(true);
447 expect(result.byteLength).toBe(bytes.length);
448 expect(result.contents).toBe("a".repeat(limit - 1));
449 }),
450 );
451​
452 it.effect("rejects binary files without leaking their contents into the error", () =>
453 Effect.gen(function* () {
454 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
455 const fileSystem = yield* FileSystem.FileSystem;
456 const path = yield* Path.Path;
457 const cwd = yield* makeTempDir;
458 const absolutePath = path.join(cwd, "asset.bin");
459 yield* fileSystem.writeFile(absolutePath, Uint8Array.from([0x61, 0, 0x62]));
460​
461 const error = yield* workspaceFileSystem
462 .readFile({ cwd, relativePath: "asset.bin" })
463 .pipe(Effect.flip);
464 const resolvedPath = yield* fileSystem.realPath(absolutePath);
465​
466 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
467 expect(error).toMatchObject({
468 workspaceRoot: cwd,
469 relativePath: "asset.bin",
470 resolvedPath,
471 });
472 expect("cause" in error).toBe(false);
473 expect("contents" in error).toBe(false);
474 }),
475 );
476 });
477​
478 describe("writeFile", () => {
479 it.effect("rejects writes outside a known workspace", () =>
480 Effect.gen(function* () {
481 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
482 const fileSystem = yield* FileSystem.FileSystem;
483 const cwd = yield* fileSystem.makeTempDirectoryScoped({
484 prefix: UNKNOWN_WORKSPACE_PREFIX,
485 });
486​
487 const error = yield* workspaceFileSystem
488 .writeFile({ cwd, relativePath: "plan.md", contents: "# nope\n" })
489 .pipe(Effect.flip);
490​
491 expect(error).toBeInstanceOf(KnownWorkspaces.UnknownWorkspaceError);
492 expect(yield* fileSystem.readDirectory(cwd)).toEqual([]);
493 }),
494 );
495​
496 it.effect("rejects writes by absolute path", () =>
497 Effect.gen(function* () {
498 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
499 const path = yield* Path.Path;
500 const cwd = yield* makeTempDir;
501 const outsideDir = yield* makeTempDir;
502 const absolutePath = path.join(outsideDir, "cleanup-report.md");
503​
504 const error = yield* workspaceFileSystem
505 .writeFile({ cwd, relativePath: absolutePath, contents: "# Edited\n" })
506 .pipe(Effect.flip);
507​
508 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
509 }),
510 );
511​
512 it.effect("invalidates workspace entry search cache after writes", () =>
513 Effect.gen(function* () {
514 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
515 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
516 const cwd = yield* makeTempDir;
517 yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
518​
519 const beforeWrite = yield* workspaceEntries.list({ cwd });
520 expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
521 false,
522 );
523​
524 yield* workspaceFileSystem.writeFile({
525 cwd,
526 relativePath: "plans/effect-rpc.md",
527 contents: "# Plan\n",
528 });
529​
530 const afterWrite = yield* workspaceEntries.list({ cwd });
531 expect(afterWrite.entries).toEqual(
532 expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
533 );
534 expect(afterWrite.truncated).toBe(false);
535 }),
536 );
537​
538 it.effect("saves over an existing file without rescanning the workspace", () =>
539 Effect.gen(function* () {
540 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
541 const fileSystem = yield* FileSystem.FileSystem;
542 const path = yield* Path.Path;
543 const cwd = yield* makeTempDir;
544 yield* writeTextFile(cwd, "src/main.ts", "export {};\n");
545​
546 yield* workspaceFileSystem.writeFile({
547 cwd,
548 relativePath: "src/main.ts",
549 contents: "export const edited = true;\n",
550 });
551​
552 expect(yield* fileSystem.readFileString(path.join(cwd, "src/main.ts"))).toBe(
553 "export const edited = true;\n",
554 );
555 }).pipe(
556 Effect.provide(
557 Layer.fresh(WorkspaceFileSystem.layer).pipe(
558 Layer.provide(layerKnownWorkspacesTest),
559 Layer.provide(WorkspacePaths.layer),
560 Layer.provide(
561 Layer.mock(WorkspaceEntries.WorkspaceEntries)({
562 refresh: () => Effect.die("An overwrite rescanned the workspace."),
563 }),
564 ),
565 ),
566 ),
567 ),
568 );
569​
570 it.effect("rejects writes outside the workspace root", () =>
571 Effect.gen(function* () {
572 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
573 const cwd = yield* makeTempDir;
574 const path = yield* Path.Path;
575 const fileSystem = yield* FileSystem.FileSystem;
576​
577 const error = yield* workspaceFileSystem
578 .writeFile({
579 cwd,
580 relativePath: "../escape.md",
581 contents: "# nope\n",
582 })
583 .pipe(Effect.flip);
584​
585 expect(error.message).toContain(
586 "Workspace file path must be relative to the project root: ../escape.md",
587 );
588​
589 const escapedPath = path.resolve(cwd, "..", "escape.md");
590 const escapedStat = yield* fileSystem
591 .stat(escapedPath)
592 .pipe(Effect.orElseSucceed(() => null));
593 expect(escapedStat).toBeNull();
594 }),
595 );
596​
597 it.effect.skipIf(!symlinksSupported)(
598 "rejects writes through symlinks that resolve outside the workspace root",
599 () =>
600 Effect.gen(function* () {
601 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
602 const fileSystem = yield* FileSystem.FileSystem;
603 const path = yield* Path.Path;
604 const cwd = yield* makeTempDir;
605 const outsideDir = yield* makeTempDir;
606 yield* writeTextFile(outsideDir, "existing.md", "outside\n");
607 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
608 yield* fileSystem.symlink(
609 path.join(outsideDir, "existing.md"),
610 path.join(cwd, "linked-file.md"),
611 );
612 yield* fileSystem.symlink(
613 path.join(outsideDir, "missing.md"),
614 path.join(cwd, "dangling.md"),
615 );
616​
617 for (const relativePath of [
618 "linked-dir/new.md",
619 "linked-dir/nested/new.md",
620 "linked-file.md",
621 ]) {
622 const error = yield* workspaceFileSystem
623 .writeFile({ cwd, relativePath, contents: "# nope\n" })
624 .pipe(Effect.flip);
625 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
626 }
627 const danglingError = yield* workspaceFileSystem
628 .writeFile({ cwd, relativePath: "dangling.md", contents: "# nope\n" })
629 .pipe(Effect.flip);
630 expect(danglingError).toBeInstanceOf(
631 WorkspaceFileSystem.WorkspaceFileSystemOperationError,
632 );
633 expect(danglingError).toMatchObject({ operation: "realpath-target" });
634​
635 expect((yield* fileSystem.readDirectory(outsideDir)).toSorted()).toEqual(["existing.md"]);
636 expect(yield* fileSystem.readFileString(path.join(outsideDir, "existing.md"))).toBe(
637 "outside\n",
638 );
639 }),
640 );
641​
642 it.effect.skipIf(!symlinksSupported)(
643 "writes through symlinks that stay inside the workspace root",
644 () =>
645 Effect.gen(function* () {
646 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
647 const fileSystem = yield* FileSystem.FileSystem;
648 const path = yield* Path.Path;
649 const parentDir = yield* makeTempDir;
650 const cwd = path.join(parentDir, "workspace");
651 const cwdAlias = path.join(parentDir, "workspace-alias");
652 yield* writeTextFile(cwd, "docs/README.md", "old\n");
653 yield* fileSystem.symlink(path.join(cwd, "docs"), path.join(cwd, "docs-alias"));
654 yield* fileSystem.symlink("docs/README.md", path.join(cwd, "README.md"));
655 yield* fileSystem.symlink(cwd, cwdAlias);
656​
657 yield* workspaceFileSystem.writeFile({
658 cwd,
659 relativePath: "docs-alias/plans/plan.md",
660 contents: "# Plan\n",
661 });
662 yield* workspaceFileSystem.writeFile({
663 cwd,
664 relativePath: "README.md",
665 contents: "new\n",
666 });
667 yield* workspaceFileSystem.writeFile({
668 cwd: cwdAlias,
669 relativePath: "notes.md",
670 contents: "notes\n",
671 });
672 // `..` after a link in cwd is resolved by name, as for the relative path.
673 yield* fileSystem.symlink(path.join(cwd, "docs/plans"), path.join(cwd, "plans-alias"));
674 yield* workspaceFileSystem.writeFile({
675 cwd: `${path.join(cwd, "plans-alias")}${path.sep}..`,
676 relativePath: "dotdot.md",
677 contents: "dotdot\n",
678 });
679​
680 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/plans/plan.md"))).toBe(
681 "# Plan\n",
682 );
683 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/README.md"))).toBe("new\n");
684 expect(yield* fileSystem.readLink(path.join(cwd, "README.md"))).toBe("docs/README.md");
685 expect(yield* fileSystem.readFileString(path.join(cwd, "notes.md"))).toBe("notes\n");
686 expect(yield* fileSystem.readFileString(path.join(cwd, "dotdot.md"))).toBe("dotdot\n");
687 }),
688 );
689​
690 // On Windows `\` is a separator, so the name cannot exist there.
691 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
692 "keeps a backslash in a file name as part of the name",
693 () =>
694 Effect.gen(function* () {
695 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
696 const fileSystem = yield* FileSystem.FileSystem;
697 const cwd = yield* makeTempDir;
698 yield* writeTextFile(cwd, "a\\b.md", "old\n");
699​
700 yield* workspaceFileSystem.writeFile({ cwd, relativePath: "a\\b.md", contents: "new\n" });
701​
702 expect(
703 (yield* workspaceFileSystem.readFile({ cwd, relativePath: "a\\b.md" })).contents,
704 ).toBe("new\n");
705 expect(yield* fileSystem.readDirectory(cwd)).toEqual(["a\\b.md"]);
706 }),
707 );
708​
709 it.effect("refuses writes into git's own folders", () =>
710 Effect.gen(function* () {
711 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
712 const fileSystem = yield* FileSystem.FileSystem;
713 const path = yield* Path.Path;
714 const cwd = yield* makeTempDir;
715 yield* writeTextFile(cwd, ".git/config", "[core]\n");
716 yield* writeTextFile(cwd, ".bare/HEAD", "ref: refs/heads/main\n");
717 yield* writeTextFile(cwd, ".bare/objects/info/packs");
718 yield* writeTextFile(cwd, ".bare/refs/heads/main");
719 yield* writeTextFile(cwd, ".bare/hooks/pre-push.sample");
720 // Only a linked worktree's `.git` file ends the upward check, not any `.git` folder.
721 yield* fileSystem.makeDirectory(path.join(cwd, ".bare/hooks/.git"));
722 yield* writeTextFile(cwd, ".bare/worktrees/main/HEAD", "ref: refs/heads/main\n");
723 yield* writeTextFile(cwd, ".bare/worktrees/main/commondir", "../..\n");
724 if (symlinksSupported) yield* fileSystem.symlink(".git", path.join(cwd, "docs"));
725​
726 for (const [folder, relativePath] of [
727 [cwd, ".git/config"],
728 [cwd, ".git/hooks/pre-commit"],
729 [cwd, "sub/.git"],
730 [cwd, ".GIT/config"],
731 [cwd, ".gıt/config"],
732 [cwd, ".git. /config"],
733 [cwd, ".git::$INDEX_ALLOCATION/config"],
734 [cwd, "GIT~1/config"],
735 [path.join(cwd, ".git"), "config"],
736 [cwd, ".bare/config"],
737 [path.join(cwd, ".bare"), "hooks/post-checkout"],
738 [path.join(cwd, ".bare/hooks"), "post-checkout"],
739 [path.join(cwd, ".bare/worktrees/main"), "commondir"],
740 ...(symlinksSupported ? [[cwd, "docs/config"] as const] : []),
741 ] as const) {
742 const error = yield* workspaceFileSystem
743 .writeFile({ cwd: folder, relativePath, contents: "[core]\n\tfsmonitor = x\n" })
744 .pipe(Effect.flip);
745 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
746 }
747​
748 expect(yield* fileSystem.readFileString(path.join(cwd, ".git/config"))).toBe("[core]\n");
749 expect(yield* fileSystem.exists(path.join(cwd, ".bare/config"))).toBe(false);
750 expect((yield* fileSystem.readDirectory(path.join(cwd, ".bare/hooks"))).toSorted()).toEqual(
751 [".git", "pre-push.sample"],
752 );
753 expect(yield* fileSystem.exists(path.join(cwd, "sub"))).toBe(false);
754 expect(
755 yield* fileSystem.readFileString(path.join(cwd, ".bare/worktrees/main/commondir")),
756 ).toBe("../..\n");
757 }),
758 );
759​
760 it.effect.skipIf(!symlinksSupported)(
761 "refuses writes through a git config that links to a file outside git's folders",
762 () =>
763 Effect.gen(function* () {
764 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
765 const fileSystem = yield* FileSystem.FileSystem;
766 const path = yield* Path.Path;
767 const cwd = yield* makeTempDir;
768 yield* writeTextFile(cwd, "shared/config", "[core]\n");
769 yield* fileSystem.makeDirectory(path.join(cwd, ".git"));
770 yield* fileSystem.symlink("../shared/config", path.join(cwd, ".git/config"));
771​
772 const error = yield* workspaceFileSystem
773 .writeFile({ cwd, relativePath: ".git/config", contents: "[core]\n\tfsmonitor = x\n" })
774 .pipe(Effect.flip);
775​
776 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
777 expect(yield* fileSystem.readFileString(path.join(cwd, "shared/config"))).toBe(
778 "[core]\n",
779 );
780 }),
781 );
782​
783 it.effect("writes files that sit beside git's folders", () =>
784 Effect.gen(function* () {
785 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
786 const fileSystem = yield* FileSystem.FileSystem;
787 const path = yield* Path.Path;
788 const parentDir = yield* makeTempDir;
789 const bare = path.join(parentDir, "repo.git");
790 yield* writeTextFile(bare, "HEAD", "ref: refs/heads/main\n");
791 yield* writeTextFile(bare, "objects/info/packs");
792 yield* writeTextFile(bare, "refs/heads/main");
793 yield* writeTextFile(bare, "main/.git", `gitdir: ${path.join(bare, "worktrees/main")}\n`);
794​
795 for (const [cwd, relativePath] of [
796 [path.join(bare, "main"), ".gitignore"],
797 [path.join(bare, "main"), ".gitattributes"],
798 [path.join(bare, "main"), ".github/workflows/ci.yml"],
799 [path.join(bare, "main"), "vendor/lib.git/README.md"],
800 [path.join(bare, "main/.github"), "CODEOWNERS"],
801 [bare, "main/plan.md"],
802 ] as const) {
803 yield* workspaceFileSystem.writeFile({ cwd, relativePath, contents: "ok\n" });
804 expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("ok\n");
805 }
806 }),
807 );
808 });
809});