Skip to content

Commit ce0fd2d

Browse files
committed
fix(sandbox): canonicalize aliased mount roots
1 parent 194c13a commit ce0fd2d

8 files changed

Lines changed: 305 additions & 130 deletions

‎src/agents/sandbox-paths.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,30 @@ describe("assertSandboxPath", () => {
206206
await fs.rm(parent, { recursive: true, force: true });
207207
}
208208
});
209+
210+
it.runIf(process.platform !== "win32")(
211+
"preserves final-symlink unlink policy through a root alias",
212+
async () => {
213+
await withSandboxRoot(async (parent) => {
214+
const realRoot = path.join(parent, "real-workspace");
215+
const linkedRoot = path.join(parent, "linked-workspace");
216+
const outside = path.join(parent, "outside.txt");
217+
await fs.mkdir(realRoot);
218+
await fs.writeFile(outside, "outside", "utf8");
219+
await fs.symlink(realRoot, linkedRoot);
220+
await fs.symlink(outside, path.join(realRoot, "link"));
221+
222+
await expect(
223+
assertSandboxPath({
224+
filePath: "link",
225+
cwd: linkedRoot,
226+
root: linkedRoot,
227+
allowFinalSymlinkForUnlink: true,
228+
}),
229+
).resolves.toMatchObject({ relative: "link" });
230+
});
231+
},
232+
);
209233
});
210234

