Skip to content

Commit 3b9dab0

Browse files
OpenShell: harden mirror sync boundaries (#57693)
* OpenShell: harden mirror sync boundaries * OpenShell: polish mirror hardening tests * OpenShell: preserve trusted mirror symlinks * OpenShell: bound mirror fs work globally
1 parent a4e447a commit 3b9dab0

3 files changed

Lines changed: 262 additions & 47 deletions

File tree

‎extensions/openshell/src/backend.ts‎

Lines changed: 43 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,11 @@ import {
2727
} from "./cli.js";
2828
import { resolveOpenShellPluginConfig, type ResolvedOpenShellPluginConfig } from "./config.js";
2929
import { createOpenShellFsBridge } from "./fs-bridge.js";
30-
import { replaceDirectoryContents } from "./mirror.js";
30+
import {
31+
DEFAULT_OPEN_SHELL_MIRROR_EXCLUDE_DIRS,
32+
replaceDirectoryContents,
33+
stageDirectoryContents,
34+
} from "./mirror.js";
3135

3236
type CreateOpenShellSandboxBackendFactoryParams = {
3337
pluginConfig: ResolvedOpenShellPluginConfig;
@@ -293,6 +297,14 @@ class OpenShellSandboxBackendImpl {
293297
});
294298
return;
295299
}
300+
if (stats.isSymbolicLink()) {
301+
await this.runRemoteShellScript({
302+
script: 'rm -rf -- "$1"',
303+
args: [remotePath],
304+
allowFailure: true,
305+
});
306+
return;
307+
}
296308
if (stats.isDirectory()) {
297309
await this.runRemoteShellScript({
298310
script: 'mkdir -p -- "$1"',
@@ -421,30 +433,43 @@ class OpenShellSandboxBackendImpl {
421433
await replaceDirectoryContents({
422434
sourceDir: tmpDir,
423435
targetDir: this.params.createParams.workspaceDir,
424-
// Never sync hooks/ from the remote sandbox — mirrored content must not
425-
// become trusted workspace hook code on the host.
426-
excludeDirs: ["hooks"],
436+
// Never sync trusted host hook directories or repository metadata from
437+
// the remote sandbox.
438+
excludeDirs: DEFAULT_OPEN_SHELL_MIRROR_EXCLUDE_DIRS,
427439
});
428440
} finally {
429441
await fs.rm(tmpDir, { recursive: true, force: true });
430442
}
431443
}
432444

433445
private async uploadPathToRemote(localPath: string, remotePath: string): Promise<void> {
434-
const result = await runOpenShellCli({
435-
context: this.params.execContext,
436-
args: [
437-
"sandbox",
438-
"upload",
439-
"--no-git-ignore",
440-
this.params.execContext.sandboxName,
441-
localPath,
442-
remotePath,
443-
],
444-
cwd: this.params.createParams.workspaceDir,
445-
});
446-
if (result.code !== 0) {
447-
throw new Error(result.stderr.trim() || "openshell sandbox upload failed");
446+
const tmpDir = await fs.mkdtemp(
447+
path.join(resolveOpenShellTmpRoot(), "openclaw-openshell-upload-"),
448+
);
449+
try {
450+
// Stage a symlink-free snapshot so upload never dereferences host paths
451+
// outside the mirrored workspace tree.
452+
await stageDirectoryContents({
453+
sourceDir: localPath,
454+
targetDir: tmpDir,
455+
});
456+
const result = await runOpenShellCli({
457+
context: this.params.execContext,
458+
args: [
459+
"sandbox",
460+
"upload",
461+
"--no-git-ignore",
462+
this.params.execContext.sandboxName,
463+
tmpDir,
464+
remotePath,
465+
],
466+
cwd: this.params.createParams.workspaceDir,
467+
});
468+
if (result.code !== 0) {
469+
throw new Error(result.stderr.trim() || "openshell sandbox upload failed");
470+
}
471+
} finally {
472+
await fs.rm(tmpDir, { recursive: true, force: true });
448473
}
449474
}
450475

‎extensions/openshell/src/mirror.test.ts‎

Lines changed: 104 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,26 @@ import fs from "node:fs/promises";
22
import os from "node:os";
33
import path from "node:path";
44
import { afterEach, describe, expect, it } from "vitest";
5-
import { replaceDirectoryContents } from "./mirror.js";
5+
import {
6+
DEFAULT_OPEN_SHELL_MIRROR_EXCLUDE_DIRS,
7+
replaceDirectoryContents,
8+
stageDirectoryContents,
9+
} from "./mirror.js";
10+
11+
const dirs: string[] = [];
12+
13+
async function makeTmpDir(): Promise<string> {
14+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-mirror-test-"));
15+
dirs.push(dir);
16+
return dir;
17+
}
18+
19+
afterEach(async () => {
20+
await Promise.all(dirs.map((d) => fs.rm(d, { recursive: true, force: true })));
21+
dirs.length = 0;
22+
});
623

724
describe("replaceDirectoryContents", () => {
8-
const dirs: string[] = [];
9-
10-
async function makeTmpDir(): Promise<string> {
11-
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-mirror-test-"));
12-
dirs.push(dir);
13-
return dir;
14-
}
15-
16-
afterEach(async () => {
17-
await Promise.all(dirs.map((d) => fs.rm(d, { recursive: true, force: true })));
18-
dirs.length = 0;
19-
});
20-
2125
it("copies source entries to target", async () => {
2226
const source = await makeTmpDir();
2327
const target = await makeTmpDir();
@@ -89,4 +93,90 @@ describe("replaceDirectoryContents", () => {
8993
// "Hooks" (variant case) must still be excluded
9094
await expect(fs.access(path.join(target, "Hooks"))).rejects.toThrow();
9195
});
96+
97+
it("preserves default excluded directories and repository metadata", async () => {
98+
const source = await makeTmpDir();
99+
const target = await makeTmpDir();
100+
101+
await fs.mkdir(path.join(source, "hooks"), { recursive: true });
102+
await fs.writeFile(path.join(source, "hooks", "pre-commit"), "malicious");
103+
await fs.mkdir(path.join(source, "git-hooks"), { recursive: true });
104+
await fs.writeFile(path.join(source, "git-hooks", "pre-commit"), "malicious");
105+
await fs.mkdir(path.join(source, ".git", "hooks"), { recursive: true });
106+
await fs.writeFile(path.join(source, ".git", "hooks", "post-checkout"), "malicious");
107+
await fs.writeFile(path.join(source, "safe.txt"), "ok");
108+
109+
await fs.mkdir(path.join(target, "hooks"), { recursive: true });
110+
await fs.writeFile(path.join(target, "hooks", "trusted"), "trusted");
111+
await fs.mkdir(path.join(target, "git-hooks"), { recursive: true });
112+
await fs.writeFile(path.join(target, "git-hooks", "trusted"), "trusted");
113+
await fs.mkdir(path.join(target, ".git"), { recursive: true });
114+
await fs.writeFile(path.join(target, ".git", "HEAD"), "ref: refs/heads/main\n");
115+
116+
await replaceDirectoryContents({
117+
sourceDir: source,
118+
targetDir: target,
119+
excludeDirs: DEFAULT_OPEN_SHELL_MIRROR_EXCLUDE_DIRS,
120+
});
121+
122+
expect(await fs.readFile(path.join(target, "safe.txt"), "utf8")).toBe("ok");
123+
expect(await fs.readFile(path.join(target, "hooks", "trusted"), "utf8")).toBe("trusted");
124+
expect(await fs.readFile(path.join(target, "git-hooks", "trusted"), "utf8")).toBe("trusted");
125+
expect(await fs.readFile(path.join(target, ".git", "HEAD"), "utf8")).toBe(
126+
"ref: refs/heads/main\n",
127+
);
128+
await expect(fs.access(path.join(target, ".git", "hooks", "post-checkout"))).rejects.toThrow();
129+
});
130+
131+
it("skips symbolic links when copying into the host workspace", async () => {
132+
const source = await makeTmpDir();
133+
const target = await makeTmpDir();
134+
135+
await fs.writeFile(path.join(source, "safe.txt"), "ok");
136+
await fs.mkdir(path.join(source, "nested"), { recursive: true });
137+
await fs.writeFile(path.join(source, "nested", "file.txt"), "nested");
138+
await fs.symlink("/tmp/host-secret", path.join(source, "escaped-link"));
139+
await fs.symlink("/tmp/host-secret-dir", path.join(source, "nested", "escaped-dir"));
140+
141+
await replaceDirectoryContents({ sourceDir: source, targetDir: target });
142+
143+
expect(await fs.readFile(path.join(target, "safe.txt"), "utf8")).toBe("ok");
144+
expect(await fs.readFile(path.join(target, "nested", "file.txt"), "utf8")).toBe("nested");
145+
await expect(fs.lstat(path.join(target, "escaped-link"))).rejects.toThrow();
146+
await expect(fs.lstat(path.join(target, "nested", "escaped-dir"))).rejects.toThrow();
147+
});
148+
149+
it("preserves existing trusted host symlinks", async () => {
150+
const source = await makeTmpDir();
151+
const target = await makeTmpDir();
152+
153+
await fs.writeFile(path.join(source, "safe.txt"), "ok");
154+
await fs.writeFile(path.join(source, "linked-entry"), "remote-plain-file");
155+
await fs.symlink("/tmp/trusted-host-target", path.join(target, "linked-entry"));
156+
157+
await replaceDirectoryContents({ sourceDir: source, targetDir: target });
158+
159+
expect(await fs.readFile(path.join(target, "safe.txt"), "utf8")).toBe("ok");
160+
expect(await fs.readlink(path.join(target, "linked-entry"))).toBe("/tmp/trusted-host-target");
161+
});
162+
});
163+
164+
describe("stageDirectoryContents", () => {
165+
it("stages upload content without symbolic links", async () => {
166+
const source = await makeTmpDir();
167+
const staged = await makeTmpDir();
168+
169+
await fs.writeFile(path.join(source, "safe.txt"), "ok");
170+
await fs.mkdir(path.join(source, "nested"), { recursive: true });
171+
await fs.writeFile(path.join(source, "nested", "file.txt"), "nested");
172+
await fs.symlink("/tmp/host-secret", path.join(source, "escaped-link"));
173+
await fs.symlink("/tmp/host-secret-dir", path.join(source, "nested", "escaped-dir"));
174+
175+
await stageDirectoryContents({ sourceDir: source, targetDir: staged });
176+
177+
expect(await fs.readFile(path.join(staged, "safe.txt"), "utf8")).toBe("ok");
178+
expect(await fs.readFile(path.join(staged, "nested", "file.txt"), "utf8")).toBe("nested");
179+
await expect(fs.lstat(path.join(staged, "escaped-link"))).rejects.toThrow();
180+
await expect(fs.lstat(path.join(staged, "nested", "escaped-dir"))).rejects.toThrow();
181+
});
92182
});

‎extensions/openshell/src/mirror.ts‎

Lines changed: 115 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,137 @@
11
import fs from "node:fs/promises";
22
import path from "node:path";
33

4+
export const DEFAULT_OPEN_SHELL_MIRROR_EXCLUDE_DIRS = ["hooks", "git-hooks", ".git"] as const;
5+
const COPY_TREE_FS_CONCURRENCY = 16;
6+
7+
function createExcludeMatcher(excludeDirs?: readonly string[]) {
8+
const excluded = new Set((excludeDirs ?? []).map((d) => d.toLowerCase()));
9+
return (name: string) => excluded.has(name.toLowerCase());
10+
}
11+
12+
function createConcurrencyLimiter(limit: number) {
13+
let active = 0;
14+
const queue: Array<() => void> = [];
15+
16+
const release = () => {
17+
active -= 1;
18+
queue.shift()?.();
19+
};
20+
21+
return async <T>(task: () => Promise<T>): Promise<T> => {
22+
if (active >= limit) {
23+
await new Promise<void>((resolve) => {
24+
queue.push(resolve);
25+
});
26+
}
27+
active += 1;
28+
try {
29+
return await task();
30+
} finally {
31+
release();
32+
}
33+
};
34+
}
35+
36+
const runLimitedFs = createConcurrencyLimiter(COPY_TREE_FS_CONCURRENCY);
37+
38+
async function lstatIfExists(targetPath: string) {
39+
return await runLimitedFs(async () => await fs.lstat(targetPath)).catch(() => null);
40+
}
41+
42+
async function copyTreeWithoutSymlinks(params: {
43+
sourcePath: string;
44+
targetPath: string;
45+
preserveTargetSymlinks?: boolean;
46+
}): Promise<void> {
47+
const stats = await runLimitedFs(async () => await fs.lstat(params.sourcePath));
48+
// Mirror sync only carries regular files and directories across the
49+
// host/sandbox boundary. Symlinks and special files are dropped.
50+
if (stats.isSymbolicLink()) {
51+
return;
52+
}
53+
const targetStats = await lstatIfExists(params.targetPath);
54+
if (params.preserveTargetSymlinks && targetStats?.isSymbolicLink()) {
55+
return;
56+
}
57+
if (stats.isDirectory()) {
58+
await runLimitedFs(async () => await fs.mkdir(params.targetPath, { recursive: true }));
59+
const entries = await runLimitedFs(async () => await fs.readdir(params.sourcePath));
60+
await Promise.all(
61+
entries.map(async (entry) => {
62+
await copyTreeWithoutSymlinks({
63+
sourcePath: path.join(params.sourcePath, entry),
64+
targetPath: path.join(params.targetPath, entry),
65+
preserveTargetSymlinks: params.preserveTargetSymlinks,
66+
});
67+
}),
68+
);
69+
return;
70+
}
71+
if (stats.isFile()) {
72+
await runLimitedFs(
73+
async () => await fs.mkdir(path.dirname(params.targetPath), { recursive: true }),
74+
);
75+
await runLimitedFs(async () => await fs.copyFile(params.sourcePath, params.targetPath));
76+
}
77+
}
78+
479
export async function replaceDirectoryContents(params: {
580
sourceDir: string;
681
targetDir: string;
782
/** Top-level directory names to exclude from sync (preserved in target, skipped from source). */
8-
excludeDirs?: string[];
83+
excludeDirs?: readonly string[];
984
}): Promise<void> {
10-
// Case-insensitive matching: on macOS/Windows the filesystem is typically
11-
// case-insensitive, so "Hooks" would resolve to the same directory as "hooks".
12-
const excluded = new Set((params.excludeDirs ?? []).map((d) => d.toLowerCase()));
13-
const isExcluded = (name: string) => excluded.has(name.toLowerCase());
85+
const isExcluded = createExcludeMatcher(params.excludeDirs);
1486
await fs.mkdir(params.targetDir, { recursive: true });
1587
const existing = await fs.readdir(params.targetDir);
1688
await Promise.all(
1789
existing
1890
.filter((entry) => !isExcluded(entry))
19-
.map((entry) =>
20-
fs.rm(path.join(params.targetDir, entry), {
21-
recursive: true,
22-
force: true,
23-
}),
24-
),
91+
.map(async (entry) => {
92+
const targetPath = path.join(params.targetDir, entry);
93+
const stats = await lstatIfExists(targetPath);
94+
if (stats?.isSymbolicLink()) {
95+
return;
96+
}
97+
await runLimitedFs(
98+
async () =>
99+
await fs.rm(targetPath, {
100+
recursive: true,
101+
force: true,
102+
}),
103+
);
104+
}),
25105
);
26106
const sourceEntries = await fs.readdir(params.sourceDir);
27107
for (const entry of sourceEntries) {
28108
if (isExcluded(entry)) {
29109
continue;
30110
}
31-
await fs.cp(path.join(params.sourceDir, entry), path.join(params.targetDir, entry), {
32-
recursive: true,
33-
force: true,
34-
dereference: false,
111+
await copyTreeWithoutSymlinks({
112+
sourcePath: path.join(params.sourceDir, entry),
113+
targetPath: path.join(params.targetDir, entry),
114+
preserveTargetSymlinks: true,
115+
});
116+
}
117+
}
118+
119+
export async function stageDirectoryContents(params: {
120+
sourceDir: string;
121+
targetDir: string;
122+
/** Top-level directory names to exclude from the staged upload. */
123+
excludeDirs?: readonly string[];
124+
}): Promise<void> {
125+
const isExcluded = createExcludeMatcher(params.excludeDirs);
126+
await fs.mkdir(params.targetDir, { recursive: true });
127+
const sourceEntries = await fs.readdir(params.sourceDir);
128+
for (const entry of sourceEntries) {
129+
if (isExcluded(entry)) {
130+
continue;
131+
}
132+
await copyTreeWithoutSymlinks({
133+
sourcePath: path.join(params.sourceDir, entry),
134+
targetPath: path.join(params.targetDir, entry),
35135
});
36136
}
37137
}

0 commit comments

Comments
 (0)