Skip to content

Commit 5295f25

Browse files
authored
fix(agents): make file reads safe and explicit (#121508)
Use fs-safe 0.5.4 for nonblocking, descriptor-validated reads. Resolve one unambiguous Unicode-equivalent path and return explicit empty/EOF results. Default local reads now reject final symlinks and special files. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 98b1e8b commit 5295f25

16 files changed

Lines changed: 558 additions & 194 deletions

‎extensions/onepassword/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"description": "1Password SecretRef resolver and audited agent secrets broker for OpenClaw",
66
"type": "module",
77
"dependencies": {
8-
"@openclaw/fs-safe": "0.5.2",
8+
"@openclaw/fs-safe": "0.5.4",
99
"execa": "10.0.0"
1010
},
1111
"devDependencies": {

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2020,7 +2020,7 @@
20202020
"@modelcontextprotocol/sdk": "1.30.0",
20212021
"@mozilla/readability": "0.6.0",
20222022
"@openclaw/ai": "workspace:*",
2023-
"@openclaw/fs-safe": "0.5.2",
2023+
"@openclaw/fs-safe": "0.5.4",
20242024
"@openclaw/proxyline": "0.3.4",
20252025
"@silvia-odwyer/photon-node": "0.3.4",
20262026
"@trycua/cua-driver": "0.14.1",

‎pnpm-lock.yaml‎

Lines changed: 7 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm-workspace.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ minimumReleaseAge: 2880
99

1010
minimumReleaseAgeExclude:
1111
- "@openclaw/[email protected]"
12-
- "@openclaw/[email protected].2"
12+
- "@openclaw/[email protected].4"
1313
- "@openclaw/[email protected]"
1414
- "@openclaw/[email protected]"
1515
- "@openclaw/[email protected]"

‎src/agents/agent-tools.create-openclaw-coding-tools.test.ts‎

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ const tinyPngBuffer = Buffer.from(
6262
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO2f7z8AAAAASUVORK5CYII=",
6363
"base64",
6464
);
65+
const avifHeaderBuffer = Buffer.from("00000018667479706176696600000000617669666d696631", "hex");
6566
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
6667
const XAI_UNSUPPORTED_SCHEMA_KEYWORDS = new Set(["minContains", "maxContains"]);
6768
function collectActionValues(schema: unknown, values: Set<string>): void {
@@ -2684,6 +2685,39 @@ describe("createOpenClawCodingTools read behavior", () => {
26842685
expect(readFile).not.toHaveBeenCalled();
26852686
});
26862687

2688+
it("resolves Unicode-equivalent filenames through sandbox operations", async () => {
2689+
const tmpDir = tempDirs.make("openclaw-sbx-unicode-");
2690+
const storedName = "re\u0301sume\u0301 3.04\u202fPM d\u2019accord.txt";
2691+
await fs.writeFile(path.join(tmpDir, storedName), "sandbox match");
2692+
const readTool = createSandboxedReadTool({
2693+
root: tmpDir,
2694+
bridge: createHostSandboxFsBridge(tmpDir),
2695+
});
2696+
2697+
const result = await readTool.execute("sandbox-unicode", {
2698+
path: "r\u00e9sum\u00e9 3.04 PM d'accord.txt",
2699+
});
2700+
2701+
expect(extractToolText(result)).toContain("Resolved filename");
2702+
expect(extractToolText(result)).toContain("sandbox match");
2703+
});
2704+
2705+
it("classifies sandbox AVIF reads from the already-read buffer", async () => {
2706+
const tmpDir = tempDirs.make("openclaw-sbx-avif-");
2707+
await fs.writeFile(path.join(tmpDir, "photo.bin"), avifHeaderBuffer);
2708+
const hostBridge = createHostSandboxFsBridge(tmpDir);
2709+
const readFile = vi.fn(hostBridge.readFile.bind(hostBridge));
2710+
const readTool = createSandboxedReadTool({
2711+
root: tmpDir,
2712+
bridge: { ...hostBridge, readFile },
2713+
});
2714+
2715+
const result = await readTool.execute("sandbox-avif", { path: "photo.bin" });
2716+
2717+
expect(extractToolText(result)).toContain("Read image file [image/avif]");
2718+
expect(readFile).toHaveBeenCalledTimes(1);
2719+
});
2720+
26872721
it("auto-pages read output across chunks when context window budget allows", async () => {
26882722
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-read-autopage-"));
26892723
const filePath = path.join(tmpDir, "big.txt");
@@ -2752,7 +2786,7 @@ describe("createOpenClawCodingTools read behavior", () => {
27522786
}
27532787
});
27542788

2755-
it("returns empty content for explicit offsets beyond EOF", async () => {
2789+
it("describes explicit offsets beyond EOF", async () => {
27562790
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-read-offset-eof-"));
27572791
await fs.writeFile(path.join(tmpDir, "notes.txt"), "one\ntwo\nthree", "utf8");
27582792
try {
@@ -2766,13 +2800,15 @@ describe("createOpenClawCodingTools read behavior", () => {
27662800
limit: 10,
27672801
});
27682802

2769-
expect(extractToolText(result)).toBe("");
2803+
expect(extractToolText(result)).toBe(
2804+
"Offset 99 is beyond end of file (3 lines total). Retry with offset <= 3.",
2805+
);
27702806
} finally {
27712807
await fs.rm(tmpDir, { recursive: true, force: true });
27722808
}
27732809
});
27742810

2775-
it("returns empty content for adaptive offsets beyond EOF", async () => {
2811+
it("ignores a trailing newline when describing offsets beyond EOF", async () => {
27762812
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-read-offset-adaptive-"));
27772813
await fs.writeFile(path.join(tmpDir, "notes.txt"), "one\ntwo\nthree\n", "utf8");
27782814
try {
@@ -2785,13 +2821,15 @@ describe("createOpenClawCodingTools read behavior", () => {
27852821
offset: 99,
27862822
});
27872823

2788-
expect(extractToolText(result)).toBe("");
2824+
expect(extractToolText(result)).toBe(
2825+
"Offset 99 is beyond end of file (3 lines total). Retry with offset <= 3.",
2826+
);
27892827
} finally {
27902828
await fs.rm(tmpDir, { recursive: true, force: true });
27912829
}
27922830
});
27932831

2794-
it("returns already-read adaptive content when pagination reaches EOF", async () => {
2832+
it("stops adaptive pagination when the current page reaches EOF", async () => {
27952833
const readResult: AgentToolResult<unknown> = {
27962834
content: [
27972835
{
@@ -2803,14 +2841,12 @@ describe("createOpenClawCodingTools read behavior", () => {
28032841
truncation: {
28042842
truncated: true,
28052843
outputLines: 1,
2844+
totalLines: 1,
28062845
firstLineExceedsLimit: false,
28072846
},
28082847
},
28092848
};
2810-
const execute = vi
2811-
.fn()
2812-
.mockResolvedValueOnce(readResult)
2813-
.mockRejectedValueOnce(new Error("Offset 2 is beyond end of file (1 lines total)"));
2849+
const execute = vi.fn().mockResolvedValue(readResult);
28142850
const readTool = createOpenClawReadTool({
28152851
name: "read",
28162852
label: "read",
@@ -2828,7 +2864,7 @@ describe("createOpenClawCodingTools read behavior", () => {
28282864
});
28292865

28302866
expect(extractToolText(result)).toBe("one");
2831-
expect(execute).toHaveBeenCalledTimes(2);
2867+
expect(execute).toHaveBeenCalledTimes(1);
28322868
});
28332869

28342870
it("keeps unrelated read failures loud", async () => {

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

Lines changed: 14 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,10 @@ type SkillReadContent = {
7676
type ReadTruncationDetails = {
7777
truncated: boolean;
7878
outputLines: number;
79+
totalLines: number;
7980
firstLineExceedsLimit: boolean;
8081
};
8182

82-
const OFFSET_BEYOND_EOF_RE = /^Offset \d+ is beyond end of file \(\d+ lines total\)$/;
8383
const READ_CONTINUATION_NOTICE_RE =
8484
/\n\n\[(?:Showing lines [^\]]*?Use offset=\d+ to continue\.|\d+ more lines in file\. Use offset=\d+ to continue\.)\]\s*$/;
8585
const DAILY_MEMORY_PATH_RE = /^memory\/\d{4}-\d{2}-\d{2}\.md$/;
@@ -184,9 +184,15 @@ function extractReadTruncationDetails(
184184
typeof outputLinesRaw === "number" && Number.isFinite(outputLinesRaw)
185185
? Math.max(0, Math.floor(outputLinesRaw))
186186
: 0;
187+
const totalLinesRaw = record.totalLines;
188+
const totalLines =
189+
typeof totalLinesRaw === "number" && Number.isFinite(totalLinesRaw)
190+
? Math.max(0, Math.floor(totalLinesRaw))
191+
: 0;
187192
return {
188193
truncated: true,
189194
outputLines,
195+
totalLines,
190196
firstLineExceedsLimit: record.firstLineExceedsLimit === true,
191197
};
192198
}
@@ -224,22 +230,6 @@ function stripReadTruncationContentDetails(
224230
};
225231
}
226232

227-
function isOffsetBeyondEof(error: unknown, args: Record<string, unknown>): boolean {
228-
const offset = args.offset;
229-
return (
230-
typeof offset === "number" &&
231-
Number.isFinite(offset) &&
232-
offset > 0 &&
233-
error instanceof Error &&
234-
OFFSET_BEYOND_EOF_RE.test(error.message)
235-
);
236-
}
237-
238-
function emptyReadResult(): AgentToolResult<unknown> {
239-
const textBlock = { type: "text", text: "" } satisfies TextContentBlock;
240-
return { content: [textBlock], details: undefined };
241-
}
242-
243233
function missingDailyMemoryReadResult(relativePath: string): AgentToolResult<unknown> {
244234
return {
245235
content: [
@@ -287,9 +277,6 @@ async function executeReadPage(params: {
287277
try {
288278
return await params.base.execute(params.toolCallId, params.args, params.signal);
289279
} catch (error) {
290-
if (isOffsetBeyondEof(error, params.args)) {
291-
return emptyReadResult();
292-
}
293280
const missingDailyMemoryPath = normalizeDailyMemoryReadPath(params.args.path);
294281
if (missingDailyMemoryPath && isNotFoundError(error)) {
295282
return missingDailyMemoryReadResult(missingDailyMemoryPath);
@@ -339,12 +326,16 @@ async function executeReadWithAdaptivePaging(params: {
339326
}
340327

341328
const truncation = extractReadTruncationDetails(pageResult);
329+
const pageEndLine = nextOffset - 1 + (truncation?.outputLines ?? 0);
330+
const reachedEof =
331+
Boolean(truncation?.truncated) && pageEndLine >= (truncation?.totalLines ?? 0);
342332
const canContinue =
343333
Boolean(truncation?.truncated) &&
344334
!truncation?.firstLineExceedsLimit &&
345335
(truncation?.outputLines ?? 0) > 0 &&
336+
pageEndLine < (truncation?.totalLines ?? 0) &&
346337
page < MAX_ADAPTIVE_READ_PAGES - 1;
347-
const pageText = canContinue ? stripReadContinuationNotice(rawText) : rawText;
338+
const pageText = canContinue || reachedEof ? stripReadContinuationNotice(rawText) : rawText;
348339
const delimiter = aggregatedText && pageText ? "\n\n" : "";
349340
const nextBytes = Buffer.byteLength(`${delimiter}${pageText}`, "utf-8");
350341

@@ -1053,10 +1044,9 @@ function createSandboxReadOperations(params: SandboxToolParams) {
10531044
readFile: (absolutePath: string) =>
10541045
params.bridge.readFile({ filePath: absolutePath, cwd: params.root }),
10551046
access: (absolutePath: string) => assertSandboxFileExists(params, absolutePath),
1056-
detectImageMimeType: async (absolutePath: string) => {
1057-
const buffer = await params.bridge.readFile({ filePath: absolutePath, cwd: params.root });
1047+
detectImageMimeType: async (absolutePath: string, buffer: Buffer) => {
10581048
const mime = await detectMime({ buffer, filePath: absolutePath });
1059-
return mime && mime.startsWith("image/") ? mime : undefined;
1049+
return mime?.startsWith("image/") ? mime : undefined;
10601050
},
10611051
} as const;
10621052
}

‎src/agents/sandbox-paths.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,16 @@ import { isNotFoundPathError, isPathInside } from "../infra/path-guards.js";
2020
import { resolvePreferredOpenClawTmpDir } from "../infra/tmp-openclaw-dir.js";
2121
import { resolveConfigDir, shortenHomePath } from "../utils.js";
2222

23-
const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
2423
const DATA_URL_RE = /^data:/i;
2524
const SANDBOX_CONTAINER_WORKDIR = "/workspace";
2625
const MANAGED_MEDIA_SUBDIRS = new Set(["outbound"]);
2726

28-
function normalizeUnicodeSpaces(str: string): string {
29-
return str.replace(UNICODE_SPACES, " ");
30-
}
31-
3227
function normalizeAtPrefix(filePath: string): string {
3328
return filePath.startsWith("@") ? filePath.slice(1) : filePath;
3429
}
3530

3631
function expandPath(filePath: string): string {
37-
const normalized = normalizeUnicodeSpaces(normalizeAtPrefix(filePath));
32+
const normalized = normalizeAtPrefix(filePath);
3833
if (normalized === "~") {
3934
return os.homedir();
4035
}

‎src/agents/sandbox/fs-bridge-mutation-helper.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,30 @@ describe("sandbox pinned mutation helper", () => {
538538
});
539539
});
540540

541+
it.runIf(process.platform !== "win32")("rejects FIFO reads without blocking", async () => {
542+
await withTempDir({ prefix: "openclaw-mutation-helper-fifo-" }, async (root) => {
543+
const workspace = path.join(root, "workspace");
544+
const fifoPath = path.join(workspace, "live.pipe");
545+
await fs.mkdir(workspace, { recursive: true });
546+
expect(spawnSync("mkfifo", [fifoPath]).status).toBe(0);
547+
548+
const result = spawnSync(
549+
"python3",
550+
["-c", SANDBOX_PINNED_MUTATION_PYTHON, "read", workspace, "", "live.pipe"],
551+
{
552+
encoding: "utf8",
553+
stdio: ["pipe", "pipe", "pipe"],
554+
timeout: 1_000,
555+
killSignal: "SIGKILL",
556+
},
557+
);
558+
559+
expect(result.error).toBeUndefined();
560+
expect(result.status).not.toBe(0);
561+
expect(result.stderr).toMatch(/only regular files are allowed/i);
562+
});
563+
});
564+
541565
it.runIf(process.platform !== "win32")(
542566
"preserves stdin payload bytes when the pinned write plan runs through sh",
543567
async () => {

‎src/agents/sandbox/fs-bridge-mutation-helper.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ export const SANDBOX_PINNED_MUTATION_PYTHON = [
4848
"READ_FLAGS = os.O_RDONLY",
4949
"if hasattr(os, 'O_NOFOLLOW'):",
5050
" READ_FLAGS |= os.O_NOFOLLOW",
51+
"if hasattr(os, 'O_NONBLOCK'):",
52+
" READ_FLAGS |= os.O_NONBLOCK",
5153
"",
5254
"WRITE_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_EXCL",
5355
"if hasattr(os, 'O_NOFOLLOW'):",

‎src/agents/sandbox/fs-bridge-path-safety.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
*/
66
import fs from "node:fs";
77
import path from "node:path";
8+
import { FsSafeError } from "../../infra/fs-safe.js";
89
import type { PathAliasPolicy } from "../../infra/path-alias-guards.js";
910
import { openRootFile, type RootFileOpenResult } from "./fs-bridge-path-safety.runtime.js";
1011
import type { SandboxResolvedFsPath, SandboxFsMount } from "./fs-paths.js";
@@ -16,6 +17,15 @@ import {
1617

1718
type BoundaryAllowedType = "file" | "directory";
1819

20+
function sandboxBoundaryError(action: string, containerPath: string, error: unknown): Error {
21+
if (error instanceof Error && !(error instanceof FsSafeError && error.code === "not-file")) {
22+
return error;
23+
}
24+
return new Error(`Sandbox boundary checks failed; cannot ${action}: ${containerPath}`, {
25+
cause: error,
26+
});
27+
}
28+
1929
/** Caller-provided path safety requirements for one fs bridge operation. */
2030
type PathSafetyOptions = {
2131
action: string;
@@ -88,9 +98,7 @@ export class SandboxFsPathGuard {
8898
): Promise<RootFileOpenResult & { ok: true }> {
8999
const opened = await this.openBoundaryWithinRequiredMount(target, "read files");
90100
if (!opened.ok) {
91-
throw opened.error instanceof Error
92-
? opened.error
93-
: new Error(`Sandbox boundary checks failed; cannot read files: ${target.containerPath}`);
101+
throw sandboxBoundaryError("read files", target.containerPath, opened.error);
94102
}
95103
return opened;
96104
}
@@ -133,11 +141,7 @@ export class SandboxFsPathGuard {
133141
const canFallbackToDirectoryStat =
134142
options.allowedType === "directory" && this.pathIsExistingDirectory(target.hostPath);
135143
if (!canFallbackToDirectoryStat) {
136-
throw guarded.error instanceof Error
137-
? guarded.error
138-
: new Error(
139-
`Sandbox boundary checks failed; cannot ${options.action}: ${target.containerPath}`,
140-
);
144+
throw sandboxBoundaryError(options.action, target.containerPath, guarded.error);
141145
}
142146
}
143147
} else {
@@ -170,7 +174,7 @@ export class SandboxFsPathGuard {
170174
absolutePath: target.hostPath,
171175
rootPath: lexicalMount.hostRoot,
172176
boundaryLabel: "sandbox mount root",
173-
// Follow in-mount symlink hops (fs-safe 0.5.2 rejects them by default):
177+
// Follow in-mount symlink hops (fs-safe rejects them by default):
174178
// escaping hops still fail with fs-safe's containment error, and the
175179
// canonical container path is re-checked against mounts afterwards.
176180
rejectSymlinks: false,

0 commit comments

Comments
 (0)