Skip to content

Commit 2c10967

Browse files
committed
fix(doctor): identify malformed legacy exec approval fields
1 parent 692cb7b commit 2c10967

4 files changed

Lines changed: 274 additions & 39 deletions

File tree

‎docs/cli/doctor.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,10 @@ the container normally.
252252

253253
Doctor reports interrupted auth-profile archive recovery even when no new migration remains or you decline another migration. If recovery cannot finish, its warning includes the failure cause and leaves the pending source for recovery; do not delete it to silence the warning.
254254

255+
For malformed legacy `exec-approvals.json`, Doctor preserves the original bytes and reports the first validation problem, for example `agents entry #2.allowlist[1].lastUsedAt: expected a finite number`. Agent entries are numbered from 1 in JavaScript `Object.keys` order; allowlist indices start at 0. This can differ from JSON text order, especially for numeric keys. To locate entry #2 locally, use `Object.keys(JSON.parse(raw).agents)[1]`, where `raw` is the file contents. Diagnostics omit agent keys and policy values, and migration receipts contain no diagnostic detail. JSON syntax and invalid UTF-8 receive separate reasons.
256+
257+
Repair the preserved file locally, then rerun `openclaw doctor --fix` with the same `OPENCLAW_STATE_DIR` setting (leave it unset if it was unset before). Exec approvals remain blocked until migration succeeds. Do not delete the file or broaden its policy to bypass validation.
258+
255259
Agent database schema upgrades are reported with the database path and the observed before and after versions, independently of media rewrites. The media persistence message appears only when transcript sessions or trajectory rows were rewritten and includes both counts. A run that does both reports both; an unchanged rerun reports neither.
256260

257261
Device Pair and Active Memory legacy JSON imports check namespace capacity before writing. If the missing entries do not fit, doctor warns and leaves the source unchanged. These imports also verify that source keys and pre-existing destination keys remain in SQLite before reporting completion and archiving the source. A retention warning keeps the source available for inspection and retry; do not delete it to silence the warning, because it may contain state that SQLite did not retain. Resolve the capacity problem before rerunning `openclaw doctor --fix`.

‎src/infra/exec-approvals-config.ts‎

Lines changed: 122 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { randomBytes } from "node:crypto";
33
import path from "node:path";
44
import { isRecord } from "@openclaw/normalization-core/record-coerce";
5+
import { err, ok, type Result } from "@openclaw/normalization-core/result";
56
import {
67
normalizeLowercaseStringOrEmpty,
78
normalizeOptionalString,
@@ -128,18 +129,133 @@ export function createFailClosedExecApprovalsFallback(): ExecApprovalsFile {
128129
});
129130
}
130131

