Skip to content

Commit 45ec7ea

Browse files
committed
fix(server): browse readable local symlink targets
1 parent dc84b09 commit 45ec7ea

4 files changed

Lines changed: 209 additions & 84 deletions

File tree

‎apps/server/src/workspace/WorkspaceEntries.test.ts‎

Lines changed: 87 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import * as FileSystem from "effect/FileSystem";
66
import * as Layer from "effect/Layer";
77
import * as Path from "effect/Path";
88
import * as PlatformError from "effect/PlatformError";
9+
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
910
import { vi } from "vite-plus/test";
1011

1112
import * as ServerConfig from "../config.ts";
@@ -222,28 +223,77 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
222223
}),
223224
);
224225

225-
it.effect(
226-
"rejects directory traversal, git internals, and symlinks outside the workspace",
226+
it.effect("rejects directory traversal and git internals", () =>
227+
Effect.gen(function* () {
228+
const cwd = yield* makeTempDir();
229+
const outside = yield* makeTempDir();
230+
yield* writeTextFile(cwd, ".git/HEAD");
231+
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
232+
for (const directoryPath of ["../", outside, ".git", "missing"]) {
233+
const error = yield* workspaceEntries.list({ cwd, directoryPath }).pipe(Effect.flip);
234+
expect(error._tag).toBe("WorkspaceEntriesReadDirectoryError");
235+
}
236+
}),
237+
);
238+
239+
it.effect.skipIf(!symlinksSupported)("lists accessible directory and file links", () =>
240+
Effect.gen(function* () {
241+
const cwd = yield* makeTempDir();
242+
const outside = yield* makeTempDir();
243+
const fs = yield* FileSystem.FileSystem;
244+
const path = yield* Path.Path;
245+
yield* writeTextFile(outside, "notes.md", "report\n");
246+
yield* fs.symlink(outside, path.join(cwd, "external"));
247+
yield* fs.symlink(path.join(outside, "notes.md"), path.join(cwd, "report.md"));
248+
yield* fs.symlink(path.join(outside, "missing"), path.join(cwd, "broken"));
249+
const entries = yield* WorkspaceEntries.WorkspaceEntries;
250+
expect((yield* entries.list({ cwd, directoryPath: "" })).entries).toEqual(
251+
expect.arrayContaining([
252+
{ path: "external", kind: "directory" },
253+
{ path: "report.md", kind: "file" },
254+
]),
255+
);
256+
expect(
257+
(yield* entries.list({ cwd, directoryPath: "" })).entries.some(
258+
(entry) => entry.path === "broken",
259+
),
260+
).toBe(false);
261+
expect((yield* entries.list({ cwd, directoryPath: "external" })).entries).toEqual([
262+
{ path: "external/notes.md", kind: "file" },
263+
]);
264+
}),
265+
);
266+
267+
it.effect.skipIf(!symlinksSupported)(
268+
"omits broken links, git links, and directory cycles",
227269
() =>
228270
Effect.gen(function* () {
229271
const cwd = yield* makeTempDir();
230272
const outside = yield* makeTempDir();
231-
const fileSystem = yield* FileSystem.FileSystem;
273+
const fs = yield* FileSystem.FileSystem;
232274
const path = yield* Path.Path;
233-
yield* writeTextFile(cwd, ".git/HEAD");
234-
const platform = yield* HostProcess.Platform;
235-
if (platform !== "win32") yield* fileSystem.symlink(outside, path.join(cwd, "external"));
236-
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
237-
for (const directoryPath of [
238-
"../",
239-
outside,
240-
".git",
241-
"missing",
242-
...(platform !== "win32" ? ["external"] : []),
243-
]) {
244-
const error = yield* workspaceEntries.list({ cwd, directoryPath }).pipe(Effect.flip);
245-
expect(error._tag).toBe("WorkspaceEntriesReadDirectoryError");
246-
}
275+
yield* writeTextFile(outside, "a/notes.md");
276+
yield* writeTextFile(outside, "b/notes.md");
277+
yield* writeTextFile(outside, ".git/HEAD");
278+
yield* fs.symlink(path.join(outside, "a"), path.join(cwd, "external"));
279+
yield* fs.symlink(".", path.join(cwd, "self"));
280+
yield* fs.symlink(path.join(outside, ".git"), path.join(cwd, "metadata"));
281+
yield* fs.symlink(path.join(outside, ".git/HEAD"), path.join(cwd, "head-link"));
282+
yield* fs.symlink(path.join(outside, "missing"), path.join(cwd, "broken"));
283+
yield* fs.symlink("../b", path.join(outside, "a/to-b"));
284+
yield* fs.symlink("../a", path.join(outside, "b/to-a"));
285+
yield* fs.symlink(".", path.join(outside, "a/self"));
286+
yield* fs.symlink("..", path.join(outside, "a/up"));
287+
const entries = yield* WorkspaceEntries.WorkspaceEntries;
288+
expect((yield* entries.list({ cwd, directoryPath: "" })).entries).toEqual([
289+
{ path: "external", kind: "directory" },
290+
]);
291+
expect((yield* entries.list({ cwd, directoryPath: "external" })).entries).toEqual([
292+
{ path: "external/notes.md", kind: "file" },
293+
{ path: "external/to-b", kind: "directory" },
294+
]);
295+
const nested = yield* entries.list({ cwd, directoryPath: "external/to-b" });
296+
expect(nested.entries).toEqual([{ path: "external/to-b/notes.md", kind: "file" }]);
247297
}),
248298
);
249299

@@ -568,6 +618,26 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
568618
});
569619

