Skip to content

Commit 5b8920b

Browse files
steipeteobviyus
andcommitted
refactor(doctor): tighten legacy approval recovery
Reuse JSON normalization and the preflight guard, preserve strict canonical policy parsing, and consolidate migration regressions with node-host and cleanup-retry coverage. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 3301b6d commit 5b8920b

6 files changed

Lines changed: 102 additions & 102 deletions

‎docs/tools/exec-approvals.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,14 @@ directory. After upgrading from a file-backed release, stop the Gateway and run
117117
`plugin-binding-approvals.json` only when it belongs to the active state
118118
directory.
119119

120+
Legacy allowlist entries may contain `null` for `lastUsedAt` or
121+
`lastUsedCommand`. Doctor treats those two usage fields as absent during
122+
import, including when the config still needs repair. This does not relax
123+
canonical policy validation: other malformed fields or conflicting legacy
124+
policies remain preserved for operator recovery, and exec approvals stay
125+
blocked until the legacy file is resolved. After repair, verify with
126+
`openclaw approvals get` using the same state directory.
127+
120128
Example schema:
121129

122130
```json

‎src/commands/doctor-config-preflight.ts‎

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -411,31 +411,23 @@ export async function runDoctorConfigPreflight(
411411
if (gatewayStartupCheckpointRequired && !freshConfigGuardAllowed) {
412412
throwStartupMigrationGuardRejected();
413413
}
414-
if (
415-
stateDirMigrations &&
416-
stateMigrationsAllowed &&
417-
freshConfigGuardAllowed &&
418-
options.doctorOnlyStateMigrations === true
419-
) {
420-
const { detectLegacyExecApprovals, migrateLegacyExecApprovals } =
421-
await import("../infra/state-migrations.exec-approvals.js");
422-
const stateDir = resolveStateDir(process.env);
423-
// Exec approvals are state-root policy. Repair them before config validity
424-
// decides which config-dependent migration graph is safe to run.
425-
noteStartupStateMigrationResult(
426-
await measurePreflightStep("exec-approvals-migration", () =>
427-
migrateLegacyExecApprovals({
428-
detected: detectLegacyExecApprovals({
414+
if (stateDirMigrations && stateMigrationsAllowed && freshConfigGuardAllowed) {
415+
if (options.doctorOnlyStateMigrations === true) {
416+
const { detectLegacyExecApprovals, migrateLegacyExecApprovals } =
417+
await import("../infra/state-migrations.exec-approvals.js");
418+
const stateDir = resolveStateDir(process.env);
419+
// Exec approvals are state-root policy. Repair them before config validity
420+
// decides which config-dependent migration graph is safe to run.
421+
noteStartupStateMigrationResult(
422+
await measurePreflightStep("exec-approvals-migration", () =>
423+
migrateLegacyExecApprovals({
424+
detected: detectLegacyExecApprovals({ stateDir, doctorOnlyStateMigrations: true }),
429425
stateDir,
430-
doctorOnlyStateMigrations: true,
426+
env: process.env,
431427
}),
432-
stateDir,
433-
env: process.env,
434-
}),
435-
),
436-
);
437-
}
438-
if (stateDirMigrations && stateMigrationsAllowed && freshConfigGuardAllowed) {
428+
),
429+
);
430+
}
439431
if (gatewayStartupCheckpointRequired && (snapshot.valid || automaticStartupRepair)) {
440432
if (!startupMigrationLease) {
441433
throw new Error("Startup plugin host-link repair requires the startup migration lease.");

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,10 @@ describe("persisted exec approvals schema", () => {
197197
{ name: "version", value: { version: 2 } },
198198
{ name: "socket token", value: { version: 1, socket: { token: 42 } } },
199199
{ name: "policy enum", value: { version: 1, defaults: { security: "none" } } },
200+
...["lastUsedAt", "lastUsedCommand"].map((field) => ({
201+
name: `null ${field}`,
202+
value: { version: 1, agents: { main: { allowlist: [{ pattern: "ls", [field]: null }] } } },
203+
})),
200204
{
201205
name: "allowlist metadata",
202206
value: {

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

Lines changed: 54 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -105,50 +105,26 @@ describe("legacy exec approvals migration", () => {
105105
);
106106
});
107107

108-
it("imports, verifies, receipts, and removes valid legacy policy", async () => {
108+
it.each([
109+
{ name: "absent", usage: {} },
110+
{ name: "historical null", usage: { lastUsedAt: null, lastUsedCommand: null } },
111+
])("imports $name usage metadata and releases the runtime gate", async ({ usage }) => {
109112
const { env, stateDir, sourcePath } = useStateDir();
110113
const expected = {
111114
version: 1 as const,
112115
socket: { path: "/tmp/approvals.sock", token: "secret" },
113116
defaults: { security: "allowlist" as const, ask: "on-miss" as const },
114-
agents: { main: { allowlist: [{ pattern: "/usr/bin/rg" }] } },
115-
};
116-
await writeLegacy(sourcePath, expected);
117-
118-
const result = await migrate({ env, stateDir });
119-
120-
expect(result.warnings).toEqual([]);
121-
expect(result.changes).toEqual(["Imported legacy exec approvals into shared SQLite state."]);
122-
const importedRaw = readExecApprovalsConfigRow(database(env))?.raw_json;
123-
expect(importedRaw).toContain('"pattern": "/usr/bin/rg"');
124-
expect(importedRaw).toContain('"id":');
125-
expect(fs.existsSync(sourcePath)).toBe(false);
126-
expect(receipt(env)).toMatchObject({
127-
removed_source: 1,
128-
source_record_count: 1,
129-
status: "completed",
130-
target_table: "exec_approvals_config",
131-
});
132-
expect(runReceipt(env)).toMatchObject({ status: "completed" });
133-
});
134-
135-
it("imports historical null allowlist usage metadata and releases the runtime gate", async () => {
136-
const { env, stateDir, sourcePath } = useStateDir();
137-
await writeLegacy(sourcePath, {
138-
version: 1,
139-
defaults: { security: "allowlist" },
140117
agents: {
141-
main: {
118+
main: { allowlist: [{ pattern: "/usr/bin/rg", ...usage }] },
119+
"*": {
142120
allowlist: [
143-
{
144-
pattern: "/usr/bin/rg",
145-
lastUsedAt: null,
146-
lastUsedCommand: null,
147-
},
121+
{ pattern: "/usr/bin/unused", ...usage },
122+
{ pattern: "/usr/bin/used", lastUsedAt: 0, lastUsedCommand: "" },
148123
],
149124
},
150125
},
151-
});
126+
};
127+
await writeLegacy(sourcePath, expected);
152128
setTestEnvValue("OPENCLAW_STATE_DIR", stateDir);
153129
execApprovalsStoreTesting.reset();
154130
expect(() => loadExecApprovals()).toThrow(ExecApprovalsMigrationRequiredError);
@@ -161,13 +137,23 @@ describe("legacy exec approvals migration", () => {
161137
"Removed retired exec approvals JSON after recording its migration decision.",
162138
]);
163139
const imported = loadExecApprovals();
140+
expect(imported.defaults).toMatchObject(expected.defaults);
141+
expect(imported.socket).toEqual(expected.socket);
164142
expect(imported.agents?.main?.allowlist).toEqual([
165-
expect.objectContaining({ pattern: "/usr/bin/rg" }),
143+
{ id: expect.any(String), pattern: "/usr/bin/rg" },
144+
]);
145+
expect(imported.agents?.["*"]?.allowlist).toEqual([
146+
{ id: expect.any(String), pattern: "/usr/bin/unused" },
147+
{ id: expect.any(String), pattern: "/usr/bin/used", lastUsedAt: 0, lastUsedCommand: "" },
166148
]);
167-
expect(imported.agents?.main?.allowlist?.[0]).not.toHaveProperty("lastUsedAt");
168-
expect(imported.agents?.main?.allowlist?.[0]).not.toHaveProperty("lastUsedCommand");
169149
expect(fs.existsSync(sourcePath)).toBe(false);
170-
expect(receipt(env)).toMatchObject({ removed_source: 1, status: "completed" });
150+
expect(receipt(env)).toMatchObject({
151+
removed_source: 1,
152+
source_record_count: 1,
153+
status: "completed",
154+
target_table: "exec_approvals_config",
155+
});
156+
expect(runReceipt(env)).toMatchObject({ status: "completed" });
171157
});
172158

173159
it("is idempotent after successful source removal", async () => {
@@ -179,37 +165,42 @@ describe("legacy exec approvals migration", () => {
179165
expect(receipt(env)).toMatchObject({ removed_source: 1 });
180166
});
181167

182-
it("preserves malformed bytes and records a non-removal receipt", async () => {
168+
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 }] } },
180+
}),
181+
})),
182+
{
183+
name: "null policy",
184+
raw: JSON.stringify({
185+
version: 1,
186+
defaults: { security: null },
187+
agents: { main: { allowlist: [{ pattern: "secret-marker", lastUsedAt: null }] } },
188+
}),
189+
},
190+
])("preserves malformed $name and records a non-removal receipt", async ({ raw }) => {
183191
const { env, stateDir, sourcePath } = useStateDir();
184-
await fsp.writeFile(sourcePath, "{malformed-secret-marker", "utf8");
192+
await fsp.writeFile(sourcePath, raw, "utf8");
185193

186194
const result = await migrate({ env, stateDir });
187195

188196
expect(result.changes).toEqual([]);
189197
expect(result.warnings[0]).toContain("Preserved malformed legacy exec approvals");
190198
expect(JSON.stringify(result)).not.toContain("secret-marker");
191-
expect(fs.readFileSync(sourcePath, "utf8")).toContain("secret-marker");
199+
expect(fs.readFileSync(sourcePath, "utf8")).toBe(raw);
192200
expect(receipt(env)).toMatchObject({ removed_source: 0, source_record_count: 0 });
193201
expect(readExecApprovalsConfigRow(database(env))).toBeUndefined();
194202
});
195203

196-
it("keeps null metadata outside the historical fields invalid", async () => {
197-
const { env, stateDir, sourcePath } = useStateDir();
198-
await writeLegacy(sourcePath, {
199-
version: 1,
200-
agents: {
201-
main: { allowlist: [{ pattern: "/usr/bin/rg", lastResolvedPath: null }] },
202-
},
203-
});
204-
205-
const result = await migrate({ env, stateDir });
206-
207-
expect(result.changes).toEqual([]);
208-
expect(result.warnings[0]).toContain("Preserved malformed legacy exec approvals");
209-
expect(fs.existsSync(sourcePath)).toBe(true);
210-
expect(readExecApprovalsConfigRow(database(env))).toBeUndefined();
211-
});
212-
213204
it("removes a byte-identical source when canonical state already exists", async () => {
214205
const { env, stateDir, sourcePath } = useStateDir();
215206
const file = { version: 1 as const, defaults: { security: "deny" as const }, agents: {} };
@@ -300,9 +291,12 @@ describe("legacy exec approvals migration", () => {
300291
expect(receipt(env)).toBeUndefined();
301292
});
302293

303-
it("retains the claim after cleanup failure and converges on retry", async () => {
294+
it("retains the null-metadata source claim after cleanup failure and converges on retry", async () => {
304295
const { env, stateDir, sourcePath } = useStateDir();
305-
await writeLegacy(sourcePath, { version: 1, agents: {} });
296+
await writeLegacy(sourcePath, {
297+
version: 1,
298+
agents: { main: { allowlist: [{ pattern: "/usr/bin/rg", lastUsedAt: null }] } },
299+
});
306300
const first = await migrate({
307301
env,
308302
stateDir,

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

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Doctor-only import for the retired exec approvals JSON store.
22
import { isDeepStrictEqual } from "node:util";
33
import { root, type Root } from "@openclaw/fs-safe";
4+
import { safeParseJsonRecord } from "@openclaw/normalization-core/json-coercion";
45
import { isRecord } from "@openclaw/normalization-core/record-coerce";
56
import { runOpenClawStateWriteTransaction } from "../state/openclaw-state-db.js";
67
import {
@@ -45,13 +46,8 @@ type MigrationDecision =
4546
| "receipt-authoritative";
4647

4748
function normalizeLegacyNullableUsageMetadata(raw: string): string {
48-
let parsed: unknown;
49-
try {
50-
parsed = JSON.parse(raw);
51-
} catch {
52-
return raw;
53-
}
54-
if (!isRecord(parsed) || !isRecord(parsed.agents)) {
49+
const parsed = safeParseJsonRecord(raw);
50+
if (!parsed || !isRecord(parsed.agents)) {
5551
return raw;
5652
}
5753

@@ -64,15 +60,13 @@ function normalizeLegacyNullableUsageMetadata(raw: string): string {
6460
if (!isRecord(entry)) {
6561
continue;
6662
}
67-
// Older writers stored never-used optional metadata as null. Repair it only at
68-
// Doctor import so canonical persisted-policy validation remains fail-closed.
69-
if (entry.lastUsedAt === null) {
70-
delete entry.lastUsedAt;
71-
changed = true;
72-
}
73-
if (entry.lastUsedCommand === null) {
74-
delete entry.lastUsedCommand;
75-
changed = true;
63+
// Legacy files can contain null usage metadata. Repair only these fields at
64+
// import so canonical policy validation remains strict.
65+
for (const key of ["lastUsedAt", "lastUsedCommand"]) {
66+
if (entry[key] === null) {
67+
delete entry[key];
68+
changed = true;
69+
}
7670
}
7771
}
7872
}

‎src/node-host/startup-state-migrations.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,11 @@ describe("node-host startup state migrations", () => {
7979
`${JSON.stringify({
8080
version: 1,
8181
defaults: { security: "deny" },
82-
agents: {},
82+
agents: {
83+
main: {
84+
allowlist: [{ pattern: "/usr/bin/rg", lastUsedAt: null, lastUsedCommand: null }],
85+
},
86+
},
8387
})}\n`,
8488
);
8589
return sourcePath;
@@ -100,7 +104,7 @@ describe("node-host startup state migrations", () => {
100104
expect(log.warn).not.toHaveBeenCalled();
101105
});
102106

103-
it("migrates legacy exec approvals into the canonical store", async () => {
107+
it("migrates legacy null exec usage metadata into the canonical store", async () => {
104108
const { env, stateDir } = useStateDir();
105109
const sourcePath = await writeExecApprovals(env);
106110
setTestEnvValue("OPENCLAW_STATE_DIR", stateDir);
@@ -109,7 +113,11 @@ describe("node-host startup state migrations", () => {
109113
await runStartupMigrations({ env, log });
110114

111115
expect(fs.existsSync(sourcePath)).toBe(false);
112-
expect(loadExecApprovals().defaults?.security).toBe("deny");
116+
const imported = loadExecApprovals();
117+
expect(imported.defaults?.security).toBe("deny");
118+
expect(imported.agents?.main?.allowlist).toEqual([
119+
{ id: expect.any(String), pattern: "/usr/bin/rg" },
120+
]);
113121
expect(log.info).toHaveBeenCalledWith(
114122
"Imported legacy exec approvals into shared SQLite state.",
115123
);

0 commit comments

Comments
 (0)