Skip to content

Commit 1d9d008

Browse files
fix(server): tighten workspace containment and git-folder write checks
- isWithinRoot treats only `..` or a `..` segment as outside, so a child named `..feature` is inside. - A thread's worktree under a managed folder is resolved like any other, so one that links to a checkout elsewhere is known. - Writes check git's folders on the path as named as well as the real path, so a `.git/config` symlink cannot redirect a write. A failed probe other than a missing entry now refuses the write instead of passing it. - WorkspaceFileSystem.writeFile asserts the known workspace itself, so the projects.writeFile handler calls one service method. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent efd6973 commit 1d9d008

6 files changed

Lines changed: 127 additions & 19 deletions

File tree

‎apps/server/src/review/ReviewService.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,10 @@ describe("ReviewService", () => {
203203

204204
assert.strictEqual((yield* review(projectRoot, [projectRoot])).cwd, projectRoot);
205205
assert.strictEqual((yield* review(projectChild, [projectRoot])).cwd, projectChild);
206+
// A child whose name starts with `..` is still inside.
207+
const dottedChild = `${projectRoot}/..feature`;
208+
yield* fs.makeDirectory(dottedChild);
209+
assert.strictEqual((yield* review(dottedChild, [projectRoot])).cwd, dottedChild);
206210
for (const [cwd, projectRoots] of [
207211
[sibling, [projectRoot]],
208212
[projectRoot, []],
@@ -258,6 +262,34 @@ describe("ReviewService", () => {
258262
}).pipe(Effect.provide(NodeServices.layer)),
259263
);
260264

265+
it.effect("allows a thread's worktree linked from a managed folder to a checkout elsewhere", () =>
266+
Effect.gen(function* () {
267+
const fs = yield* FileSystem.FileSystem;
268+
const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
269+
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
270+
const managed = yield* fs.realPath(
271+
yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-worktrees-" }),
272+
);
273+
const checkout = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-checkout-" });
274+
yield* fs.symlink(checkout, `${managed}/feature`);
275+
276+
const result = yield* Effect.gen(function* () {
277+
const review = yield* ReviewService.ReviewService;
278+
return yield* review.getDiffPreview({ cwd: checkout });
279+
}).pipe(
280+
Effect.provide(
281+
layer({
282+
workspaceRoot,
283+
baseDir,
284+
worktreesDirectory: managed,
285+
threadWorktrees: [{ worktreePath: `${managed}/feature` }],
286+
}),
287+
),
288+
);
289+
assert.strictEqual(result.cwd, checkout);
290+
}).pipe(Effect.provide(NodeServices.layer)),
291+
);
292+
261293
it.effect("allows diff preview cwd inside the configured workspace root", () =>
262294
Effect.gen(function* () {
263295
const fs = yield* FileSystem.FileSystem;

‎apps/server/src/server.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,7 @@ const layerWorkspaceEntries = WorkspaceEntries.layer.pipe(Layer.provide(Workspac
426426
const layerWorkspaceFileSystem = WorkspaceFileSystem.layer.pipe(
427427
Layer.provide(WorkspacePaths.layer),
428428
Layer.provide(layerWorkspaceEntries),
429+
Layer.provide(layerKnownWorkspaces),
429430
);
430431

431432
const layerWorkspace = Layer.mergeAll(

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

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,10 @@ export class UnknownWorkspaceError extends Schema.TaggedError<UnknownWorkspaceEr
3434
/** Whether `candidate` is `root` or inside it. Resolve both the same way first. */
3535
export const isWithinRoot = (path: Path.Path, candidate: string, root: string) => {
3636
const relative = path.relative(root, candidate);
37-
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
37+
return (
38+
relative === "" ||
39+
(relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
40+
);
3841
};
3942

4043
export class KnownWorkspaces extends Context.Service<
@@ -93,13 +96,9 @@ export const make = Effect.gen(function* () {
9396
WHERE deleted_at IS NULL AND json_extract(payload_json, '$.worktreePath') IS NOT NULL
9497
`.pipe(Effect.orElseSucceed(() => []));
9598
for (const { worktreePath } of threads) {
96-
// Worktrees T3 made sit in a managed folder, which was checked above.
97-
if (
98-
!path.isAbsolute(worktreePath) ||
99-
managed.some((root) => path.resolve(worktreePath).startsWith(`${root}${path.sep}`))
100-
) {
101-
continue;
102-
}
99+
// A relative path would resolve against the server's own cwd. One under a
100+
// managed folder is still resolved: it can be a symlink to a checkout elsewhere.
101+
if (!path.isAbsolute(worktreePath)) continue;
103102
if (within(yield* resolveRoot(worktreePath))) return true;
104103
}
105104
return false;

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,24 @@ import * as Path from "effect/Path";
1111
import * as ServerConfig from "../config.ts";
1212
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
1313
import * as VcsProcess from "../vcs/VcsProcess.ts";
14+
import * as KnownWorkspaces from "./KnownWorkspaces.ts";
1415
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
1516
import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts";
1617
import * as WorkspacePaths from "./WorkspacePaths.ts";
1718
import * as HostProcess from "@t3tools/shared/HostProcess";
1819
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
1920

21+
// Temp folders count as known workspaces unless named as unknown.
22+
const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-";
23+
const layerKnownWorkspacesTest = Layer.mock(KnownWorkspaces.KnownWorkspaces)({
24+
assertContains: (cwd) =>
25+
cwd.includes(UNKNOWN_WORKSPACE_PREFIX)
26+
? Effect.fail(new KnownWorkspaces.UnknownWorkspaceError({ cwd }))
27+
: Effect.void,
28+
});
29+
2030
const layerProject = WorkspaceFileSystem.layer.pipe(
31+
Layer.provide(layerKnownWorkspacesTest),
2132
Layer.provide(WorkspacePaths.layer),
2233
Layer.provide(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
2334
);
@@ -360,6 +371,23 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
360371
}),
361372
);
362373

374+
it.effect("rejects writes outside a known workspace", () =>
375+
Effect.gen(function* () {
376+
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
377+
const fileSystem = yield* FileSystem.FileSystem;
378+
const cwd = yield* fileSystem.makeTempDirectoryScoped({
379+
prefix: UNKNOWN_WORKSPACE_PREFIX,
380+
});
381+
382+
const error = yield* workspaceFileSystem
383+
.writeFile({ cwd, relativePath: "plan.md", contents: "# nope\n" })
384+
.pipe(Effect.flip);
385+
386+
expect(error).toBeInstanceOf(KnownWorkspaces.UnknownWorkspaceError);
387+
expect(yield* fileSystem.readDirectory(cwd)).toEqual([]);
388+
}),
389+
);
390+
363391
it.effect("rejects writes by absolute path", () =>
364392
Effect.gen(function* () {
365393
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -593,6 +621,29 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
593621
}),
594622
);
595623

624+
it.effect.skipIf(!symlinksSupported)(
625+
"refuses writes through a git config that links to a file outside git's folders",
626+
() =>
627+
Effect.gen(function* () {
628+
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
629+
const fileSystem = yield* FileSystem.FileSystem;
630+
const path = yield* Path.Path;
631+
const cwd = yield* makeTempDir;
632+
yield* writeTextFile(cwd, "shared/config", "[core]\n");
633+
yield* fileSystem.makeDirectory(path.join(cwd, ".git"));
634+
yield* fileSystem.symlink("../shared/config", path.join(cwd, ".git/config"));
635+
636+
const error = yield* workspaceFileSystem
637+
.writeFile({ cwd, relativePath: ".git/config", contents: "[core]\n\tfsmonitor = x\n" })
638+
.pipe(Effect.flip);
639+
640+
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
641+
expect(yield* fileSystem.readFileString(path.join(cwd, "shared/config"))).toBe(
642+
"[core]\n",
643+
);
644+
}),
645+
);
646+
596647
it.effect("writes files that sit beside git's folders", () =>
597648
Effect.gen(function* () {
598649
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;

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

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import * as Layer from "effect/Layer";
2020
import * as Path from "effect/Path";
2121
import * as Schema from "effect/Schema";
2222

23+
import * as KnownWorkspaces from "./KnownWorkspaces.ts";
2324
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
2425
import * as WorkspacePaths from "./WorkspacePaths.ts";
2526
import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
@@ -119,11 +120,14 @@ export class WorkspaceFileSystem extends Context.Service<
119120
ProjectReadFileResult,
120121
WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
121122
>;
123+
/** Writes inside a known workspace only. */
122124
readonly writeFile: (
123125
input: ProjectWriteFileInput,
124126
) => Effect.Effect<
125127
ProjectWriteFileResult,
126-
WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
128+
| WorkspaceFileSystemError
129+
| WorkspacePaths.WorkspacePathOutsideRootError
130+
| KnownWorkspaces.UnknownWorkspaceError
127131
>;
128132
}
129133
>()("t3/workspace/WorkspaceFileSystem") {}
@@ -133,6 +137,7 @@ export const make = Effect.gen(function* () {
133137
const fileSystem = yield* FileSystem.FileSystem;
134138
const path = yield* Path.Path;
135139
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
140+
const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
136141
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
137142

138143
const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
@@ -192,15 +197,19 @@ export const make = Effect.gen(function* () {
192197
* Git runs config and hooks from its own folders, so a write never lands in one:
193198
* a `.git` entry, or a repository folder under another name such as `.bare`.
194199
* Folders are checked upward to a linked worktree's top, which holds a `.git`
195-
* file, since worktrees can sit inside a bare repository. `realPath` must be a
196-
* real path.
200+
* file, since worktrees can sit inside a bare repository. `absolutePath` must
201+
* be normalized.
197202
*/
198-
const isInGitFolder = async (realPath: string) => {
199-
if (realPath.split(path.sep).some(isGitMetadataName)) return true;
200-
for (let folder = path.dirname(realPath); ; folder = path.dirname(folder)) {
203+
const isInGitFolder = async (absolutePath: string) => {
204+
if (absolutePath.split(path.sep).some(isGitMetadataName)) return true;
205+
for (let folder = path.dirname(absolutePath); ; folder = path.dirname(folder)) {
201206
const [head, commondir, objects, refs, dotGit] = await Promise.all(
202207
["HEAD", "commondir", "objects", "refs", ".git"].map((name) =>
203-
NodeFSP.lstat(path.join(folder, name)).catch(() => null),
208+
NodeFSP.lstat(path.join(folder, name)).catch((error: NodeJS.ErrnoException) => {
209+
// Any other failure leaves the folder unknown, so the write is refused.
210+
if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
211+
throw error;
212+
}),
204213
),
205214
);
206215
// What git reads as a repository: HEAD, plus objects and refs here or in
@@ -424,9 +433,26 @@ export const make = Effect.gen(function* () {
424433
cause,
425434
}),
426435
});
436+
// The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
437+
const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
438+
const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
439+
Effect.tryPromise({
440+
try: () => isInGitFolder(checkedPath),
441+
catch: (cause) =>
442+
new WorkspaceFileSystemOperationError({
443+
workspaceRoot: input.cwd,
444+
relativePath: input.relativePath,
445+
resolvedPath: realTargetPath,
446+
operationPath: checkedPath,
447+
operation: "stat",
448+
cause,
449+
}),
450+
}),
451+
);
427452
if (
428453
!isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
429-
(yield* Effect.promise(() => isInGitFolder(realTargetPath)))
454+
(yield* inGitFolder(realTargetPath)) ||
455+
(yield* inGitFolder(namedTargetPath))
430456
) {
431457
return yield* new WorkspaceFilePathEscapeError({
432458
workspaceRoot: input.cwd,
@@ -441,6 +467,7 @@ export const make = Effect.gen(function* () {
441467
const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
442468
"WorkspaceFileSystem.writeFile",
443469
)(function* (input) {
470+
yield* knownWorkspaces.assertContains(input.cwd);
444471
const target = yield* resolveWriteTarget(input);
445472
const realTargetPath = target.realTargetPath;
446473

‎apps/server/src/ws.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1264,7 +1264,6 @@ const layerWsRpc = (
12641264
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
12651265
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
12661266
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
1267-
const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
12681267
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
12691268
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
12701269
const rpcClientIds = yield* Ref.make(new Set<RpcClientId>());
@@ -2644,8 +2643,7 @@ const layerWsRpc = (
26442643
),
26452644
),
26462645
[WS_METHODS.projectsWriteFile]: (input) =>
2647-
knownWorkspaces.assertContains(input.cwd).pipe(
2648-
Effect.andThen(workspaceFileSystem.writeFile(input)),
2646+
workspaceFileSystem.writeFile(input).pipe(
26492647
Effect.mapError(
26502648
(cause) =>
26512649
new ProjectWriteFileError({

0 commit comments

Comments
 (0)