Skip to content

Commit c6f3475

Browse files
committed
fix(oc-path): bound CLI file reads
1 parent eea8f96 commit c6f3475

5 files changed

Lines changed: 165 additions & 39 deletions

File tree

‎docs/cli/path.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,9 +182,10 @@ Non-canonical query parameters are ignored except for the first non-empty
182182

183183
Hard limits: a path caps at 4096 bytes, at most 4 slots (file/section/item/
184184
field), at most 64 dotted sub-segments per slot, and at most 256 nested
185-
traversal levels for deep JSON paths. Separately, any JSONC/JSON file input
186-
over 16 MiB is refused with a parse diagnostic instead of being parsed, for
187-
any verb that loads that file.
185+
traversal levels for deep JSON paths. Separately, every file input over 16 MiB
186+
is refused before parsing for any verb that loads the file. JSONC/JSON keeps
187+
the `OC_JSONC_INPUT_TOO_LARGE` diagnostic; other file kinds use
188+
`OC_PATH_INPUT_TOO_LARGE`.
188189

189190
## Addressing by file kind
190191

‎extensions/oc-path/src/cli.test.ts‎

Lines changed: 93 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,17 @@
44
* Tests invoke each subcommand through the retained Commander registration.
55
* Assertions inspect captured process output and the resulting exit code.
66
*/
7-
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
7+
import { execFileSync } from "node:child_process";
8+
import {
9+
closeSync,
10+
constants as fsConstants,
11+
mkdtempSync,
12+
openSync,
13+
promises as fs,
14+
readFileSync,
15+
writeFileSync,
16+
writeSync,
17+
} from "node:fs";
818
import { tmpdir } from "node:os";
919
import { join } from "node:path";
1020
import { Command, CommanderError } from "commander";
@@ -289,20 +299,92 @@ describe("openclaw path CLI", () => {
289299
expect(stderrText(rt)).toContain("missing required argument");
290300
});
291301

292-
it("rejects oversized multibyte JSONC with the typed diagnostic", async () => {
302+
it("bounds every file-loading verb before parsing oversized input", async () => {
293303
const filePath = join(workspaceDir, "oversized.json");
294304
const content = `"${"界".repeat(Math.floor(JSONC_INPUT_LIMIT_BYTES / 3) + 1)}"`;
295305
writeFileSync(filePath, content, "utf-8");
296-
const rt = createTestRuntime();
297-
298-
await pathResolveCommand("oc://oversized.json/value", { cwd: workspaceDir, json: true }, rt);
299-
300-
expect(rt.exitCode).toBe(2);
301-
expect(stdoutText(rt)).toBe("");
302-
expect(JSON.parse(stderrText(rt))).toMatchObject({
303-
error: { code: "OC_JSONC_INPUT_TOO_LARGE" },
304-
});
306+
const unboundedRead = vi
307+
.spyOn(fs, "readFile")
308+
.mockRejectedValue(new Error("unbounded file read"));
309+
const cases: ReadonlyArray<{
310+
code: string;
311+
run: (runtime: TestRuntime) => Promise<void>;
312+
}> = [
313+
{
314+
code: "OC_JSONC_INPUT_TOO_LARGE",
315+
run: (runtime) =>
316+
pathResolveCommand(
317+
"oc://oversized.json/value",
318+
{ file: filePath, json: true },
319+
runtime,
320+
),
321+
},
322+
{
323+
code: "OC_JSONC_INPUT_TOO_LARGE",
324+
run: (runtime) =>
325+
pathFindCommand("oc://oversized.json/*", { file: filePath, json: true }, runtime),
326+
},
327+
{
328+
code: "OC_JSONC_INPUT_TOO_LARGE",
329+
run: (runtime) =>
330+
pathSetCommand(
331+
"oc://oversized.json/value",
332+
"next",
333+
{ file: filePath, json: true, dryRun: true },
334+
runtime,
335+
),
336+
},
337+
{
338+
code: "OC_JSONC_INPUT_TOO_LARGE",
339+
run: (runtime) => pathEmitCommand(filePath, { json: true }, runtime),
340+
},
341+
{
342+
code: "OC_PATH_INPUT_TOO_LARGE",
343+
run: (runtime) =>
344+
pathResolveCommand("oc://oversized.md/value", { file: filePath, json: true }, runtime),
345+
},
346+
];
347+
348+
try {
349+
for (const testCase of cases) {
350+
const rt = createTestRuntime();
351+
await testCase.run(rt);
352+
expect(rt.exitCode).toBe(2);
353+
expect(stdoutText(rt)).toBe("");
354+
expect(JSON.parse(stderrText(rt))).toMatchObject({
355+
error: { code: testCase.code },
356+
});
357+
}
358+
expect(unboundedRead).not.toHaveBeenCalled();
359+
} finally {
360+
unboundedRead.mockRestore();
361+
}
305362
});
363+
364+
it.runIf(process.platform !== "win32")(
365+
"rejects a FIFO without waiting for a writer",
366+
async () => {
367+
const fifoPath = join(workspaceDir, "input.json");
368+
execFileSync("mkfifo", [fifoPath]);
369+
const releaseBlockedReader = setTimeout(() => {
370+
const fd = openSync(fifoPath, fsConstants.O_WRONLY | fsConstants.O_NONBLOCK);
371+
writeSync(fd, '{"ok":true}');
372+
closeSync(fd);
373+
}, 250);
374+
const rt = createTestRuntime();
375+
376+
try {
377+
await pathResolveCommand("oc://input.json/ok", { file: fifoPath, json: true }, rt);
378+
} finally {
379+
clearTimeout(releaseBlockedReader);
380+
}
381+
382+
expect(rt.exitCode).toBe(2);
383+
expect(JSON.parse(stderrText(rt))).toMatchObject({
384+
error: { code: "OC_PATH_FILE_NOT_REGULAR" },
385+
});
386+
},
387+
);
306388
});
307389