570620
describe("browse", () => {
621+
it.effect.skipIf(!symlinksSupported)("offers linked directories when choosing a project", () =>
622+
Effect.gen(function* () {
623+
const cwd = yield* makeTempDir();
624+
const target = yield* makeTempDir();
625+
const fs = yield* FileSystem.FileSystem;
626+
const path = yield* Path.Path;
627+
yield* fs.symlink(target, path.join(cwd, "project-link"));
628+
yield* fs.symlink(path.join(target, "missing"), path.join(cwd, "broken"));
629+
const entries = yield* WorkspaceEntries.WorkspaceEntries;
630+
const result = yield* entries.browse({ partialPath: yield* appendSeparator(cwd) });
631+
expect(result.entries).toEqual([
632+
{ name: "project-link", fullPath: path.join(cwd, "project-link") },
633+
]);
634+
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
635+
expect(yield* workspacePaths.normalizeWorkspaceRoot(result.entries[0]!.fullPath)).toBe(
636+
path.join(cwd, "project-link"),
637+
);
638+
}),
639+
);
640+
571641
it.effect("shows dot directories in directory mode and hidden-prefix mode", () =>
572642
Effect.gen(function* () {
573643
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;

‎apps/server/src/workspace/WorkspaceEntries.ts‎

Lines changed: 78 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// @effect-diagnostics nodeBuiltinImport:off
2+
import type * as NodeFS from "node:fs";
23
import * as NodeFSP from "node:fs/promises";
34

45
import * as Context from "effect/Context";
@@ -22,11 +23,12 @@ import type {
2223
ProjectSearchEntriesResult,
2324
} from "@t3tools/contracts";
2425
import * as HostProcess from "@t3tools/shared/HostProcess";
25-
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
26+
import { isExplicitRelativePath, isWindowsAbsolutePath, isNetworkPath } from "@t3tools/shared/path";
2627
import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
2728

2829
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
2930
import * as VcsProcess from "../vcs/VcsProcess.ts";
31+
import * as KnownWorkspaces from "./KnownWorkspaces.ts";
3032
import * as WorkspacePaths from "./WorkspacePaths.ts";
3133
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
3234

@@ -198,6 +200,15 @@ export const make = Effect.gen(function* () {
198200
},
199201
);
200202

203+
// Per-entry filesystem calls share the browse/list span.
204+
const entryType = Effect.fnUntraced(function* (parent: string, entry: NodeFS.Dirent) {
205+
if (!entry.isSymbolicLink()) return entry;
206+
return yield* Effect.tryPromise({
207+
try: () => NodeFSP.stat(path.join(parent, entry.name)),
208+
catch: () => null,
209+
}).pipe(Effect.orElseSucceed(() => null));
210+
});
211+
201212
const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
202213
function* (input) {
203214
const resolvedInputPath = yield* resolveBrowseTarget(input, path);
@@ -226,23 +237,25 @@ export const make = Effect.gen(function* () {
226237

227238
const showHidden = endsWithSeparator || prefix.startsWith(".");
228239
const lowerPrefix = prefix.toLowerCase();
229-
const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
230-
for (const dirent of dirents) {
231-
if (
232-
dirent.isDirectory() &&
233-
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
234-
(showHidden || !dirent.name.startsWith("."))
235-
) {
236-
entries.push({
237-
name: dirent.name,
238-
fullPath: path.join(parentPath, dirent.name),
239-
});
240-
}
241-
}
240+
const candidates = dirents.filter(
241+
(entry) =>
242+
entry.name.toLowerCase().startsWith(lowerPrefix) &&
243+
(showHidden || !entry.name.startsWith(".")),
244+
);
245+
const entries = yield* Effect.forEach(
246+
candidates,
247+
Effect.fnUntraced(function* (entry) {
248+
const type = yield* entryType(parentPath, entry);
249+
return type?.isDirectory()
250+
? [{ name: entry.name, fullPath: path.join(parentPath, entry.name) }]
251+
: [];
252+
}),
253+
{ concurrency: 8 },
254+
);
242255

243256
return {
244257
parentPath,
245-
entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
258+
entries: entries.flat().toSorted((left, right) => left.name.localeCompare(right.name)),
246259
};
247260
},
248261
);
@@ -303,37 +316,73 @@ export const make = Effect.gen(function* () {
303316
relativePath: directoryPath,
304317
})
305318
.pipe(Effect.mapError(toError));
306-
const { entries, throughSymlink } = yield* Effect.tryPromise({
319+
const { children, directory, root, throughSymlink } = yield* Effect.tryPromise({
307320
try: async () => {
308321
const root = await NodeFSP.realpath(normalizedCwd);
309322
const directory = await NodeFSP.realpath(target.absolutePath);
310323
const relative = path.relative(root, directory);
311324
if (
312-
relative === ".." ||
313-
relative.startsWith(`..${path.sep}`) ||
314-
path.isAbsolute(relative) ||
325+
(isNetworkPath(directory) && !KnownWorkspaces.isWithinRoot(path, directory, root)) ||
315326
relative.split(path.sep).includes(".git") ||
316327
target.relativePath.split("/").includes(".git")
317328
) {
318-
throw new Error("Directory must be inside the workspace and outside .git.");
329+
throw new Error(
330+
"Directory must be outside .git and network targets must stay inside the workspace.",
331+
);
319332
}
320333
const children = await NodeFSP.readdir(directory, { withFileTypes: true });
321334
return {
322-
entries: children.flatMap((child): ProjectEntry[] => {
323-
if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) return [];
324-
return [
325-
{
326-
path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
327-
kind: child.isDirectory() ? "directory" : "file",
328-
},
329-
];
330-
}),
335+
children,
336+
directory,
337+
root,
331338
// Git refuses to classify paths beyond a symbolic link.
332339
throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
333340
};
334341
},
335342
catch: toError,
336343
});
344+
let ancestors: Promise<ReadonlyArray<string>> | undefined;
345+
const readAncestors = async () => {
346+
const paths = [root];
347+
let candidate = normalizedCwd;
348+
for (const segment of target.relativePath.split("/").filter(Boolean)) {
349+
candidate = path.join(candidate, segment);
350+
paths.push(await NodeFSP.realpath(candidate));
351+
}
352+
return paths;
353+
};
354+
const entries = (yield* Effect.forEach(
355+
children,
356+
Effect.fnUntraced(function* (child) {
357+
if (child.name === ".git") return [];
358+
const type = yield* entryType(directory, child);
359+
if (!type || (!type.isDirectory() && !type.isFile())) return [];
360+
if (child.isSymbolicLink()) {
361+
const allowed = yield* Effect.tryPromise({
362+
try: async () => {
363+
const real = await NodeFSP.realpath(path.join(directory, child.name));
364+
if (real.split(path.sep).includes(".git")) return false;
365+
if (isNetworkPath(real) && !KnownWorkspaces.isWithinRoot(path, real, root))
366+
return false;
367+
if (!type.isDirectory()) return true;
368+
ancestors ??= readAncestors();
369+
return !(await ancestors).some((ancestor) =>
370+
KnownWorkspaces.isWithinRoot(path, ancestor, real),
371+
);
372+
},
373+
catch: () => false,
374+
}).pipe(Effect.orElseSucceed(() => false));
375+
if (!allowed) return [];
376+
}
377+
return [
378+
{
379+
path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
380+
kind: type.isDirectory() ? "directory" : "file",
381+
} satisfies ProjectEntry,
382+
];
383+
}),
384+
{ concurrency: 8 },
385+
)).flat();
337386
// stdin avoids argument limits; ignore classification is optional without git/repositories.
338387
const checkIgnore = (paths: ReadonlyArray<string>) =>
339388
vcsProcess

‎apps/server/src/workspace/WorkspaceFileSystem.test.ts‎

Lines changed: 39 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,29 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
247247
}),
248248
);
249249

250+
it.effect("refuses a workspace link that resolves to an external network path", () =>
251+
Effect.gen(function* () {
252+
const cwd = String.raw`C:\workspace`;
253+
const networkPath = String.raw`\\attacker.test\share\report.md`;
254+
const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe(
255+
Effect.provide(
256+
Layer.mergeAll(
257+
layerKnownWorkspacesTest,
258+
NodePath.layerWin32,
259+
WorkspacePaths.layer.pipe(Layer.provide(NodePath.layerWin32)),
260+
),
261+
),
262+
);
263+
using realpath = vi.spyOn(NodeFSP, "realpath");
264+
realpath.mockResolvedValueOnce(cwd).mockResolvedValueOnce(networkPath);
265+
const error = yield* workspaceFileSystem
266+
.readFile({ cwd, relativePath: "report-link.md" })
267+
.pipe(Effect.flip);
268+
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
269+
expect(error).toMatchObject({ relativePath: "report-link.md", resolvedPath: networkPath });
270+
}),
271+
);
272+
250273
// This resolves inside the project, but Windows reads `\\?\` paths as
251274
// written, so realpath on the raw string signed in to attacker.test.
252275
it.effect("reads the network path it checked", () =>
@@ -298,47 +321,32 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
298321
);
299322

300323
it.effect.skipIf(!symlinksSupported)(
301-
"rejects symlinks that resolve outside the workspace root",
324+
"reads accessible file and directory links outside the workspace root",
302325
() =>
303326
Effect.gen(function* () {
304327
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
305328
const fileSystem = yield* FileSystem.FileSystem;
306329
const path = yield* Path.Path;
307330
const cwd = yield* makeTempDir;
308331
const outsideDir = yield* makeTempDir;
309-
yield* writeTextFile(outsideDir, "secret.txt", "outside\n");
332+
yield* writeTextFile(outsideDir, "report.txt", "outside\n");
310333
yield* fileSystem.symlink(
311-
path.join(outsideDir, "secret.txt"),
312-
path.join(cwd, "linked-secret.txt"),
334+
path.join(outsideDir, "report.txt"),
335+
path.join(cwd, "report-link.txt"),
313336
);
314-
315-
const error = yield* workspaceFileSystem
316-
.readFile({ cwd, relativePath: "linked-secret.txt" })
317-
.pipe(Effect.flip);
318-
const resolvedWorkspaceRoot = yield* fileSystem.realPath(cwd);
319-
const resolvedPath = yield* fileSystem.realPath(path.join(outsideDir, "secret.txt"));
320-
321-
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
322-
expect(error).toMatchObject({
323-
workspaceRoot: cwd,
324-
relativePath: "linked-secret.txt",
325-
resolvedWorkspaceRoot,
326-
resolvedPath,
327-
});
328-
expect("cause" in error).toBe(false);
329-
330337
yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
331-
const missingChildError = yield* workspaceFileSystem
332-
.readFile(
333-
Object.assign(
334-
{ cwd, relativePath: "linked-dir/missing/t3.json" },
335-
{ allowMissing: true },
336-
),
337-
)
338-
.pipe(Effect.flip);
339-
expect(missingChildError).toBeInstanceOf(
340-
WorkspaceFileSystem.WorkspaceFilePathEscapeError,
341-
);
338+
for (const relativePath of ["report-link.txt", "linked-dir/report.txt"]) {
339+
expect((yield* workspaceFileSystem.readFile({ cwd, relativePath })).contents).toBe(
340+
"outside\n",
341+
);
342+
}
343+
expect(
344+
yield* workspaceFileSystem.readFile({
345+
cwd,
346+
relativePath: "linked-dir/missing/t3.json",
347+
allowMissing: true,
348+
}),
349+
).toMatchObject({ exists: false });
342350
}),
343351
);
344352

0 commit comments

Comments
 (0)