Skip to content

Commit 3eb373d

Browse files
author
Peter Steinberger
committed
fix(agents): keep workspace symlink contract under fs-safe 0.5.2
1 parent 0eaccc8 commit 3eb373d

6 files changed

Lines changed: 55 additions & 10 deletions

File tree

‎src/agents/agent-tools.read.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1142,6 +1142,13 @@ async function writeWorkspaceFile(
11421142
// succeeds. Eagerly starting it would orphan a rejecting root promise as an unhandled
11431143
// rejection when validation fails first — the readFile/access paths already defer the same way.
11441144
const relative = await toCanonicalRelativeWorkspacePath(root, absolutePath);
1145+
// fs-safe 0.5.2 atomically replaces a final symlink on write. The workspace
1146+
// contract rejects symlink write targets so the link and its target survive.
1147+
const rootReal = await fs.realpath(root);
1148+
const targetStat = await fs.lstat(path.resolve(rootReal, relative)).catch(() => undefined);
1149+
if (targetStat?.isSymbolicLink()) {
1150+
throw new FsSafeError("symlink", `refusing to write to symlink: ${absolutePath}`);
1151+
}
11451152
await (await getRoot()).write(relative, content, { mkdir: true });
11461153
}
11471154

@@ -1189,7 +1196,10 @@ function createHostWriteOperations(
11891196
writeFile: (absolutePath: string, content: string) =>
11901197
writeWorkspaceFile(root, getRoot, absolutePath, content),
11911198
readFile: async (absolutePath: string) => {
1192-
const relative = toRelativeWorkspacePath(root, absolutePath);
1199+
// Canonicalize symlink parents like the write path: fs-safe 0.5.2
1200+
// rejects intermediate symlinks by default, but in-workspace symlink
1201+
// parents are part of the workspace contract.
1202+
const relative = await toCanonicalRelativeWorkspacePath(root, absolutePath);
11931203
return (await (await getRoot()).read(relative)).buffer;
11941204
},
11951205
statFile: async (absolutePath: string) => {
@@ -1236,7 +1246,10 @@ function createHostEditOperations(
12361246
return withMemoryWriteProvenance(
12371247
{
12381248
readFile: async (absolutePath: string) => {
1239-
const relative = toRelativeWorkspacePath(root, absolutePath);
1249+
// Canonicalize symlink parents like the write path: fs-safe 0.5.2
1250+
// rejects intermediate symlinks by default, but in-workspace symlink
1251+
// parents are part of the workspace contract.
1252+
const relative = await toCanonicalRelativeWorkspacePath(root, absolutePath);
12401253
const safeRead = await (await getRoot()).read(relative);
12411254
return safeRead.buffer;
12421255
},
@@ -1249,7 +1262,8 @@ function createHostEditOperations(
12491262
access: async (absolutePath: string) => {
12501263
let relative: string;
12511264
try {
1252-
relative = toRelativeWorkspacePath(root, absolutePath);
1265+
// Canonicalized like readFile so in-workspace symlink parents pass.
1266+
relative = await toCanonicalRelativeWorkspacePath(root, absolutePath);
12531267
} catch {
12541268
// Path escapes workspace root. Don't throw here – the upstream
12551269
// library replaces any `access` error with a misleading "File not

‎src/agents/apply-patch-file-ops.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import syncFs from "node:fs";
22
import fs from "node:fs/promises";
3-
import { openRootFile, type RootFileOpenResult } from "../infra/boundary-file-read.js";
3+
import {
4+
openRootFileFollowingParents,
5+
type RootFileOpenResult,
6+
} from "../infra/boundary-file-read.js";
47
import { FsSafeError, root as fsRoot } from "../infra/fs-safe.js";
58
import {
69
type MemoryWriteProvenanceObserver,
@@ -104,7 +107,7 @@ export function resolvePatchFileOps(options: ApplyPatchFileOptions): PatchFileOp
104107
observer: options.memoryWriteProvenance,
105108
operations: {
106109
readFile: async (filePath) => {
107-
const opened = await openRootFile({
110+
const opened = await openRootFileFollowingParents({
108111
absolutePath: filePath,
109112
rootPath: options.cwd,
110113
boundaryLabel: "workspace root",

‎src/agents/apply-patch.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -886,7 +886,9 @@ describe("applyPatch", () => {
886886
*** End Patch`;
887887

888888
await expect(applyPatch(patch, { cwd: dir })).rejects.toThrow(
889-
/path is not a regular file under root|symlink open blocked/i,
889+
// fs-safe 0.5.2 reports the symlink rejection through the boundary-read
890+
// validation path ("unsafe path") instead of a symlink-specific message.
891+
/path is not a regular file under root|symlink open blocked|unsafe path/i,
890892
);
891893
const contents = await fs.readFile(target, "utf8");
892894
expect(contents).toBe("initial\n");

‎src/agents/workspace.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import path from "node:path";
1010
import { Minimatch } from "minimatch";
1111
import { extractFrontmatterBlock } from "../../packages/markdown-core/src/frontmatter.js";
1212
import type { ChatType } from "../channels/chat-type.js";
13-
import { openRootFile } from "../infra/boundary-file-read.js";
13+
import { openRootFileFollowingParents } from "../infra/boundary-file-read.js";
1414
import { sameFileIdentity, type FileIdentityStat } from "../infra/fs-safe-advanced.js";
1515
import { pathExists } from "../infra/fs-safe.js";
1616
import { isPathInside } from "../infra/path-guards.js";
@@ -140,7 +140,7 @@ async function readWorkspaceFileWithGuards(params: {
140140
// in openRootFile still protects against a swapped file between attempts.
141141
return await retryAsync(
142142
async () => {
143-
const opened = await openRootFile({
143+
const opened = await openRootFileFollowingParents({
144144
absolutePath: params.filePath,
145145
rootPath: params.workspaceDir,
146146
boundaryLabel: "workspace root",

‎src/infra/boundary-file-read.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
// Exposes root-scoped file open helpers with fs-safe defaults.
22
import "./fs-safe-defaults.js";
3+
import path from "node:path";
34
import {
5+
canonicalPathFromExistingAncestor,
46
matchRootFileOpenFailure as matchRootFileOpenFailureFsSafe,
7+
openRootFile,
8+
type OpenRootFileParams,
59
readFileDescriptorBounded as readFileDescriptorBoundedFsSafe,
610
readFileDescriptorBoundedSync as readFileDescriptorBoundedSyncFsSafe,
711
type RootFileOpenFailure,
12+
type RootFileOpenResult,
813
} from "@openclaw/fs-safe/advanced";
914
import { FsSafeError } from "@openclaw/fs-safe/errors";
1015

@@ -19,6 +24,25 @@ export {
1924
type RootFileOpenResult,
2025
} from "@openclaw/fs-safe/advanced";
2126

27+
/**
28+
* Opens a root-scoped file after canonicalizing symlink parents. fs-safe 0.5.2
29+
* rejects every symlink path component by default; the workspace contract
30+
* follows contained parent symlinks (directory aliases) while final-symlink
31+
* targets and out-of-root escapes stay rejected by openRootFile itself.
32+
*/
33+
export async function openRootFileFollowingParents(
34+
params: OpenRootFileParams,
35+
): Promise<RootFileOpenResult> {
36+
let absolutePath = path.resolve(params.absolutePath);
37+
try {
38+
const canonicalParent = await canonicalPathFromExistingAncestor(path.dirname(absolutePath));
39+
absolutePath = path.join(canonicalParent, path.basename(absolutePath));
40+
} catch {
41+
// Keep the lexical path; openRootFile reports the boundary or IO failure.
42+
}
43+
return await openRootFile({ ...params, absolutePath });
44+
}
45+
2246
// fs-safe folds ENOENT, ENOTDIR, and ELOOP into its `path` reason. Only the
2347
// first two mean the artifact is absent; a symlink loop is an unreadable path.
2448
const MISSING_PATH_ERROR_CODES: ReadonlySet<string> = new Set(["ENOENT", "ENOTDIR"]);

‎src/infra/gateway-lock.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -958,7 +958,7 @@ describe("gateway lock", () => {
958958
openSpy.mockRestore();
959959
});
960960

961-
it("closes handle and removes lock file when writeFile fails after open succeeds", async () => {
961+
it("closes handle and preserves an unowned lock file when writeFile fails after open succeeds", async () => {
962962
vi.useRealTimers();
963963
const env = await makeEnv();
964964
const { stateLockPath } = resolveLockPath(env);
@@ -983,7 +983,9 @@ describe("gateway lock", () => {
983983
});
984984

985985
expect(close).toHaveBeenCalledTimes(1);
986-
await expect(fs.access(stateLockPath)).rejects.toMatchObject({ code: "ENOENT" });
986+
// fs-safe 0.5.2 failure cleanup removes the lock file only when it matches
987+
// the snapshot fs-safe wrote itself; this out-of-band file is preserved.
988+
await expect(fs.readFile(stateLockPath, "utf8")).resolves.toBe("partial");
987989

988990
openSpy.mockRestore();
989991
});

0 commit comments

Comments
 (0)