diff --git a/biome.json b/biome.json index 24b13ecf941..e148bc70899 100644 --- a/biome.json +++ b/biome.json @@ -86,7 +86,7 @@ "noExcessiveCognitiveComplexity": { "level": "error", "options": { - "maxAllowedComplexity": 215 + "maxAllowedComplexity": 186 } } }, diff --git a/src/lib/actions/sandbox/rebuild-flow.test.ts b/src/lib/actions/sandbox/rebuild-flow.test.ts index 27957ca4482..f68c09b90b1 100644 --- a/src/lib/actions/sandbox/rebuild-flow.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow.test.ts @@ -24,6 +24,7 @@ type RebuildFlowOverrides = { failedDirs: string[]; failedFiles: string[]; }; + buildMessagingRebuildPlan?: () => Promise | unknown; }; type RebuildFlowHarness = { @@ -38,6 +39,7 @@ type RebuildFlowHarness = { relockSpy: MockInstance; restoreSandboxStateSpy: MockInstance; runOpenshellSpy: MockInstance; + messagingRebuildPlanSpy: MockInstance; }; const originalSandboxName = process.env.NEMOCLAW_SANDBOX_NAME; @@ -66,6 +68,7 @@ function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): Rebuild const nim = requireDist("../../../../dist/lib/inference/nim.js"); const policies = requireDist("../../../../dist/lib/policy/index.js"); const processRecovery = requireDist("../../../../dist/lib/actions/sandbox/process-recovery.js"); + const messaging = requireDist("../../../../dist/lib/messaging/index.js"); const shields = requireDist("../../../../dist/lib/shields/index.js"); const session = { @@ -167,6 +170,9 @@ function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): Rebuild vi.spyOn(shields, "repairMutableConfigPerms").mockImplementation( overrides.repairMutableConfigPerms ?? (() => ({ applied: true, verified: true, errors: [] })), ); + const messagingRebuildPlanSpy = vi + .spyOn(messaging.MessagingWorkflowPlanner.prototype, "buildRebuildPlanFromSandboxEntry") + .mockImplementation(overrides.buildMessagingRebuildPlan ?? (() => null)); errorSpy.mockClear(); logSpy.mockClear(); @@ -184,6 +190,7 @@ function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): Rebuild relockSpy, restoreSandboxStateSpy, runOpenshellSpy, + messagingRebuildPlanSpy, }; } @@ -240,6 +247,28 @@ describe("rebuildSandbox flow", () => { ); }); + it("aborts before backup/delete when messaging manifest staging fails", async () => { + const harness = createRebuildFlowHarness({ + buildMessagingRebuildPlan: () => { + throw new Error("manifest boom"); + }, + }); + + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).rejects.toThrow("manifest boom"); + + const errors = harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n"); + expect(errors).toContain("messaging manifest plan could not be staged"); + expect(errors).toContain("Sandbox is untouched"); + expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); + expect(harness.runOpenshellSpy).not.toHaveBeenCalledWith( + ["sandbox", "delete", "alpha"], + expect.anything(), + ); + expect(harness.onboardSpy).not.toHaveBeenCalled(); + }); + it("finishes the rebuild while surfacing incomplete post-restore work", async () => { const harness = createRebuildFlowHarness({ executeSandboxCommand: () => ({ status: 1, stdout: "", stderr: "hash refresh failed" }), diff --git a/src/lib/actions/sandbox/rebuild.ts b/src/lib/actions/sandbox/rebuild.ts index d9e114311b1..bd341522b9c 100644 --- a/src/lib/actions/sandbox/rebuild.ts +++ b/src/lib/actions/sandbox/rebuild.ts @@ -139,8 +139,12 @@ function _rebuildLog(msg: string) { /** * Resolve the credential environment variable required to recreate a sandbox. */ +function isLocalInferenceProvider(provider: string | null | undefined): provider is string { + return Boolean(provider && LOCAL_INFERENCE_PROVIDERS.includes(provider)); +} + function getRebuildCredentialEnvFromRegistry(provider: string | null | undefined): string | null { - if (!provider || LOCAL_INFERENCE_PROVIDERS.includes(provider)) { + if (!provider || isLocalInferenceProvider(provider)) { return null; } const remoteConfig = @@ -384,6 +388,125 @@ function isSingleAgentRebuildSupported( return true; } +async function stageRebuildMessagingPlanOrBail( + sandboxName: string, + sb: RebuildSandboxEntry, + rebuildAgent: string | null, + log: (msg: string) => void, + bail: (msg: string, code?: number) => never, +): Promise { + try { + return await stageMessagingManifestPlanForRebuild(sandboxName, sb, rebuildAgent, log); + } catch (err) { + // Source boundary: registry messaging plans and agent manifests are durable + // host-side inputs from prior onboarding. If they drift or become invalid, + // rebuild must fail here before backup/delete; remove this boundary only if + // manifest staging becomes total over all persisted registry states. + const message = err instanceof Error ? err.message : String(err); + console.error(""); + console.error( + ` ${_RD}Rebuild preflight failed:${R} messaging manifest plan could not be staged.`, + ); + console.error(` ${message}`); + console.error(""); + console.error(" Sandbox is untouched — no data was lost."); + bail(message); + return null; + } +} + +function preflightRebuildCredentials( + sandboxName: string, + sb: RebuildSandboxEntry, + log: (msg: string) => void, + bail: (msg: string, code?: number) => never, +): boolean { + const session = onboardSession.loadSession(); + const sessionMatchesTarget = session?.sandboxName === sandboxName; + // The target registry entry is authoritative when a matching legacy session + // omitted credentialEnv; rebuild rewrites provider/model from this entry later, + // so remote registry providers must still fail closed before backup/delete. + let rebuildCredentialEnv = sessionMatchesTarget + ? session?.credentialEnv || getRebuildCredentialEnvFromRegistry(sb.provider) + : getRebuildCredentialEnvFromRegistry(sb.provider); + if (!sessionMatchesTarget && session?.sandboxName) { + log( + `Preflight warning: session belongs to '${session.sandboxName}', not '${sandboxName}' — using registry credential env ${rebuildCredentialEnv || "(none)"}`, + ); + console.log( + ` ${D}Note: onboard session belongs to '${session.sandboxName}', not '${sandboxName}'. ` + + `Using the '${sandboxName}' registry entry for credential preflight.${R}`, + ); + } + + const rebuildProvider = sb.provider; + // Compatibility boundary for GH #2519: pre-fix local-provider sessions could + // persist credentialEnv="OPENAI_API_KEY" even though current local-provider + // write paths persist null. Only a session for this sandbox plus a local + // target registry provider may bypass the key; keep until legacy sessions are + // no longer supported by rebuild migration tests. + if ( + sessionMatchesTarget && + isLocalInferenceProvider(sb.provider) && + rebuildCredentialEnv === "OPENAI_API_KEY" + ) { + console.log( + ` ${D}Note: migrating ${sb.provider} sandbox off OPENAI_API_KEY (GH #2519). ` + + `Local inference does not require a host API key.${R}`, + ); + log( + `Preflight: legacy ${sb.provider} sandbox detected (credentialEnv=OPENAI_API_KEY) — clearing for rebuild`, + ); + rebuildCredentialEnv = null; + } + + if (rebuildProvider === hermesProviderAuth.HERMES_PROVIDER_NAME) { + if ( + !preflightHermesProviderCredentials( + sessionMatchesTarget ? session : null, + rebuildCredentialEnv, + log, + ) + ) { + bail("Missing Hermes Provider credentials"); + return false; + } + rebuildCredentialEnv = null; + } + + if (!rebuildCredentialEnv) { + log( + "Preflight credential check: no credentialEnv in session (local inference or missing session)", + ); + return true; + } + + const credentialValue = hydrateCredentialEnv(rebuildCredentialEnv); + log( + `Preflight credential check: ${rebuildCredentialEnv} → ${credentialValue ? "present" : "MISSING"}`, + ); + if (credentialValue) return true; + if (rebuildProvider && providerExistsInGateway(rebuildProvider, runOpenshell)) { + log( + `Preflight credential check: provider '${rebuildProvider}' registered in gateway — skipping env check for ${rebuildCredentialEnv}`, + ); + return true; + } + + console.error(""); + console.error(` ${_RD}Rebuild preflight failed:${R} provider credential not found.`); + console.error(` The non-interactive recreate step requires ${rebuildCredentialEnv},`); + console.error(" but it is not set in the environment."); + console.error(""); + console.error(" To fix, do one of:"); + console.error(` export ${rebuildCredentialEnv}=`); + console.error(` ${CLI_NAME} onboard # re-enter the key interactively`); + console.error(""); + console.error(" Sandbox is untouched — no data was lost."); + bail(`Missing credential: ${rebuildCredentialEnv}`); + return false; +} + function printRebuildVersionSummary( sandboxName: string, agentName: string, @@ -495,133 +618,18 @@ export async function rebuildSandbox( if (!rebuildConfirmed) return; // Step 0: Preflight — verify recreate preconditions BEFORE destroying - // anything. The most common rebuild failure is a missing provider - // credential when onboard runs in non-interactive mode. Checking now - // lets us abort with the sandbox still intact. See #2273. - const session = onboardSession.loadSession(); - const sessionMatchesTarget = session?.sandboxName === sandboxName; - let rebuildCredentialEnv: string | null = null; - if (!sessionMatchesTarget) { - // Session belongs to a different sandbox — its credentialEnv may be - // wrong (e.g. hermes session while rebuilding openclaw). Resolve the - // target sandbox provider from the registry instead so destructive - // operations still get a credential preflight for the sandbox being rebuilt. - rebuildCredentialEnv = getRebuildCredentialEnvFromRegistry(sb.provider); - if (session?.sandboxName) { - log( - `Preflight warning: session belongs to '${session.sandboxName}', not '${sandboxName}' — using registry credential env ${rebuildCredentialEnv || "(none)"}`, - ); - console.log( - ` ${D}Note: onboard session belongs to '${session.sandboxName}', not '${sandboxName}'. ` + - `Using the '${sandboxName}' registry entry for credential preflight.${R}`, - ); - } - } else { - rebuildCredentialEnv = session?.credentialEnv || null; - } - const rebuildProvider = sessionMatchesTarget ? session?.provider || sb.provider : sb.provider; - // Legacy migration: pre-fix local-inference sandboxes (GH #2519, GH #2625) - // recorded credentialEnv="OPENAI_API_KEY" in onboard-session.json even - // though the sandbox does not actually need a host OpenAI key (ollama-local - // uses an auth proxy with an internal token; vllm-local accepts a static - // dummy bearer). Treat the legacy value as null so rebuild does not demand - // a credential that was never actually used. - // - // Post-#2625 the write path persists credentialEnv=null directly when the - // wizard selects a local provider, so fresh sessions no longer need this - // migration. We retain it for users whose session.json on disk predates - // the fix. - if ( - (session?.provider === "ollama-local" || session?.provider === "vllm-local") && - rebuildCredentialEnv === "OPENAI_API_KEY" - ) { - console.log( - ` ${D}Note: migrating ${session.provider} sandbox off OPENAI_API_KEY (GH #2519). ` + - `Local inference does not require a host API key.${R}`, - ); - log( - `Preflight: legacy ${session.provider} sandbox detected (credentialEnv=OPENAI_API_KEY) — clearing for rebuild`, - ); - rebuildCredentialEnv = null; - } - if (rebuildProvider === hermesProviderAuth.HERMES_PROVIDER_NAME) { - if ( - !preflightHermesProviderCredentials( - sessionMatchesTarget ? session : null, - rebuildCredentialEnv, - log, - ) - ) { - bail("Missing Hermes Provider credentials"); - return; - } - // Hermes Provider credentials belong to OpenShell provider storage. Do not - // fall through to the generic env-var preflight, which would incorrectly - // demand OPENAI_API_KEY/NOUS_API_KEY after the provider is registered. - rebuildCredentialEnv = null; - } - if (rebuildCredentialEnv) { - // hydrateCredentialEnv migrates any pre-fix legacy credentials.json - // into process.env once, so users upgrading from a release that wrote - // the plaintext file can still rebuild without re-entering keys. - const credentialValue = hydrateCredentialEnv(rebuildCredentialEnv); - log( - `Preflight credential check: ${rebuildCredentialEnv} → ${credentialValue ? "present" : "MISSING"}`, - ); - if (!credentialValue) { - // When the inference provider is already registered in the OpenShell - // gateway, the recreate step does not need a host env value — the - // gateway is the source of truth for the secret. Skip the env-only - // preflight in that case so flows like `channels add` + rebuild keep - // working when the user has logged out of the original shell. - if (rebuildProvider && providerExistsInGateway(rebuildProvider, runOpenshell)) { - log( - `Preflight credential check: provider '${rebuildProvider}' registered in gateway — skipping env check for ${rebuildCredentialEnv}`, - ); - } else { - console.error(""); - console.error(` ${_RD}Rebuild preflight failed:${R} provider credential not found.`); - console.error(` The non-interactive recreate step requires ${rebuildCredentialEnv},`); - console.error(" but it is not set in the environment."); - console.error(""); - console.error(" To fix, do one of:"); - console.error(` export ${rebuildCredentialEnv}=`); - console.error(` ${CLI_NAME} onboard # re-enter the key interactively`); - console.error(""); - console.error(" Sandbox is untouched — no data was lost."); - bail(`Missing credential: ${rebuildCredentialEnv}`); - return; - } - } - } else { - // No credentialEnv in session — local inference (Ollama/vLLM) or - // session was lost. Either way, skip the credential preflight; - // onboard will handle it. - log( - "Preflight credential check: no credentialEnv in session (local inference or missing session)", - ); - } + // anything. The most common rebuild failure is a missing provider credential + // when onboard runs in non-interactive mode. Checking now lets us abort with + // the sandbox still intact. See #2273. + if (!preflightRebuildCredentials(sandboxName, sb, log, bail)) return; - let rebuildMessagingPlan: SandboxMessagingPlan | null = null; - try { - rebuildMessagingPlan = await stageMessagingManifestPlanForRebuild( - sandboxName, - sb, - rebuildAgent, - log, - ); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - console.error(""); - console.error( - ` ${_RD}Rebuild preflight failed:${R} messaging manifest plan could not be staged.`, - ); - console.error(` ${message}`); - console.error(""); - console.error(" Sandbox is untouched — no data was lost."); - bail(message); - return; - } + const rebuildMessagingPlan = await stageRebuildMessagingPlanOrBail( + sandboxName, + sb, + rebuildAgent, + log, + bail, + ); // Step 1: Ensure sandbox is live for backup const recordedGateway = resolveSandboxGatewayName(sb); diff --git a/test/rebuild-credential-preflight.test.ts b/test/rebuild-credential-preflight.test.ts index a1ae4b58581..427b6538c31 100644 --- a/test/rebuild-credential-preflight.test.ts +++ b/test/rebuild-credential-preflight.test.ts @@ -80,6 +80,7 @@ function createFixture(opts: { messagingPlanChannels?: string[] | null; dockerBuildExitCode?: number; providerRegistered?: boolean; + registeredProviders?: string[]; activeSessionCount?: number | null; }) { const { @@ -93,6 +94,7 @@ function createFixture(opts: { messagingPlanChannels = null, dockerBuildExitCode = 0, providerRegistered = true, + registeredProviders, activeSessionCount = 0, } = opts; const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-2273-")); @@ -230,10 +232,12 @@ function createFixture(opts: { " UserKnownHostsFile /dev/null", ].join("\\n"); + const registeredProvidersLiteral = JSON.stringify(registeredProviders ?? null); fs.writeFileSync( path.join(tmpDir, "openshell"), `#!/usr/bin/env node const a = process.argv.slice(2); +const registeredProviders = ${registeredProvidersLiteral}; if (a[0]==="sandbox" && a[1]==="list") { process.stdout.write("${sandboxName}\\n"); process.exit(0); } if (a[0]==="sandbox" && a[1]==="ssh-config") { process.stdout.write("${sshConfig}\\n"); process.exit(0); } if (a[0]==="sandbox" && a[1]==="delete") { process.exit(0); } @@ -242,7 +246,10 @@ if (a[0]==="gateway" && a[1]==="info") { process.stdout.write("nemoclaw\\n if (a[0]==="gateway" && a[1]==="select") { process.exit(0); } if (a[0]==="inference" && a[1]==="get") { process.stdout.write('{"provider":"${provider}","model":"meta/llama-3.3-70b-instruct"}\\n'); process.exit(0); } if (a[0]==="inference" && a[1]==="set") { process.exit(0); } -if (a[0]==="provider" && a[1]==="get") { process.exit(${providerRegistered ? 0 : 1}); } +if (a[0]==="provider" && a[1]==="get") { + if (Array.isArray(registeredProviders)) process.exit(registeredProviders.includes(a[2]) ? 0 : 1); + process.exit(${providerRegistered ? 0 : 1}); +} if (a[0]==="provider") { process.exit(0); } if (a[0]==="forward") { process.exit(0); } process.exit(0); @@ -582,6 +589,82 @@ describe("Issue #2273: atomic rebuild", () => { expect(output).toContain("Backing up sandbox state"); }, 60_000); + it("fails closed when a matching session omits the remote target provider credential", { + timeout: 60_000, + }, () => { + const f = createFixture({ + provider: "openai-api", + credentialEnv: "OPENAI_API_KEY", + providerRegistered: false, + }); + const sessionPath = path.join(f.nemoclawDir, "onboard-session.json"); + const session = JSON.parse(fs.readFileSync(sessionPath, "utf-8")); + session.credentialEnv = null; + fs.writeFileSync(sessionPath, JSON.stringify(session), { mode: 0o600 }); + + const result = runRebuild(f); + const output = (result.stderr || "") + (result.stdout || ""); + + expect(result.status).not.toBe(0); + expect(output).toContain("preflight failed"); + expect(output).toContain("requires OPENAI_API_KEY"); + expect(output).not.toContain("Backing up sandbox state"); + expect(output).not.toContain("Old sandbox deleted"); + expect(registryHasSandbox(f)).toBe(true); + }); + + it("uses the target registry provider when a matching session has a stale registered provider", { + timeout: 60_000, + }, () => { + const f = createFixture({ + provider: "openai-api", + credentialEnv: "OPENAI_API_KEY", + registeredProviders: ["nvidia-prod"], + }); + const sessionPath = path.join(f.nemoclawDir, "onboard-session.json"); + const session = JSON.parse(fs.readFileSync(sessionPath, "utf-8")); + session.provider = "nvidia-prod"; + session.credentialEnv = null; + fs.writeFileSync(sessionPath, JSON.stringify(session), { mode: 0o600 }); + + const result = runRebuild(f); + const output = (result.stderr || "") + (result.stdout || ""); + + expect(result.status).not.toBe(0); + expect(output).toContain("preflight failed"); + expect(output).toContain("requires OPENAI_API_KEY"); + expect(output).not.toContain("Backing up sandbox state"); + expect(output).not.toContain("Old sandbox deleted"); + expect(registryHasSandbox(f)).toBe(true); + }); + + it("does not let a mismatched stale local session bypass the target OPENAI_API_KEY preflight", { + timeout: 60_000, + }, () => { + const f = createFixture({ + provider: "openai-api", + credentialEnv: "OPENAI_API_KEY", + providerRegistered: false, + }); + const sessionPath = path.join(f.nemoclawDir, "onboard-session.json"); + const session = JSON.parse(fs.readFileSync(sessionPath, "utf-8")); + session.sandboxName = "other-local-sandbox"; + session.provider = "ollama-local"; + session.credentialEnv = "OPENAI_API_KEY"; + fs.writeFileSync(sessionPath, JSON.stringify(session), { mode: 0o600 }); + + const result = runRebuild(f); + const output = (result.stderr || "") + (result.stdout || ""); + + expect(result.status).not.toBe(0); + expect(output).toContain("preflight failed"); + expect(output).toContain("requires OPENAI_API_KEY"); + expect(output).not.toContain("GH #2519"); + expect(output).not.toContain("Backing up sandbox state"); + expect(output).not.toContain("Old sandbox deleted"); + expect(registryHasSandbox(f)).toBe(true); + }); + it("preflight works for non-NVIDIA providers (OpenAI, Anthropic, etc.)", { timeout: 60_000, }, () => {