Skip to content

Commit ce3b4a6

Browse files
committed
fix(doctor): finish legacy exec approvals migration
1 parent a4f9f8b commit ce3b4a6

5 files changed

Lines changed: 65 additions & 153 deletions

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

Lines changed: 17 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,20 @@ describe("doctor invalid config process exit", () => {
181181
version: 1,
182182
agents: {
183183
jup: {
184-
allowlist: [{ pattern: "/usr/bin/rg", lastUsedAt: null, lastUsedCommand: null }],
184+
allowlist: [
185+
{
186+
pattern: "/usr/bin/rg",
187+
source: "allow-always",
188+
lastUsedAt: null,
189+
lastUsedCommand: null,
190+
},
191+
{
192+
pattern: "=command:durable",
193+
source: "allow-always",
194+
lastUsedAt: null,
195+
lastUsedCommand: null,
196+
},
197+
],
185198
},
186199
},
187200
}),
@@ -209,6 +222,7 @@ describe("doctor invalid config process exit", () => {
209222
expect(result.status, output).toBe(0);
210223
expect(result.signal, output).toBeNull();
211224
expect(output).toContain("Imported legacy exec approvals into shared SQLite state.");
225+
expect(output).toContain("Exec approvals updated: removed 1 older generated approval");
212226
expect(output).toContain("Doctor complete.");
213227

214228
expect(fs.existsSync(approvalsPath)).toBe(false);
@@ -219,7 +233,8 @@ describe("doctor invalid config process exit", () => {
219233
const row = database
220234
.prepare("SELECT raw_json FROM exec_approvals_config WHERE config_key = 'current'")
221235
.get() as { raw_json?: string } | undefined;
222-
expect(row?.raw_json).toContain('"pattern": "/usr/bin/rg"');
236+
expect(row?.raw_json).not.toContain('"pattern": "/usr/bin/rg"');
237+
expect(row?.raw_json).toContain('"pattern": "=command:durable"');
223238
expect(row?.raw_json).not.toContain("lastUsedAt");
224239
expect(row?.raw_json).not.toContain("lastUsedCommand");
225240
} finally {
@@ -283,120 +298,6 @@ describe("doctor invalid config process exit", () => {
283298
}, 75_000);
284299
});
285300

286-
describe("doctor legacy exec approvals process repair", () => {
287-
it("imports legacy approvals before renewing obsolete generated grants", async () => {
288-
const root = fs.realpathSync(tempDirs.make("openclaw-doctor-exec-approvals-order-"));
289-
const stateDir = path.join(root, "state");
290-
const configPath = path.join(stateDir, "openclaw.json");
291-
const sourcePath = path.join(stateDir, "exec-approvals.json");
292-
const databasePath = path.join(stateDir, "state", "openclaw.sqlite");
293-
const env: NodeJS.ProcessEnv = {
294-
...process.env,
295-
HOME: root,
296-
USERPROFILE: root,
297-
OPENCLAW_CONFIG_PATH: configPath,
298-
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
299-
OPENCLAW_NO_RESPAWN: "1",
300-
OPENCLAW_SKIP_CHANNELS: "1",
301-
OPENCLAW_STATE_DIR: stateDir,
302-
OPENCLAW_TEST_FAST: "1",
303-
NO_COLOR: "1",
304-
};
305-
delete env.NODE_ENV;
306-
delete env.NODE_OPTIONS;
307-
delete env.OPENCLAW_GATEWAY_PASSWORD;
308-
delete env.OPENCLAW_GATEWAY_TOKEN;
309-
delete env.OPENCLAW_GATEWAY_URL;
310-
delete env.OPENCLAW_HOME;
311-
delete env.VITEST;
312-
delete env.VITEST_POOL_ID;
313-
delete env.VITEST_WORKER_ID;
314-
315-
fs.mkdirSync(stateDir, { recursive: true });
316-
fs.writeFileSync(
317-
configPath,
318-
JSON.stringify({ gateway: { mode: "local", auth: { mode: "none" } } }),
319-
);
320-
fs.writeFileSync(
321-
sourcePath,
322-
JSON.stringify({
323-
version: 1,
324-
agents: {
325-
main: {
326-
allowlist: [
327-
{ pattern: "/usr/bin/rg", source: "allow-always" },
328-
{ pattern: "=command:durable", source: "allow-always" },
329-
],
330-
},
331-
},
332-
}),
333-
);
334-
const preflightUrl = new URL("./doctor-config-preflight.ts", import.meta.url).href;
335-
await runIsolatedModuleScript(
336-
env,
337-
`
338-
const { runDoctorConfigPreflight } = await import(${JSON.stringify(preflightUrl)});
339-
await runDoctorConfigPreflight({
340-
migrateLegacyConfig: false,
341-
invalidConfigNote: false,
342-
observe: false,
343-
requireStartupMigrationCheckpoint: true,
344-
beforeStateMigrations: async () => true,
345-
});
346-
`,
347-
);
348-
expect(fs.existsSync(sourcePath)).toBe(true);
349-
350-
const result = spawnSync(
351-
process.execPath,
352-
[
353-
"--import",
354-
"tsx",
355-
path.resolve("src/entry.ts"),
356-
"doctor",
357-
"--fix",
358-
"--non-interactive",
359-
"--no-workspace-suggestions",
360-
],
361-
{
362-
cwd: path.resolve("."),
363-
encoding: "utf8",
364-
env,
365-
timeout: 60_000,
366-
},
367-
);
368-
const output = `${result.stderr}\n${result.stdout}`;
369-
370-
expect(result.error, output).toBeUndefined();
371-
expect(result.status, output).toBe(0);
372-
expect(result.signal, output).toBeNull();
373-
expect(output).toContain("Doctor complete.");
374-
expect(fs.existsSync(sourcePath)).toBe(false);
375-
376-
const database = new DatabaseSync(databasePath, { readOnly: true });
377-
try {
378-
const row = database
379-
.prepare("SELECT raw_json FROM exec_approvals_config WHERE config_key = 'current'")
380-
.get() as { raw_json: string } | undefined;
381-
const approvals = JSON.parse(row?.raw_json ?? "null") as {
382-
agents?: { main?: { allowlist?: Array<{ pattern?: string }> } };
383-
} | null;
384-
expect(approvals?.agents?.main?.allowlist).toEqual([
385-
expect.objectContaining({ pattern: "=command:durable" }),
386-
]);
387-
expect(
388-
database
389-
.prepare(
390-
"SELECT status, removed_source FROM migration_sources WHERE migration_kind = 'legacy-exec-approvals-json'",
391-
)
392-
.get(),
393-
).toMatchObject({ status: "completed", removed_source: 1 });
394-
} finally {
395-
database.close();
396-
}
397-
}, 75_000);
398-
});
399-
400301
// Synchronous CLI probes must not consume neighboring cases' timeout budgets.
401302
describe("gateway startup-migration refusal", () => {
402303
it("repairs the stable upgrade config and additive state schema before readiness", async () => {

‎src/commands/doctor-security.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,11 +103,11 @@ describe("noteSecurityWarnings gateway exposure", () => {
103103
closeOpenClawStateDatabaseForTest();
104104
execApprovalsStoreTesting.reset();
105105

106-
const findings = await collectSecurityWarnings({});
106+
const findings = await collectSecurityWarnings({ approvals: { exec: { enabled: false } } });
107107

108108
expect(findings).toEqual(
109109
expect.arrayContaining([
110-
expect.objectContaining({ checkId: "doctor.exec_approvals_migration_pending" }),
110+
expect.objectContaining({ checkId: "doctor.approval_forwarding_disabled" }),
111111
]),
112112
);
113113
});

‎src/commands/doctor-security.ts‎

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -198,11 +198,7 @@ function collectExecPolicyConflictWarnings(
198198
return findings;
199199
}
200200

201-
function collectDurableExecApprovalWarnings(
202-
cfg: OpenClawConfig,
203-
approvals: ExecApprovalsFile,
204-
): SecurityAuditFinding[] {
205-
void cfg;
201+
function collectDurableExecApprovalWarnings(approvals: ExecApprovalsFile): SecurityAuditFinding[] {
206202
const count = countObsoleteGeneratedExecApprovals(approvals);
207203
if (count === 0) {
208204
return [];
@@ -317,24 +313,16 @@ export async function collectSecurityWarnings(
317313
if (!(error instanceof ExecApprovalsMigrationRequiredError)) {
318314
throw error;
319315
}
320-
// Doctor owns this migration later in the same repair flow. Security
321-
// diagnostics must not invoke the runtime gate first and make
322-
// `doctor --fix` abort with an instruction to run itself.
323-
findings.push({
324-
checkId: "doctor.exec_approvals_migration_pending",
325-
severity: "warn",
326-
title: "Exec approvals migration pending",
327-
detail: error.message,
328-
remediation: "Continue this Doctor repair to migrate the retired approvals store.",
329-
});
316+
// Preflight already reported why it preserved the legacy source.
317+
// Skip only approval-dependent checks so the rest of Doctor can continue.
330318
}
331319
if (approvals) {
332320
findings.push(...collectExecPolicyConflictWarnings(cfg, approvals));
333321
}
334322
findings.push(...collectExecFilesystemPolicyWarnings(cfg));
335323
findings.push(...collectPlaintextConfigSecretWarnings(cfg));
336324
if (approvals) {
337-
findings.push(...collectDurableExecApprovalWarnings(cfg, approvals));
325+
findings.push(...collectDurableExecApprovalWarnings(approvals));
338326
}
339327

340328
// Network exposure needs auth proof before doctor can treat non-loopback bind as intentional.

‎src/flows/doctor-health-contributions.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2203,6 +2203,30 @@ describe("doctor health contributions", () => {
22032203
});
22042204
});
22052205

2206+
it("renews exec approvals when an unrelated legacy migration is declined", async () => {
2207+
const contribution = requireDoctorContribution("doctor:legacy-state");
2208+
mocks.detectLegacyStateMigrations.mockResolvedValue({
2209+
preview: ["legacy sessions"],
2210+
warnings: [],
2211+
notices: [],
2212+
});
2213+
mocks.repairObsoleteGeneratedExecApprovals.mockReturnValue(1);
2214+
const ctx = createDoctorContext({
2215+
shouldRepair: true,
2216+
options: { repair: true },
2217+
prompter: buildDoctorPrompter(false),
2218+
});
2219+
2220+
await contribution.run(ctx);
2221+
2222+
expect(mocks.runLegacyStateMigrations).not.toHaveBeenCalled();
2223+
expect(mocks.repairObsoleteGeneratedExecApprovals).toHaveBeenCalledOnce();
2224+
expect(mocks.note).toHaveBeenCalledWith(
2225+
expect.stringContaining("removed 1 older generated approval"),
2226+
"Doctor changes",
2227+
);
2228+
});
2229+
22062230
it("prints legacy state migration notices during manual doctor runs", async () => {
22072231
const contribution = requireDoctorContribution("doctor:legacy-state");
22082232
const detected = { preview: ["legacy sessions"], warnings: [], notices: [] };

‎src/flows/doctor-health-contributions.ts‎

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -293,25 +293,24 @@ async function runLegacyStateHealth(ctx: DoctorHealthFlowContext): Promise<void>
293293
message: "Migrate detected legacy state now?",
294294
initialValue: true,
295295
});
296-
if (!migrate) {
297-
return;
298-
}
299-
const migrated = await runLegacyStateMigrations({
300-
detected: legacyState,
301-
config: ctx.cfg,
302-
...(doctorOnlyStateMigrations ? { doctorOnlyStateMigrations: true } : {}),
303-
recoverCorruptTargetStore: ctx.options.repair === true || ctx.options.yes === true,
304-
legacySessionSurfaces,
305-
});
306-
if (migrated.changes.length > 0) {
307-
note(migrated.changes.join("\n"), "Doctor changes");
308-
}
309-
const notices = migrated.notices ?? [];
310-
if (notices.length > 0) {
311-
note(notices.join("\n"), "Doctor notices");
312-
}
313-
if (migrated.warnings.length > 0) {
314-
note(migrated.warnings.join("\n"), "Doctor warnings");
296+
if (migrate) {
297+
const migrated = await runLegacyStateMigrations({
298+
detected: legacyState,
299+
config: ctx.cfg,
300+
...(doctorOnlyStateMigrations ? { doctorOnlyStateMigrations: true } : {}),
301+
recoverCorruptTargetStore: ctx.options.repair === true || ctx.options.yes === true,
302+
legacySessionSurfaces,
303+
});
304+
if (migrated.changes.length > 0) {
305+
note(migrated.changes.join("\n"), "Doctor changes");
306+
}
307+
const notices = migrated.notices ?? [];
308+
if (notices.length > 0) {
309+
note(notices.join("\n"), "Doctor notices");
310+
}
311+
if (migrated.warnings.length > 0) {
312+
note(migrated.warnings.join("\n"), "Doctor warnings");
313+
}
315314
}
316315
}
317316
if (!doctorOnlyStateMigrations) {

0 commit comments

Comments
 (0)