131-
/** Parse only structurally valid persisted approvals without inventing fallback policy. */
132-
export function tryParsePersistedExecApprovals(raw: string): ExecApprovalsFile | null {
132+
// Only schema field names may enter diagnostics; agent keys are always replaced by ordinals.
133+
const diagnosticFields = new Set([
134+
"version",
135+
"socket",
136+
"path",
137+
"token",
138+
"defaults",
139+
"agents",
140+
"security",
141+
"ask",
142+
"askFallback",
143+
"autoAllowSkills",
144+
"allowlist",
145+
"pattern",
146+
"id",
147+
"source",
148+
"commandText",
149+
"argPattern",
150+
"lastUsedAt",
151+
"lastUsedCommand",
152+
"lastResolvedPath",
153+
]);
154+
155+
function formatPersistedExecApprovalsIssue(issue: z.core.$ZodIssue, parsed: unknown): string {
156+
// Only the object arm has field issues. The string arm's root error would
157+
// misdiagnose object metadata; Zod's union child paths are relative.
158+
const fieldIssue =
159+
issue.code === "invalid_union"
160+
? issue.errors[1]?.find((child) => child.path.length === 1)
161+
: undefined;
162+
const detail = fieldIssue ?? issue;
163+
const issuePath = fieldIssue ? [...issue.path, ...fieldIssue.path] : issue.path;
164+
let location = "";
165+
// The schema has at most five path segments. Fixed field names and numeric
166+
// indices bound the output even when source keys or values are enormous.
167+
for (const [index, segment] of issuePath.slice(0, 5).entries()) {
168+
if (index === 1 && issuePath[0] === "agents") {
169+
const agents = isRecord(parsed) && isRecord(parsed.agents) ? parsed.agents : {};
170+
const ordinal = typeof segment === "string" ? Object.keys(agents).indexOf(segment) + 1 : 0;
171+
if (!ordinal) {
172+
break;
173+
}
174+
location += ` entry #${ordinal}`;
175+
} else if (
176+
index === 3 &&
177+
issuePath[2] === "allowlist" &&
178+
typeof segment === "number" &&
179+
Number.isSafeInteger(segment) &&
180+
segment >= 0
181+
) {
182+
location += `[${segment}]`;
183+
} else if (typeof segment === "string" && diagnosticFields.has(segment)) {
184+
location += `${location ? "." : ""}${segment}`;
185+
} else {
186+
break;
187+
}
188+
}
189+
let reason = "invalid value";
190+
switch (detail.code) {
191+
case "invalid_type":
192+
switch (detail.expected) {
193+
case "string":
194+
reason = "expected a string";
195+
break;
196+
case "number":
197+
reason = "expected a finite number";
198+
break;
199+
case "boolean":
200+
reason = "expected a boolean";
201+
break;
202+
case "array":
203+
reason = "expected an array";
204+
break;
205+
case "object":
206+
reason = "expected an object";
207+
break;
208+
default:
209+
break;
210+
}
211+
break;
212+
case "invalid_value":
213+
reason = "expected a supported value";
214+
break;
215+
case "invalid_union":
216+
reason = "expected a non-empty string or an object with a non-empty pattern";
217+
break;
218+
case "too_small":
219+
reason = "expected a non-empty string";
220+
break;
221+
case "custom":
222+
if (issuePath.at(-1) === "pattern") {
223+
reason = "expected a non-empty string";
224+
}
225+
break;
226+
default:
227+
// Other Zod issue kinds retain a value-free reason, never raw error text.
228+
break;
229+
}
230+
return `${location || "document"}: ${reason}`;
231+
}
232+
233+
/** Validate canonical policy and expose only a bounded, value-free failure diagnostic. */
234+
export function parsePersistedExecApprovals(raw: string): Result<ExecApprovalsFile, string> {
235+
let parsed: unknown;
236+
try {
237+
parsed = JSON.parse(raw) as unknown;
238+
} catch {
239+
return err("invalid JSON syntax");
240+
}
133241
try {
134-
const parsed = JSON.parse(raw) as unknown;
135242
const result = persistedExecApprovalsSchema.safeParse(parsed);
136243
if (result.success) {
137-
return normalizeExecApprovalsInternal(result.data);
244+
return ok(normalizeExecApprovalsInternal(result.data));
138245
}
246+
const issue = result.error.issues[0];
247+
return err(
248+
issue ? formatPersistedExecApprovalsIssue(issue, parsed) : "invalid approvals structure",
249+
);
139250
} catch {
140-
// A partial Windows fallback write is existing state, not a missing policy.
251+
return err("invalid approvals structure");
141252
}
142-
return null;
253+
}
254+
255+
/** Parse only structurally valid persisted approvals without inventing fallback policy. */
256+
export function tryParsePersistedExecApprovals(raw: string): ExecApprovalsFile | null {
257+
const result = parsePersistedExecApprovals(raw);
258+
return result.ok ? result.value : null;
143259
}
144260

145261
function normalizeAllowlistPattern(value: string | undefined): string | null {

‎src/infra/state-migrations.exec-approvals.test.ts‎

Lines changed: 133 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Covers Doctor-only import of the retired exec approvals JSON file.
2+
import { createHash } from "node:crypto";
23
import fs from "node:fs";
34
import fsp from "node:fs/promises";
45
import { afterEach, describe, expect, it } from "vitest";
@@ -165,41 +166,147 @@ describe("legacy exec approvals migration", () => {
165166
expect(receipt(env)).toMatchObject({ removed_source: 1 });
166167
});
167168

169+
function legacyWithInvalidEntry(entry: unknown, agentKey = "private-marker-agent"): string {
170+
return JSON.stringify({
171+
version: 1,
172+
socket: { path: "/private-marker/socket", token: "private-marker-token" },
173+
agents: {
174+
first: { allowlist: ["/usr/bin/true"] },
175+
[agentKey]: { allowlist: ["/usr/bin/true", entry] },
176+
third: { security: "deny" },
177+
},
178+
});
179+
}
180+
168181
it.each([
169-
{ name: "invalid JSON", raw: "{malformed-secret-marker" },
170-
...[
171-
{ lastUsedAt: "now", lastUsedCommand: null },
172-
{ lastUsedAt: null, lastUsedCommand: 42 },
173-
{ lastUsedAt: null, argPattern: null },
174-
{ lastUsedCommand: null, lastResolvedPath: null },
175-
].map((metadata) => ({
176-
name: JSON.stringify(metadata),
177-
raw: JSON.stringify({
178-
version: 1,
179-
agents: { main: { allowlist: [{ pattern: "secret-marker", ...metadata }] } },
182+
{
183+
name: "metadata in the second agent's second entry",
184+
raw: legacyWithInvalidEntry({
185+
pattern: "/private-marker/pattern",
186+
id: "private-marker-id",
187+
commandText: "private-marker-command",
188+
lastUsedAt: "private-marker-time",
189+
lastUsedCommand: null,
180190
}),
191+
problem: "agents entry #2.allowlist[1].lastUsedAt: expected a finite number",
192+
},
193+
...[
194+
{ metadata: { lastUsedAt: null, lastUsedCommand: 42 }, field: "lastUsedCommand" },
195+
{ metadata: { lastUsedAt: null, argPattern: null }, field: "argPattern" },
196+
{ metadata: { lastUsedCommand: null, lastResolvedPath: null }, field: "lastResolvedPath" },
197+
].map(({ metadata, field }) => ({
198+
name: `invalid ${field} alongside historical null usage`,
199+
raw: legacyWithInvalidEntry({ pattern: "private-marker-pattern", ...metadata }),
200+
problem: `agents entry #2.allowlist[1].${field}: expected a string`,
181201
})),
182202
{
183-
name: "null policy",
203+
name: "null policy alongside historical null usage",
184204
raw: JSON.stringify({
185205
version: 1,
186206
defaults: { security: null },
187-
agents: { main: { allowlist: [{ pattern: "secret-marker", lastUsedAt: null }] } },
207+
agents: { main: { allowlist: [{ pattern: "private-marker", lastUsedAt: null }] } },
188208
}),
209+
problem: "defaults.security: expected a supported value",
189210
},
190-
])("preserves malformed $name and records a non-removal receipt", async ({ raw }) => {
191-
const { env, stateDir, sourcePath } = useStateDir();
192-
await fsp.writeFile(sourcePath, raw, "utf8");
193-
194-
const result = await migrate({ env, stateDir });
195-
196-
expect(result.changes).toEqual([]);
197-
expect(result.warnings[0]).toContain("Preserved malformed legacy exec approvals");
198-
expect(JSON.stringify(result)).not.toContain("secret-marker");
199-
expect(fs.readFileSync(sourcePath, "utf8")).toBe(raw);
200-
expect(receipt(env)).toMatchObject({ removed_source: 0, source_record_count: 0 });
201-
expect(readExecApprovalsConfigRow(database(env))).toBeUndefined();
202-
});
211+
{
212+
name: "hostile long keys, values, and multiple failures",
213+
raw: legacyWithInvalidEntry(
214+
{
215+
pattern: "/private-marker/pattern",
216+
lastUsedAt: { ["private-marker-value".repeat(1_000)]: "private-marker" },
217+
lastUsedCommand: 42,
218+
},
219+
"private-marker-\n\u001b[31m".repeat(1_000),
220+
),
221+
problem: "agents entry #2.allowlist[1].lastUsedAt: expected a finite number",
222+
},
223+
{
224+
name: "numeric-like agent key enumeration",
225+
raw: '{"version":1,"agents":{"20":{},"3":{"security":"private-marker"}}}',
226+
problem: "agents entry #1.security: expected a supported value",
227+
},
228+
{
229+
name: "policy",
230+
raw: JSON.stringify({ version: 1, defaults: { security: "private-marker" } }),
231+
problem: "defaults.security: expected a supported value",
232+
},
233+
{
234+
name: "socket token",
235+
raw: JSON.stringify({ version: 1, socket: { token: { "private-marker": true } } }),
236+
problem: "socket.token: expected a string",
237+
},
238+
{
239+
name: "whole entry shape",
240+
raw: legacyWithInvalidEntry(42),
241+
problem:
242+
"agents entry #2.allowlist[1]: expected a non-empty string or an object with a non-empty pattern",
243+
},
244+
{
245+
name: "blank string entry",
246+
raw: legacyWithInvalidEntry(" "),
247+
problem: "agents entry #2.allowlist[1]: expected a non-empty string",
248+
},
249+
{
250+
name: "blank object pattern without a union wrapper",
251+
raw: legacyWithInvalidEntry({ pattern: " " }),
252+
problem: "agents entry #2.allowlist[1].pattern: expected a non-empty string",
253+
},
254+
{
255+
name: "JSON syntax",
256+
raw: "{malformed-private-marker",
257+
problem: "invalid JSON syntax",
258+
},
259+
{
260+
name: "UTF-8 encoding",
261+
raw: Buffer.concat([Buffer.from("private-marker"), Buffer.from([0xff])]),
262+
problem: "invalid UTF-8 encoding",
263+
},
264+
])(
265+
"diagnoses $name while preserving bytes and a non-removal receipt",
266+
async ({ raw, problem }) => {
267+
const { env, stateDir, sourcePath } = useStateDir();
268+
const original = Buffer.from(raw);
269+
await fsp.writeFile(sourcePath, original);
270+
setTestEnvValue("OPENCLAW_STATE_DIR", stateDir);
271+
expect(() => loadExecApprovals()).toThrow(ExecApprovalsMigrationRequiredError);
272+
273+
const result = await migrate({ env, stateDir });
274+
275+
expect(result.changes).toEqual([]);
276+
expect(result.warnings).toEqual([
277+
`Preserved malformed legacy exec approvals for operator recovery. First problem: ${problem}. Repair exec-approvals.json locally, then rerun \`openclaw doctor --fix\` with the same OPENCLAW_STATE_DIR.`,
278+
]);
279+
expect(result.warnings[0]?.length).toBeLessThan(400);
280+
expect(JSON.stringify(result)).not.toContain("private-marker");
281+
expect(fs.readFileSync(sourcePath)).toEqual(original);
282+
expect(fs.existsSync(`${sourcePath}.doctor-importing`)).toBe(false);
283+
const sourceReceipt = receipt(env);
284+
expect(sourceReceipt).toMatchObject({
285+
removed_source: 0,
286+
source_record_count: 0,
287+
status: "completed",
288+
source_size_bytes: original.length,
289+
});
290+
const report = {
291+
source: "legacy-exec-approvals-json",
292+
target: "exec_approvals_config",
293+
decision: "malformed-legacy-preserved",
294+
sourceSha256: createHash("sha256").update(original).digest("hex"),
295+
sourceValid: false,
296+
importedRecordCount: 0,
297+
preservedSqliteRecordCount: 0,
298+
removesSource: false,
299+
};
300+
expect(JSON.parse(sourceReceipt?.report_json ?? "null")).toEqual(report);
301+
expect(JSON.parse(runReceipt(env)?.report_json ?? "null")).toEqual(report);
302+
expect(JSON.stringify([sourceReceipt, runReceipt(env)])).not.toContain("private-marker");
303+
expect(readExecApprovalsConfigRow(database(env))).toBeUndefined();
304+
expect(() => loadExecApprovals()).toThrow(ExecApprovalsMigrationRequiredError);
305+
expect(await migrate({ env, stateDir })).toEqual(result);
306+
expect(fs.readFileSync(sourcePath)).toEqual(original);
307+
expect(() => loadExecApprovals()).toThrow(ExecApprovalsMigrationRequiredError);
308+
},
309+
);
203310

204311
it("removes a byte-identical source when canonical state already exists", async () => {
205312
const { env, stateDir, sourcePath } = useStateDir();

0 commit comments

Comments
 (0)