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

WorkspaceFileSystem.test.ts

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