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

WorkspaceFileSystem.test.ts

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