211235
describe("resolveSandboxedMediaSource", () => {

‎src/agents/sandbox-paths.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -115,15 +115,21 @@ async function assertRawParentWithinRoot(params: {
115115
filePath: string;
116116
cwd: string;
117117
root: string;
118-
}): Promise<string> {
118+
}): Promise<{ rootCanonical: string; targetCanonical: string }> {
119119
// Win32 resolves reparse-point/.. paths lexically, so it has no equivalent escape.
120120
// Avoid adding another realpath to this hot path on Windows, where it is expensive.
121121
if (process.platform === "win32") {
122-
return resolveSandboxInputPath(params.filePath, params.cwd);
122+
return {
123+
rootCanonical: path.resolve(params.root),
124+
targetCanonical: resolveSandboxInputPath(params.filePath, params.cwd),
125+
};
123126
}
124127
const expanded = expandPath(params.filePath);
125128
if (isWindowsDrivePath(expanded)) {
126-
return path.win32.normalize(expanded);
129+
return {
130+
rootCanonical: path.resolve(params.root),
131+
targetCanonical: path.win32.normalize(expanded),
132+
};
127133
}
128134
// Do not use path.resolve here: it would erase the symlink-sensitive `..` before
129135
// native realpath can traverse the raw parent chain. The final component stays
@@ -146,7 +152,7 @@ async function assertRawParentWithinRoot(params: {
146152
`Path escapes sandbox root (${shortenHomePath(rootCanonical)}): ${params.filePath}`,
147153
);
148154
}
149-
return targetCanonical;
155+
return { rootCanonical, targetCanonical };
150156
}
151157

152158
export async function assertSandboxPath(params: {
@@ -170,10 +176,10 @@ export async function assertSandboxPath(params: {
170176
// The alias guard owns its specific symlink/hardlink errors; this closes the raw
171177
// symlink-then-`..` gap that lexical normalization hides from that guard.
172178
const rawTarget = await assertRawParentWithinRoot(params);
173-
if (path.resolve(rawTarget) !== path.resolve(resolved.resolved)) {
179+
if (path.resolve(rawTarget.targetCanonical) !== path.resolve(resolved.resolved)) {
174180
await assertNoPathAliasEscape({
175-
absolutePath: rawTarget,
176-
rootPath: params.root,
181+
absolutePath: rawTarget.targetCanonical,
182+
rootPath: rawTarget.rootCanonical,
177183
boundaryLabel: "sandbox root",
178184
policy,
179185
});

‎src/agents/sandbox/fs-bridge-stat-parse.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@
66
import { parseStrictNonNegativeInteger } from "../../infra/parse-finite-number.js";
77
import { asDateTimestampMs } from "../../shared/number-coercion.js";
88

9+
export function hasMultipleHardlinks(raw: string): boolean {
10+
const linkCount = parseStrictNonNegativeInteger(raw);
11+
return linkCount === undefined ? /^\d+$/.test(raw) : linkCount > 1;
12+
}
13+
914
/** Parses file sizes, capping huge integer strings at the largest safe JS integer. */
1015
export function parseSandboxStatSize(value: string | undefined): number {
1116
const raw = value ?? "0";
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/** Canonical path resolution for remote shell-backed sandbox mounts. */
2+
import path from "node:path";
3+
import type {
4+
SandboxBackendCommandParams,
5+
SandboxBackendCommandResult,
6+
} from "./backend-handle.types.js";
7+
import { relativePathEscapesContainerRoot } from "./path-utils.js";
8+
import { normalizeContainerPath } from "./remote-fs-bridge-paths.js";
9+
10+
export type RemoteCanonicalPath = {
11+
canonicalPath: string;
12+
canonicalMountRoot: string;
13+
logicalPath: string;
14+
};
15+
16+
export async function resolveRemoteCanonicalPath(params: {
17+
containerPath: string;
18+
mountRootPath: string;
19+
action: string;
20+
allowFinalSymlinkForUnlink?: boolean;
21+
signal?: AbortSignal;
22+
runRemoteShellScript(command: SandboxBackendCommandParams): Promise<SandboxBackendCommandResult>;
23+
}): Promise<RemoteCanonicalPath> {
24+
// Canonicalize the nearest existing ancestor and append the missing suffix.
25+
// This lets create/write operations validate paths that do not exist yet.
26+
const script = [
27+
"set -eu",
28+
'target="$1"',
29+
'allow_final="$2"',
30+
'suffix=""',
31+
'probe="$target"',
32+
'if [ "$allow_final" = "1" ] && [ -L "$target" ]; then probe=$(dirname -- "$target"); fi',
33+
'cursor="$probe"',
34+
'while [ ! -e "$cursor" ] && [ ! -L "$cursor" ]; do',
35+
' parent=$(dirname -- "$cursor")',
36+
' if [ "$parent" = "$cursor" ]; then break; fi',
37+
' base=$(basename -- "$cursor")',
38+
' suffix="/$base$suffix"',
39+
' cursor="$parent"',
40+
"done",
41+
'canonical=$(readlink -f -- "$cursor")',
42+
'canonical_root=$(readlink -f -- "$3")',
43+
'printf "%s%s\\n%s\\n" "$canonical" "$suffix" "$canonical_root"',
44+
].join("\n");
45+
const result = await params.runRemoteShellScript({
46+
script,
47+
args: [
48+
params.containerPath,
49+
params.allowFinalSymlinkForUnlink ? "1" : "0",
50+
params.mountRootPath,
51+
],
52+
signal: params.signal,
53+
});
54+
const [canonicalRaw = "", canonicalRootRaw = ""] = result.stdout
55+
.toString("utf8")
56+
.trim()
57+
.split("\n");
58+
if (!canonicalRaw || !canonicalRootRaw) {
59+
throw new Error(
60+
`Sandbox path canonicalization failed; cannot ${params.action}: ${params.containerPath}`,
61+
);
62+
}
63+
const canonicalPath = normalizeContainerPath(canonicalRaw);
64+
const canonicalMountRoot = normalizeContainerPath(canonicalRootRaw);
65+
const relative = path.posix.relative(canonicalMountRoot, canonicalPath);
66+
if (relativePathEscapesContainerRoot(relative)) {
67+
throw new Error(
68+
`Sandbox path escapes allowed mounts; cannot ${params.action}: ${params.containerPath}`,
69+
);
70+
}
71+
return {
72+
canonicalPath,
73+
canonicalMountRoot,
74+
logicalPath:
75+
relative === "."
76+
? params.mountRootPath
77+
: normalizeContainerPath(path.posix.join(params.mountRootPath, relative)),
78+
};
79+
}

‎src/agents/sandbox/remote-fs-bridge-paths.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,26 @@ export function compareRemoteMountsByLocalPath(a: RemoteMountInfo, b: RemoteMoun
101101
return b.localRoot.length - a.localRoot.length || mountPriority(b) - mountPriority(a);
102102
}
103103

104+
export function buildRemoteProtectedSkillRoots(params: {
105+
workspaceContainerRoot: string;
106+
agentContainerRoot: string;
107+
includeAgentMount: boolean;
108+
}): string[] {
109+
const roots = [
110+
path.posix.join(params.workspaceContainerRoot, "skills"),
111+
path.posix.join(params.workspaceContainerRoot, ".agents", "skills"),
112+
path.posix.join(params.workspaceContainerRoot, ".openclaw", "sandbox-skills", "skills"),
113+
];
114+
if (params.includeAgentMount) {
115+
roots.push(
116+
path.posix.join(params.agentContainerRoot, "skills"),
117+
path.posix.join(params.agentContainerRoot, ".agents", "skills"),
118+
path.posix.join(params.agentContainerRoot, ".openclaw", "sandbox-skills", "skills"),
119+
);
120+
}
121+
return roots;
122+
}
123+
104124
function mountPriority(mount: RemoteMountInfo): number {
105125
if (mount.source === "protectedSkill") {
106126
return 2;

‎src/agents/sandbox/remote-fs-bridge.test.ts‎

Lines changed: 61 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ function createStatRuntime(
2727
return shellResult("1\n");
2828
}
2929
if (command.script.includes('readlink -f -- "$cursor"')) {
30-
return shellResult(`${workspaceDir}/note.txt\n`);
30+
return shellResult(`${workspaceDir}/note.txt\n${workspaceDir}\n`);
3131
}
3232
if (command.script.includes('stat -c "%F|%h"')) {
3333
return shellResult(`${outputs.hardlinks(command.script)}\n`);
@@ -168,6 +168,53 @@ describe("remote sandbox fs bridge", () => {
168168
},
169169
);
170170

171+
it.runIf(process.platform !== "win32")(
172+
"accepts a symlinked mount root while rejecting escapes through it",
173+
async () => {
174+
await withTempDir("openclaw-remote-fs-linked-root-", async (stateDir) => {
175+
const realWorkspaceDir = path.join(stateDir, "real-workspace");
176+
const linkedWorkspaceDir = path.join(stateDir, "linked-workspace");
177+
const outsideDir = path.join(stateDir, "outside");
178+
await fs.mkdir(realWorkspaceDir);
179+
await fs.mkdir(outsideDir);
180+
await fs.symlink(realWorkspaceDir, linkedWorkspaceDir, "dir");
181+
await fs.symlink(outsideDir, path.join(realWorkspaceDir, "escape"), "dir");
182+
const { runtime } = createLocalRemoteRuntime({
183+
remoteWorkspaceDir: linkedWorkspaceDir,
184+
remoteAgentWorkspaceDir: linkedWorkspaceDir,
185+
});
186+
const bridge = createRemoteShellSandboxFsBridge({
187+
sandbox: createSandbox({
188+
workspaceDir: linkedWorkspaceDir,
189+
agentWorkspaceDir: linkedWorkspaceDir,
190+
}),
191+
runtime,
192+
});
193+
const createFileExclusive = bridge.createFileExclusive?.bind(bridge);
194+
expect(createFileExclusive).toBeTypeOf("function");
195+
196+
await expect(
197+
createFileExclusive!({ filePath: "inside.txt", data: "inside" }),
198+
).resolves.toBe("created");
199+
await expect(bridge.readFile({ filePath: "inside.txt" })).resolves.toEqual(
200+
Buffer.from("inside"),
201+
);
202+
await expect(bridge.mkdirp({ filePath: "nested/dir" })).resolves.toBeUndefined();
203+
await expect(fs.readFile(path.join(realWorkspaceDir, "inside.txt"), "utf8")).resolves.toBe(
204+
"inside",
205+
);
206+
await expect(
207+
fs
208+
.stat(path.join(realWorkspaceDir, "nested", "dir"))
209+
.then((entry) => entry.isDirectory()),
210+
).resolves.toBe(true);
211+
await expect(
212+
createFileExclusive!({ filePath: "escape/outside.txt", data: "blocked" }),
213+
).rejects.toThrow(/escapes allowed mounts/);
214+
});
215+
},
216+
);
217+
171218
it.runIf(process.platform !== "win32")(
172219
"reads files with the pinned mutation helper",
173220
async () => {
@@ -192,11 +239,11 @@ describe("remote sandbox fs bridge", () => {
192239
await expect(bridge.readFile({ filePath: "note.txt" })).resolves.toEqual(
193240
Buffer.from("hello"),
194241
);
195-
expect(calls).toHaveLength(1);
196-
expect(calls[0]?.args?.[0]).toBe("read");
197-
expect(calls[0]?.script).toContain("python3 /dev/fd/3 \"$@\" 3<<'PY'");
198-
expect(calls[0]?.script).toContain("read_file(parent_fd, basename)");
199-
expect(calls[0]?.script).not.toContain('cat -- "$1"');
242+
expect(calls).toHaveLength(2);
243+
const readCall = calls.find((call) => call.args?.[0] === "read");
244+
expect(readCall?.script).toContain("python3 /dev/fd/3 \"$@\" 3<<'PY'");
245+
expect(readCall?.script).toContain("read_file(parent_fd, basename)");
246+
expect(readCall?.script).not.toContain('cat -- "$1"');
200247
});
201248
},
202249
);
@@ -222,14 +269,20 @@ describe("remote sandbox fs bridge", () => {
222269
await expect(bridge.readFile({ filePath: "note.txt", maxBytes: 5 })).resolves.toEqual(
223270
Buffer.from("hello"),
224271
);
225-
expect(calls[0]?.args).toEqual(["read", workspaceDir, "", "note.txt", "5"]);
272+
expect(calls.find((call) => call.args?.[0] === "read")?.args).toEqual([
273+
"read",
274+
workspaceDir,
275+
"",
276+
"note.txt",
277+
"5",
278+
]);
226279
await expect(bridge.readFile({ filePath: "note.txt", maxBytes: 4 })).rejects.toThrow(
227280
/bounded read limit/i,
228281
);
229282
await expect(bridge.readFile({ filePath: "note.txt", maxBytes: -1 })).rejects.toThrow(
230283
/non-negative safe integer/i,
231284
);
232-
expect(calls).toHaveLength(2);
285+
expect(calls).toHaveLength(4);
233286
});
234287
},
235288
);

0 commit comments

Comments
 (0)