Skip to content

Commit 8952582

Browse files
xialongleeobviyus
andauthored
fix(cli): reject non-finite config numbers (#120156)
fix(cli): reject non-finite config numbers (#120156) Reject non-finite numeric values at config parsing and serialization boundaries. Preserve root and included config files by failing before JSON.stringify. Keep retired provider bypass flags unavailable. Co-authored-by: xialonglee <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent ced723c commit 8952582

11 files changed

Lines changed: 186 additions & 4 deletions

‎src/cli/config-cli-input.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { describe, expect, it } from "vitest";
5+
import { readConfigPatchOperations } from "./config-cli-input.js";
6+
7+
async function withPatchFile<T>(
8+
contents: string,
9+
run: (patchPath: string) => Promise<T>,
10+
): Promise<T> {
11+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-config-cli-input-"));
12+
const patchPath = path.join(tempDir, "patch.json5");
13+
fs.writeFileSync(patchPath, contents, "utf8");
14+
try {
15+
return await run(patchPath);
16+
} finally {
17+
fs.rmSync(tempDir, { recursive: true, force: true });
18+
}
19+
}
20+
21+
describe("readConfigPatchOperations", () => {
22+
it("rejects patch files containing non-finite numbers", async () => {
23+
await withPatchFile('{ "channels": { "custom": { "timeout": 1e999 } } }', async (patchPath) => {
24+
await expect(readConfigPatchOperations({ file: patchPath })).rejects.toThrow(
25+
"Value must be a finite number",
26+
);
27+
});
28+
});
29+
});

‎src/cli/config-cli-input.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { isRecord as isPlainRecord } from "@openclaw/normalization-core/record-c
44
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
55
import { normalizeStringEntries } from "@openclaw/normalization-core/string-normalization";
66
import JSON5 from "json5";
7+
import { rejectConfigNonFiniteNumbers } from "../config/io.read-helpers.js";
78
import {
89
coerceSecretRef,
910
isValidEnvSecretRefId,
@@ -516,11 +517,14 @@ async function readConfigPatchInput(opts: ConfigPatchOptions): Promise<unknown>
516517
} else {
517518
raw = readConfigMutationFileSync(file as string, "--file");
518519
}
520+
let parsed: unknown;
519521
try {
520-
return JSON5.parse(raw);
522+
parsed = JSON5.parse(raw);
521523
} catch (err) {
522524
throw new Error(`Failed to parse ${sourceLabel} as JSON5: ${String(err)}`, { cause: err });
523525
}
526+
rejectConfigNonFiniteNumbers(parsed);
527+
return parsed;
524528
}
525529

526530
function buildDeleteOperation(path: PathSegment[]): ConfigSetOperation {

‎src/cli/config-cli-path.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { describe, expect, it } from "vitest";
2+
import { parseConfigSetValue } from "./config-cli-path.js";
3+
4+
describe("parseConfigSetValue", () => {
5+
it.each([
6+
{ raw: "42", expected: 42 },
7+
{ raw: "3.14", expected: 3.14 },
8+
{ raw: "-0", expected: -0 },
9+
{ raw: "true", expected: true },
10+
{ raw: "false", expected: false },
11+
{ raw: "null", expected: null },
12+
{ raw: "{a:1}", expected: { a: 1 } },
13+
{ raw: "[1,2]", expected: [1, 2] },
14+
])("parses $raw as expected", ({ raw, expected }) => {
15+
expect(parseConfigSetValue(raw, false)).toEqual(expected);
16+
});
17+
18+
it("falls back to the raw string when JSON5 parsing fails", () => {
19+
expect(parseConfigSetValue("hello", false)).toBe("hello");
20+
});
21+
22+
it.each([
23+
{ raw: "Infinity", label: "Infinity" },
24+
{ raw: "-Infinity", label: "negative Infinity" },
25+
{ raw: "NaN", label: "NaN" },
26+
{ raw: "1e999", label: "overflow exponent" },
27+
{ raw: "{timeout:1e999}", label: "object with overflow exponent" },
28+
{ raw: "[1e999]", label: "array with overflow exponent" },
29+
])("rejects $label in value mode", ({ raw }) => {
30+
expect(() => parseConfigSetValue(raw, false)).toThrow("Value must be a finite number");
31+
});
32+
33+
it("rejects overflow exponent in strict JSON mode with the finite-number error", () => {
34+
expect(() => parseConfigSetValue("1e999", true)).toThrow("Value must be a finite number");
35+
});
36+
37+
it.each([
38+
{ raw: "Infinity", label: "Infinity" },
39+
{ raw: "-Infinity", label: "negative Infinity" },
40+
{ raw: "NaN", label: "NaN" },
41+
])("rejects $label in strict JSON mode as invalid JSON", ({ raw }) => {
42+
expect(() => parseConfigSetValue(raw, true)).toThrow();
43+
});
44+
45+
it("still reports JSON parse errors in strict JSON mode", () => {
46+
expect(() => parseConfigSetValue("not-json", true)).toThrow(
47+
/(Unexpected token|Expected).*not-json/,
48+
);
49+
});
50+
});

‎src/cli/config-cli-path.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { isRecord as isPlainRecord } from "@openclaw/normalization-core/record-coerce";
22
import JSON5 from "json5";
3+
import { rejectConfigNonFiniteNumbers } from "../config/io.read-helpers.js";
34
import { isBlockedObjectKey } from "../infra/prototype-keys.js";
45
import { toDotPath } from "../shared/dot-path.js";
56
import { parseConfigPathArrayIndex } from "../shared/path-array-index.js";
@@ -161,17 +162,23 @@ export function parseConfigSetPath(path: string): string[] {
161162
export function parseConfigSetValue(raw: string, strictJson: boolean): unknown {
162163
const trimmed = raw.trim();
163164
if (strictJson) {
165+
let parsed: unknown;
164166
try {
165-
return JSON.parse(trimmed);
167+
parsed = JSON.parse(trimmed);
166168
} catch (err) {
167169
throw new Error(formatStrictJsonParseFailure({ value: raw, cause: err }), { cause: err });
168170
}
171+
rejectConfigNonFiniteNumbers(parsed);
172+
return parsed;
169173
}
174+
let parsed: unknown;
170175
try {
171-
return JSON5.parse(trimmed);
176+
parsed = JSON5.parse(trimmed);
172177
} catch {
173178
return raw;
174179
}
180+
rejectConfigNonFiniteNumbers(parsed);
181+
return parsed;
175182
}
176183

177184
export function validatePathSegments(path: PathSegment[]): void {

‎src/cli/config-set-input.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,4 +171,12 @@ describe("config set input parsing", () => {
171171
expect(parsed).toEqual([{ path: "gateway.port", value: 19000 }]);
172172
});
173173
});
174+
175+
it("rejects batch entries with non-finite numbers", () => {
176+
expect(() =>
177+
parseBatchSource({
178+
batchJson: '[{"path":"channels.custom.timeout","value":1e999}]',
179+
}),
180+
).toThrow("Value must be a finite number");
181+
});
174182
});

