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