308390
describe("set", () => {

‎extensions/oc-path/src/cli.ts‎

Lines changed: 66 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66
* / `--human` override.
77
*/
88

9-
import { promises as fs } from "node:fs";
9+
import { constants as fsConstants, promises as fs } from "node:fs";
1010
import { resolve as resolvePath } from "node:path";
1111
import type { Command } from "commander";
1212
import {
13+
MAX_JSONC_INPUT_BYTES,
1314
OcEmitSentinelError,
1415
OcPathError,
1516
REDACTED_SENTINEL,
@@ -50,6 +51,15 @@ interface PathCommandOptions {
5051

5152
type OutputMode = "human" | "json";
5253

54+
// Keep every parser behind the shipped JSONC ceiling so user-selected files
55+
// cannot allocate an unbounded input before format-specific validation runs.
56+
const MAX_OC_PATH_INPUT_BYTES = MAX_JSONC_INPUT_BYTES;
57+
58+
type LoadedOcPathFile = {
59+
readonly ast: OcAst;
60+
readonly raw: string;
61+
};
62+
5363
const SCRUB_PLACEHOLDER = "[REDACTED]";
5464

5565
const defaultRuntime: OutputRuntimeEnv = {
@@ -160,14 +170,47 @@ function catchSentinel<T>(
160170
}
161171
}
162172

163-
async function loadAst(
173+
async function loadOcPathFile(
164174
absPath: string,
165175
fileName: string,
166176
runtime: OutputRuntimeEnv,
167177
mode: OutputMode,
168-
): Promise<OcAst | null> {
169-
const raw = await fs.readFile(absPath, "utf-8");
178+
): Promise<LoadedOcPathFile | null> {
170179
const kind = inferKind(fileName);
180+
// A blocking open can hang on a FIFO before stat can reject it. O_NONBLOCK
181+
// preserves regular-file and symlink reads while making that check reachable.
182+
const handle = await fs.open(absPath, fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
183+
let raw: string;
184+
try {
185+
const stat = await handle.stat();
186+
if (!stat.isFile()) {
187+
emitError(runtime, mode, `not a regular file: ${absPath}`, "OC_PATH_FILE_NOT_REGULAR");
188+
runtime.exit(2);
189+
return null;
190+
}
191+
// `end` is inclusive, so a raced growth can return at most the cap plus one byte.
192+
const bytes =
193+
stat.size > MAX_OC_PATH_INPUT_BYTES
194+
? null
195+
: Buffer.concat(
196+
await handle
197+
.createReadStream({ autoClose: false, end: MAX_OC_PATH_INPUT_BYTES, start: 0 })
198+
.toArray(),
199+
);
200+
if (bytes === null || bytes.length > MAX_OC_PATH_INPUT_BYTES) {
201+
emitError(
202+
runtime,
203+
mode,
204+
`input exceeds ${MAX_OC_PATH_INPUT_BYTES} bytes${stat.size > MAX_OC_PATH_INPUT_BYTES ? `; got ${stat.size}` : ""}`,
205+
kind === "jsonc" ? "OC_JSONC_INPUT_TOO_LARGE" : "OC_PATH_INPUT_TOO_LARGE",
206+
);
207+
runtime.exit(2);
208+
return null;
209+
}
210+
raw = bytes.toString("utf8");
211+
} finally {
212+
await handle.close();
213+
}
171214
if (kind === "jsonc") {
172215
const result = parseJsonc(raw);
173216
const sizeDiagnostic = result.diagnostics.find(
@@ -178,15 +221,15 @@ async function loadAst(
178221
runtime.exit(2);
179222
return null;
180223
}
181-
return result.ast;
224+
return { ast: result.ast, raw };
182225
}
183226
if (kind === "jsonl") {
184-
return parseJsonl(raw).ast;
227+
return { ast: parseJsonl(raw).ast, raw };
185228
}
186229
if (kind === "yaml") {
187-
return parseYaml(raw).ast;
230+
return { ast: parseYaml(raw).ast, raw };
188231
}
189-
return parseMd(raw).ast;
232+
return { ast: parseMd(raw).ast, raw };
190233
}
191234

192235
function emitForKind(ast: OcAst, fileName?: string): string {
@@ -297,13 +340,13 @@ async function pathResolveCommand(
297340
if (ocPath === null) {
298341
return;
299342
}
300-
const ast = await loadAst(resolveFsPath(ocPath, options), ocPath.file, runtime, mode);
301-
if (ast === null) {
343+
const loaded = await loadOcPathFile(resolveFsPath(ocPath, options), ocPath.file, runtime, mode);
344+
if (loaded === null) {
302345
return;
303346
}
304347
let match: OcMatch | null;
305348
try {
306-
match = resolveOcPath(ast, ocPath);
349+
match = resolveOcPath(loaded.ast, ocPath);
307350
} catch (err) {
308351
if (err instanceof OcPathError) {
309352
// resolveOcPath throws on wildcard patterns — point at find.
@@ -349,14 +392,13 @@ async function pathSetCommand(
349392
return;
350393
}
351394
const fsPath = resolveFsPath(ocPath, options);
352-
const oldBytes = await fs.readFile(fsPath, "utf-8");
353-
const ast = await loadAst(fsPath, ocPath.file, runtime, mode);
354-
if (ast === null) {
395+
const loaded = await loadOcPathFile(fsPath, ocPath.file, runtime, mode);
396+
if (loaded === null) {
355397
return;
356398
}
357399

358400
const result = catchSentinel("set", runtime, mode, () =>
359-
setOcPath(ast, ocPath, value, { valueJson: options.valueJson === true }),
401+
setOcPath(loaded.ast, ocPath, value, { valueJson: options.valueJson === true }),
360402
);
361403
if (result === null) {
362404
return;
@@ -381,7 +423,8 @@ async function pathSetCommand(
381423
const byteLength = Buffer.byteLength(newBytes, "utf8");
382424

383425
if (options.dryRun === true) {
384-
const diff = options.diff === true ? formatUnifiedDiff(oldBytes, newBytes, fsPath) : undefined;
426+
const diff =
427+
options.diff === true ? formatUnifiedDiff(loaded.raw, newBytes, fsPath) : undefined;
385428
emit(
386429
runtime,
387430
mode,
@@ -427,11 +470,11 @@ async function pathFindCommand(
427470
runtime.exit(2);
428471
return;
429472
}
430-
const ast = await loadAst(resolveFsPath(pattern, options), pattern.file, runtime, mode);
431-
if (ast === null) {
473+
const loaded = await loadOcPathFile(resolveFsPath(pattern, options), pattern.file, runtime, mode);
474+
if (loaded === null) {
432475
return;
433476
}
434-
const matches = findOcPaths(ast, pattern);
477+
const matches = findOcPaths(loaded.ast, pattern);
435478
emit(
436479
runtime,
437480
mode,
@@ -529,16 +572,16 @@ async function pathEmitCommand(
529572
? resolvePath(options.file)
530573
: resolvePath(options.cwd ?? process.cwd(), fileArg);
531574
const fileName = fsPath.split(/[\\/]/).pop() ?? fileArg;
532-
const ast = await loadAst(fsPath, fileName, runtime, mode);
533-
if (ast === null) {
575+
const loaded = await loadOcPathFile(fsPath, fileName, runtime, mode);
576+
if (loaded === null) {
534577
return;
535578
}
536-
const bytes = catchSentinel("emit", runtime, mode, () => emitForKind(ast, fileName));
579+
const bytes = catchSentinel("emit", runtime, mode, () => emitForKind(loaded.ast, fileName));
537580
if (bytes === null) {
538581
return;
539582
}
540583
if (mode === "json") {
541-
runtime.writeStdout(scrubSentinel(JSON.stringify({ ok: true, kind: ast.kind, bytes })));
584+
runtime.writeStdout(scrubSentinel(JSON.stringify({ ok: true, kind: loaded.ast.kind, bytes })));
542585
return;
543586
}
544587
runtime.writeStdout(bytes);

‎extensions/oc-path/src/oc-path/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export type { OcPath } from "./oc-path.js";
1111
export { OcPathError, formatOcPath, parseOcPath } from "./oc-path.js";
1212

1313
export { parseMd } from "./parse.js";
14-
export { parseJsonc } from "./jsonc/parse.js";
14+
export { MAX_JSONC_INPUT_BYTES, parseJsonc } from "./jsonc/parse.js";
1515
export { parseJsonl } from "./jsonl/parse.js";
1616
export { parseYaml } from "./yaml/parse.js";
1717

‎extensions/oc-path/src/oc-path/jsonc/parse.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const MAX_PARSE_DEPTH = 256;
1919
* by patching this constant — no SDK affordance because it isn't a
2020
* supported configuration.
2121
*/
22-
const MAX_JSONC_INPUT_BYTES = 16 * 1024 * 1024;
22+
export const MAX_JSONC_INPUT_BYTES = 16 * 1024 * 1024;
2323
const JSONC_PARSE_INVALID_SYMBOL = 1;
2424
const JSONC_PARSE_END_OF_FILE_EXPECTED = 9;
2525

0 commit comments

Comments
 (0)