‎src/cli/config-set-input.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
normalizeStringifiedOptionalString,
66
} from "@openclaw/normalization-core/string-coerce";
77
import JSON5 from "json5";
8+
import { rejectConfigNonFiniteNumbers } from "../config/io.read-helpers.js";
89
import { readFileDescriptorBoundedSync } from "../infra/boundary-file-read.js";
910
import { hasErrnoCode } from "../infra/errors.js";
1011

@@ -115,11 +116,14 @@ export function hasProviderBuilderOptions(opts: ConfigSetOptions): boolean {
115116
}
116117

117118
function parseJson5Raw(raw: string, label: string): unknown {
119+
let parsed: unknown;
118120
try {
119-
return JSON5.parse(raw);
121+
parsed = JSON5.parse(raw);
120122
} catch (err) {
121123
throw new Error(`Failed to parse ${label}: ${String(err)}`, { cause: err });
122124
}
125+
rejectConfigNonFiniteNumbers(parsed);
126+
return parsed;
123127
}
124128

125129
function parseBatchEntries(raw: string, sourceLabel: string): ConfigSetBatchEntry[] {

‎src/config/io.read-helpers.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,26 @@ export function resolveGatewayMode(value: unknown): string | null {
8282
return trimmed.length > 0 ? trimmed : null;
8383
}
8484

85+
export function rejectConfigNonFiniteNumbers(value: unknown): void {
86+
if (typeof value === "number") {
87+
if (!Number.isFinite(value)) {
88+
throw new Error(`Value must be a finite number, got ${String(value)}`);
89+
}
90+
return;
91+
}
92+
if (Array.isArray(value)) {
93+
for (const entry of value) {
94+
rejectConfigNonFiniteNumbers(entry);
95+
}
96+
return;
97+
}
98+
if (isRecord(value)) {
99+
for (const entry of Object.values(value)) {
100+
rejectConfigNonFiniteNumbers(entry);
101+
}
102+
}
103+
}
104+
85105
export function collectEnvRefPaths(
86106
value: unknown,
87107
pathLocal: string,

‎src/config/io.write-config.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1671,6 +1671,25 @@ describe("config io write", () => {
16711671
expect(persisted.plugins).toEqual({});
16721672
});
16731673

1674+
itWithHome(
1675+
"rejects non-finite numbers before serializing the normal config writer",
1676+
async (home) => {
1677+
const { configPath } = await writeConfigFixture(home, {
1678+
plugins: { entries: { demo: { enabled: true } } },
1679+
});
1680+
const io = createFastConfigIO(home);
1681+
const originalRaw = await fs.readFile(configPath, "utf-8");
1682+
1683+
await expect(
1684+
io.writeConfigFile({
1685+
plugins: { entries: { demo: { enabled: true, config: { timeout: Infinity } } } },
1686+
}),
1687+
).rejects.toThrow("Value must be a finite number, got Infinity");
1688+
1689+
await expect(fs.readFile(configPath, "utf-8")).resolves.toBe(originalRaw);
1690+
},
1691+
);
1692+
16741693
it("preserves escaped root literals before validating unrelated includes", async () => {
16751694
mockLoadPluginManifestRegistry.mockReturnValue({
16761695
diagnostics: [],

‎src/config/io.write.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import {
5050
hashConfigRaw,
5151
hasConfigMeta,
5252
parseConfigJson5,
53+
rejectConfigNonFiniteNumbers,
5354
resolveConfigSnapshotHash,
5455
resolveGatewayMode,
5556
restoreAuthoredTildePathsForWrite,
@@ -421,6 +422,7 @@ export async function writeConfigFileFromContext(
421422
options.lastTouchedVersionOverride,
422423
snapshot.exists ? snapshot.parsed : null,
423424
);
425+
rejectConfigNonFiniteNumbers(stampedOutputConfig);
424426
const json = JSON.stringify(stampedOutputConfig, null, 2).trimEnd().concat("\n");
425427
const nextHash = hashConfigRaw(json);
426428
const previousHash = resolveConfigSnapshotHash(snapshot);

‎src/config/mutate.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1369,6 +1369,43 @@ describe("config mutate helpers", () => {
13691369
);
13701370
});
13711371

1372+
it("rejects non-finite numbers before serializing single-file top-level include writes", async () => {
1373+
const home = await suiteRootTracker.make("include-non-finite");
1374+
const { configPath, pluginsPath } = await createPluginIncludeFixture(home);
1375+
const initialPluginsRaw = `${JSON.stringify({ entries: {} }, null, 2)}\n`;
1376+
await fs.writeFile(pluginsPath, initialPluginsRaw, "utf-8");
1377+
const snapshot = createSnapshot({
1378+
hash: "hash-include-non-finite",
1379+
path: configPath,
1380+
parsed: { plugins: { $include: "./config/plugins.json5" } },
1381+
sourceConfig: { plugins: { entries: {} } },
1382+
});
1383+
1384+
await expect(
1385+
replaceConfigFile({
1386+
baseHash: snapshot.hash,
1387+
snapshot,
1388+
writeOptions: {
1389+
expectedConfigPath: snapshot.path,
1390+
assertConfigPathForWrite: allowConfigPathWrite,
1391+
includeFileTargetsForWrite: { [pluginsPath]: await resolveIncludeTarget(pluginsPath) },
1392+
},
1393+
nextConfig: {
1394+
plugins: {
1395+
entries: {
1396+
demo: { config: { timeout: Infinity } },
1397+
},
1398+
},
1399+
},
1400+
}),
1401+
).rejects.toThrow("Value must be a finite number, got Infinity");
1402+
1403+
await expect(fs.readFile(pluginsPath, "utf-8")).resolves.toBe(initialPluginsRaw);
1404+
await expect(fs.readFile(configPath, "utf-8")).resolves.toBe(
1405+
`${JSON.stringify({ plugins: { $include: "./config/plugins.json5" } }, null, 2)}\n`,
1406+
);
1407+
});
1408+
13721409
it("preflights single-file top-level include writes before persisting", async () => {
13731410
const home = await suiteRootTracker.make("include-runtime-preflight");
13741411
const { configPath, pluginsPath } = await createPluginIncludeFixture(home);

0 commit comments

Comments
 (0)