diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 83487a3ab33..95b9ce31464 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -28,7 +28,7 @@ "src/lib/security/redact.ts": 54, "src/lib/state/onboard-session.ts": 36, "src/lib/state/mcp-lifecycle-lock.ts": 21, - "src/lib/state/registry.ts": 100, + "src/lib/state/registry.ts": 103, "src/lib/state/state-root.ts": 21, "src/lib/subprocess-env.ts": 24, "src/lib/validation.ts": 24 diff --git a/src/lib/actions/sandbox/mcp-bridge-contracts.ts b/src/lib/actions/sandbox/mcp-bridge-contracts.ts index e17775bf0e3..29d81e01b07 100644 --- a/src/lib/actions/sandbox/mcp-bridge-contracts.ts +++ b/src/lib/actions/sandbox/mcp-bridge-contracts.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { AgentMcpAdapter } from "../../agent/defs"; +import type { AgentMcpAdapter } from "../../agent/definition-types"; + +export { isAgentMcpAdapter } from "../../agent/definition-types"; export const MCP_BRIDGE_POLICY_SOURCE = "generated:nemoclaw-mcp-bridge"; export type McpBridgeErrorReasonCode = "rejected" | "unresolved"; @@ -93,7 +95,3 @@ export interface McpBridgeStatus { addedAt?: string; updatedAt?: string; } - -export function isAgentMcpAdapter(value: unknown): value is AgentMcpAdapter { - return value === "mcporter" || value === "hermes-config" || value === "deepagents-config"; -} diff --git a/src/lib/actions/sandbox/mcp-bridge-rebuild-policy-authority.test.ts b/src/lib/actions/sandbox/mcp-bridge-rebuild-policy-authority.test.ts new file mode 100644 index 00000000000..4203f830675 --- /dev/null +++ b/src/lib/actions/sandbox/mcp-bridge-rebuild-policy-authority.test.ts @@ -0,0 +1,239 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { PolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; +import type { McpBridgeEntry, SandboxEntry } from "../../state/registry"; + +const mocks = vi.hoisted(() => ({ + assertAdapterConfigMutationsAllowed: vi.fn(), + assertAdapterTeardownRuntimeCapabilities: vi.fn(), + assertDestroyNotPending: vi.fn(), + assertGeneratedPolicyMutationSafe: vi.fn(), + assertNoProviderCredentialCollisions: vi.fn(), + assertProviderRecoverable: vi.fn(), + attachProvider: vi.fn(), + bridgeState: vi.fn(), + detachProvider: vi.fn(), + discardSafeIncompleteAdds: vi.fn(), + ensureSandboxGatewaySelected: vi.fn(), + getSandboxOrThrow: vi.fn(), + inspectExactDestroyProvider: vi.fn(), + preflightEntryTargets: vi.fn(), + removeGeneratedPolicy: vi.fn(), + refreshProviderEnvironment: vi.fn(), + restoreRuntime: vi.fn(), + rollbackScrubbedAdapters: vi.fn(), + scrubAdapter: vi.fn(), + setBridgeState: vi.fn(), + waitForDetachedCredential: vi.fn(), + waitForAttachedCredential: vi.fn(), +})); + +vi.mock("./mcp-bridge-adapter-teardown", () => ({ + rollbackScrubbedMcpAdapters: mocks.rollbackScrubbedAdapters, + scrubManagedMcpAdapterOrThrow: mocks.scrubAdapter, +})); + +vi.mock("./mcp-bridge-destroy", () => ({ + cloneMcpBridgeEntry: (entry: McpBridgeEntry) => structuredClone(entry), + discardSafeIncompleteMcpAdds: mocks.discardSafeIncompleteAdds, + inspectExactMcpDestroyProvider: mocks.inspectExactDestroyProvider, +})); + +vi.mock("./mcp-bridge-policy", () => ({ + assertGeneratedPolicyMutationSafe: mocks.assertGeneratedPolicyMutationSafe, + assertGeneratedPolicyRegistrationMutationSafe: vi.fn(), + removeGeneratedPolicy: mocks.removeGeneratedPolicy, +})); + +vi.mock("./mcp-bridge-provider", () => ({ + assertMcpProviderRecoverable: mocks.assertProviderRecoverable, + assertNoProviderCredentialCollisions: mocks.assertNoProviderCredentialCollisions, + assertNoRegisteredProviderCredentialCollisions: vi.fn(), + attachProvider: mocks.attachProvider, + detachProvider: mocks.detachProvider, + preflightMcpEntryTargets: mocks.preflightEntryTargets, + refreshMcpProviderEnvironment: mocks.refreshProviderEnvironment, + waitForAttachedMcpCredential: mocks.waitForAttachedCredential, + waitForDetachedMcpCredential: mocks.waitForDetachedCredential, +})); + +vi.mock("./mcp-bridge-restart", () => ({ + restoreExistingMcpBridgeRuntime: mocks.restoreRuntime, +})); + +vi.mock("./mcp-bridge-runtime-capabilities", () => ({ + assertMcpAdapterConfigMutationsAllowed: mocks.assertAdapterConfigMutationsAllowed, + assertMcpAdapterTeardownRuntimeCapabilities: mocks.assertAdapterTeardownRuntimeCapabilities, +})); + +vi.mock("./mcp-bridge-state", () => ({ + assertMcpDestroyNotPending: mocks.assertDestroyNotPending, + bridgeState: mocks.bridgeState, + ensureSandboxGatewaySelected: mocks.ensureSandboxGatewaySelected, + getSandboxOrThrow: mocks.getSandboxOrThrow, + setBridgeState: mocks.setBridgeState, +})); + +const { prepareMcpBridgesForRebuild, restoreMcpBridgesAfterRebuild } = + await import("./mcp-bridge-rebuild"); + +let entry: McpBridgeEntry; +let sandbox: SandboxEntry; + +describe("MCP rebuild policy authority", () => { + beforeEach(() => { + vi.clearAllMocks(); + entry = { + server: "github", + agent: "openclaw", + adapter: "mcporter", + url: "https://mcp.example.test/mcp", + env: ["GITHUB_TOKEN"], + providerName: "alpha-mcp-github", + providerId: "provider-1", + policyName: "mcp-bridge-github", + addedAt: "2026-08-20T00:00:00.000Z", + }; + sandbox = { + name: "alpha", + agent: "openclaw", + policyAuthority: "externally-managed", + mcp: { bridges: { github: entry } }, + }; + mocks.getSandboxOrThrow.mockReturnValue(sandbox); + mocks.bridgeState.mockImplementation((current: SandboxEntry) => current.mcp?.bridges ?? {}); + mocks.discardSafeIncompleteAdds.mockResolvedValue(sandbox); + mocks.detachProvider.mockReturnValue("detached"); + mocks.rollbackScrubbedAdapters.mockReturnValue([]); + mocks.scrubAdapter.mockImplementation((_name, _sandbox, current: McpBridgeEntry) => ({ + ...current, + credentialRevision: "v1", + })); + }); + + it("preserves externally managed policy while preparing adapter and provider state (#9833)", async () => { + const validatePolicyAuthority = vi.fn().mockResolvedValue(undefined); + + await expect( + prepareMcpBridgesForRebuild("alpha", validatePolicyAuthority), + ).resolves.toMatchObject({ + entries: [entry], + detachedProviderEntries: [entry], + scrubbedAdapterEntries: [entry], + }); + + expect(mocks.removeGeneratedPolicy).not.toHaveBeenCalled(); + expect(validatePolicyAuthority).toHaveBeenCalledTimes(3); + expect(validatePolicyAuthority.mock.invocationCallOrder[1]).toBeLessThan( + mocks.scrubAdapter.mock.invocationCallOrder[0], + ); + expect(validatePolicyAuthority.mock.invocationCallOrder[2]).toBeLessThan( + mocks.detachProvider.mock.invocationCallOrder[0], + ); + }); + + it("preserves the authority refusal before MCP teardown mutation (#9833)", async () => { + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + const validatePolicyAuthority = vi + .fn() + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(refusal); + + await expect(prepareMcpBridgesForRebuild("alpha", validatePolicyAuthority)).rejects.toBe( + refusal, + ); + + expect(mocks.scrubAdapter).not.toHaveBeenCalled(); + expect(mocks.removeGeneratedPolicy).not.toHaveBeenCalled(); + expect(mocks.detachProvider).not.toHaveBeenCalled(); + }); + + it("rolls back an adapter scrub when authority changes before policy removal (#9833)", async () => { + sandbox.policyAuthority = "nemoclaw-managed"; + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + const validatePolicyAuthority = vi + .fn() + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(refusal); + + await expect(prepareMcpBridgesForRebuild("alpha", validatePolicyAuthority)).rejects.toBe( + refusal, + ); + + expect(mocks.rollbackScrubbedAdapters).toHaveBeenCalledExactlyOnceWith("alpha", sandbox, [ + expect.objectContaining({ server: "github", credentialRevision: "v1" }), + ]); + expect(mocks.removeGeneratedPolicy).not.toHaveBeenCalled(); + expect(mocks.detachProvider).not.toHaveBeenCalled(); + expect(mocks.restoreRuntime).not.toHaveBeenCalled(); + }); + + it("reattaches a detached provider when authority changes before the next detach (#9833)", async () => { + const second = { + ...entry, + server: "gitlab", + env: ["GITLAB_TOKEN"], + providerName: "alpha-mcp-gitlab", + providerId: "provider-2", + policyName: "mcp-bridge-gitlab", + }; + sandbox.mcp = { bridges: { github: entry, gitlab: second } }; + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + const validatePolicyAuthority = vi + .fn() + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(refusal); + + await expect(prepareMcpBridgesForRebuild("alpha", validatePolicyAuthority)).rejects.toBe( + refusal, + ); + + expect(mocks.attachProvider).toHaveBeenCalledExactlyOnceWith("alpha", entry); + expect(mocks.refreshProviderEnvironment).toHaveBeenCalledExactlyOnceWith(entry); + expect(mocks.waitForAttachedCredential).toHaveBeenCalledExactlyOnceWith("alpha", entry); + expect(mocks.rollbackScrubbedAdapters).toHaveBeenCalledWith( + "alpha", + sandbox, + expect.arrayContaining([ + expect.objectContaining({ server: "github", credentialRevision: "v1" }), + expect.objectContaining({ server: "gitlab", credentialRevision: "v1" }), + ]), + ); + expect(mocks.removeGeneratedPolicy).not.toHaveBeenCalled(); + expect(mocks.restoreRuntime).not.toHaveBeenCalled(); + }); + + it("revalidates between registry recovery and runtime restoration (#9833)", async () => { + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + const validatePolicyAuthority = vi + .fn() + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(refusal); + + await expect( + restoreMcpBridgesAfterRebuild("alpha", [entry], validatePolicyAuthority), + ).rejects.toBe(refusal); + + expect(mocks.setBridgeState).toHaveBeenCalledOnce(); + expect(mocks.restoreRuntime).not.toHaveBeenCalled(); + }); + + it("revalidates after MCP runtime restoration before returning success (#9833)", async () => { + const validatePolicyAuthority = vi.fn().mockResolvedValue(undefined); + + await expect( + restoreMcpBridgesAfterRebuild("alpha", [entry], validatePolicyAuthority), + ).resolves.toBeUndefined(); + + expect(validatePolicyAuthority).toHaveBeenCalledTimes(3); + expect(mocks.restoreRuntime.mock.invocationCallOrder[0]).toBeLessThan( + validatePolicyAuthority.mock.invocationCallOrder[2], + ); + }); +}); diff --git a/src/lib/actions/sandbox/mcp-bridge-rebuild.ts b/src/lib/actions/sandbox/mcp-bridge-rebuild.ts index 027e4f6da86..4ce8e992bce 100644 --- a/src/lib/actions/sandbox/mcp-bridge-rebuild.ts +++ b/src/lib/actions/sandbox/mcp-bridge-rebuild.ts @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import type { McpBridgeEntry } from "../../state/registry"; +import { + isPolicyAuthorityRefusalError, + PolicyAuthorityRefusalError, +} from "../../adapters/openshell/policy-authority"; import { rollbackScrubbedMcpAdapters, scrubManagedMcpAdapterOrThrow, @@ -22,8 +26,11 @@ import { assertMcpProviderRecoverable, assertNoProviderCredentialCollisions, assertNoRegisteredProviderCredentialCollisions, + attachProvider, detachProvider, preflightMcpEntryTargets, + refreshMcpProviderEnvironment, + waitForAttachedMcpCredential, waitForDetachedMcpCredential, } from "./mcp-bridge-provider"; import { restoreExistingMcpBridgeRuntime } from "./mcp-bridge-restart"; @@ -50,11 +57,32 @@ export interface McpRebuildPreparation { assertDeleteEdgeUnchanged?: () => void; } +function compensatePolicyAuthorityRefusal( + sandboxName: string, + sandbox: ReturnType, + detachedEntries: readonly McpBridgeEntry[], + scrubbedAdapterEntries: readonly McpScrubbedAdapterEntry[], +): string[] { + const failures: string[] = []; + for (const entry of detachedEntries) { + try { + attachProvider(sandboxName, entry); + refreshMcpProviderEnvironment(entry); + waitForAttachedMcpCredential(sandboxName, entry); + } catch (error) { + failures.push(error instanceof Error ? error.message : String(error)); + } + } + failures.push(...rollbackScrubbedMcpAdapters(sandboxName, sandbox, scrubbedAdapterEntries)); + return failures; +} + export { prepareMcpBridgesForExecUnavailableRebuild } from "./mcp-bridge-rebuild-exec-unavailable"; async function getCompleteMcpRebuildEntries( sandboxName: string, options: { sandboxAbsent?: boolean } = {}, + validatePolicyAuthority?: () => Promise, ): Promise { validateSandboxName(sandboxName); const currentSandbox = getSandboxOrThrow(sandboxName); @@ -73,6 +101,7 @@ async function getCompleteMcpRebuildEntries( entriesRequiringExternalCleanup, ); } + await validatePolicyAuthority?.(); const sandbox = await discardSafeIncompleteMcpAdds(sandboxName, currentSandbox, options); const entries = Object.values(bridgeState(sandbox)).map(cloneMcpBridgeEntry); const incompleteAdd = entries.find((entry) => entry.addState); @@ -117,9 +146,14 @@ export async function prepareMcpBridgesForAbsentSandboxRebuild( export async function prepareMcpBridgesForRebuild( sandboxName: string, + validatePolicyAuthority?: () => Promise, ): Promise { const sandbox = getSandboxOrThrow(sandboxName); - const entries = await getCompleteMcpRebuildEntries(sandboxName); + const entries = await getCompleteMcpRebuildEntries( + sandboxName, + undefined, + validatePolicyAuthority, + ); if (entries.length === 0) { return { entries: [], @@ -141,6 +175,7 @@ export async function prepareMcpBridgesForRebuild( // `/sandbox` may be a retained PVC. Scrub before delete so a replacement // Hermes/agent cannot boot with a stale placeholder while its provider // is intentionally detached during recreate. + await validatePolicyAuthority?.(); scrubbedAdapters.push(scrubManagedMcpAdapterOrThrow(sandboxName, sandbox, entry)); } for (const entry of entries) { @@ -148,12 +183,16 @@ export async function prepareMcpBridgesForRebuild( // MCP teardown. Keep exact generated-policy ownership in that preserved // row while removing only the live policy; inner onboarding excludes the // generated name and post-rebuild restoration reuses this ownership. - removeGeneratedPolicy(sandboxName, entry, { preserveRegistryOwnership: true }); - removedPolicies.push(entry); + if (sandbox.policyAuthority !== "externally-managed") { + await validatePolicyAuthority?.(); + removeGeneratedPolicy(sandboxName, entry, { preserveRegistryOwnership: true }); + removedPolicies.push(entry); + } } for (const entry of entries) { // Keep the provider and its host-only credentials for the replacement // sandbox, but detach it before OpenShell deletes the old attachment. + await validatePolicyAuthority?.(); inspectExactMcpDestroyProvider(entry, { allowMissing: false }); const detachOutcome = detachProvider(sandboxName, entry); if (detachOutcome === "unknown") { @@ -168,10 +207,26 @@ export async function prepareMcpBridgesForRebuild( detached.push(entry); } } catch (error) { + if (isPolicyAuthorityRefusalError(error)) { + const rollbackFailures = compensatePolicyAuthorityRefusal( + sandboxName, + sandbox, + detached, + scrubbedAdapters, + ); + if (rollbackFailures.length === 0) throw error; + const detail = error instanceof Error ? error.message : String(error); + throw new PolicyAuthorityRefusalError( + `${detail}\nMCP rebuild rollback could not reattach: ${rollbackFailures.join("; ")}`, + error instanceof PolicyAuthorityRefusalError ? error.observedAuthority : undefined, + { cause: error }, + ); + } const rollbackFailures: string[] = []; let runtimeRestored = false; if (removedPolicies.length > 0) { try { + await validatePolicyAuthority?.(); await restoreExistingMcpBridgeRuntime(sandboxName, removedPolicies, { lifecyclePhase: "teardown-rollback", }); @@ -183,9 +238,16 @@ export async function prepareMcpBridgesForRebuild( } } if (!runtimeRestored) { - rollbackFailures.push( - ...rollbackScrubbedMcpAdapters(sandboxName, sandbox, scrubbedAdapters), - ); + try { + await validatePolicyAuthority?.(); + rollbackFailures.push( + ...rollbackScrubbedMcpAdapters(sandboxName, sandbox, scrubbedAdapters), + ); + } catch (rollbackError) { + rollbackFailures.push( + rollbackError instanceof Error ? rollbackError.message : String(rollbackError), + ); + } } const detail = error instanceof Error ? error.message : String(error); throw new McpBridgeError( @@ -205,6 +267,7 @@ export async function reattachMcpProvidersAfterRebuildAbort( sandboxName: string, entries: readonly McpBridgeEntry[], scrubbedAdapterEntries: readonly McpScrubbedAdapterEntry[] = [], + validatePolicyAuthority?: () => Promise, ): Promise { if (entries.length === 0 && scrubbedAdapterEntries.length === 0) return; await ensureSandboxGatewaySelected(sandboxName); @@ -218,6 +281,7 @@ export async function reattachMcpProvidersAfterRebuildAbort( let runtimeRestored = false; if (entries.length > 0) { try { + await validatePolicyAuthority?.(); await restoreExistingMcpBridgeRuntime(sandboxName, entries, { lifecyclePhase: "teardown-rollback", }); @@ -227,6 +291,7 @@ export async function reattachMcpProvidersAfterRebuildAbort( } } if (!runtimeRestored) { + await validatePolicyAuthority?.(); failures.push(...rollbackScrubbedMcpAdapters(sandboxName, sandbox, scrubbedAdapterEntries)); } if (failures.length > 0) { @@ -237,6 +302,7 @@ export async function reattachMcpProvidersAfterRebuildAbort( export async function restoreMcpBridgesAfterRebuild( sandboxName: string, entries: readonly McpBridgeEntry[], + validatePolicyAuthority?: () => Promise, ): Promise { if (entries.length === 0) return; for (const entry of entries) assertAuthenticatedBridgeEntry(entry); @@ -245,6 +311,9 @@ export async function restoreMcpBridgesAfterRebuild( ); // Persist the recovery contract before touching the gateway. If refresh // fails, `mcp restart` remains retryable after the operator fixes the cause. + await validatePolicyAuthority?.(); setBridgeState(sandboxName, bridges); + await validatePolicyAuthority?.(); await restoreExistingMcpBridgeRuntime(sandboxName, entries); + await validatePolicyAuthority?.(); } diff --git a/src/lib/actions/sandbox/mcp-bridge.ts b/src/lib/actions/sandbox/mcp-bridge.ts index 34f4c5ca6d7..be85538880c 100644 --- a/src/lib/actions/sandbox/mcp-bridge.ts +++ b/src/lib/actions/sandbox/mcp-bridge.ts @@ -149,27 +149,31 @@ export async function prepareMcpBridgesForAbsentSandboxRebuild( export async function prepareMcpBridgesForRebuild( sandboxName: string, + validatePolicyAuthority?: () => Promise, ): Promise { - return prepareMcpBridgesForRebuildLifecycle(sandboxName); + return prepareMcpBridgesForRebuildLifecycle(sandboxName, validatePolicyAuthority); } export async function reattachMcpProvidersAfterRebuildAbort( sandboxName: string, entries: readonly McpBridgeEntry[], scrubbedAdapterEntries: readonly McpScrubbedAdapterEntry[] = [], + validatePolicyAuthority?: () => Promise, ): Promise { return reattachMcpProvidersAfterRebuildAbortLifecycle( sandboxName, entries, scrubbedAdapterEntries, + validatePolicyAuthority, ); } export async function restoreMcpBridgesAfterRebuild( sandboxName: string, entries: readonly McpBridgeEntry[], + validatePolicyAuthority?: () => Promise, ): Promise { - return restoreMcpBridgesAfterRebuildLifecycle(sandboxName, entries); + return restoreMcpBridgesAfterRebuildLifecycle(sandboxName, entries, validatePolicyAuthority); } function parseJsonFlag(args: string[]): { json: boolean; rest: string[] } { diff --git a/src/lib/actions/sandbox/messaging-host-forward-lifecycle.ts b/src/lib/actions/sandbox/messaging-host-forward-lifecycle.ts index 96cf9088560..07b5b52065a 100644 --- a/src/lib/actions/sandbox/messaging-host-forward-lifecycle.ts +++ b/src/lib/actions/sandbox/messaging-host-forward-lifecycle.ts @@ -44,6 +44,7 @@ function getMessagingForwardHealth(sandboxName: string, port: number): true | fa export function ensureMessagingHostForwardAfterRebuild( sandboxName: string, plan: SandboxMessagingPlan | null | undefined, + note: (message: string) => void = console.log, ): boolean { const forward = resolveMessagingHostForward(plan); if (!forward) return true; @@ -67,6 +68,6 @@ export function ensureMessagingHostForwardAfterRebuild( port, label, ), - note: console.log, + note, }); } diff --git a/src/lib/actions/sandbox/policy-authority/mcp-requirements.test.ts b/src/lib/actions/sandbox/policy-authority/mcp-requirements.test.ts new file mode 100644 index 00000000000..e45878ee555 --- /dev/null +++ b/src/lib/actions/sandbox/policy-authority/mcp-requirements.test.ts @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import YAML from "yaml"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + preflightMcpEntryTargets: vi.fn(), +})); + +vi.mock("../mcp-bridge-provider", () => ({ + preflightMcpEntryTargets: mocks.preflightMcpEntryTargets, +})); + +import { buildMcpBridgePolicyName } from "../mcp-bridge-policy"; +import { resolveManagedMcpPolicyRequirementContents } from "./mcp-requirements"; + +describe("policy-authority managed MCP requirements", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.preflightMcpEntryTargets.mockResolvedValue( + new Map([["github", { addresses: ["8.8.8.8"] }]]), + ); + }); + + it("derives the exact requirement from the retained bridge and validated pins (#9833)", async () => { + const requirements = await resolveManagedMcpPolicyRequirementContents( + { + name: "alpha", + agent: "openclaw", + mcp: { + bridges: { + github: { + server: "github", + agent: "openclaw", + adapter: "mcporter", + url: "https://mcp.example.test/mcp", + env: ["GITHUB_TOKEN"], + providerName: "alpha-mcp-github", + providerId: "provider-1", + policyName: buildMcpBridgePolicyName("github"), + addedAt: "2026-08-20T00:00:00.000Z", + }, + }, + }, + }, + "rebuild sandbox 'alpha'", + ); + + expect(requirements).toHaveLength(1); + expect(YAML.parse(requirements[0] ?? "")).toMatchObject({ + network_policies: { + mcp_bridge_github: { + endpoints: [ + expect.objectContaining({ + allowed_ips: ["8.8.8.8"], + credential_binding: { provider: "alpha-mcp-github" }, + }), + ], + }, + }, + }); + }); +}); diff --git a/src/lib/actions/sandbox/policy-authority/mcp-requirements.ts b/src/lib/actions/sandbox/policy-authority/mcp-requirements.ts new file mode 100644 index 00000000000..4b4964d4da5 --- /dev/null +++ b/src/lib/actions/sandbox/policy-authority/mcp-requirements.ts @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import YAML from "yaml"; + +import { isAgentMcpAdapter } from "../../../agent/definition-types"; +import type { SandboxEntry } from "../../../state/registry"; +import { buildMcpBridgePolicyName, buildMcpBridgePolicyYaml } from "../mcp-bridge-policy"; +import { preflightMcpEntryTargets } from "../mcp-bridge-provider"; +import { assertAuthenticatedBridgeEntry } from "../mcp-bridge-validation"; + +/** Build exact MCP policy requirements from durable bridges and current target pins. */ +export async function resolveManagedMcpPolicyRequirementContents( + sandboxEntry: SandboxEntry, + operation: string, +): Promise { + const mcp = sandboxEntry.mcp; + if (!mcp) return []; + if (mcp.destroyPreparedAt || mcp.destroyPendingAt) { + throw new Error(`Refusing to ${operation}: managed MCP destruction is incomplete.`); + } + + const bridges = Object.values(mcp.bridges).sort((left, right) => + left.server.localeCompare(right.server), + ); + for (const bridge of bridges) { + if (bridge.addState) { + throw new Error( + `Refusing to ${operation}: managed MCP server '${bridge.server}' has an incomplete add transaction.`, + ); + } + assertAuthenticatedBridgeEntry(bridge); + if (!bridge.providerId) { + throw new Error( + `Refusing to ${operation}: managed MCP server '${bridge.server}' has no exact provider identity.`, + ); + } + if (!isAgentMcpAdapter(bridge.adapter)) { + throw new Error( + `Refusing to ${operation}: managed MCP server '${bridge.server}' has no exact adapter identity.`, + ); + } + if (bridge.policyName !== buildMcpBridgePolicyName(bridge.server)) { + throw new Error( + `Refusing to ${operation}: managed MCP server '${bridge.server}' has a non-canonical policy name.`, + ); + } + } + + let targets: Awaited>; + try { + targets = await preflightMcpEntryTargets(bridges); + } catch (error) { + throw new Error( + `Refusing to ${operation}: managed MCP target pins could not be validated: ${error instanceof Error ? error.message : String(error)}`, + ); + } + return bridges.map((bridge) => { + const adapter = bridge.adapter; + if (!isAgentMcpAdapter(adapter)) { + throw new Error( + `Refusing to ${operation}: managed MCP server '${bridge.server}' has no exact adapter identity.`, + ); + } + const providerName = bridge.providerName; + if (typeof providerName !== "string" || providerName.length === 0) { + throw new Error( + `Refusing to ${operation}: managed MCP server '${bridge.server}' has no exact provider name.`, + ); + } + const target = targets.get(bridge.server); + if (!target) { + throw new Error( + `Refusing to ${operation}: managed MCP server '${bridge.server}' has no validated target pins.`, + ); + } + const requiredPolicy = YAML.parse( + buildMcpBridgePolicyYaml(bridge.server, bridge.url, adapter, target, providerName), + ) as Record; + delete requiredPolicy.preset; + return YAML.stringify(requiredPolicy); + }); +} diff --git a/src/lib/actions/sandbox/policy-authority/preflight.test.ts b/src/lib/actions/sandbox/policy-authority/preflight.test.ts new file mode 100644 index 00000000000..310517ec80b --- /dev/null +++ b/src/lib/actions/sandbox/policy-authority/preflight.test.ts @@ -0,0 +1,190 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import * as policyAuthority from "../../../adapters/openshell/policy-authority"; +import type { SandboxEntry } from "../../../state/registry"; +import * as registry from "../../../state/registry"; +import { preflightSandboxPolicyAuthority } from "./preflight"; + +const REQUIRED_POLICY = [ + "network_policies:", + " messaging_api:", + " endpoints:", + " - host: api.example.test", + " port: 443", + "", +].join("\n"); + +describe("sandbox policy authority preflight", () => { + let current: SandboxEntry; + let updateSandbox: ReturnType; + + beforeEach(() => { + current = { name: "alpha", gatewayName: "nemoclaw" } as SandboxEntry; + vi.spyOn(registry, "getSandbox").mockImplementation(() => current); + updateSandbox = vi.spyOn(registry, "updateSandbox").mockImplementation((_name, update) => { + current = { ...current, ...update } as SandboxEntry; + return true; + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("records external authority after every required entry matches (#9833)", () => { + const inspect = vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { + network_policies: { + messaging_api: { + endpoints: [{ host: "api.example.test", port: 443 }], + }, + }, + }, + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }); + + expect( + preflightSandboxPolicyAuthority({ + externalPolicy: "verify", + operation: "add channel 'example'", + requiredPolicyContents: [REQUIRED_POLICY], + sandboxName: "alpha", + }), + ).toBe("externally-managed"); + + expect(inspect).toHaveBeenCalledWith({ + gatewayName: "nemoclaw", + sandboxName: "alpha", + }); + expect(updateSandbox).toHaveBeenCalledWith("alpha", { + policyAuthority: "externally-managed", + }); + }); + + it("records external authority before rejecting a missing entry (#9833)", () => { + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { network_policies: {} }, + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }); + + expect(() => + preflightSandboxPolicyAuthority({ + externalPolicy: "verify", + operation: "add channel 'example'", + requiredPolicyContents: [REQUIRED_POLICY], + sandboxName: "alpha", + }), + ).toThrow(/missing entries "messaging_api"/); + expect(updateSandbox).toHaveBeenCalledWith("alpha", { + policyAuthority: "externally-managed", + }); + }); + + it("rejects policy authority drift before recording state (#9833)", () => { + current = { ...current, policyAuthority: "nemoclaw-managed" }; + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { network_policies: {} }, + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }); + + expect(() => + preflightSandboxPolicyAuthority({ + externalPolicy: "verify", + operation: "start channel 'example'", + requiredPolicyContents: [REQUIRED_POLICY], + sandboxName: "alpha", + }), + ).toThrow(/policy authority changed/); + expect(updateSandbox).not.toHaveBeenCalled(); + }); + + it("propagates an inconclusive policy inspection before recording state (#9833)", () => { + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockImplementation(() => { + throw new Error("OpenShell returned an unknown policy source"); + }); + + expect(() => + preflightSandboxPolicyAuthority({ + externalPolicy: "verify", + operation: "add channel 'example'", + requiredPolicyContents: [REQUIRED_POLICY], + sandboxName: "alpha", + }), + ).toThrow(/unknown policy source/); + expect(updateSandbox).not.toHaveBeenCalled(); + }); + + it("records external authority before refusing removal (#9833)", () => { + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { network_policies: {} }, + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }); + + expect(() => + preflightSandboxPolicyAuthority({ + externalPolicy: "refuse", + operation: "remove channel 'example'", + sandboxName: "alpha", + }), + ).toThrow(/externally managed/); + expect(updateSandbox).toHaveBeenCalledWith("alpha", { + policyAuthority: "externally-managed", + }); + }); + + it("records NemoClaw authority without requiring external entries (#9833)", () => { + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + policyIdentity: { hash: "managed-policy", activeVersion: 1 }, + }); + + expect( + preflightSandboxPolicyAuthority({ + externalPolicy: "verify", + operation: "restart managed MCP servers", + sandboxName: "alpha", + }), + ).toBe("nemoclaw-managed"); + expect(updateSandbox).toHaveBeenCalledWith("alpha", { + policyAuthority: "nemoclaw-managed", + }); + }); + + it("rejects an invalid required policy before inspecting or recording authority (#9833)", () => { + const inspect = vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority"); + + expect(() => + preflightSandboxPolicyAuthority({ + externalPolicy: "verify", + operation: "add channel 'example'", + requiredPolicyContents: ["network_policies: [invalid]"], + sandboxName: "alpha", + }), + ).toThrow(/required network policy document is invalid/); + expect(inspect).not.toHaveBeenCalled(); + expect(updateSandbox).not.toHaveBeenCalled(); + }); + + it("rejects an empty required policy before inspecting or recording authority (#9833)", () => { + const inspect = vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority"); + + expect(() => + preflightSandboxPolicyAuthority({ + externalPolicy: "verify", + operation: "add channel 'example'", + requiredPolicyContents: ["network_policies: {}"], + sandboxName: "alpha", + }), + ).toThrow(/required network policy document is invalid/); + expect(inspect).not.toHaveBeenCalled(); + expect(updateSandbox).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/policy-authority/preflight.ts b/src/lib/actions/sandbox/policy-authority/preflight.ts new file mode 100644 index 00000000000..847597bcdfd --- /dev/null +++ b/src/lib/actions/sandbox/policy-authority/preflight.ts @@ -0,0 +1,234 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isDeepStrictEqual } from "node:util"; +import YAML from "yaml"; + +import { + assertExternalPolicyRequirements, + assertObservedPolicyRequirements, + assertRecordedPolicyAuthority, + inspectActiveGlobalPolicy, + inspectOpenShellSandboxIdentityFingerprint, + inspectSandboxPolicyAuthority, + assertOpenShellGatewayPortBinding, + type SandboxPolicyAuthority, + type SandboxPolicyAuthorityInspection, +} from "../../../adapters/openshell/policy-authority"; +import { + qualifyGlobalPolicyAuthority, + qualifySandboxPolicyAuthority, +} from "../../../onboard/policy-authority/preflight"; +import { parseOpenShellPolicy } from "../../../policy/merge"; +import { isPresetPolicyMap, parseNetworkPolicies } from "../../../policy/preset-parsing"; +import * as registry from "../../../state/registry"; +import { getPersistedSandboxTargetGatewayName } from "../gateway-target"; + +export { isPolicyAuthorityRefusalError } from "../../../adapters/openshell/policy-authority"; + +interface SandboxPolicyAuthorityPreflightOptions { + readonly externalPolicy: "verify" | "refuse"; + readonly operation: string; + readonly requiredPolicyContents?: readonly string[]; + readonly sandboxName: string; +} + +export type RequiredPolicy = Record; +export type RecordedPolicyAuthority = Exclude; + +export interface PolicyAuthorityInspectionDeps { + readonly assertOpenShellGatewayPortBinding?: typeof assertOpenShellGatewayPortBinding; + readonly inspectActiveGlobalPolicy?: typeof inspectActiveGlobalPolicy; + readonly inspectOpenShellSandboxIdentityFingerprint?: typeof inspectOpenShellSandboxIdentityFingerprint; + readonly inspectSandboxPolicyAuthority?: typeof inspectSandboxPolicyAuthority; +} + +export interface PolicyAuthorityInspectionOptions { + readonly gatewayName: string; + readonly inspectLiveSource: boolean; + readonly operation: string; + readonly recordedAuthority: SandboxPolicyAuthority | null | undefined; + readonly requiredPolicies: readonly RequiredPolicy[]; + readonly sandboxName: string; + readonly verifyGlobalCreatePolicy: boolean; +} + +export function parseRequiredPolicyDocument(content: string, operation: string): RequiredPolicy { + try { + return parseOpenShellPolicy(content).policy; + } catch { + // The common refusal below owns invalid policy document errors. + } + throw new Error(`Refusing to ${operation}: a required network policy document is invalid.`); +} + +/** Inspect live and create policy authority, then verify requirements after the caller records it. */ +export function inspectPolicyAuthorityRequirements( + options: PolicyAuthorityInspectionOptions, + deps: PolicyAuthorityInspectionDeps = {}, +) { + const inspections: SandboxPolicyAuthorityInspection[] = []; + const authorities: RecordedPolicyAuthority[] = []; + const preparedRequirement = { + appliedPresets: [], + policyPath: "", + sourceBytes: Buffer.from( + YAML.stringify(options.requiredPolicies[0] ?? { version: 1, network_policies: {} }), + ), + }; + if (options.inspectLiveSource) { + const observed = (deps.inspectSandboxPolicyAuthority ?? inspectSandboxPolicyAuthority)({ + sandboxName: options.sandboxName, + gatewayName: options.gatewayName, + }); + if (observed.authority !== "owner-unknown") { + authorities.push(observed.authority); + if (observed.authority === "externally-managed") inspections.push(observed); + } else { + const recordedSandbox = registry.getSandbox(options.sandboxName); + const qualified = qualifySandboxPolicyAuthority( + { + sandboxName: options.sandboxName, + gatewayName: options.gatewayName, + liveExists: true, + recordedAuthorities: [options.recordedAuthority], + recordedSandbox, + readRecordedSandbox: registry.getSandbox, + prepareRequiredPolicy: () => preparedRequirement, + operation: options.operation, + }, + deps, + ); + authorities.push(qualified.authority); + if (qualified.authority === "externally-managed") inspections.push(qualified.inspection); + } + } + if (options.verifyGlobalCreatePolicy) { + const qualified = qualifyGlobalPolicyAuthority( + { + gatewayName: options.gatewayName, + recordedAuthority: options.inspectLiveSource ? undefined : options.recordedAuthority, + operation: options.operation, + }, + deps, + ); + authorities.push(qualified.authority); + if (qualified.authority === "externally-managed") inspections.push(qualified.inspection); + } + const [authority, ...additionalAuthorities] = authorities; + if (!authority) { + throw new Error(`Refusing to ${options.operation}: policy authority could not be inspected.`); + } + if (options.recordedAuthority !== undefined && options.recordedAuthority !== null) { + assertRecordedPolicyAuthority(options.recordedAuthority, authority, options.operation); + } + for (const additional of additionalAuthorities) { + assertRecordedPolicyAuthority(authority, additional, options.operation); + } + return { + authority, + liveInspection: options.inspectLiveSource ? (inspections[0] ?? null) : null, + verifyRequirements: () => assertPolicyAuthorityRequirements(options, inspections), + }; +} + +function assertPolicyAuthorityRequirements( + options: PolicyAuthorityInspectionOptions, + inspections: readonly SandboxPolicyAuthorityInspection[], +): void { + for (const inspection of inspections) { + for (const requiredPolicy of options.requiredPolicies) { + const assertRequirements = + inspection.authority === "owner-unknown" + ? assertObservedPolicyRequirements + : assertExternalPolicyRequirements; + assertRequirements({ + inspection, + requiredPolicy, + operation: options.operation, + sandboxName: options.sandboxName, + }); + } + } +} + +export function assertManagedMcpPolicyRequirementsUnchanged( + current: readonly RequiredPolicy[], + qualified: readonly RequiredPolicy[], + operation: string, + timing: string, +): void { + if (isDeepStrictEqual(current, qualified)) return; + throw new Error(`Refusing to ${operation}: managed MCP policy requirements changed ${timing}.`); +} + +function operationLabel(operation: string): string { + return operation.trim() || "continue the policy-dependent operation"; +} + +function persistObservedAuthority( + sandboxName: string, + authority: RecordedPolicyAuthority, + operation: string, +): void { + const current = registry.getSandbox(sandboxName); + if (!current) { + throw new Error(`Refusing to ${operation}: sandbox '${sandboxName}' is not registered.`); + } + if (current.policyAuthority !== undefined) { + assertRecordedPolicyAuthority(current.policyAuthority, authority, operation); + return; + } + if (registry.updateSandbox(sandboxName, { policyAuthority: authority })) return; + throw new Error( + `Refusing to ${operation}: the observed policy authority could not be recorded for sandbox '${sandboxName}'.`, + ); +} + +/** Inspect and persist policy authority before a policy-dependent lifecycle mutation. */ +export function preflightSandboxPolicyAuthority({ + externalPolicy, + operation, + requiredPolicyContents = [], + sandboxName, +}: SandboxPolicyAuthorityPreflightOptions): RecordedPolicyAuthority { + const label = operationLabel(operation); + const sandbox = registry.getSandbox(sandboxName); + if (!sandbox) { + throw new Error(`Refusing to ${label}: sandbox '${sandboxName}' is not registered.`); + } + const requiredPolicies = requiredPolicyContents.map((content) => { + const networkPolicies = parseNetworkPolicies(content); + if (!networkPolicies || !isPresetPolicyMap(networkPolicies)) { + throw new Error(`Refusing to ${label}: a required network policy document is invalid.`); + } + return { network_policies: networkPolicies }; + }); + const authorityOptions = { + gatewayName: getPersistedSandboxTargetGatewayName(sandbox), + inspectLiveSource: true, + operation: label, + recordedAuthority: sandbox.policyAuthority, + requiredPolicies, + sandboxName, + verifyGlobalCreatePolicy: false, + }; + const inspection = inspectPolicyAuthorityRequirements(authorityOptions); + persistObservedAuthority(sandboxName, inspection.authority, label); + + if (inspection.authority === "externally-managed") { + if (externalPolicy === "refuse") { + throw new Error( + `Refusing to ${label}: this sandbox policy is externally managed. Ask the external policy authority to remove this policy-dependent capability.`, + ); + } + if (requiredPolicyContents.length === 0) { + throw new Error( + `Refusing to ${label}: no required network policy entries were supplied for external verification.`, + ); + } + inspection.verifyRequirements(); + } + + return inspection.authority; +} diff --git a/src/lib/actions/sandbox/policy-authority/rebuild.test.ts b/src/lib/actions/sandbox/policy-authority/rebuild.test.ts new file mode 100644 index 00000000000..efd1da081a9 --- /dev/null +++ b/src/lib/actions/sandbox/policy-authority/rebuild.test.ts @@ -0,0 +1,491 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import YAML from "yaml"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + preflightMcpEntryTargets: vi.fn(), +})); + +vi.mock("../mcp-bridge-provider", () => ({ + preflightMcpEntryTargets: mocks.preflightMcpEntryTargets, +})); + +import * as policies from "../../../policy"; +import * as onboardSession from "../../../state/onboard-session"; +import * as registry from "../../../state/registry"; +import { buildMcpBridgePolicyName, buildMcpBridgePolicyYaml } from "../mcp-bridge-policy"; +import type { RebuildSandboxEntry } from "../rebuild-flow-helpers"; +import { makePreparedRecoveryManifest } from "../rebuild-flow-test-fixtures"; +import { qualifyRebuildPolicyAuthority } from "./rebuild"; + +const CUSTOM_POLICY = ` +network_policies: + custom-api: + endpoints: + - host: custom.example.com + port: 443 +`; + +function externalEffectivePolicy(includeCustom = true): Record { + const baseline = policies.resolveAgentBaselinePolicy("openclaw")!; + const parsedBaseline = YAML.parse(baseline.content) as Record & { + network_policies: Record; + }; + const parsedCustom = YAML.parse(CUSTOM_POLICY) as { + network_policies: Record; + }; + return { + ...parsedBaseline, + network_policies: { + ...parsedBaseline.network_policies, + ...(includeCustom ? parsedCustom.network_policies : {}), + }, + }; +} + +function sandboxEntry( + policyAuthority: RebuildSandboxEntry["policyAuthority"], +): RebuildSandboxEntry { + return { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + policyAuthority, + policies: [], + policyTier: "restricted", + customPolicies: [{ name: "custom-api", content: CUSTOM_POLICY, sourcePath: "/tmp/policy" }], + } as RebuildSandboxEntry; +} + +describe("rebuild policy authority preflight", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.preflightMcpEntryTargets.mockResolvedValue( + new Map([["github", { addresses: ["8.8.8.8"] }]]), + ); + vi.spyOn(onboardSession, "loadSession").mockReturnValue(null); + vi.spyOn(registry, "getConfiguredMessagingChannelsFromEntry").mockReturnValue([]); + vi.spyOn(registry, "getDisabledMessagingChannelsFromEntry").mockReturnValue([]); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("verifies every rebuild policy requirement before accepting external authority (#9833)", async () => { + const entry = sandboxEntry("externally-managed"); + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + const updateSandbox = vi.spyOn(registry, "updateSandbox"); + + const receipt = await qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: vi.fn(() => inspection), + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "active" as const, inspection })), + }, + ); + + expect(receipt.authority).toBe("externally-managed"); + expect(receipt.requiredPolicies).toHaveLength(2); + expect(updateSandbox).not.toHaveBeenCalled(); + }); + + it("verifies a durably external sandbox policy whose live owner is unknown (#9833)", async () => { + const recorded = { + ...sandboxEntry("externally-managed"), + gatewayPort: 8080, + lifecycleGeneration: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + lifecycleLiveIdentityFingerprint: "sandbox-identity", + } as RebuildSandboxEntry; + const inputEntry = { ...recorded }; + const sandboxInspection = { + authority: "owner-unknown" as const, + effectivePolicy: externalEffectivePolicy(), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + const globalInspection = { + ...sandboxInspection, + authority: "externally-managed" as const, + }; + vi.spyOn(registry, "getSandbox").mockReturnValue(recorded as never); + + const receipt = await qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: inputEntry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + assertOpenShellGatewayPortBinding: vi.fn(), + inspectOpenShellSandboxIdentityFingerprint: vi.fn(() => "sandbox-identity"), + inspectSandboxPolicyAuthority: vi.fn(() => sandboxInspection), + inspectActiveGlobalPolicy: vi.fn(() => ({ + state: "active" as const, + inspection: globalInspection, + })), + }, + ); + + expect(receipt.authority).toBe("externally-managed"); + expect(receipt.requiredPolicies).toHaveLength(2); + }); + + it("rejects a missing requirement from a durably external owner-unknown policy (#9833)", async () => { + const recorded = { + ...sandboxEntry("externally-managed"), + gatewayPort: 8080, + lifecycleGeneration: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + lifecycleLiveIdentityFingerprint: "sandbox-identity", + } as RebuildSandboxEntry; + const sandboxInspection = { + authority: "owner-unknown" as const, + effectivePolicy: externalEffectivePolicy(false), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + const globalInspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + vi.spyOn(registry, "getSandbox").mockReturnValue(recorded as never); + + await expect( + qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: { ...recorded }, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + assertOpenShellGatewayPortBinding: vi.fn(), + inspectOpenShellSandboxIdentityFingerprint: vi.fn(() => "sandbox-identity"), + inspectSandboxPolicyAuthority: vi.fn(() => sandboxInspection), + inspectActiveGlobalPolicy: vi.fn(() => ({ + state: "active" as const, + inspection: globalInspection, + })), + }, + ), + ).rejects.toThrow(/missing entries "custom-api"/); + }); + + it.each([ + ["an empty mapping", "{}\n"], + ["a diagnostic mapping", "diagnostic: failed\n"], + ["a non-positive version", "version: 0\nnetwork_policies: {}\n"], + ["a non-mapping network policy set", "version: 1\nnetwork_policies: []\n"], + ])("rejects %s as a required custom policy document (#9833)", async (_label, content) => { + const entry = sandboxEntry("externally-managed"); + entry.customPolicies = [{ name: "invalid", content, sourcePath: "/tmp/invalid-policy" }]; + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + + await expect( + qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: vi.fn(() => inspection), + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "active" as const, inspection })), + }, + ), + ).rejects.toThrow("a required network policy document is invalid"); + }); + + it("retains only agreed legacy authority when an external requirement is missing (#9833)", async () => { + const entry = sandboxEntry(undefined); + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(false), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + const updateSandbox = vi.spyOn(registry, "updateSandbox").mockReturnValue(true); + + await expect( + qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: vi.fn(() => inspection), + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "active" as const, inspection })), + }, + ), + ).rejects.toThrow(/missing entries "custom-api"/); + expect(updateSandbox).toHaveBeenCalledWith("alpha", { + policyAuthority: "externally-managed", + }); + expect(entry).toEqual({ + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + policies: [], + policyAuthority: "externally-managed", + }); + }); + + it("backfills legacy rebuild authority after live and global requirements match (#9833)", async () => { + const entry = sandboxEntry(undefined); + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + const updateSandbox = vi.spyOn(registry, "updateSandbox").mockReturnValue(true); + + const receipt = await qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: vi.fn(() => inspection), + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "active" as const, inspection })), + }, + ); + + expect(updateSandbox).toHaveBeenCalledWith("alpha", { + policyAuthority: "externally-managed", + }); + expect(entry).toEqual({ + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + policies: [], + policyAuthority: "externally-managed", + }); + expect(receipt.authority).toBe("externally-managed"); + }); + + it("uses recorded global authority when the rebuild source is absent (#9833)", async () => { + const entry = sandboxEntry("externally-managed"); + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + const inspectSandbox = vi.fn(); + + const receipt = await qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "missing" as const), + inspectSandboxPolicyAuthority: inspectSandbox, + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "active" as const, inspection })), + }, + ); + + expect(receipt.authority).toBe("externally-managed"); + expect(inspectSandbox).not.toHaveBeenCalled(); + }); + + it("omits a validated MCP recovery preset while retaining its exact requirement (#9833)", async () => { + const entry = sandboxEntry("externally-managed"); + const bridge = { + server: "github", + agent: "openclaw", + adapter: "mcporter" as const, + url: "https://mcp.example.test/mcp", + env: ["GITHUB_TOKEN"], + providerName: "alpha-mcp-github", + providerId: "provider-1", + policyName: buildMcpBridgePolicyName("github"), + addedAt: "2026-08-20T00:00:00.000Z", + }; + entry.mcp = { bridges: { github: bridge } }; + const manifest = { + ...makePreparedRecoveryManifest(), + policyPresets: ["npm", bridge.policyName], + customPolicies: entry.customPolicies, + }; + const baseline = policies.resolveAgentBaselinePolicy("openclaw")!; + const effectivePolicy = YAML.parse( + policies.mergePresetNamesIntoPolicy(baseline.content, ["npm"], { + agent: "openclaw", + }).policy, + ) as { + network_policies: Record; + }; + const customPolicy = YAML.parse(CUSTOM_POLICY) as { + network_policies: Record; + }; + const mcpPolicy = YAML.parse( + buildMcpBridgePolicyYaml( + bridge.server, + bridge.url, + bridge.adapter, + { addresses: ["8.8.8.8"] }, + bridge.providerName, + ), + ) as { network_policies: Record }; + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: { + ...effectivePolicy, + network_policies: { + ...effectivePolicy.network_policies, + ...customPolicy.network_policies, + ...mcpPolicy.network_policies, + }, + }, + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + + const receipt = await qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: vi.fn(() => inspection), + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "active" as const, inspection })), + }, + ); + + expect(receipt.requiredPolicies).toHaveLength(3); + expect(receipt.requiredPolicies[0]).toMatchObject({ + network_policies: { npm_yarn: expect.any(Object) }, + }); + expect(receipt.managedMcpPolicies).toHaveLength(1); + expect(receipt.requiredPolicies).toContainEqual(receipt.managedMcpPolicies[0]); + expect(receipt.managedMcpPolicies[0]).toMatchObject({ + network_policies: { + mcp_bridge_github: { + endpoints: [ + expect.objectContaining({ + allowed_ips: ["8.8.8.8"], + credential_binding: { provider: "alpha-mcp-github" }, + }), + ], + }, + }, + }); + }); + + it("refuses an unknown non-MCP preset from a recovery manifest (#9833)", async () => { + const entry = sandboxEntry("externally-managed"); + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + const inspectSandbox = vi.fn(() => inspection); + const inspectGlobal = vi.fn(() => ({ state: "active" as const, inspection })); + + await expect( + qualifyRebuildPolicyAuthority( + { + sandboxName: "alpha", + sandboxEntry: entry, + manifest: { + ...makePreparedRecoveryManifest(), + policyPresets: ["retired-custom-policy"], + }, + }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: inspectSandbox, + inspectActiveGlobalPolicy: inspectGlobal, + }, + ), + ).rejects.toThrow( + "recorded policy preset \"retired-custom-policy\" is neither a current built-in policy preset for 'openclaw' nor a validated managed MCP policy", + ); + expect(inspectSandbox).toHaveBeenCalledOnce(); + expect(inspectGlobal).toHaveBeenCalledOnce(); + }); + + it("refuses malformed recorded preset metadata (#9833)", async () => { + const entry = sandboxEntry("externally-managed"); + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + + await expect( + qualifyRebuildPolicyAuthority( + { + sandboxName: "alpha", + sandboxEntry: entry, + manifest: { + ...makePreparedRecoveryManifest(), + policyPresets: [null] as never, + }, + }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: vi.fn(() => inspection), + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "active" as const, inspection })), + }, + ), + ).rejects.toThrow("recorded policy preset metadata is invalid"); + }); + + it("refuses malformed custom policy metadata before reading its source (#9833)", async () => { + const entry = sandboxEntry("externally-managed"); + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + + await expect( + qualifyRebuildPolicyAuthority( + { + sandboxName: "alpha", + sandboxEntry: entry, + manifest: { + ...makePreparedRecoveryManifest(), + customPolicies: [null] as never, + }, + }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: vi.fn(() => inspection), + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "active" as const, inspection })), + }, + ), + ).rejects.toThrow("required custom policy metadata is invalid"); + }); + + it("refuses an absent legacy source without recording current global authority (#9833)", async () => { + const entry = sandboxEntry(undefined); + const inspectSandbox = vi.fn(); + const updateSandbox = vi.spyOn(registry, "updateSandbox"); + + await expect( + qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "missing" as const), + inspectSandboxPolicyAuthority: inspectSandbox, + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "absent" as const })), + }, + ), + ).rejects.toThrow(/sandbox is absent and its recorded policy authority is missing/); + expect(inspectSandbox).not.toHaveBeenCalled(); + expect(updateSandbox).not.toHaveBeenCalled(); + }); + + it("rejects missing external requirements while the rebuild source is absent (#9833)", async () => { + const entry = sandboxEntry("externally-managed"); + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: externalEffectivePolicy(false), + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }; + const inspectSandbox = vi.fn(); + + await expect( + qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "missing" as const), + inspectSandboxPolicyAuthority: inspectSandbox, + inspectActiveGlobalPolicy: vi.fn(() => ({ state: "active" as const, inspection })), + }, + ), + ).rejects.toThrow(/missing entries "custom-api"/); + expect(inspectSandbox).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/policy-authority/rebuild.ts b/src/lib/actions/sandbox/policy-authority/rebuild.ts new file mode 100644 index 00000000000..6941d9a8e1b --- /dev/null +++ b/src/lib/actions/sandbox/policy-authority/rebuild.ts @@ -0,0 +1,286 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; + +import { assertRecordedPolicyAuthority } from "../../../adapters/openshell/policy-authority"; + +export { isPolicyAuthorityRefusalError } from "../../../adapters/openshell/policy-authority"; +import { prepareInitialSandboxCreatePolicy } from "../../../onboard/initial-policy"; +import { mergeRebuildMessagingPolicyPresets } from "../../../onboard/messaging-policy-presets"; +import { normalizePolicyTierName } from "../../../onboard/policy-tier-suppression"; +import { + observeSandboxPresenceOnGateway, + type SandboxGatewayPresence, +} from "../../../onboard/sandbox-recreate-probe"; +import * as policies from "../../../policy"; +import * as registry from "../../../state/registry"; +import type { RebuildManifest } from "../../../state/sandbox"; +import { getPersistedSandboxTargetGatewayName } from "../gateway-target"; +import { MCP_BRIDGE_POLICY_SOURCE } from "../mcp-bridge-policy"; +import { normalizeRebuildTargetPolicyPresets } from "../rebuild-backup-phase"; +import { resolveRebuildDurableConfig } from "../rebuild-durable-config"; +import type { RebuildSandboxEntry } from "../rebuild-flow-helpers"; +import { resolveManagedMcpPolicyRequirementContents } from "./mcp-requirements"; +import { + assertManagedMcpPolicyRequirementsUnchanged, + inspectPolicyAuthorityRequirements, + parseRequiredPolicyDocument, + type PolicyAuthorityInspectionDeps, + type RecordedPolicyAuthority, + type RequiredPolicy, +} from "./preflight"; + +export interface RebuildPolicyAuthorityReceipt { + readonly authority: RecordedPolicyAuthority; + readonly gatewayName: string; + readonly managedMcpPolicies: readonly RequiredPolicy[]; + readonly operation: string; + readonly requiredPolicies: readonly RequiredPolicy[]; + readonly sandboxName: string; +} + +interface RebuildPolicyAuthorityDeps extends PolicyAuthorityInspectionDeps { + readonly observeSandboxPresence?: (target: { + readonly gatewayName: string; + readonly sandboxName: string; + }) => SandboxGatewayPresence; +} + +function parseRequiredPolicy(content: string, operation: string): RequiredPolicy { + const parsed = parseRequiredPolicyDocument(content, operation); + const networkPolicies = parsed.network_policies; + if ( + networkPolicies !== undefined && + (typeof networkPolicies !== "object" || + networkPolicies === null || + Array.isArray(networkPolicies)) + ) { + throw new Error(`Refusing to ${operation}: a required network policy document is invalid.`); + } + return parsed; +} + +function readPreparedPolicy( + policy: ReturnType, + operation: string, +): string { + let content: string; + let cleanupFailed = false; + try { + content = fs.readFileSync(policy.policyPath, "utf8"); + } catch { + throw new Error(`Refusing to ${operation}: the required rebuild policy is unreadable.`); + } finally { + if (policy.cleanup && policy.cleanup() !== true) cleanupFailed = true; + } + if (cleanupFailed) { + throw new Error(`Refusing to ${operation}: the temporary rebuild policy could not be removed.`); + } + return content; +} + +async function resolveRequiredPolicies(input: { + readonly manifest: RebuildManifest | null; + readonly operation: string; + readonly requestedObservabilityEnabled?: boolean; + readonly sandboxEntry: RebuildSandboxEntry; + readonly sandboxName: string; +}): Promise<{ managedMcpPolicies: RequiredPolicy[]; requiredPolicies: RequiredPolicy[] }> { + const { manifest, operation, requestedObservabilityEnabled, sandboxEntry, sandboxName } = input; + const agentName = sandboxEntry.agent || "openclaw"; + const baseline = policies.resolveAgentBaselinePolicy(agentName); + if (!baseline) { + throw new Error( + `Refusing to ${operation}: the '${agentName}' baseline network policy is unavailable.`, + ); + } + + const durableConfig = resolveRebuildDurableConfig(sandboxName, sandboxEntry); + if (durableConfig.webSearchError) { + throw new Error(`Refusing to ${operation}: ${durableConfig.webSearchError}.`); + } + const managedMcpPolicies = ( + await resolveManagedMcpPolicyRequirementContents(sandboxEntry, operation) + ).map((content) => parseRequiredPolicy(content, operation)); + const validatedMcpPresetNames = new Set( + Object.values(sandboxEntry.mcp?.bridges ?? {}).map((bridge) => bridge.policyName), + ); + const disabledChannels = registry.getDisabledMessagingChannelsFromEntry(sandboxEntry); + const activeChannels = registry + .getConfiguredMessagingChannelsFromEntry(sandboxEntry) + .filter((channel) => !disabledChannels.includes(channel)); + const builtinPresetNames = new Set( + policies.listPresets({ agent: agentName }).map((preset) => preset.name), + ); + const authoritativePresets = manifest?.policyPresets ?? sandboxEntry.policies ?? []; + const recordedPresets: string[] = []; + for (const preset of authoritativePresets) { + if (typeof preset !== "string" || preset.length === 0) { + throw new Error(`Refusing to ${operation}: recorded policy preset metadata is invalid.`); + } + if (builtinPresetNames.has(preset)) { + recordedPresets.push(preset); + continue; + } + if (validatedMcpPresetNames.has(preset)) continue; + throw new Error( + `Refusing to ${operation}: recorded policy preset ${JSON.stringify(preset)} is neither a current built-in policy preset for '${agentName}' nor a validated managed MCP policy.`, + ); + } + const manifestPresets = manifest?.policyPresets === undefined ? undefined : recordedPresets; + const mergedPresets = mergeRebuildMessagingPolicyPresets( + manifestPresets, + recordedPresets, + activeChannels, + disabledChannels, + ); + const targetEntry = { + ...sandboxEntry, + observabilityEnabled: requestedObservabilityEnabled ?? sandboxEntry.observabilityEnabled, + }; + const targetPresets = normalizeRebuildTargetPolicyPresets( + mergedPresets, + targetEntry, + durableConfig.webSearchConfig, + ); + const prepared = prepareInitialSandboxCreatePolicy(baseline.policyPath, activeChannels, { + additionalPresets: targetPresets, + agentName, + baselineExclusions: sandboxEntry.baselineExclusions ?? [], + policyTier: normalizePolicyTierName(sandboxEntry.policyTier), + }); + const required = [parseRequiredPolicy(readPreparedPolicy(prepared, operation), operation)]; + const customPolicies = manifest?.customPolicies ?? sandboxEntry.customPolicies ?? []; + for (const custom of customPolicies) { + if ( + !custom || + typeof custom.name !== "string" || + custom.name.length === 0 || + typeof custom.content !== "string" || + custom.content.length === 0 + ) { + throw new Error(`Refusing to ${operation}: required custom policy metadata is invalid.`); + } + if (custom.sourcePath === MCP_BRIDGE_POLICY_SOURCE) continue; + required.push(parseRequiredPolicy(custom.content, operation)); + } + required.push(...managedMcpPolicies); + return { managedMcpPolicies, requiredPolicies: required }; +} + +function inspectRebuildPolicyAuthority( + receipt: Omit, + recordedAuthority: RebuildSandboxEntry["policyAuthority"], + deps: RebuildPolicyAuthorityDeps, +): ReturnType { + const inspectLiveSource = + (deps.observeSandboxPresence ?? observeSandboxPresenceOnGateway)({ + sandboxName: receipt.sandboxName, + gatewayName: receipt.gatewayName, + }) !== "missing"; + if (!inspectLiveSource && recordedAuthority === undefined) { + throw new Error( + `Refusing to ${receipt.operation}: the sandbox is absent and its recorded policy authority is missing.`, + ); + } + return inspectPolicyAuthorityRequirements( + { + ...receipt, + inspectLiveSource, + recordedAuthority, + verifyGlobalCreatePolicy: true, + }, + deps, + ); +} + +/** Qualify both the live source and its recreate policy before rebuild effects. */ +export async function qualifyRebuildPolicyAuthority( + input: { + readonly manifest: RebuildManifest | null; + readonly requestedObservabilityEnabled?: boolean; + readonly sandboxEntry: RebuildSandboxEntry; + readonly sandboxName: string; + }, + deps: RebuildPolicyAuthorityDeps = {}, +): Promise { + const operation = `rebuild sandbox '${input.sandboxName}'`; + const requirementEntry = { ...input.sandboxEntry }; + const authorityReceipt = { + gatewayName: getPersistedSandboxTargetGatewayName(input.sandboxEntry), + managedMcpPolicies: [], + operation, + requiredPolicies: [], + sandboxName: input.sandboxName, + }; + const authorityInspection = inspectRebuildPolicyAuthority( + authorityReceipt, + input.sandboxEntry.policyAuthority, + deps, + ); + const { authority } = authorityInspection; + if ( + input.sandboxEntry.policyAuthority === undefined && + !registry.updateSandbox(input.sandboxName, { policyAuthority: authority }) + ) { + throw new Error( + `Refusing to ${operation}: the observed policy authority could not be recorded.`, + ); + } + const normalizedEntry = registry.normalizeSandboxPolicyAttribution({ + ...input.sandboxEntry, + policyAuthority: authority, + }); + delete input.sandboxEntry.policies; + delete input.sandboxEntry.customPolicies; + delete input.sandboxEntry.baselineExclusions; + delete input.sandboxEntry.baselineExclusionTransition; + delete input.sandboxEntry.policyPresetsFinalized; + delete input.sandboxEntry.policyTier; + delete input.sandboxEntry.policyAuthority; + Object.assign(input.sandboxEntry, normalizedEntry); + authorityInspection.verifyRequirements(); + + if (authority === "nemoclaw-managed") { + return { ...authorityReceipt, authority }; + } + + const { managedMcpPolicies, requiredPolicies } = await resolveRequiredPolicies({ + ...input, + sandboxEntry: requirementEntry, + operation, + }); + const receipt = { ...authorityReceipt, managedMcpPolicies, requiredPolicies }; + const requirementInspection = inspectRebuildPolicyAuthority(receipt, authority, deps); + requirementInspection.verifyRequirements(); + return { ...receipt, authority }; +} + +/** Recheck the exact rebuild policy authority immediately before lifecycle effects. */ +export async function revalidateRebuildPolicyAuthority( + receipt: RebuildPolicyAuthorityReceipt, + deps: RebuildPolicyAuthorityDeps = {}, +): Promise { + const current = registry.getSandbox(receipt.sandboxName); + if (!current) { + throw new Error(`Refusing to ${receipt.operation}: the sandbox is no longer registered.`); + } + if (current.policyAuthority === undefined) { + throw new Error(`Refusing to ${receipt.operation}: the recorded policy authority is missing.`); + } + assertRecordedPolicyAuthority(current.policyAuthority, receipt.authority, receipt.operation); + if (receipt.authority === "externally-managed") { + const currentManagedMcpPolicies = ( + await resolveManagedMcpPolicyRequirementContents(current, receipt.operation) + ).map((content) => parseRequiredPolicy(content, receipt.operation)); + assertManagedMcpPolicyRequirementsUnchanged( + currentManagedMcpPolicies, + receipt.managedMcpPolicies, + receipt.operation, + "after qualification", + ); + } + const authorityCheck = inspectRebuildPolicyAuthority(receipt, current.policyAuthority, deps); + authorityCheck.verifyRequirements(); +} diff --git a/src/lib/actions/sandbox/rebuild-backup-phase.test.ts b/src/lib/actions/sandbox/rebuild-backup-phase.test.ts index 146a6c4d22e..dbfa25b478e 100644 --- a/src/lib/actions/sandbox/rebuild-backup-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-backup-phase.test.ts @@ -71,6 +71,7 @@ describe("rebuild web-search policy normalization", () => { sandboxEntry: { name: "alpha", agent: "openclaw", + policyAuthority: "nemoclaw-managed", policies: ["tavily"], customPolicies: [{ name: "tavily", content: "allow: []" }], policyPresetsFinalized: true, @@ -94,6 +95,44 @@ describe("rebuild web-search policy normalization", () => { expect(result?.backupWasForceSkipped).toBe(false); }); + it.each([ + ["absent", undefined], + ["null", null], + ] as const)( + "does not infer managed preset carry-forward when policy authority is %s (#9833)", + (_label, policyAuthority) => { + const result = runRebuildBackupPhase({ + sandboxName: "alpha", + sandboxEntry: { + name: "alpha", + agent: "openclaw", + policyAuthority: policyAuthority as never, + policies: ["github"], + policyPresetsFinalized: true, + policyTier: "personal", + observabilityEnabled: true, + }, + staleRecovery: false, + preparedRecoveryManifest: { + policyPresets: ["npm"], + } as never, + messagingPlan: { + channels: [{ channelId: "slack", disabled: false }], + disabledChannels: [], + } as never, + webSearchConfig: { fetchEnabled: true, provider: "tavily" }, + log: vi.fn(), + bail: (message): never => { + throw new Error(message); + }, + relockShieldsIfNeeded: () => true, + }); + + expect(result?.policyPresets).toEqual([]); + expect(result?.sessionPolicyPresets).toBeNull(); + }, + ); + it("removes inactive built-in Hermes channel egress during rebuild", () => { const customDiscordPolicy = { name: "discord", content: "network_policies: {}\n" }; const preparedRecoveryManifest = { @@ -106,6 +145,7 @@ describe("rebuild web-search policy normalization", () => { sandboxEntry: { name: "alpha", agent: "hermes", + policyAuthority: "nemoclaw-managed", policies: ["discord"], customPolicies: [customDiscordPolicy], policyPresetsFinalized: true, diff --git a/src/lib/actions/sandbox/rebuild-backup-phase.ts b/src/lib/actions/sandbox/rebuild-backup-phase.ts index 940cfde728d..f1a8dae71a5 100644 --- a/src/lib/actions/sandbox/rebuild-backup-phase.ts +++ b/src/lib/actions/sandbox/rebuild-backup-phase.ts @@ -214,46 +214,60 @@ export function runRebuildBackupPhase( const backupWasForceSkipped = input.force === true && !input.staleRecovery && backupManifest === null; - const registryPolicyPresets = Array.isArray(input.sandboxEntry.policies) - ? input.sandboxEntry.policies.filter( - (value: unknown): value is string => typeof value === "string", - ) + const carriesManagedPolicyPresets = input.sandboxEntry.policyAuthority === "nemoclaw-managed"; + const registryPolicyPresets = carriesManagedPolicyPresets + ? Array.isArray(input.sandboxEntry.policies) + ? input.sandboxEntry.policies.filter( + (value: unknown): value is string => typeof value === "string", + ) + : [] : []; - const disabledChannels = [...(input.messagingPlan?.disabledChannels ?? [])]; - const enabledChannelIds = (input.messagingPlan?.channels ?? []) - .filter((channel) => !channel.disabled) - .map((channel) => channel.channelId); - const mergedPolicyPresets = mergeRebuildMessagingPolicyPresets( - backupManifest?.policyPresets, - registryPolicyPresets, - enabledChannelIds, - disabledChannels, - ); - const activeMessagingPolicyPresets = input.messagingPlan - ? pruneInactiveMessagingPolicyPresets( - mergedPolicyPresets, + const disabledChannels = carriesManagedPolicyPresets + ? [...(input.messagingPlan?.disabledChannels ?? [])] + : []; + const enabledChannelIds = carriesManagedPolicyPresets + ? (input.messagingPlan?.channels ?? []) + .filter((channel) => !channel.disabled) + .map((channel) => channel.channelId) + : []; + const mergedPolicyPresets = carriesManagedPolicyPresets + ? mergeRebuildMessagingPolicyPresets( + backupManifest?.policyPresets, + registryPolicyPresets, enabledChannelIds, - new Set( - (input.sandboxEntry.customPolicies ?? []).map((policy) => - policy.name.trim().toLowerCase(), + disabledChannels, + ) + : []; + const activeMessagingPolicyPresets = + carriesManagedPolicyPresets && input.messagingPlan + ? pruneInactiveMessagingPolicyPresets( + mergedPolicyPresets, + enabledChannelIds, + new Set( + (input.sandboxEntry.customPolicies ?? []).map((policy) => + policy.name.trim().toLowerCase(), + ), ), - ), + ) + : mergedPolicyPresets; + const policyPresets = carriesManagedPolicyPresets + ? normalizeRebuildTargetPolicyPresets( + activeMessagingPolicyPresets, + input.sandboxEntry, + input.webSearchConfig, ) - : mergedPolicyPresets; - const policyPresets = normalizeRebuildTargetPolicyPresets( - activeMessagingPolicyPresets, - input.sandboxEntry, - input.webSearchConfig, - ); - const sessionPolicyPresets = resolveRecreatePolicyPresets( - policyPresets, - input.sandboxEntry.policyPresetsFinalized === true, - // Rebuild now replays exact custom policy content after recreate, so the - // built-in selection can independently preserve an intentional empty set. - false, - {}, - true, - ).policyPresets; + : []; + const sessionPolicyPresets = carriesManagedPolicyPresets + ? resolveRecreatePolicyPresets( + policyPresets, + input.sandboxEntry.policyPresetsFinalized === true, + // Rebuild now replays exact custom policy content after recreate, so the + // built-in selection can independently preserve an intentional empty set. + false, + {}, + true, + ).policyPresets + : null; return { backupManifest, backupWasForceSkipped, policyPresets, sessionPolicyPresets }; } diff --git a/src/lib/actions/sandbox/rebuild-dcode-mutation-edge.test.ts b/src/lib/actions/sandbox/rebuild-dcode-mutation-edge.test.ts index a4d3c5f98fa..bfb4aa50016 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-mutation-edge.test.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-mutation-edge.test.ts @@ -90,7 +90,11 @@ describe("rebuildSandbox DCode flow: mutation edge", () => { expect(harness.disposePreparedDcodeRebuildImageSpy).toHaveBeenCalledWith( harness.preparedDcodeBuildContext, ); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + [mcpEntry], + expect.any(Function), + ); }); it("rolls back managed MCP mutation when DCode inputs drift during MCP preparation (#6195)", async () => { const detached = { server: "search", providerName: "mcp-search" }; @@ -112,11 +116,15 @@ describe("rebuildSandbox DCode flow: mutation edge", () => { harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), ).rejects.toThrow("the prepared DCode replacement inputs changed before deletion"); - expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith("alpha"); + expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith( + "alpha", + expect.any(Function), + ); expect(harness.reattachMcpProvidersAfterRebuildAbortSpy).toHaveBeenCalledWith( "alpha", [detached], [scrubbed], + expect.any(Function), ); expectNoSandboxDelete(harness.runOpenshellSpy); expect(harness.onboardSpy).not.toHaveBeenCalled(); diff --git a/src/lib/actions/sandbox/rebuild-dcode-pre-delete-drift.test.ts b/src/lib/actions/sandbox/rebuild-dcode-pre-delete-drift.test.ts index 5dffdc1549a..518763cbc23 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-pre-delete-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-pre-delete-drift.test.ts @@ -130,6 +130,8 @@ describe("rebuildSandbox DCode flow: pre-delete drift", () => { sandboxEntryReads: [ originalEntry, // Initial rebuild target. originalEntry, // Exact post-confirmation lock guard. + originalEntry, // Managed-policy receipt qualification. + originalEntry, // Managed-policy receipt stability read. originalEntry, // Messaging config hydration. originalEntry, // Messaging-conflict gateway lookup (#5954). driftedEntry, // Final pre-backup target verification. @@ -180,10 +182,15 @@ describe("rebuildSandbox DCode flow: pre-delete drift", () => { sandboxEntryReads: [ originalEntry, // Initial rebuild target. originalEntry, // Exact post-confirmation lock guard. + originalEntry, // Managed-policy receipt qualification. + originalEntry, // Managed-policy receipt stability read. originalEntry, // Messaging config hydration. originalEntry, // Messaging-conflict gateway lookup (#5954). originalEntry, // Final pre-backup target verification. - driftedEntry, // Registry reread at the destructive boundary. + originalEntry, // Destructive-edge receipt qualification. + originalEntry, // Destructive-edge receipt stability read. + originalEntry, // Destructive-edge authority reread. + driftedEntry, // Policy-authority reread at the destructive boundary. ], dcodeRouteResults: [{ ok: true }, { ok: true }, { ok: true }], }); diff --git a/src/lib/actions/sandbox/rebuild-dcode-preflight.test.ts b/src/lib/actions/sandbox/rebuild-dcode-preflight.test.ts index f7bc8f017d0..21d356169c6 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-preflight.test.ts @@ -28,25 +28,28 @@ describe("rebuildSandbox DCode flow: preflight", () => { "thread-opt-in", "recorded dcodeAutoApprovalMode value must be disabled or thread-opt-in", ], - ] as const)("resolves durable DCode mode: %s (#6478)", (_label, recorded, requested, expected, error) => { - const config = resolveRebuildDurableConfig( - "alpha", - { - name: "alpha", - agent: "langchain-deepagents-code", - nemoclawVersion: "0.1.0", - ...(recorded !== undefined ? { dcodeAutoApprovalMode: recorded as never } : {}), - }, - null, - undefined, - undefined, - false, - requested, - ); - - expect(config.dcodeAutoApprovalMode).toBe(expected); - expect(config.dcodeAutoApprovalModeError).toBe(error); - }); + ] as const)( + "resolves durable DCode mode: %s (#6478)", + (_label, recorded, requested, expected, error) => { + const config = resolveRebuildDurableConfig( + "alpha", + { + name: "alpha", + agent: "langchain-deepagents-code", + nemoclawVersion: "0.1.0", + ...(recorded !== undefined ? { dcodeAutoApprovalMode: recorded as never } : {}), + }, + null, + undefined, + undefined, + false, + requested, + ); + + expect(config.dcodeAutoApprovalMode).toBe(expected); + expect(config.dcodeAutoApprovalModeError).toBe(error); + }, + ); it("rejects a DCode auto-approval override for unsupported agents before mutation (#6478)", async () => { const harness = createRebuildFlowHarness({ diff --git a/src/lib/actions/sandbox/rebuild-dcode-recovery.test.ts b/src/lib/actions/sandbox/rebuild-dcode-recovery.test.ts index ff8dc935287..2dc2122b5c1 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-recovery.test.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-recovery.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest"; import { configureDcodeSession, + expectNoDcodeMutation, makeDcodeSandboxEntry, } from "../../../../test/helpers/rebuild-dcode-flow-helpers"; import { @@ -53,6 +54,30 @@ describe("rebuildSandbox DCode flow: recovery", () => { { targetAgentType: "langchain-deepagents-code" }, ); }); + + it("refuses an absent legacy DCode sandbox without a recorded policy authority (#9833)", async () => { + const harness = createRebuildFlowHarness({ + agentName: "langchain-deepagents-code", + sandboxEntry: { + ...makeDcodeSandboxEntry(), + policyAuthority: undefined, + }, + sandboxInventory: { sandboxes: [] }, + reconciledSandboxGatewayState: { state: "missing", output: "" }, + }); + configureDcodeSession(harness); + + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).rejects.toThrow("Policy authority preflight failed"); + + expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain( + "the sandbox is absent and its recorded policy authority is missing", + ); + expect(harness.registryUpdateSpy).not.toHaveBeenCalled(); + expectNoDcodeMutation(harness); + }); + it("replays captured custom policies during stale DCode recovery without a backup (#6195)", async () => { const customPolicy = { name: "custom-egress", @@ -64,6 +89,7 @@ describe("rebuildSandbox DCode flow: recovery", () => { sandboxEntry: { ...makeDcodeSandboxEntry(), customPolicies: [customPolicy], + policyAuthority: "nemoclaw-managed", policyPresetsFinalized: true, }, sandboxInventory: { sandboxes: [] }, @@ -181,68 +207,85 @@ describe("rebuildSandbox DCode flow: recovery", () => { backupPresets: ["observability-otlp-local"], gatewayPresets: ["observability-otlp-local"], }, - ])("$label observability transactionally while preserving managed MCP state", async ({ - flag, - before, - expected, - expectedObservabilityApplyCalls, - backupPresets, - gatewayPresets, - }) => { - const mcpEntry = { server: "search", providerName: "mcp-search" }; - const harness = createRebuildFlowHarness({ - agentName: "langchain-deepagents-code", - applyPreset: () => true, - backupPolicyPresets: backupPresets, - dcodeRouteResults: [{ ok: true }, { ok: true }, { ok: true }, { ok: true }], + ])( + "$label observability transactionally while preserving managed MCP state", + async ({ + flag, + before, + expected, + expectedObservabilityApplyCalls, + backupPresets, gatewayPresets, - mcpPreparation: { - entries: [mcpEntry], - detachedProviderEntries: [mcpEntry], - scrubbedAdapterEntries: [], - }, - sandboxEntry: { - ...makeDcodeSandboxEntry(), - observabilityEnabled: before, - policies: backupPresets, - policyPresetsFinalized: true, - policyTier: "balanced", - mcp: { - bridges: { search: mcpEntry }, - managedServerNames: ["search"], + }) => { + const mcpEntry = { + server: "search", + agent: "langchain-deepagents-code", + adapter: "deepagents-config", + url: "https://mcp.example.test/mcp", + env: ["SEARCH_API_KEY"], + providerName: "mcp-search", + providerId: "provider-search", + policyName: "mcp-bridge-search", + addedAt: "2026-06-01T00:00:00.000Z", + }; + const harness = createRebuildFlowHarness({ + agentName: "langchain-deepagents-code", + applyPreset: () => true, + backupPolicyPresets: backupPresets, + dcodeRouteResults: [{ ok: true }, { ok: true }, { ok: true }, { ok: true }], + gatewayPresets, + mcpPreparation: { + entries: [mcpEntry], + detachedProviderEntries: [mcpEntry], + scrubbedAdapterEntries: [], }, - }, - }); - configureDcodeSession(harness); - harness.session.observabilityEnabled = before; + sandboxEntry: { + ...makeDcodeSandboxEntry(), + observabilityEnabled: before, + policies: backupPresets, + policyPresetsFinalized: true, + policyTier: "balanced", + mcp: { + bridges: { search: mcpEntry }, + managedServerNames: ["search"], + }, + }, + }); + configureDcodeSession(harness); + harness.session.observabilityEnabled = before; - await expect( - harness.rebuildSandbox("alpha", ["--yes", flag], { throwOnError: true }), - ).resolves.toBeUndefined(); + await expect( + harness.rebuildSandbox("alpha", ["--yes", flag], { throwOnError: true }), + ).resolves.toBeUndefined(); - expect(harness.onboardSpy).toHaveBeenCalledWith( - expect.objectContaining({ - observabilityEnabled: expected, - observabilityRequestedExplicitly: true, - }), - ); - expect(harness.session.observabilityEnabled).toBe(expected); - expect(harness.session.observabilityRequestedExplicitly).toBe(true); - const observabilityApplyCalls = harness.applyPresetSpy.mock.calls.filter( - ([sandboxName, presetName]) => - sandboxName === "alpha" && presetName === "observability-otlp-local", - ); - expect(observabilityApplyCalls).toEqual(expectedObservabilityApplyCalls); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); - expect(harness.registryUpdateSpy).toHaveBeenCalledWith( - "alpha", - expect.objectContaining({ - policies: expected ? ["observability-otlp-local"] : [], - policyTier: "balanced", - policyPresetsFinalized: true, - }), - ); - }); + expect(harness.onboardSpy).toHaveBeenCalledWith( + expect.objectContaining({ + observabilityEnabled: expected, + observabilityRequestedExplicitly: true, + }), + ); + expect(harness.session.observabilityEnabled).toBe(expected); + expect(harness.session.observabilityRequestedExplicitly).toBe(true); + const observabilityApplyCalls = harness.applyPresetSpy.mock.calls.filter( + ([sandboxName, presetName]) => + sandboxName === "alpha" && presetName === "observability-otlp-local", + ); + expect(observabilityApplyCalls).toEqual(expectedObservabilityApplyCalls); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + [mcpEntry], + expect.any(Function), + ); + expect(harness.registryUpdateSpy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + policies: expected ? ["observability-otlp-local"] : [], + policyTier: "balanced", + policyPresetsFinalized: true, + }), + ); + }, + ); it("preserves a fresh agent-required preset introduced by inner onboard", async () => { const freshRequiredPreset = "future-dcode-required"; diff --git a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts index 7407778b1c2..d9ceda0b10b 100644 --- a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts @@ -319,52 +319,56 @@ describe("rebuild destroy phase", () => { gatewayPort: 29080, }, ], - ])("refuses deletion when the registry %s changes before MCP preparation (#7062)", async (_label, currentEntry) => { - mocks.getSandbox.mockReturnValue(currentEntry); - mocks.prepareMcpForRebuild.mockResolvedValue({ - entries: [{ server: "github" }], - detachedProviderEntries: [{ server: "github" }], - scrubbedAdapterEntries: [], - }); - const relockShieldsIfNeeded = vi.fn(() => true); - - await expect( - runRebuildDestroyPhase({ - sandboxName: "alpha", - sandboxEntry: { - name: "alpha", - agent: "openclaw", - gatewayName: "nemoclaw", - gatewayPort: 8080, - }, - staleRecovery: false, - recreateJournal: stubRecreateJournal(), - backupManifest: null, - force: true, - log: vi.fn(), - bail: vi.fn((message: string): never => { - throw new Error(message); + ])( + "refuses deletion when the registry %s changes before MCP preparation (#7062)", + async (_label, currentEntry) => { + mocks.getSandbox.mockReturnValue(currentEntry); + mocks.prepareMcpForRebuild.mockResolvedValue({ + entries: [{ server: "github" }], + detachedProviderEntries: [{ server: "github" }], + scrubbedAdapterEntries: [], + }); + const relockShieldsIfNeeded = vi.fn(() => true); + + await expect( + runRebuildDestroyPhase({ + sandboxName: "alpha", + sandboxEntry: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + gatewayPort: 8080, + }, + staleRecovery: false, + recreateJournal: stubRecreateJournal(), + backupManifest: null, + force: true, + log: vi.fn(), + bail: vi.fn((message: string): never => { + throw new Error(message); + }), + relockShieldsIfNeeded, + onDeleted: vi.fn(), }), - relockShieldsIfNeeded, - onDeleted: vi.fn(), - }), - ).rejects.toThrow("Sandbox delete target changed during rebuild preparation."); - - expect(mocks.getSandbox).toHaveBeenCalledTimes(2); - expect(mocks.prepareMcpForRebuild.mock.invocationCallOrder[0]).toBeLessThan( - mocks.getSandbox.mock.invocationCallOrder[1] ?? Number.POSITIVE_INFINITY, - ); - expect(mocks.runOpenshell).not.toHaveBeenCalled(); - expect(mocks.reattachMcpAfterDeleteFailure).toHaveBeenCalledWith( - "alpha", - [{ server: "github" }], - [], - ); - expect(mocks.removeSandboxRegistryEntryWithReceipt).not.toHaveBeenCalled(); - expect(mocks.stopNimContainer).not.toHaveBeenCalled(); - expect(mocks.stopNimContainerByName).not.toHaveBeenCalled(); - expect(relockShieldsIfNeeded).toHaveBeenCalledWith(true); - }); + ).rejects.toThrow("Sandbox delete target changed during rebuild preparation."); + + expect(mocks.getSandbox).toHaveBeenCalledTimes(2); + expect(mocks.prepareMcpForRebuild.mock.invocationCallOrder[0]).toBeLessThan( + mocks.getSandbox.mock.invocationCallOrder[1] ?? Number.POSITIVE_INFINITY, + ); + expect(mocks.runOpenshell).not.toHaveBeenCalled(); + expect(mocks.reattachMcpAfterDeleteFailure).toHaveBeenCalledWith( + "alpha", + [{ server: "github" }], + [], + undefined, + ); + expect(mocks.removeSandboxRegistryEntryWithReceipt).not.toHaveBeenCalled(); + expect(mocks.stopNimContainer).not.toHaveBeenCalled(); + expect(mocks.stopNimContainerByName).not.toHaveBeenCalled(); + expect(relockShieldsIfNeeded).toHaveBeenCalledWith(true); + }, + ); it("refuses sandbox deletion when read-only MCP state drifts at the delete edge (#7062)", async () => { const revalidateBeforeDelete = vi.fn().mockRejectedValue(new Error("live policy drifted")); @@ -442,7 +446,7 @@ describe("rebuild destroy phase", () => { expect(revalidateBeforeDelete.mock.invocationCallOrder[0]).toBeLessThan( mocks.runOpenshell.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY, ); - expect(mocks.reattachMcpAfterDeleteFailure).toHaveBeenCalledWith("alpha", [], []); + expect(mocks.reattachMcpAfterDeleteFailure).toHaveBeenCalledWith("alpha", [], [], undefined); expect(mocks.removeSandboxRegistryEntryWithReceipt).not.toHaveBeenCalled(); expect(onDeleted).not.toHaveBeenCalled(); expect(mocks.stopNimContainer).not.toHaveBeenCalled(); @@ -938,6 +942,59 @@ describe("rebuild destroy phase", () => { expect(recreateJournal.confirmDeleted).toHaveBeenCalledOnce(); }); + it("reports confirmed deletion and preserves recovery state when post-delete validation fails (#9833)", async () => { + const order: string[] = []; + const recreateJournal = stubRecreateJournal(); + vi.mocked(recreateJournal.confirmDeleted).mockImplementation(() => { + order.push("journal:confirmed-deleted"); + }); + mocks.runOpenshell.mockReturnValue({ status: 0, stdout: "deleted", stderr: "" }); + const validateAfterDeleteConfirmation = vi.fn(async () => { + order.push("validate:policy-authority"); + return { + ok: false as const, + message: "Policy authority changed after sandbox deletion.", + }; + }); + const onDeleted = vi.fn(() => order.push("on-deleted")); + const onDeleteStateAmbiguous = vi.fn(); + + await expect( + runRebuildDestroyPhase({ + sandboxName: "alpha", + sandboxEntry: { name: "alpha", agent: "openclaw", gatewayName: "nemoclaw" }, + staleRecovery: false, + recreateJournal, + backupManifest: { backupPath: "/tmp/rebuild-backups/alpha/backup" } as never, + log: vi.fn(), + bail: vi.fn((message: string): never => { + throw new Error(message); + }), + relockShieldsIfNeeded: vi.fn(() => true), + validateAfterDeleteConfirmation, + onDeleted, + onDeleteStateAmbiguous, + }), + ).rejects.toThrow("Policy authority changed after sandbox deletion."); + + expect(order).toEqual(["journal:confirmed-deleted", "validate:policy-authority", "on-deleted"]); + expect(onDeleteStateAmbiguous).not.toHaveBeenCalled(); + expect(mocks.stopNimContainer).not.toHaveBeenCalled(); + expect(mocks.stopNimContainerByName).not.toHaveBeenCalled(); + expect(console.error).toHaveBeenCalledWith( + " Sandbox deletion was confirmed, but policy authority validation failed before recreation.", + ); + expect(console.error).toHaveBeenCalledWith( + " State backup is preserved at: /tmp/rebuild-backups/alpha/backup", + ); + expect(console.error).toHaveBeenCalledWith( + " The replacement journal remains available for recovery.", + ); + expect(console.error).toHaveBeenCalledWith( + " Resolve the policy authority failure, then rerun the rebuild for 'alpha' with --yes.", + ); + }); + it("journals the delete boundary before the destructive command (#7734)", async () => { const order: string[] = []; const recreateJournal = stubRecreateJournal(); @@ -1001,6 +1058,7 @@ describe("rebuild destroy phase", () => { "alpha", [{ providerName: "nemoclaw-mcp-alpha-github" }], [{ server: "github" }], + undefined, ); expect(relockShieldsIfNeeded).toHaveBeenCalledWith(true); expect(mocks.runOpenshell).not.toHaveBeenCalledWith( diff --git a/src/lib/actions/sandbox/rebuild-destroy-phase.ts b/src/lib/actions/sandbox/rebuild-destroy-phase.ts index 9688c4cfa82..8841d996f81 100644 --- a/src/lib/actions/sandbox/rebuild-destroy-phase.ts +++ b/src/lib/actions/sandbox/rebuild-destroy-phase.ts @@ -42,8 +42,12 @@ export interface RebuildDestroyPhaseInput { bail: RebuildBail; relockShieldsIfNeeded: (sandboxStillExists: boolean) => boolean; force?: boolean; + validateBeforeMcpPreparation?: () => Promise; + validateMcpPolicyAuthorityReceipt?: () => Promise; validateAfterMcpPreparation?: () => Promise; + validateBeforeDeleteCommit?: () => Promise; validateAtDeleteEdge?: () => RebuildDeleteValidationResult; + validateAfterDeleteConfirmation?: () => Promise; onDeleted: () => void; onDeleteStateAmbiguous?: () => void; } @@ -234,8 +238,12 @@ export async function runRebuildDestroyPhase( log, bail, relockShieldsIfNeeded, + validateBeforeMcpPreparation, + validateMcpPolicyAuthorityReceipt, validateAfterMcpPreparation, + validateBeforeDeleteCommit, validateAtDeleteEdge, + validateAfterDeleteConfirmation, onDeleted, } = input; const deleteTarget = resolveRebuildDeleteTarget(sandboxName, input.sandboxEntry); @@ -270,13 +278,39 @@ export async function runRebuildDestroyPhase( }; const mcpPreparation = await prepareMcpBeforeBestEffortNimStop({ prepareMcp: async () => { - const preparation = await prepareMcpForRebuild( - sandboxName, - staleRecovery, - input.force === true, - relockShieldsIfNeeded, - bail, - ); + if (validateBeforeMcpPreparation) { + let validation: RebuildDeleteValidationResult; + try { + validation = await validateBeforeMcpPreparation(); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + log(`Unexpected pre-MCP validation failure: ${redactFull(detail)}`); + validation = { + ok: false, + message: "Policy authority validation failed before MCP preparation.", + }; + } + if (!validation.ok) { + relockShieldsIfNeeded(true); + bail(validation.message, validation.code); + } + } + const preparation = await (validateMcpPolicyAuthorityReceipt + ? prepareMcpForRebuild( + sandboxName, + staleRecovery, + input.force === true, + relockShieldsIfNeeded, + bail, + validateMcpPolicyAuthorityReceipt, + ) + : prepareMcpForRebuild( + sandboxName, + staleRecovery, + input.force === true, + relockShieldsIfNeeded, + bail, + )); return preparation; }, afterPrepare: async (preparation) => { @@ -302,6 +336,7 @@ export async function runRebuildDestroyPhase( sandboxName, preparation.detachedProviderEntries, preparation.scrubbedAdapterEntries, + validateMcpPolicyAuthorityReceipt, ); relockShieldsIfNeeded(true); bail( @@ -351,6 +386,7 @@ export async function runRebuildDestroyPhase( sandboxName, rebuildDetachedMcpProviderEntries, rebuildScrubbedMcpAdapterEntries, + validateMcpPolicyAuthorityReceipt, ); relockShieldsIfNeeded(true); bail( @@ -378,6 +414,7 @@ export async function runRebuildDestroyPhase( sandboxName, rebuildDetachedMcpProviderEntries, rebuildScrubbedMcpAdapterEntries, + validateMcpPolicyAuthorityReceipt, ); relockShieldsIfNeeded(true); bail( @@ -390,18 +427,65 @@ export async function runRebuildDestroyPhase( } } - // MCP adapter entries are already detached and scrubbed here. A journal write - // that fails must reattach them before the rebuild gives up, or the still - // running sandbox is left without its MCP wiring. + // MCP adapter entries are already detached and scrubbed here. Observe the + // source before the final awaited authority proof. Refusal must leave the + // delete journal, inference runtime, registry, and live sandbox unchanged. let sourcePresence: RebuildRecreateSourcePresence; try { sourcePresence = recreateJournal.observeSourceForDelete(); + } catch (error) { + const mcpRecoveryFailure = await reattachMcpAfterDeleteFailure( + sandboxName, + rebuildDetachedMcpProviderEntries, + rebuildScrubbedMcpAdapterEntries, + validateMcpPolicyAuthorityReceipt, + ); + relockShieldsIfNeeded(true); + const detail = error instanceof Error ? error.message : String(error); + bail( + mcpRecoveryFailure + ? `Sandbox deletion could not be journaled: ${redactFull(detail)} MCP provider recovery also failed: ${mcpRecoveryFailure}` + : `Sandbox deletion could not be journaled: ${redactFull(detail)}`, + ); + return null; + } + if (validateBeforeDeleteCommit) { + let validation: RebuildDeleteValidationResult; + try { + validation = await validateBeforeDeleteCommit(); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + log(`Unexpected delete-commit validation failure: ${redactFull(detail)}`); + validation = { + ok: false, + message: "Policy authority validation failed before sandbox deletion.", + }; + } + if (!validation.ok) { + const mcpRecoveryFailure = await reattachMcpAfterDeleteFailure( + sandboxName, + rebuildDetachedMcpProviderEntries, + rebuildScrubbedMcpAdapterEntries, + validateMcpPolicyAuthorityReceipt, + ); + relockShieldsIfNeeded(true); + bail( + mcpRecoveryFailure + ? `${validation.message} MCP provider recovery also failed: ${mcpRecoveryFailure}` + : validation.message, + validation.code, + ); + return null; + } + } + try { recreateJournal.markDeleting(); } catch (error) { const mcpRecoveryFailure = await reattachMcpAfterDeleteFailure( sandboxName, rebuildDetachedMcpProviderEntries, rebuildScrubbedMcpAdapterEntries, + validateMcpPolicyAuthorityReceipt, ); relockShieldsIfNeeded(true); const detail = error instanceof Error ? error.message : String(error); @@ -412,6 +496,35 @@ export async function runRebuildDestroyPhase( ); return null; } + if (validateBeforeDeleteCommit) { + let validation: RebuildDeleteValidationResult; + try { + validation = await validateBeforeDeleteCommit(); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + log(`Unexpected delete-commit validation failure: ${redactFull(detail)}`); + validation = { + ok: false, + message: "Policy authority validation failed before sandbox deletion.", + }; + } + if (!validation.ok) { + const mcpRecoveryFailure = await reattachMcpAfterDeleteFailure( + sandboxName, + rebuildDetachedMcpProviderEntries, + rebuildScrubbedMcpAdapterEntries, + validateMcpPolicyAuthorityReceipt, + ); + relockShieldsIfNeeded(true); + bail( + mcpRecoveryFailure + ? `${validation.message} MCP provider recovery also failed: ${mcpRecoveryFailure}` + : validation.message, + validation.code, + ); + return null; + } + } if (sourcePresence === "missing") { log(`Skipping delete: gateway ${gatewayName} reports '${sandboxName}' already absent`); } else { @@ -441,6 +554,7 @@ export async function runRebuildDestroyPhase( sandboxName, rebuildDetachedMcpProviderEntries, rebuildScrubbedMcpAdapterEntries, + validateMcpPolicyAuthorityReceipt, ); if (mcpRecoveryFailure) { console.error( @@ -503,6 +617,34 @@ export async function runRebuildDestroyPhase( bail(`Sandbox deletion could not be journaled: ${redactFull(detail)}`); return null; } + if (validateAfterDeleteConfirmation) { + let validation: RebuildDeleteValidationResult; + try { + validation = await validateAfterDeleteConfirmation(); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + log(`Unexpected post-delete validation failure: ${redactFull(detail)}`); + validation = { + ok: false, + message: "Policy authority validation failed after sandbox deletion.", + }; + } + if (!validation.ok) { + console.error( + " Sandbox deletion was confirmed, but policy authority validation failed before recreation.", + ); + if (backupManifest) { + console.error(" State backup is preserved at: " + backupManifest.backupPath); + } + console.error(" The replacement journal remains available for recovery."); + console.error( + ` Resolve the policy authority failure, then rerun the rebuild for '${sandboxName}' with --yes.`, + ); + onDeleted(); + bail(validation.message, validation.code); + return null; + } + } stopNimBestEffort(); onDeleted(); const removalReceipt: registry.SandboxRemovalReceipt | null = null; diff --git a/src/lib/actions/sandbox/rebuild-durable-config.ts b/src/lib/actions/sandbox/rebuild-durable-config.ts index d42e0cc4c3c..9ddb94e6e42 100644 --- a/src/lib/actions/sandbox/rebuild-durable-config.ts +++ b/src/lib/actions/sandbox/rebuild-durable-config.ts @@ -26,7 +26,11 @@ import { normalizeDcodeAutoApprovalMode, } from "../../onboard/dcode-auto-approval"; import { resolveHermesDashboardOnboardState } from "../../onboard/hermes-dashboard"; -import { hasInvalidSessionToolDisclosure, type Session } from "../../state/onboard-session"; +import { + hasInvalidSessionToolDisclosure, + loadSession, + type Session, +} from "../../state/onboard-session"; import { DEFAULT_TOOL_DISCLOSURE, invalidRecordedToolDisclosure, @@ -127,7 +131,7 @@ function builtinWebSearchPolicyProviders(entry: RebuildSandboxEntry): WebSearchP export function resolveRebuildDurableConfig( sandboxName: string, entry: RebuildSandboxEntry, - session: Session | null, + session: Session | null = loadSession(), resolvedSelection: { provider: string | null; model: string | null } = { provider: entry.provider ?? null, model: entry.model ?? null, diff --git a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts index c0f907c1711..d426f9696a4 100644 --- a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts @@ -158,6 +158,7 @@ describe("rebuildSandbox flow: credential preflight", () => { model: MODEL, credentialEnv: "COMPATIBLE_API_KEY", endpointUrl: "https://inference.example.test/v1", + policyAuthority: "nemoclaw-managed", preferredInferenceApi: "openai-completions", }, hydrateCredentialEnv: () => "host-provider-key", @@ -209,6 +210,7 @@ describe("rebuildSandbox flow: credential preflight", () => { model: MODEL, credentialEnv: "COMPATIBLE_API_KEY", endpointUrl: "https://inference.example.test/v1", + policyAuthority: "nemoclaw-managed", preferredInferenceApi: "openai-completions", }, hydrateCredentialEnv: () => "host-provider-key", @@ -240,6 +242,7 @@ describe("rebuildSandbox flow: credential preflight", () => { model: MODEL, credentialEnv: "COMPATIBLE_API_KEY", endpointUrl: "https://inference.example.test/v1", + policyAuthority: "nemoclaw-managed", preferredInferenceApi: "openai-completions", }, hydrateCredentialEnv: () => { @@ -280,6 +283,7 @@ describe("rebuildSandbox flow: credential preflight", () => { model: MODEL, credentialEnv: "COMPATIBLE_API_KEY", endpointUrl: "https://inference.example.test/v1", + policyAuthority: "nemoclaw-managed", preferredInferenceApi: "openai-completions", }, hydrateCredentialEnv: () => "host-provider-key", @@ -312,6 +316,7 @@ describe("rebuildSandbox flow: credential preflight", () => { model: MODEL, credentialEnv: "COMPATIBLE_API_KEY", endpointUrl: "https://inference.example.test/v1", + policyAuthority: "nemoclaw-managed", preferredInferenceApi: "openai-completions", }, hydrateCredentialEnv: () => null, @@ -392,25 +397,25 @@ describe("rebuildSandbox flow: credential preflight", () => { expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); }); - it.each([ - "ollama-local", - "vllm-local", - ])("migrates a legacy %s target away from OPENAI_API_KEY (#2519)", async (provider) => { - const harness = createRebuildFlowHarness({ - sandboxEntry: { provider, model: MODEL, credentialEnv: "OPENAI_API_KEY" }, - }); - configureSession(harness, provider, "OPENAI_API_KEY"); + it.each(["ollama-local", "vllm-local"])( + "migrates a legacy %s target away from OPENAI_API_KEY (#2519)", + async (provider) => { + const harness = createRebuildFlowHarness({ + sandboxEntry: { provider, model: MODEL, credentialEnv: "OPENAI_API_KEY" }, + }); + configureSession(harness, provider, "OPENAI_API_KEY"); - await expect( - harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).resolves.toBeUndefined(); + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).resolves.toBeUndefined(); - const output = harness.logSpy.mock.calls.flat().map(String).join("\n"); - expect(output).toContain("GH #2519"); - expect(output).toContain(provider); - expect(harness.session.credentialEnv).toBeNull(); - expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); - }); + const output = harness.logSpy.mock.calls.flat().map(String).join("\n"); + expect(output).toContain("GH #2519"); + expect(output).toContain(provider); + expect(harness.session.credentialEnv).toBeNull(); + expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); + }, + ); it("fails closed when a matching session omits the remote target credential", async () => { const harness = createRebuildFlowHarness({ diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.ts index 877874b8baa..1c89a32d9c4 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.ts @@ -3,6 +3,7 @@ import { dockerRmi } from "../../adapters/docker/image"; import { printOpenShellStateRpcIssue } from "../../adapters/openshell/gateway-drift"; +import type { SandboxPolicyAuthority } from "../../adapters/openshell/policy-authority"; import { loadAgent } from "../../agent/defs"; import { bindLocalAgentBaseImageHandoffToResolution, @@ -42,10 +43,14 @@ import * as sandboxState from "../../state/sandbox"; import * as userManagedFilesProbe from "../../state/user-managed-files-probe"; import { getReconciledSandboxGatewayState, - printSandboxGatewayStateHint, + printGatewayLifecycleHint, printWrongGatewayActiveGuidance, } from "./gateway-state"; -import { openRebuildShieldsWindow, type RebuildShieldsWindow } from "./rebuild-shields"; +import { + openAbsentRebuildShieldsWindow, + openRebuildShieldsWindow, + type RebuildShieldsWindow, +} from "./rebuild-shields"; import * as snapshotBackup from "./snapshot/backup-authority"; export type RebuildSandboxEntry = SandboxEntry & { agents?: unknown[] }; @@ -250,7 +255,7 @@ export async function resolveRebuildLiveState( ` Sandbox '${sandboxName}' is not visible on gateway '${recordedGateway}' and its live state could not be confirmed.`, ); console.error(" Your local registry entry has been preserved — nothing was removed."); - printSandboxGatewayStateHint(reconciled, sandboxName, console.error); + printGatewayLifecycleHint(reconciled.output || "", sandboxName, console.error); } bail(`Could not confirm live state of '${sandboxName}' (gateway not in a known-good state).`); return null; @@ -259,16 +264,18 @@ export async function resolveRebuildLiveState( export function openRebuildShieldsWindowForState( sandboxName: string, recoveryRecreate: boolean, + policyAuthority: SandboxPolicyAuthority = "nemoclaw-managed", ): { rebuildShieldsWindow: RebuildShieldsWindow | null; staleSandboxWasLocked: boolean } { if (recoveryRecreate) { + const absent = openAbsentRebuildShieldsWindow(sandboxName, policyAuthority); return { - staleSandboxWasLocked: !shields.isShieldsDown(sandboxName), - rebuildShieldsWindow: { relocked: false, wasLocked: false }, + staleSandboxWasLocked: absent.staleSandboxWasLocked, + rebuildShieldsWindow: absent.window, }; } return { staleSandboxWasLocked: false, - rebuildShieldsWindow: openRebuildShieldsWindow(sandboxName, CLI_NAME), + rebuildShieldsWindow: openRebuildShieldsWindow(sandboxName, CLI_NAME, policyAuthority), }; } diff --git a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts index 2a2b5bb7378..e2740154097 100644 --- a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import YAML from "yaml"; import { expectNoSandboxDelete } from "../../../../test/helpers/rebuild-delete-assertions"; +import * as policies from "../../policy"; +import { digestBaselineEntry, getBaselineEntry } from "../../policy/baseline-exclusion"; import { createRebuildFlowHarness, installRebuildFlowTestHooks, @@ -12,6 +15,11 @@ import { } from "../../../../test/helpers/rebuild-flow-generic-harness"; import { makePreparedRecoveryManifest } from "./rebuild-flow-test-fixtures"; +const OPENCLAW_BASELINE = policies.resolveAgentBaselinePolicy("openclaw")!; +const OPENCLAW_DOCS_DIGEST = digestBaselineEntry( + getBaselineEntry(OPENCLAW_BASELINE.content, "openclaw_docs")!, +); + describe("rebuildSandbox flow: lifecycle", () => { installRebuildFlowTestHooks(); @@ -50,6 +58,109 @@ describe("rebuildSandbox flow: lifecycle", () => { expectNoSandboxDelete(harness.runOpenshellSpy); }); + it("stops before rebuild effects when external policy requirements are missing (#9833)", async () => { + const harness = createRebuildFlowHarness({ + sandboxEntry: { policyAuthority: "externally-managed" }, + policyAuthorityInspection: { + authority: "externally-managed", + effectivePolicy: { network_policies: {} }, + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }, + }); + + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).rejects.toThrow("Policy authority preflight failed"); + + expect(harness.ensureTargetGatewaySpy).not.toHaveBeenCalled(); + expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); + expect(harness.onboardSpy).not.toHaveBeenCalled(); + expect(harness.relockSpy).not.toHaveBeenCalled(); + expectNoSandboxDelete(harness.runOpenshellSpy); + }); + + it("rebuilds a live Shields-up external-policy sandbox without policy mutation (#9833)", async () => { + const harness = createRebuildFlowHarness({ + applyPreset: () => { + throw new Error("external rebuild attempted policy replay"); + }, + backupPolicyPresets: [], + sandboxEntry: { + policies: [], + policyAuthority: "externally-managed", + }, + policyAuthorityInspection: { + authority: "externally-managed", + effectivePolicy: YAML.parse(OPENCLAW_BASELINE.content) as Record, + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + }, + }); + + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).resolves.toBeUndefined(); + + expect(harness.openRebuildShieldsWindowSpy).toHaveBeenCalledWith( + "alpha", + "nemoclaw", + "externally-managed", + ); + expect(harness.relockSpy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + sourceDeleted: true, + }), + true, + "nemoclaw", + ); + expect(harness.applyPresetSpy).not.toHaveBeenCalled(); + expect(harness.runOpenshellSpy).toHaveBeenCalledWith( + ["sandbox", "delete", "-g", "nemoclaw", "alpha"], + expect.objectContaining({ ignoreError: true }), + ); + }); + + it("stops before replacement restore when authority flips after recreate (#9833)", async () => { + let authorityFlipped = false; + const managedInspection = { + authority: "owner-unknown" as const, + effectivePolicy: {}, + policyIdentity: { hash: "policy-alpha", activeVersion: 7 }, + }; + const harness = createRebuildFlowHarness({ + onboard: () => { + authorityFlipped = true; + }, + }); + const inspectChangedAuthority = () => + authorityFlipped + ? { + authority: "externally-managed" as const, + effectivePolicy: {}, + policyIdentity: { hash: "external-policy", activeVersion: 2 }, + } + : managedInspection; + harness.inspectSandboxPolicyAuthoritySpy.mockImplementation(inspectChangedAuthority); + harness.inspectGlobalPolicyAuthoritySpy.mockImplementation(() => + authorityFlipped + ? { state: "active", inspection: inspectChangedAuthority() } + : { state: "absent" }, + ); + + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).rejects.toThrow("policy authority changed"); + + expect(harness.restoreSandboxStateSpy).not.toHaveBeenCalled(); + expect(harness.applyPresetSpy).not.toHaveBeenCalled(); + expect(harness.executeSandboxCommandSpy).not.toHaveBeenCalled(); + expect(harness.restoreMcpBridgesAfterRebuildSpy).not.toHaveBeenCalled(); + expect(harness.registryUpdateSpy).not.toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ agentVersion: "0.2.0" }), + ); + }); + it("backs up once, recreates, restores, reapplies policy, and relocks on a successful OpenClaw rebuild", async ({ onTestFinished, }) => { @@ -71,6 +182,7 @@ describe("rebuildSandbox flow: lifecycle", () => { applyPreset: () => true, backupPolicyPresets: ["npm", "bad", "throw", "mcp-bridge-github"], sandboxEntry: { + mcp: { bridges: { github: mcpEntry } }, policies: ["npm", "mcp-bridge-github"], policyPresetsFinalized: true, policyTier: "balanced", @@ -93,7 +205,10 @@ describe("rebuildSandbox flow: lifecycle", () => { "alpha", expect.objectContaining({ captureStateFile: expect.any(Function) }), ); - expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith("alpha"); + expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith( + "alpha", + expect.any(Function), + ); expect(harness.prepareMcpBridgesForRebuildSpy.mock.invocationCallOrder[0]).toBeLessThan( harness.warnUnpreservedUserManagedFilesSpy.mock.invocationCallOrder[0], ); @@ -138,7 +253,11 @@ describe("rebuildSandbox flow: lifecycle", () => { "/tmp/nemoclaw-rebuild-backup", { targetAgentType: "openclaw" }, ); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + [mcpEntry], + expect.any(Function), + ); expect(harness.removeSandboxRegistryEntryWithReceiptSpy).not.toHaveBeenCalled(); expect(harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n")).toContain( "Preserving journaled source registry entry across sandbox recreation", @@ -193,7 +312,7 @@ describe("rebuildSandbox flow: lifecycle", () => { version: 1, agent: "openclaw", key: "openclaw_docs", - digest: "baseline-digest", + digest: OPENCLAW_DOCS_DIGEST, acknowledgedAt: "2026-07-19T00:00:00.000Z", appliedAgentVersion: "2026.6.10", }, @@ -205,7 +324,10 @@ describe("rebuildSandbox flow: lifecycle", () => { harness.rebuildSandbox("alpha", ["--yes", "--verbose"], { throwOnError: true }), ).resolves.toBeUndefined(); - expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith("alpha"); + expect(harness.prepareMcpBridgesForRebuildSpy).toHaveBeenCalledWith( + "alpha", + expect.any(Function), + ); expect(harness.removeSandboxRegistryEntryWithReceiptSpy).not.toHaveBeenCalled(); expect(harness.onboardSpy).toHaveBeenCalledOnce(); expect(harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n")).toContain( @@ -244,10 +366,10 @@ network_policies: await expect( harness.rebuildSandbox("alpha", ["--yes", "--verbose"], { throwOnError: true }), - ).rejects.toThrow("Replacement onboarding preflight failed"); + ).rejects.toThrow("Policy authority preflight failed"); expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain( - "does not satisfy the shipped sandbox policy schema", + "invalid versioned baseline exclusion", ); expect(harness.registryUpdateSpy).not.toHaveBeenCalled(); expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); @@ -265,7 +387,7 @@ network_policies: version: 1, agent: "openclaw", key: "openclaw_docs", - digest: "baseline-digest", + digest: OPENCLAW_DOCS_DIGEST, acknowledgedAt: "2026-07-19T00:00:00.000Z", appliedAgentVersion: "2026.6.10", }, @@ -290,26 +412,40 @@ network_policies: it("waits for post-delete sandbox absence before inner onboarding (#7194)", async () => { const events: string[] = []; - let sandboxGetAttempts = 0; - const probeSequence = [ - { - event: "stale-live", - result: { status: 0, output: "Sandbox: alpha\nId: sbx-0d6f4c2a91\nPhase: Ready" }, - }, - { - event: "absent", - result: { status: 1, output: "", stderr: "Error: sandbox alpha not found" }, - }, - ]; + let sourceDeleted = false; + let replacementCreated = false; const harness = createRebuildFlowHarness({ captureOpenshell: () => { - const probe = probeSequence[Math.min(sandboxGetAttempts, probeSequence.length - 1)]; - sandboxGetAttempts += 1; - events.push(probe.event); - return probe.result; + const sandboxIsLive = !sourceDeleted || replacementCreated; + events.push( + sandboxIsLive + ? replacementCreated + ? "replacement-live" + : "source-live" + : "source-missing", + ); + return sandboxIsLive + ? { + status: 0, + output: "Sandbox: alpha\nId: sbx-0d6f4c2a91\nPhase: Ready", + stdout: "Sandbox: alpha\nId: sbx-0d6f4c2a91\nPhase: Ready", + stderr: "", + } + : { + status: 1, + output: "", + stdout: "", + stderr: "Error: sandbox alpha not found", + }; + }, + runOpenshell: (argv) => { + const deletesSource = argv.join(" ") === "sandbox delete -g nemoclaw alpha"; + sourceDeleted ||= deletesSource; + return deletesSource ? { status: 0, output: "" } : undefined; }, onboard: () => { events.push("onboard"); + replacementCreated = true; }, }); @@ -317,14 +453,11 @@ network_policies: harness.rebuildSandbox("alpha", ["--yes", "--verbose"], { throwOnError: true }), ).resolves.toBeUndefined(); - // Open the journal against the live source, wait for absence, then prove - // absence once more before the journal records the deleted phase (#7734). - expect(events).toEqual(["stale-live", "absent", "absent", "onboard"]); - expect( - harness.captureOpenshellSpy.mock.calls.filter( - ([args]) => Array.isArray(args) && args.join(" ") === "sandbox get -g nemoclaw alpha", - ), - ).toHaveLength(3); + const stateTransitions = events.filter( + (event, index) => index === 0 || event !== events[index - 1], + ); + expect(stateTransitions).toEqual(["source-live", "source-missing", "onboard"]); + expect(events.indexOf("source-missing")).toBeLessThan(events.indexOf("onboard")); }); it("accepts the agent version cached by the confirmation probe before lock acquisition", async () => { @@ -425,7 +558,11 @@ network_policies: expect.objectContaining({ toolDisclosure: "direct" }), ); expect(harness.session.toolDisclosure).toBe("direct"); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + [mcpEntry], + expect.any(Function), + ); harness.registryUpdateSpy.mock.calls.forEach(([, update]) => { expect(update).not.toHaveProperty("toolDisclosure"); }); @@ -455,6 +592,7 @@ network_policies: const recoveryArtifactPath = "/tmp/shields-external-policy-alpha.yaml"; const harness = createRebuildFlowHarness({ staleRecovery: true, + sandboxEntry: { policyAuthority: "nemoclaw-managed" }, clearShieldsState: () => { throw new Error( `Could not remove external Shields policy recovery artifact '${recoveryArtifactPath}': permission denied`, @@ -495,7 +633,10 @@ network_policies: try { const harness = createRebuildFlowHarness({ staleRecovery: true, - sandboxEntry: { mcp: { bridges: { github: mcpEntry } } }, + sandboxEntry: { + mcp: { bridges: { github: mcpEntry } }, + policyAuthority: "nemoclaw-managed", + }, baseImagePreflight: { ok: true, imageRef: "nemoclaw-hermes-sandbox-base-local:image-preflighted", @@ -524,7 +665,11 @@ network_policies: expect(harness.prepareMcpBridgesForRebuildSpy).not.toHaveBeenCalled(); expect(harness.warnUnpreservedUserManagedFilesSpy).not.toHaveBeenCalled(); expect(harness.reattachMcpProvidersAfterRebuildAbortSpy).not.toHaveBeenCalled(); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + [mcpEntry], + expect.any(Function), + ); expect(disposeImageRef).toHaveBeenCalledOnce(); } finally { restoreEnv(); @@ -536,6 +681,7 @@ network_policies: const harness = createRebuildFlowHarness({ sandboxInventory: { sandboxes: [] }, reconciledSandboxGatewayState: { state: "unknown", output: "indeterminate" }, + sandboxEntry: { policyAuthority: "nemoclaw-managed" }, baseImagePreflight: { ok: true, imageRef: `nemoclaw-hermes-sandbox-base-local:rebuild-123-${"a".repeat(16)}-image-${"b".repeat(64)}`, @@ -611,7 +757,11 @@ network_policies: expect(harness.session.compatibleEndpointReasoningEffort).toBe("high"); expect(process.env.NEMOCLAW_REASONING).toBe("false"); expect(process.env.NEMOCLAW_REASONING_EFFORT).toBe("low"); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + [mcpEntry], + expect.any(Function), + ); } finally { restoreEnv(); } diff --git a/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts b/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts index 9fadcf83056..17f09acfdc7 100644 --- a/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts @@ -112,10 +112,11 @@ describe("rebuildSandbox flow: recovery", () => { const REPLACEMENT_PROBE = "Name: alpha\nId: sbx-replacement\nPhase: Ready\n"; const FOREIGN_PROBE = "Name: alpha\nId: sbx-foreign\nPhase: Ready\n"; const REPLACEMENT_IDENTITY = fingerprintSandboxLiveIdentity(REPLACEMENT_PROBE); + const REPLACEMENT_GENERATION = "11111111-1111-4111-8111-111111111111"; const POST_DELETE_PHASES = ["creating", "created", "registry_committing", "completed"] as const; const provenReplacement = { sandboxEntry: { - lifecycleGeneration: "generation-1", + lifecycleGeneration: REPLACEMENT_GENERATION, lifecycleLiveIdentityFingerprint: REPLACEMENT_IDENTITY, }, }; @@ -131,7 +132,7 @@ describe("rebuildSandbox flow: recovery", () => { (session.checkpoint as { sandboxRecreate: Record }).sandboxRecreate, { phase, - targetGeneration: "generation-1", + targetGeneration: REPLACEMENT_GENERATION, targetLiveIdentityFingerprint: REPLACEMENT_IDENTITY, }, ); @@ -230,6 +231,7 @@ describe("rebuildSandbox flow: recovery", () => { function restartFromJournaledSource(probes: readonly (string | null)[], checkpoint: unknown) { const restarted = createRebuildFlowHarness({ captureOpenshell: sandboxGetProbes(probes), + sandboxEntry: { policyAuthority: "nemoclaw-managed" }, }); restarted.session.checkpoint = checkpoint; restarted.runOpenshellSpy.mockClear(); @@ -494,6 +496,7 @@ describe("rebuildSandbox flow: recovery", () => { "alpha", [attached], undefined, + expect.any(Function), ); expect(harness.onboardSpy).not.toHaveBeenCalled(); }); @@ -540,7 +543,11 @@ describe("rebuildSandbox flow: recovery", () => { harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), ).resolves.toBeUndefined(); - expect(harness.ensureMessagingHostForwardAfterRebuildSpy).toHaveBeenCalledWith("alpha", plan); + expect(harness.ensureMessagingHostForwardAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + plan, + expect.any(Function), + ); expect( harness.ensureMessagingHostForwardAfterRebuildSpy.mock.invocationCallOrder[0], ).toBeGreaterThan(harness.onboardSpy.mock.invocationCallOrder[0]); diff --git a/src/lib/actions/sandbox/rebuild-flow-shields-window.test.ts b/src/lib/actions/sandbox/rebuild-flow-shields-window.test.ts index 31b768782d7..e43da89e226 100644 --- a/src/lib/actions/sandbox/rebuild-flow-shields-window.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-shields-window.test.ts @@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ isShieldsDown: vi.fn(), + openAbsentRebuildShieldsWindow: vi.fn(), openRebuildShieldsWindow: vi.fn(), })); @@ -13,6 +14,7 @@ vi.mock("../../shields", () => ({ })); vi.mock("./rebuild-shields", () => ({ + openAbsentRebuildShieldsWindow: mocks.openAbsentRebuildShieldsWindow, openRebuildShieldsWindow: mocks.openRebuildShieldsWindow, })); @@ -31,18 +33,35 @@ describe("rebuild Shields window selection", () => { rebuildShieldsWindow: window, staleSandboxWasLocked: false, }); - expect(mocks.openRebuildShieldsWindow).toHaveBeenCalledWith("alpha", "nemoclaw"); + expect(mocks.openRebuildShieldsWindow).toHaveBeenCalledWith( + "alpha", + "nemoclaw", + "nemoclaw-managed", + ); expect(mocks.isShieldsDown).not.toHaveBeenCalled(); }); it("records Shields up for a stale sandbox without applying Shields down", () => { - mocks.isShieldsDown.mockReturnValue(false); + mocks.openAbsentRebuildShieldsWindow.mockReturnValue({ + staleSandboxWasLocked: true, + window: { + policyAuthority: "nemoclaw-managed", + relocked: false, + sourceDeleted: true, + wasLocked: false, + }, + }); expect(openRebuildShieldsWindowForState("alpha", true)).toEqual({ - rebuildShieldsWindow: { relocked: false, wasLocked: false }, + rebuildShieldsWindow: { + policyAuthority: "nemoclaw-managed", + relocked: false, + sourceDeleted: true, + wasLocked: false, + }, staleSandboxWasLocked: true, }); - expect(mocks.isShieldsDown).toHaveBeenCalledWith("alpha"); + expect(mocks.openAbsentRebuildShieldsWindow).toHaveBeenCalledWith("alpha", "nemoclaw-managed"); expect(mocks.openRebuildShieldsWindow).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts index c815270c985..b96c3493999 100644 --- a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts @@ -54,9 +54,12 @@ describe("rebuildSandbox flow: target credentials", () => { search: { server: "search", agent: "openclaw", + adapter: "mcporter", url: "https://mcp.example.com/mcp", env: ["TAVILY_API_KEY"], - policyName: "alpha-mcp-search", + providerName: "nemoclaw-mcp-alpha-search", + providerId: "provider-search", + policyName: "mcp-bridge-search", addedAt: "2026-07-03T00:00:00.000Z", }, }, diff --git a/src/lib/actions/sandbox/rebuild-hermes-accepted-target.test.ts b/src/lib/actions/sandbox/rebuild-hermes-accepted-target.test.ts index f5a8e2b0688..95d79b922c9 100644 --- a/src/lib/actions/sandbox/rebuild-hermes-accepted-target.test.ts +++ b/src/lib/actions/sandbox/rebuild-hermes-accepted-target.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { PolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; const phaseMocks = vi.hoisted(() => ({ openRecreateJournal: vi.fn(), @@ -12,6 +13,7 @@ const phaseMocks = vi.hoisted(() => ({ runPostRestore: vi.fn(), runPreflight: vi.fn(), runShields: vi.fn(), + revalidateAuthority: vi.fn(), })); const gatewayAuthority = { @@ -25,6 +27,15 @@ const gatewayAuthority = { requiredCapabilities: [], } as const; +const policyAuthorityReceipt = { + authority: "nemoclaw-managed", + gatewayName: "nemoclaw", + managedMcpPolicies: [], + operation: "rebuild sandbox 'alpha'", + requiredPolicies: [], + sandboxName: "alpha", +} as const; + vi.mock("./rebuild-recreate-journal", () => ({ fingerprintRebuildRecreateTargetIntent: () => "intent-1", openRebuildRecreateJournal: phaseMocks.openRecreateJournal, @@ -36,6 +47,12 @@ vi.mock("./rebuild-backup-phase", () => ({ vi.mock("./rebuild-preflight-phase", () => ({ finalizePreparedRebuildImageMessagingPlan: vi.fn(), + isPolicyAuthorityRefusalError: (error: unknown) => + typeof error === "object" && + error !== null && + "code" in error && + error.code === "NEMOCLAW_POLICY_AUTHORITY_REFUSAL", + revalidateRebuildPolicyAuthority: phaseMocks.revalidateAuthority, runHermesCronRestoreBackupPreflight: () => ({ plan: null }), runRebuildPreflightPhase: phaseMocks.runPreflight, })); @@ -70,6 +87,7 @@ describe("Hermes accepted replacement recovery", () => { vi.clearAllMocks(); vi.spyOn(console, "error").mockImplementation(() => {}); vi.spyOn(console, "log").mockImplementation(() => {}); + phaseMocks.revalidateAuthority.mockResolvedValue(undefined); phaseMocks.recoverCronRestore.mockReturnValue("dispatch-reactivated"); phaseMocks.runPreflight.mockResolvedValue({ sandboxEntry: { name: "alpha", customPolicies: [] }, @@ -104,6 +122,7 @@ describe("Hermes accepted replacement recovery", () => { revalidateBeforeDelete: vi.fn(async () => true), }, preparedImage: null, + policyAuthorityReceipt, routePreflightReceipt: {}, releaseOnboardLock, log, @@ -175,6 +194,26 @@ describe("Hermes accepted replacement recovery", () => { expect(completeAcceptedTarget).toHaveBeenCalledOnce(); }); + it("preserves authority refusal after accepted replacement recovery (#9833)", async () => { + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + let recoveryCompleted = false; + phaseMocks.recoverCronRestore.mockImplementation(() => { + recoveryCompleted = true; + return "dispatch-reactivated"; + }); + phaseMocks.revalidateAuthority.mockImplementation(() => + recoveryCompleted ? Promise.reject(refusal) : Promise.resolve(), + ); + + await expect(rebuildSandbox("alpha", ["--yes"], { throwOnError: true })).rejects.toBe(refusal); + + expect(completeAcceptedTarget).not.toHaveBeenCalled(); + expect(bail).not.toHaveBeenCalled(); + expect(vi.mocked(console.log).mock.calls.flat().join("\n")).not.toContain( + "already holds the replacement", + ); + }); + it("retains the replacement journal when cron validation fails (#7806)", async () => { phaseMocks.recoverCronRestore.mockImplementation(() => { throw new Error("restored job script is missing"); diff --git a/src/lib/actions/sandbox/rebuild-hermes-cron-restore.test.ts b/src/lib/actions/sandbox/rebuild-hermes-cron-restore.test.ts index b8187d5b3e5..36349d8d5b8 100644 --- a/src/lib/actions/sandbox/rebuild-hermes-cron-restore.test.ts +++ b/src/lib/actions/sandbox/rebuild-hermes-cron-restore.test.ts @@ -257,7 +257,12 @@ describe("Hermes cron rebuild restore contract", () => { const leadingHyphenToken = "-restore-token"; processMocks.dockerSpawnSync.mockImplementation((argv: string[]) => ({ status: 0, - stdout: receipt(argv.includes("validate") ? "validate" : "begin", 41, 902, leadingHyphenToken), + stdout: receipt( + argv.includes("validate") ? "validate" : "begin", + 41, + 902, + leadingHyphenToken, + ), stderr: "", })); @@ -269,21 +274,21 @@ describe("Hermes cron rebuild restore contract", () => { ); }); - it("keeps dispatch drained when state restore is incomplete", () => { + it("keeps dispatch drained when state restore is incomplete", async () => { processMocks.dockerSpawnSync.mockReturnValue({ status: 0, stdout: receipt("begin"), stderr: "", }); - expect(() => - runHermesCronRestoreTransaction("alpha", () => ({ restoreSucceeded: false })), - ).toThrow("state restore was incomplete"); + await expect( + runHermesCronRestoreTransaction("alpha", async () => ({ restoreSucceeded: false })), + ).rejects.toThrow("state restore was incomplete"); expect(processMocks.dockerSpawnSync).toHaveBeenCalledOnce(); expect(processMocks.privilegedSandboxExecArgv.mock.calls[0]?.[1]).toContain("begin"); }); - it("keeps dispatch held after restore validation until gateway replacement (#8472)", () => { + it("keeps dispatch held after restore validation until gateway replacement (#8472)", async () => { const events: string[] = []; processMocks.dockerSpawnSync.mockImplementation((argv: string[]) => { const action = argv.includes("validate") ? "validate" : "begin"; @@ -291,9 +296,9 @@ describe("Hermes cron rebuild restore contract", () => { return { status: 0, stdout: receipt(action), stderr: "" }; }); - const transaction = runHermesCronRestoreTransaction( + const transaction = await runHermesCronRestoreTransaction( "alpha", - () => { + async () => { events.push("restore"); return { restoreSucceeded: true, restored: "state" }; }, @@ -493,29 +498,29 @@ describe("Hermes cron rebuild restore contract", () => { ); }); - it.each([ - "gate-prepared", - "not-required", - ] as const)("returns the %s pre-repair disposition", (disposition) => { - processMocks.dockerSpawnSync.mockReturnValue({ - status: 0, - stdout: preparationReceipt(disposition), - stderr: "", - }); - - expect(prepareHermesCronRestoreRecovery("alpha")).toBe(disposition); - expect(processMocks.privilegedSandboxExecArgv).toHaveBeenCalledWith( - "alpha", - [ - "/opt/hermes/.venv/bin/python", - "-I", - "/usr/local/lib/nemoclaw/hermes-cron-restore-control.py", - "prepare-recover", - ], - false, - true, - ); - }); + it.each(["gate-prepared", "not-required"] as const)( + "returns the %s pre-repair disposition", + (disposition) => { + processMocks.dockerSpawnSync.mockReturnValue({ + status: 0, + stdout: preparationReceipt(disposition), + stderr: "", + }); + + expect(prepareHermesCronRestoreRecovery("alpha")).toBe(disposition); + expect(processMocks.privilegedSandboxExecArgv).toHaveBeenCalledWith( + "alpha", + [ + "/opt/hermes/.venv/bin/python", + "-I", + "/usr/local/lib/nemoclaw/hermes-cron-restore-control.py", + "prepare-recover", + ], + false, + true, + ); + }, + ); it("rejects an inconsistent pre-repair receipt", () => { processMocks.dockerSpawnSync.mockReturnValue({ diff --git a/src/lib/actions/sandbox/rebuild-hermes-post-restore.test.ts b/src/lib/actions/sandbox/rebuild-hermes-post-restore.test.ts index 144a0d4b71a..51bfc13b253 100644 --- a/src/lib/actions/sandbox/rebuild-hermes-post-restore.test.ts +++ b/src/lib/actions/sandbox/rebuild-hermes-post-restore.test.ts @@ -321,27 +321,26 @@ describe("Hermes gateway post-restore recheck", () => { expect(checkAndRecoverSandboxProcesses).toHaveBeenCalledTimes(2); }); - it.each([ - "forwardRecoveryFailed", - "secretBoundaryRefused", - "mcpReconciliationRefused", - ] as const)("fails immediately when recovery reports %s (#7084)", (failureFlag) => { - const checkAndRecoverSandboxProcesses = vi.fn(() => ({ - checked: true, - wasRunning: true, - recovered: false, - [failureFlag]: true, - })); + it.each(["forwardRecoveryFailed", "secretBoundaryRefused", "mcpReconciliationRefused"] as const)( + "fails immediately when recovery reports %s (#7084)", + (failureFlag) => { + const checkAndRecoverSandboxProcesses = vi.fn(() => ({ + checked: true, + wasRunning: true, + recovered: false, + [failureFlag]: true, + })); - expect( - ensureHermesGatewayAfterStateRestore("alpha", "hermes", { - restartSandboxGateway: () => RESTART_SUCCEEDED, - checkAndRecoverSandboxProcesses, - }), - ).toBe("unverified"); + expect( + ensureHermesGatewayAfterStateRestore("alpha", "hermes", { + restartSandboxGateway: () => RESTART_SUCCEEDED, + checkAndRecoverSandboxProcesses, + }), + ).toBe("unverified"); - expect(checkAndRecoverSandboxProcesses).toHaveBeenCalledOnce(); - }); + expect(checkAndRecoverSandboxProcesses).toHaveBeenCalledOnce(); + }, + ); it("fails closed after the bounded gateway recheck remains inconclusive (#7084)", () => { const checkAndRecoverSandboxProcesses = vi.fn(() => ({ @@ -393,7 +392,11 @@ describe("Hermes rebuild post-restore verification", () => { expect(output).toContain("Hermes gateway health was not verified after state restore"); expect(output).not.toContain("MCP bridge definitions were preserved but not fully refreshed"); expect(output).not.toContain("rebuilt successfully"); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + [mcpEntry], + expect.any(Function), + ); }); it("restores MCP after gateway restart and before final health verification (#7084)", async () => { @@ -421,7 +424,11 @@ describe("Hermes rebuild post-restore verification", () => { harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), ).resolves.toBeUndefined(); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + [mcpEntry], + expect.any(Function), + ); expect(harness.restartSandboxGatewaySpy.mock.invocationCallOrder[0]).toBeLessThan( harness.restoreMcpBridgesAfterRebuildSpy.mock.invocationCallOrder[0], ); @@ -484,36 +491,40 @@ describe("Hermes rebuild post-restore verification", () => { harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), ).rejects.toThrow("Hermes post-restore verification failed"); - expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith("alpha", [mcpEntry]); + expect(harness.restoreMcpBridgesAfterRebuildSpy).toHaveBeenCalledWith( + "alpha", + [mcpEntry], + expect.any(Function), + ); expect(harness.logSpy).not.toHaveBeenCalledWith( expect.stringContaining("rebuilt successfully"), ); }); - it.each([ - "forwardRecoveryFailed", - "secretBoundaryRefused", - ] as const)("fails when the final gateway check reports %s (#7084)", async (failureFlag) => { - const harness = createRebuildFlowHarness({ - agentName: "hermes", - checkAndRecoverSandboxProcesses: () => ({ - checked: true, - wasRunning: true, - recovered: false, - forwardRecovered: false, - [failureFlag]: true, - }), - sandboxEntry: { agent: "hermes" }, - }); + it.each(["forwardRecoveryFailed", "secretBoundaryRefused"] as const)( + "fails when the final gateway check reports %s (#7084)", + async (failureFlag) => { + const harness = createRebuildFlowHarness({ + agentName: "hermes", + checkAndRecoverSandboxProcesses: () => ({ + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + [failureFlag]: true, + }), + sandboxEntry: { agent: "hermes" }, + }); - await expect( - harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow("Hermes post-restore verification failed"); + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).rejects.toThrow("Hermes post-restore verification failed"); - expect(harness.logSpy).not.toHaveBeenCalledWith( - expect.stringContaining("rebuilt successfully"), - ); - }); + expect(harness.logSpy).not.toHaveBeenCalledWith( + expect.stringContaining("rebuilt successfully"), + ); + }, + ); it("fails when the final gateway health probe is unavailable (#7084)", async () => { const harness = createRebuildFlowHarness({ diff --git a/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts b/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts index abbef103048..e62272763dd 100644 --- a/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts +++ b/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts @@ -700,14 +700,14 @@ export function recoverHermesCronRestore(sandboxName: string): HermesCronRestore throw new Error("Hermes cron recover returned an invalid disposition"); } -export function runHermesCronRestoreTransaction( +export async function runHermesCronRestoreTransaction( sandboxName: string, - restore: () => T, + restore: () => Promise, onGateTransition: (state: "acquired", identity: HermesCronRestoreIdentity) => void = () => {}, -): PendingHermesCronRestore { +): Promise> { const identity = beginHermesCronRestore(sandboxName); onGateTransition("acquired", identity); - const result = restore(); + const result = await restore(); if (!result.restoreSucceeded) { throw new HermesCronRestoreIncompleteError(); } diff --git a/src/lib/actions/sandbox/rebuild-mcp-phase.test.ts b/src/lib/actions/sandbox/rebuild-mcp-phase.test.ts index 5ec7cf3ef24..ff6a645267b 100644 --- a/src/lib/actions/sandbox/rebuild-mcp-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-mcp-phase.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { PolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; const mocks = vi.hoisted(() => ({ executeSandboxCommand: vi.fn(), @@ -9,14 +10,16 @@ const mocks = vi.hoisted(() => ({ prepareAbsent: vi.fn(), prepareExecUnavailable: vi.fn(), prepareLive: vi.fn(), + reattach: vi.fn(), + restore: vi.fn(), })); vi.mock("./mcp-bridge", () => ({ prepareMcpBridgesForAbsentSandboxRebuild: mocks.prepareAbsent, prepareMcpBridgesForExecUnavailableRebuild: mocks.prepareExecUnavailable, prepareMcpBridgesForRebuild: mocks.prepareLive, - reattachMcpProvidersAfterRebuildAbort: vi.fn(), - restoreMcpBridgesAfterRebuild: vi.fn(), + reattachMcpProvidersAfterRebuildAbort: mocks.reattach, + restoreMcpBridgesAfterRebuild: mocks.restore, })); vi.mock("./process-recovery", () => ({ @@ -24,7 +27,12 @@ vi.mock("./process-recovery", () => ({ executeSandboxExecCommand: mocks.executeSandboxExecCommand, })); -import { prepareMcpForRebuild, printMcpRebuildRetryCommand } from "./rebuild-mcp-phase"; +import { + prepareMcpForRebuild, + printMcpRebuildRetryCommand, + reattachMcpAfterDeleteFailure, + restoreMcpAfterRebuild, +} from "./rebuild-mcp-phase"; const emptyPreparation = { entries: [], @@ -112,28 +120,29 @@ describe("forced rebuild MCP preparation", () => { expect(relock).not.toHaveBeenCalled(); }); - it.each([ - 1, 64, 126, 127, 255, - ])("routes every nonzero exec result (%i) through explicit force recovery (#7062)", async (status) => { - mocks.executeSandboxExecCommand.mockReturnValue({ - status, - stdout: "", - stderr: "exec failed", - }); - const relock = vi.fn(() => true); - const bail = vi.fn((message: string): never => { - throw new Error(message); - }); - - await expect(prepareMcpForRebuild("alpha", false, true, relock, bail)).resolves.toEqual( - emptyPreparation, - ); - - expect(mocks.prepareExecUnavailable).toHaveBeenCalledWith("alpha"); - expect(mocks.prepareLive).not.toHaveBeenCalled(); - expect(mocks.prepareAbsent).not.toHaveBeenCalled(); - expect(relock).not.toHaveBeenCalled(); - }); + it.each([1, 64, 126, 127, 255])( + "routes every nonzero exec result (%i) through explicit force recovery (#7062)", + async (status) => { + mocks.executeSandboxExecCommand.mockReturnValue({ + status, + stdout: "", + stderr: "exec failed", + }); + const relock = vi.fn(() => true); + const bail = vi.fn((message: string): never => { + throw new Error(message); + }); + + await expect(prepareMcpForRebuild("alpha", false, true, relock, bail)).resolves.toEqual( + emptyPreparation, + ); + + expect(mocks.prepareExecUnavailable).toHaveBeenCalledWith("alpha"); + expect(mocks.prepareLive).not.toHaveBeenCalled(); + expect(mocks.prepareAbsent).not.toHaveBeenCalled(); + expect(relock).not.toHaveBeenCalled(); + }, + ); it("does not mask a live-path safety failure after a successful exec probe (#7062)", async () => { mocks.prepareLive.mockRejectedValue(new Error("generated policy drifted")); @@ -277,21 +286,21 @@ describe("MCP rebuild retry guidance", () => { expect(command).not.toContain("--no-observability"); }); - it.each([ - "disabled", - "thread-opt-in", - ] as const)("preserves an explicit DCode auto-approval=%s override", (mode) => { - const error = vi.spyOn(console, "error").mockImplementation(() => undefined); + it.each(["disabled", "thread-opt-in"] as const)( + "preserves an explicit DCode auto-approval=%s override", + (mode) => { + const error = vi.spyOn(console, "error").mockImplementation(() => undefined); - printMcpRebuildRetryCommand("alpha", [{} as never], "progressive", undefined, { - mode, - requestedExplicitly: true, - }); + printMcpRebuildRetryCommand("alpha", [{} as never], "progressive", undefined, { + mode, + requestedExplicitly: true, + }); - expect(error.mock.calls.flat().join("\n")).toContain( - `nemoclaw alpha rebuild --yes --tool-disclosure progressive --dcode-auto-approval ${mode}`, - ); - }); + expect(error.mock.calls.flat().join("\n")).toContain( + `nemoclaw alpha rebuild --yes --tool-disclosure progressive --dcode-auto-approval ${mode}`, + ); + }, + ); it("keeps inherited DCode auto-approval state implicit on retry", () => { const error = vi.spyOn(console, "error").mockImplementation(() => undefined); @@ -305,3 +314,55 @@ describe("MCP rebuild retry guidance", () => { expect(command).not.toContain("--dcode-auto-approval"); }); }); + +describe("MCP rebuild policy authority forwarding", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.reattach.mockResolvedValue(undefined); + mocks.restore.mockResolvedValue(undefined); + }); + + it("passes the containing receipt to delete-abort restoration (#9833)", async () => { + const validateContainingPolicyReceipt = vi.fn(async () => undefined); + const entries = [{} as never]; + + await expect( + reattachMcpAfterDeleteFailure("alpha", entries, entries, validateContainingPolicyReceipt), + ).resolves.toBeUndefined(); + + expect(mocks.reattach).toHaveBeenCalledWith( + "alpha", + entries, + entries, + validateContainingPolicyReceipt, + ); + }); + + it("passes the containing receipt to post-rebuild restoration (#9833)", async () => { + vi.spyOn(console, "log").mockImplementation(() => undefined); + const validateContainingPolicyReceipt = vi.fn(async () => undefined); + const entries = [{} as never]; + + await expect( + restoreMcpAfterRebuild("alpha", entries, validateContainingPolicyReceipt), + ).resolves.toBe(true); + + expect(mocks.restore).toHaveBeenCalledWith("alpha", entries, validateContainingPolicyReceipt); + }); + + it("preserves policy authority refusal during live preparation (#9833)", async () => { + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + mocks.prepareLive.mockRejectedValueOnce(refusal); + const relock = vi.fn(() => true); + const bail = vi.fn((message: string): never => { + throw new Error(message); + }); + + await expect(prepareMcpForRebuild("alpha", false, false, relock, bail, vi.fn())).rejects.toBe( + refusal, + ); + + expect(relock).not.toHaveBeenCalled(); + expect(bail).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/rebuild-mcp-phase.ts b/src/lib/actions/sandbox/rebuild-mcp-phase.ts index 7cb1ed1497b..827e0f937e3 100644 --- a/src/lib/actions/sandbox/rebuild-mcp-phase.ts +++ b/src/lib/actions/sandbox/rebuild-mcp-phase.ts @@ -14,6 +14,7 @@ import { reattachMcpProvidersAfterRebuildAbort, restoreMcpBridgesAfterRebuild, } from "./mcp-bridge"; +import { isPolicyAuthorityRefusalError } from "./policy-authority/preflight"; import { executeSandboxCommand, executeSandboxExecCommand } from "./process-recovery"; import type { RebuildBail } from "./rebuild-credential-preflight"; import type { RebuildSandboxEntry } from "./rebuild-flow-helpers"; @@ -38,6 +39,7 @@ export async function prepareMcpForRebuild( force: boolean, relockShieldsIfNeeded: (sandboxStillExists: boolean) => boolean, bail: RebuildBail, + validateContainingPolicyReceipt?: () => Promise, ): Promise { // invalidState: OpenShell still reports a live sandbox, but the // side-effect-free `:` command cannot cross every transport required by live @@ -67,8 +69,11 @@ export async function prepareMcpForRebuild( try { return await (staleRecovery ? prepareMcpBridgesForAbsentSandboxRebuild(sandboxName) - : prepareMcpBridgesForRebuild(sandboxName)); + : validateContainingPolicyReceipt + ? prepareMcpBridgesForRebuild(sandboxName, validateContainingPolicyReceipt) + : prepareMcpBridgesForRebuild(sandboxName)); } catch (error) { + if (isPolicyAuthorityRefusalError(error)) throw error; relockShieldsIfNeeded(!staleRecovery); bail( `Failed to preserve MCP bridges before rebuild: ${error instanceof Error ? error.message : String(error)}`, @@ -81,9 +86,17 @@ export async function reattachMcpAfterDeleteFailure( sandboxName: string, entries: McpRebuildPreparation["detachedProviderEntries"], scrubbedAdapterEntries: McpRebuildPreparation["scrubbedAdapterEntries"], + validateContainingPolicyReceipt?: () => Promise, ): Promise { try { - await reattachMcpProvidersAfterRebuildAbort(sandboxName, entries, scrubbedAdapterEntries); + await (validateContainingPolicyReceipt + ? reattachMcpProvidersAfterRebuildAbort( + sandboxName, + entries, + scrubbedAdapterEntries, + validateContainingPolicyReceipt, + ) + : reattachMcpProvidersAfterRebuildAbort(sandboxName, entries, scrubbedAdapterEntries)); return undefined; } catch (error) { return error instanceof Error ? error.message : String(error); @@ -150,14 +163,19 @@ export function printMcpRebuildRetryCommand( export async function restoreMcpAfterRebuild( sandboxName: string, entries: McpRebuildPreparation["entries"], + validatePolicyAuthority: () => Promise, ): Promise { + await validatePolicyAuthority(); if (entries.length === 0) return true; console.log(" Restoring MCP bridges..."); try { - await restoreMcpBridgesAfterRebuild(sandboxName, entries); + await restoreMcpBridgesAfterRebuild(sandboxName, entries, validatePolicyAuthority); + await validatePolicyAuthority(); console.log(` ${G}✓${R} MCP bridges restored`); return true; } catch (error) { + if (isPolicyAuthorityRefusalError(error)) throw error; + await validatePolicyAuthority(); console.error( ` ${YW}⚠${R} MCP bridge restore incomplete: ${error instanceof Error ? error.message : String(error)}`, ); diff --git a/src/lib/actions/sandbox/rebuild-messaging-phase.ts b/src/lib/actions/sandbox/rebuild-messaging-phase.ts index d62300abb39..26ac7aaa901 100644 --- a/src/lib/actions/sandbox/rebuild-messaging-phase.ts +++ b/src/lib/actions/sandbox/rebuild-messaging-phase.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { runOpenshell } from "../../adapters/openshell/runtime"; +import { isPolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; import { RD as _RD, D, G, R } from "../../cli/terminal-style"; import { MessagingSetupApplier } from "../../messaging/applier/setup-applier"; import type { @@ -75,6 +76,7 @@ export async function reapplyMessagingManifestAfterOpenClawDoctor( sandboxName: string, plan: SandboxMessagingPlan | null, log: (message: string) => void, + beforeSuccess?: () => Promise, ): Promise { if (!plan || plan.agent !== "openclaw") { log("Messaging manifest reapply skipped: no OpenClaw messaging plan"); @@ -87,6 +89,7 @@ export async function reapplyMessagingManifestAfterOpenClawDoctor( runOpenshell: runMessagingOpenshell, runHook: (request) => hookOutputsFromBuildSteps(plan, request), }); + await beforeSuccess?.(); log( `messaging manifest reapply: targets=${result.appliedTargets.join(",")}, hooks=${result.appliedHooks.join(",")}`, ); @@ -94,6 +97,7 @@ export async function reapplyMessagingManifestAfterOpenClawDoctor( console.log(` ${G}\u2713${R} Messaging manifest config reapplied`); } } catch (error) { + if (isPolicyAuthorityRefusalError(error)) throw error; const message = error instanceof Error ? error.message : String(error); log(`Messaging manifest reapply failed: ${message}`); console.log(` ${D}Messaging manifest config reapply skipped (${message})${R}`); diff --git a/src/lib/actions/sandbox/rebuild-messaging-policy-authority.test.ts b/src/lib/actions/sandbox/rebuild-messaging-policy-authority.test.ts new file mode 100644 index 00000000000..ee8c6ef8996 --- /dev/null +++ b/src/lib/actions/sandbox/rebuild-messaging-policy-authority.test.ts @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { PolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; +import { MessagingSetupApplier } from "../../messaging/applier/setup-applier"; +import { reapplyMessagingManifestAfterOpenClawDoctor } from "./rebuild-messaging-phase"; + +describe("rebuild messaging policy authority", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("withholds messaging success when authority changes during config application (#9833)", async () => { + vi.spyOn(MessagingSetupApplier, "applyAgentConfigAtOpenShell").mockResolvedValue({ + appliedHooks: ["telegram-config"], + appliedTargets: ["openclaw-config"], + } as never); + const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined); + const log = vi.fn(); + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + + await expect( + reapplyMessagingManifestAfterOpenClawDoctor( + "alpha", + { agent: "openclaw", buildSteps: [] } as never, + log, + vi.fn(async () => { + throw refusal; + }), + ), + ).rejects.toBe(refusal); + + expect(consoleLog.mock.calls.flat().join("\n")).not.toContain( + "Messaging manifest config reapplied", + ); + expect(log.mock.calls.flat().join("\n")).not.toContain("messaging manifest reapply: targets="); + }); +}); diff --git a/src/lib/actions/sandbox/rebuild-onboard-dependencies.ts b/src/lib/actions/sandbox/rebuild-onboard-dependencies.ts index f93d591bc14..6f24fbc8901 100644 --- a/src/lib/actions/sandbox/rebuild-onboard-dependencies.ts +++ b/src/lib/actions/sandbox/rebuild-onboard-dependencies.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { isPolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; import type { CheckpointGatewayAuthority } from "../../state/onboard-checkpoint-types"; import type { RebuildDurableConfig } from "./rebuild-durable-config"; import type { RebuildRecreateOnboardOpts } from "./rebuild-gpu-opt-out"; @@ -35,6 +36,7 @@ function loadOnboardModule(): RebuildOnboardModule { * the onboarding APIs are side-effect-free named imports. */ export const rebuildOnboardDependencies = { + isPolicyAuthorityRefusalError, ensureValidatedWebSearchCredential( config: NonNullable, nonInteractive?: boolean, diff --git a/src/lib/actions/sandbox/rebuild-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index 51003e38a2d..b3a401ee05d 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -43,6 +43,8 @@ import { } from "./rebuild-preflight-guards"; import { finalizePreparedRebuildImageMessagingPlan, + isPolicyAuthorityRefusalError, + revalidateRebuildPolicyAuthority, runHermesCronRestoreBackupPreflight, runRebuildPreflightPhase, } from "./rebuild-preflight-phase"; @@ -98,30 +100,31 @@ export async function rebuildSandbox( sessionFile: onboardSession.SESSION_FILE, stateDir: path.dirname(onboardSession.SESSION_FILE), }, - () => withMcpLifecycleLock(sandboxName, async () => { - assertSandboxRebuildCommandAvailable(sandboxName); - const scopedEnvKeys = [ - BRAVE_API_KEY_ENV, - TAVILY_API_KEY_ENV, - MESSAGING_SETUP_APPLIER_ENV_KEY, - "OPENSHELL_GATEWAY", - DOCKER_GPU_PATCH_NETWORK_ENV, - ...REBUILD_HERMES_DASHBOARD_ENV_KEYS, - ...MESSAGING_CHANNEL_CONFIG_ENV_KEYS, - ]; - const savedEnv = scopedEnvKeys.map((key) => [key, process.env[key]] as const); - try { - await rebuildSandboxUnlocked(sandboxName, options, opts); - } finally { - for (const key of scopedEnvKeys) delete process.env[key]; - Object.assign( - process.env, - Object.fromEntries( - savedEnv.filter((entry): entry is [string, string] => entry[1] !== undefined), - ), - ); - } - }), + () => + withMcpLifecycleLock(sandboxName, async () => { + assertSandboxRebuildCommandAvailable(sandboxName); + const scopedEnvKeys = [ + BRAVE_API_KEY_ENV, + TAVILY_API_KEY_ENV, + MESSAGING_SETUP_APPLIER_ENV_KEY, + "OPENSHELL_GATEWAY", + DOCKER_GPU_PATCH_NETWORK_ENV, + ...REBUILD_HERMES_DASHBOARD_ENV_KEYS, + ...MESSAGING_CHANNEL_CONFIG_ENV_KEYS, + ]; + const savedEnv = scopedEnvKeys.map((key) => [key, process.env[key]] as const); + try { + await rebuildSandboxUnlocked(sandboxName, options, opts); + } finally { + for (const key of scopedEnvKeys) delete process.env[key]; + Object.assign( + process.env, + Object.fromEntries( + savedEnv.filter((entry): entry is [string, string] => entry[1] !== undefined), + ), + ); + } + }), { loadRegistry, withLifecycleLock: withMcpLifecycleLock }, ); } @@ -146,6 +149,7 @@ async function rebuildSandboxUnlocked( recoveryManifest: validatedRecoveryManifest, dcodePreflight, preparedImage: initiallyPreparedImage, + policyAuthorityReceipt, routePreflightReceipt, releaseOnboardLock, log, @@ -171,6 +175,12 @@ async function rebuildSandboxUnlocked( const recoveryRecreate = staleRecovery || preparedBackupRecovery; try { if (blockRebuildOnPendingBaselineTransition(sandboxEntry, sandboxName, bail)) return; + try { + await revalidateRebuildPolicyAuthority(policyAuthorityReceipt); + } catch (error) { + bail(error instanceof Error ? error.message : String(error)); + return; + } let recoveryRegistrySnapshot = preparedBackupRecovery ? JSON.parse(JSON.stringify(loadRegistry())) : liveState.staleRegistrySnapshot; @@ -184,6 +194,7 @@ async function rebuildSandboxUnlocked( const shieldsPhase = runRebuildShieldsPhase( sandboxName, recoveryRecreate, + policyAuthorityReceipt.authority, releaseOnboardLock, bail, ); @@ -191,6 +202,7 @@ async function rebuildSandboxUnlocked( const { window: rebuildShieldsWindow, staleSandboxWasLocked, + markSourceDeleted: markRebuildShieldsSourceDeleted, relock: relockShieldsIfNeeded, } = shieldsPhase; let sandboxStillExists = true; @@ -320,6 +332,21 @@ async function rebuildSandboxUnlocked( }); recreateOptions.rebuildGatewayAuthority = recreateJournal.gatewayAuthority; + const validatePolicyAuthority = async () => { + try { + await revalidateRebuildPolicyAuthority(policyAuthorityReceipt); + return { ok: true as const }; + } catch (error) { + return { + ok: false as const, + message: error instanceof Error ? error.message : String(error), + }; + } + }; + const requireValidPolicyAuthority = async (): Promise => { + await revalidateRebuildPolicyAuthority(policyAuthorityReceipt); + }; + // An earlier run of this rebuild already registered and proved the // replacement. Retire its journal and stop before the destroy phase so a // restart converges to that sandbox instead of deleting it. @@ -329,7 +356,9 @@ async function rebuildSandboxUnlocked( // Hermes target before retiring the replacement journal. if (rebuildAgent === "hermes") { try { + await requireValidPolicyAuthority(); const outcome = recoverHermesCronRestore(sandboxName); + await requireValidPolicyAuthority(); if (outcome === "unsupported") { console.error(""); console.error( @@ -347,6 +376,7 @@ async function rebuildSandboxUnlocked( } log(`Hermes cron restore recovery for accepted replacement: ${outcome}`); } catch (error) { + if (isPolicyAuthorityRefusalError(error)) throw error; console.error(""); console.error( ` Hermes cron restore could not validate and release the accepted replacement: ${rebuildFailureDetail(error)}`, @@ -358,7 +388,9 @@ async function rebuildSandboxUnlocked( ); } } + await requireValidPolicyAuthority(); recreateJournal.completeAcceptedTarget(); + await requireValidPolicyAuthority(); log(`Recovered journaled replacement ${recreateJournal.id} for '${sandboxName}'`); console.log( ` Sandbox '${sandboxName}' already holds the replacement from the interrupted rebuild.`, @@ -379,7 +411,11 @@ async function rebuildSandboxUnlocked( log, bail, relockShieldsIfNeeded, + validateBeforeMcpPreparation: validatePolicyAuthority, + validateMcpPolicyAuthorityReceipt: requireValidPolicyAuthority, validateAfterMcpPreparation: async () => { + const policyAuthority = await validatePolicyAuthority(); + if (!policyAuthority.ok) return policyAuthority; const providerReconfigure = recreateOptions.rebuildProviderReconfigure; if (providerReconfigure && !hydrateCredentialEnv(providerReconfigure.credentialEnv)) { return { @@ -411,6 +447,8 @@ async function rebuildSandboxUnlocked( recreateOptions.targetGatewayPort, ); }, + validateBeforeDeleteCommit: validatePolicyAuthority, + validateAfterDeleteConfirmation: validatePolicyAuthority, validateAtDeleteEdge: () => revalidateManagedWorkloadRebuildBeforeDelete( sandboxName, @@ -418,12 +456,14 @@ async function rebuildSandboxUnlocked( ) ?? revalidateRebuildRouteBeforeDelete(routePreflightReceipt), onDeleted: () => { sandboxStillExists = false; + markRebuildShieldsSourceDeleted(); }, onDeleteStateAmbiguous: () => { sandboxExistenceAmbiguous = true; }, }); if (!mcpPreparation) return; + await requireValidPolicyAuthority(); registryRollback.recordRemoval(mcpPreparation.removalReceipt); const restoreDcodeGpuPatchNetwork = dcodePreflight.applyDockerGpuPatchNetwork(); @@ -453,6 +493,7 @@ async function rebuildSandboxUnlocked( mcpEntries: mcpPreparation.entries, rebuildShieldsWindow, relockShieldsIfNeeded, + validatePolicyAuthority: requireValidPolicyAuthority, onCreated: () => { sandboxStillExists = true; }, @@ -506,14 +547,16 @@ async function rebuildSandboxUnlocked( backupManifest: backup.backupManifest, policyPresets: targetPolicyPresets, customPolicies: customPoliciesWithRegistryPinAuthority, + policyAuthority: policyAuthorityReceipt.authority, + validatePolicyAuthority: requireValidPolicyAuthority, reconcileManagedDcodeObservability: rebuildAgent === DCODE_AGENT_NAME, log, }); let hermesCronRestoreIdentity: HermesCronRestoreIdentity | undefined; const restored = hermesCronRestorePlan?.requiresDispatchGate - ? (() => { + ? await (async () => { try { - const transaction = runHermesCronRestoreTransaction( + const transaction = await runHermesCronRestoreTransaction( sandboxName, restore, (state, identity) => { @@ -536,7 +579,7 @@ async function rebuildSandboxUnlocked( return bail("Hermes cron restore validation failed; dispatch was not re-enabled."); } })() - : restore(); + : await restore(); await runRebuildPostRestorePhase({ sandboxName, sandboxEntry, @@ -551,6 +594,8 @@ async function rebuildSandboxUnlocked( finalBuiltinPresets: restored.finalBuiltinPresets, failedPresetRemovals: restored.failedPresetRemovals, policyPresetReconciliationVerified: restored.policyPresetReconciliationVerified, + policyAuthority: policyAuthorityReceipt.authority, + validatePolicyAuthority: requireValidPolicyAuthority, staleRecovery, recoveryRecreate, preparedBackupRecovery, diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts index f4a0fbb3c97..d686e613871 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { PolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; import * as agentDefs from "../../agent/defs"; import * as agentRuntime from "../../agent/runtime"; import * as shields from "../../shields"; @@ -117,6 +118,8 @@ describe("rebuild post-restore phase", () => { backupWasForceSkipped: false, failedPresets: [], finalBuiltinPresets: [], + policyAuthority: "nemoclaw-managed" as const, + validatePolicyAuthority: vi.fn(async () => undefined), failedPresetRemovals: [], policyPresetReconciliationVerified: true, staleRecovery: false, @@ -151,6 +154,32 @@ describe("rebuild post-restore phase", () => { ); }); + it("keeps external rebuild policy authority without NemoClaw preset attribution (#9833)", async () => { + const args = { + ...input(), + policyAuthority: "externally-managed" as const, + finalBuiltinPresets: ["npm"], + sandboxEntry: { + baselineExclusions: [{ key: "openclaw_docs" }], + customPolicies: [{ name: "custom-api", content: "network_policies: {}" }], + policies: ["npm"], + policyTier: "restricted", + } as never, + }; + + await runRebuildPostRestorePhase(args); + + expect(registry.updateSandbox).toHaveBeenCalledWith("alpha", { + agentVersion: null, + baselineExclusions: [], + customPolicies: [], + policies: [], + policyAuthority: "externally-managed", + policyPresetsFinalized: undefined, + policyTier: null, + }); + }); + it("does not record a final hash without trusted doctor completion (#9946)", async () => { vi.mocked(processRecovery.executeSandboxExecCommand).mockReturnValue(null); const args = input(); @@ -171,6 +200,44 @@ describe("rebuild post-restore phase", () => { expect(output).not.toContain("rebuilt successfully"); }); + it("withholds doctor success when policy authority changes during repair (#9833)", async () => { + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + const args = input(); + vi.mocked(args.validatePolicyAuthority) + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(refusal); + + await expect(runRebuildPostRestorePhase(args)).rejects.toBe(refusal); + + expect(sessionModels.reconcileStalePinnedSessionModelsAfterRebuild).not.toHaveBeenCalled(); + expect(rebuildMcp.restoreMcpAfterRebuild).not.toHaveBeenCalled(); + const output = vi.mocked(console.log).mock.calls.flat().join("\n"); + expect(output).not.toContain("Post-upgrade structure check passed"); + expect(output).not.toContain("rebuilt successfully"); + }); + + it("withholds forward and rebuild success when policy authority changes during forwarding (#9833)", async () => { + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + let authorityChanged = false; + vi.mocked(messagingHostForward.ensureMessagingHostForwardAfterRebuild).mockImplementation( + (_sandboxName, _plan, note) => { + authorityChanged = true; + note?.("Messaging forward ready"); + return true; + }, + ); + const args = input(); + vi.mocked(args.validatePolicyAuthority).mockImplementation(() => + authorityChanged ? Promise.reject(refusal) : Promise.resolve(), + ); + + await expect(runRebuildPostRestorePhase(args)).rejects.toBe(refusal); + + const output = vi.mocked(console.log).mock.calls.flat().join("\n"); + expect(output).not.toContain("Messaging forward ready"); + expect(output).not.toContain("rebuilt successfully"); + }); + it("does not seal OpenClaw config after unverified MCP restoration (#9946)", async () => { vi.mocked(rebuildMcp.restoreMcpAfterRebuild).mockResolvedValue(false); const args = input(); @@ -198,17 +265,11 @@ describe("rebuild post-restore phase", () => { await runRebuildPostRestorePhase(args); - expect( - sessionModels.reconcileStalePinnedSessionModelsAfterRebuild, - ).not.toHaveBeenCalled(); + expect(sessionModels.reconcileStalePinnedSessionModelsAfterRebuild).not.toHaveBeenCalled(); expect(rebuildMessaging.reapplyMessagingManifestAfterOpenClawDoctor).not.toHaveBeenCalled(); expect(shields.repairMutableConfigPerms).not.toHaveBeenCalled(); - expect( - rebuildHermesPostRestore.restartHermesGatewayAfterStateRestore, - ).not.toHaveBeenCalled(); - expect( - rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestore, - ).not.toHaveBeenCalled(); + expect(rebuildHermesPostRestore.restartHermesGatewayAfterStateRestore).not.toHaveBeenCalled(); + expect(rebuildHermesPostRestore.verifyHermesGatewayAfterStateRestore).not.toHaveBeenCalled(); expect(rebuildMcp.restoreMcpAfterRebuild).not.toHaveBeenCalled(); expect( rebuildConfigHash.refreshMutableOpenClawConfigHashAfterPostRestoreWrites, @@ -448,6 +509,36 @@ describe("rebuild post-restore phase", () => { expect(output).toContain("nemoclaw alpha recover"); }); + it("preserves policy refusal after Hermes cron release without publishing success (#9833)", async () => { + agentName = "hermes"; + const refusal = new PolicyAuthorityRefusalError("policy authority changed"); + let cronReleased = false; + vi.mocked( + rebuildHermesPostRestore.completeHermesCronRestoreAfterGatewayReplacement, + ).mockImplementation(() => { + cronReleased = true; + return { pid: 77, start_time: 903, drain_token: "restore-token" }; + }); + const args = { + ...input(), + hermesCronRestoreIdentity: { + pid: 41, + start_time: 902, + drain_token: "restore-token", + }, + }; + vi.mocked(args.validatePolicyAuthority).mockImplementation(() => + cronReleased ? Promise.reject(refusal) : Promise.resolve(), + ); + + await expect(runRebuildPostRestorePhase(args)).rejects.toBe(refusal); + + expect(args.bail).not.toHaveBeenCalled(); + const output = vi.mocked(console.log).mock.calls.flat().join("\n"); + expect(output).not.toContain("Hermes gateway restarted and verified"); + expect(output).not.toContain("rebuilt successfully"); + }); + it("reports preserved recovery authority when release marker rollback fails (#8472)", async () => { agentName = "hermes"; const rollbackFailure = new Error( diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts index 97c03adfd15..6142c9f2c24 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts @@ -3,6 +3,10 @@ import { loadAgent } from "../../agent/defs"; import * as agentRuntime from "../../agent/runtime"; +import { + isPolicyAuthorityRefusalError, + type SandboxPolicyAuthority, +} from "../../adapters/openshell/policy-authority"; import { CLI_NAME } from "../../cli/branding"; import { D, G, R, YW } from "../../cli/terminal-style"; import type { SandboxMessagingPlan } from "../../messaging"; @@ -85,6 +89,8 @@ export interface RebuildPostRestorePhaseInput { backupWasForceSkipped: boolean; failedPresets: string[]; finalBuiltinPresets: string[]; + policyAuthority: SandboxPolicyAuthority; + validatePolicyAuthority: () => Promise; failedPresetRemovals: string[]; policyPresetReconciliationVerified: boolean; staleRecovery: boolean; @@ -188,6 +194,8 @@ export async function runRebuildPostRestorePhase( backupWasForceSkipped, failedPresets, finalBuiltinPresets, + policyAuthority, + validatePolicyAuthority, failedPresetRemovals, policyPresetReconciliationVerified, staleRecovery, @@ -224,6 +232,7 @@ export async function runRebuildPostRestorePhase( bail("Recreated sandbox agent identity did not match the authoritative rebuild target."); return; } + await validatePolicyAuthority(); const agentDef = loadAgent(targetAgentName); const rebuiltAgentName = agentDef.displayName; let mutablePermsRepairUnverified = false; @@ -243,6 +252,7 @@ export async function runRebuildPostRestorePhase( OPENCLAW_DOCTOR_TIMEOUT_MS, { allowLocalDockerFallback: false }, ); + await validatePolicyAuthority(); log(`doctor --fix: exit=${doctorResult?.status ?? "unverified"}`); if (doctorResult === null) { console.log(` ${D}Post-upgrade structure repair completion was not verified${R}`); @@ -258,12 +268,20 @@ export async function runRebuildPostRestorePhase( } console.log(` ${G}\u2713${R} Post-upgrade structure check passed`); + await validatePolicyAuthority(); // #7102: clear stale per-session pinned models left over from an // `inference set` before this rebuild, while the gateway is still down. reconcileStalePinnedSessionModelsAfterRebuild(sandboxName, log); + await validatePolicyAuthority(); - await reapplyMessagingManifestAfterOpenClawDoctor(sandboxName, messagingPlan, log); + await reapplyMessagingManifestAfterOpenClawDoctor( + sandboxName, + messagingPlan, + log, + validatePolicyAuthority, + ); + await validatePolicyAuthority(); log("Restoring mutable OpenClaw config permissions after post-restore config writes"); let permRepair: ReturnType | null = null; try { @@ -274,6 +292,7 @@ export async function runRebuildPostRestorePhase( ` ${YW}\u26a0${R} Mutable config permission repair errored: ${error instanceof Error ? error.message : String(error)}`, ); } + await validatePolicyAuthority(); if (permRepair === null) { // The thrown error was reported above. } else if (!permRepair.applied) { @@ -298,19 +317,38 @@ export async function runRebuildPostRestorePhase( // Restart before restoring MCP. The Hermes MCP transaction performs an // acknowledged reload of its own; restarting afterwards would replace the // only runtime whose managed MCP configuration was proven to have loaded. + await validatePolicyAuthority(); const hermesGatewayRestartState = restartHermesGatewayAfterStateRestore( sandboxName, targetAgentName, ); - const mcpBridgeRestoreUnverified = !(await restoreMcpAfterRebuild(sandboxName, mcpEntries)); + await validatePolicyAuthority(); + const mcpBridgeRestoreUnverified = !(await restoreMcpAfterRebuild( + sandboxName, + mcpEntries, + validatePolicyAuthority, + )); if (targetAgentName === "openclaw" && mcpBridgeRestoreUnverified) { mutableConfigHashRefreshUnverified = true; } else if (targetAgentName === "openclaw") { log("Refreshing mutable OpenClaw config hash after MCP restoration"); - if (!refreshMutableOpenClawConfigHashAfterPostRestoreWrites(sandboxName, log)) { + const refreshedMutableConfigHash = refreshMutableOpenClawConfigHashAfterPostRestoreWrites( + sandboxName, + () => undefined, + ); + const verifiedMutableConfigHash = + refreshedMutableConfigHash && + verifyFinalMutableOpenClawConfigHash(sandboxName, () => undefined); + await validatePolicyAuthority(); + if (!refreshedMutableConfigHash) { mutableConfigHashRefreshUnverified = true; - } else if (!verifyFinalMutableOpenClawConfigHash(sandboxName, log)) { + } else { + log("Mutable OpenClaw config hash refreshed after post-restore config writes"); + } + if (refreshedMutableConfigHash && !verifiedMutableConfigHash) { finalMutableConfigHashUnverified = true; + } else if (verifiedMutableConfigHash) { + log("Final mutable OpenClaw config hash verified after post-restore finalization"); } } const hermesGatewayVerification = hermesCronRestoreIdentity @@ -328,6 +366,7 @@ export async function runRebuildPostRestorePhase( ), replacementIdentity: undefined, }; + await validatePolicyAuthority(); const hermesGatewayRestoreState = hermesGatewayVerification.state; const hermesGatewayRestoreUnverified = hermesGatewayRestoreState === "unverified"; if (hermesCronRestoreIdentity) { @@ -358,12 +397,15 @@ export async function runRebuildPostRestorePhase( } let completedIdentity: HermesCronRestoreIdentity; try { + await validatePolicyAuthority(); completedIdentity = completeHermesCronRestoreAfterGatewayReplacement( sandboxName, hermesCronRestoreIdentity, replacementIdentity, ); + await validatePolicyAuthority(); } catch (error) { + if (isPolicyAuthorityRefusalError(error)) throw error; const errorDetail = error instanceof Error ? error.message : String(error); if (isHermesCronRestoreDrainMarkerRollbackFailure(error)) { return bailAfterHermesCronRestoreFailure( @@ -391,21 +433,28 @@ export async function runRebuildPostRestorePhase( } else if (hermesGatewayRestoreState === "recovered") { console.log(` ${G}\u2713${R} Hermes gateway recovered after state restore`); } - const { policies: restoredBuiltinPresets, policyPresetsFinalized } = - resolveRestoredPolicyRegistryState( - { - policyPresetsFinalized: sb.policyPresetsFinalized, - }, - finalBuiltinPresets, - failedPresets, - policyPresetReconciliationVerified, - ); + const externallyManagedPolicy = policyAuthority === "externally-managed"; + const { policies: restoredBuiltinPresets, policyPresetsFinalized } = externallyManagedPolicy + ? { policies: [], policyPresetsFinalized: undefined } + : resolveRestoredPolicyRegistryState( + { + policyPresetsFinalized: sb.policyPresetsFinalized, + }, + finalBuiltinPresets, + failedPresets, + policyPresetReconciliationVerified, + ); + await validatePolicyAuthority(); registry.updateSandbox(sandboxName, { agentVersion: agentDef.expectedVersion || null, policies: restoredBuiltinPresets, - policyTier: normalizePolicyTierName(sb.policyTier), + policyTier: externallyManagedPolicy ? null : normalizePolicyTierName(sb.policyTier), policyPresetsFinalized, + ...(externallyManagedPolicy + ? { baselineExclusions: [], customPolicies: [], policyAuthority } + : {}), }); + await validatePolicyAuthority(); log( `Registry updated: agentVersion=${agentDef.expectedVersion}, policies=[${restoredBuiltinPresets.join(",")}], policyPresetsFinalized=${String(policyPresetsFinalized === true)}`, ); @@ -414,18 +463,34 @@ export async function runRebuildPostRestorePhase( bail("Failed to re-apply shields lockdown."); return; } - if (!ensureMessagingHostForwardAfterRebuild(sandboxName, messagingPlan)) { + await validatePolicyAuthority(); + const messagingForwardNotes: string[] = []; + if ( + !ensureMessagingHostForwardAfterRebuild(sandboxName, messagingPlan, (message) => + messagingForwardNotes.push(message), + ) + ) { messagingHostForwardUnverified = true; } + await validatePolicyAuthority(); + for (const message of messagingForwardNotes) console.log(message); + let finalMutableConfigHashVerified = false; if ( targetAgentName === "openclaw" && !mcpBridgeRestoreUnverified && !mutableConfigHashRefreshUnverified && - !verifyFinalMutableOpenClawConfigHash(sandboxName, log) + !(finalMutableConfigHashVerified = verifyFinalMutableOpenClawConfigHash( + sandboxName, + () => undefined, + )) ) { finalMutableConfigHashUnverified = true; } + await validatePolicyAuthority(); + if (finalMutableConfigHashVerified) { + log("Final mutable OpenClaw config hash verified after post-restore finalization"); + } console.log(""); const postRestoreComplete = postRestoreCompleted({ hermesGatewayRestoreUnverified, diff --git a/src/lib/actions/sandbox/rebuild-preflight-guards.ts b/src/lib/actions/sandbox/rebuild-preflight-guards.ts index 0d8ca2ae3aa..320d67b6cdc 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-guards.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-guards.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { isDeepStrictEqual } from "node:util"; + import { detectOpenShellStateRpcPreflightIssue, printOpenShellStateRpcIssue, @@ -405,7 +407,9 @@ export function assertRebuildEntryUnchanged( bail: RebuildBail, ): void { const lockedEntry = registry.getSandbox(sandboxName); - if (lockedEntry && JSON.stringify(lockedEntry) === confirmedEntrySnapshot) return; + const confirmedEntry = JSON.parse(confirmedEntrySnapshot) as RebuildSandboxEntry; + const lockedSnapshot = lockedEntry ? JSON.parse(JSON.stringify(lockedEntry)) : null; + if (isDeepStrictEqual(lockedSnapshot, confirmedEntry)) return; printRebuildPreflightFailure( "the sandbox configuration changed while rebuild confirmation was pending.", "Review the current sandbox state and rerun rebuild.", diff --git a/src/lib/actions/sandbox/rebuild-preflight-phase.ts b/src/lib/actions/sandbox/rebuild-preflight-phase.ts index caa7b676ab3..63ce2af3d71 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-phase.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-phase.ts @@ -52,6 +52,15 @@ import { } from "./rebuild-preflight-guards"; import { prepareRebuildTargetPreflights } from "./rebuild-preflight-target-phase"; import { disposePreparedBuildContext } from "./rebuild-prepared-image-context"; +import { + qualifyRebuildPolicyAuthority, + type RebuildPolicyAuthorityReceipt, +} from "./policy-authority/rebuild"; + +export { + isPolicyAuthorityRefusalError, + revalidateRebuildPolicyAuthority, +} from "./policy-authority/rebuild"; import { type RebuildSandboxExecutionOptions, validatePreparedRecoveryManifest, @@ -73,6 +82,7 @@ export interface RebuildPreflightPhaseResult { recoveryManifest: RebuildManifest | null; dcodePreflight: DcodeRebuildOrchestrator; preparedImage: PreparedRebuildImage | null; + policyAuthorityReceipt: RebuildPolicyAuthorityReceipt; routePreflightReceipt: RebuildRoutePreflightReceipt; releaseOnboardLock: () => void; log: RebuildLog; @@ -157,7 +167,6 @@ export async function runRebuildPreflightPhase( ); return null; } - const confirmedEntrySnapshot = JSON.stringify(sandboxEntry); const allowLegacyManagedImageRecovery = opts.recoveryManifest !== undefined && opts.allowLegacyManagedImageRecovery === true; const recoveryManifest = validatePreparedRecoveryManifest( @@ -167,6 +176,7 @@ export async function runRebuildPreflightPhase( allowLegacyManagedImageRecovery, bail, ); + const confirmedEntrySnapshot = JSON.stringify(sandboxEntry); if (!isSingleAgentRebuildSupported(sandboxEntry, bail)) return null; const rebuildAgent = sandboxEntry.agent || null; @@ -223,6 +233,23 @@ export async function runRebuildPreflightPhase( confirmedEntrySnapshot, versionCheck, ); + let policyAuthorityReceipt: RebuildPolicyAuthorityReceipt; + try { + policyAuthorityReceipt = await qualifyRebuildPolicyAuthority({ + sandboxName, + sandboxEntry: expectedSandboxEntry, + manifest: recoveryManifest, + requestedObservabilityEnabled, + }); + } catch (error) { + printRebuildPreflightFailure( + `policy authority could not be qualified: ${error instanceof Error ? error.message : String(error)}`, + "Confirm the recorded OpenShell gateway policy source and every required network-policy entry before retrying.", + "Policy authority preflight failed.", + bail, + ); + return null; + } const dcodePreflight = createDcodeRebuildOrchestrator({ sandboxName, entry: expectedSandboxEntry, @@ -324,6 +351,7 @@ export async function runRebuildPreflightPhase( liveState, recoveryManifest, dcodePreflight, + policyAuthorityReceipt, releaseOnboardLock, log, bail, diff --git a/src/lib/actions/sandbox/rebuild-recreate-journal.test.ts b/src/lib/actions/sandbox/rebuild-recreate-journal.test.ts index 5a7a01a30f9..242714adc81 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-journal.test.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-journal.test.ts @@ -21,6 +21,7 @@ vi.mock("../../onboard/gateway-teardown-authority", async (importOriginal) => ({ import type { CheckpointGatewayAuthority } from "../../state/onboard-checkpoint-types"; import type { Session } from "../../state/onboard-session"; import * as onboardSession from "../../state/onboard-session"; +import { observeSandboxPresenceOnGateway } from "../../onboard/sandbox-recreate-probe"; import * as registry from "../../state/registry"; import type { RebuildRecreateOnboardOpts } from "./rebuild-gpu-opt-out"; import { @@ -198,6 +199,40 @@ describe("rebuild replacement observation", () => { }); }); + it("reports policy-preflight presence without requiring a lifecycle identity (#9833)", () => { + mocks.captureOpenshell.mockReturnValue({ + status: 0, + output: "Name: alpha\nPhase: Pending\n", + stdout: "Name: alpha\nPhase: Pending\n", + stderr: "", + }); + + expect(observeSandboxPresenceOnGateway(NON_DEFAULT_TARGET)).toBe("present"); + }); + + it("reports explicit policy-preflight absence on the recorded gateway (#9833)", () => { + mocks.captureOpenshell.mockReturnValue(absentProbe()); + + expect(observeSandboxPresenceOnGateway(NON_DEFAULT_TARGET)).toBe("missing"); + expect(mocks.captureOpenshell).toHaveBeenCalledWith( + ["sandbox", "get", "-g", "nemoclaw-9090", "alpha"], + expect.objectContaining({ ignoreError: true, includeStreams: true }), + ); + }); + + it("refuses ambiguous policy-preflight presence output (#9833)", () => { + mocks.captureOpenshell.mockReturnValue({ + status: 1, + output: "", + stdout: "", + stderr: "Error: connection refused", + }); + + expect(() => observeSandboxPresenceOnGateway(NON_DEFAULT_TARGET)).toThrow( + /reported neither presence nor explicit absence/, + ); + }); + it("hashes a live identity instead of recording it", () => { mocks.captureOpenshell.mockReturnValue(livePresentProbe()); diff --git a/src/lib/actions/sandbox/rebuild-recreate-observability.test.ts b/src/lib/actions/sandbox/rebuild-recreate-observability.test.ts index f4873859e9e..104319a8016 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-observability.test.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-observability.test.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { restoreEnv } from "../../../../test/helpers/env-test-helpers"; +import { PolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; import * as shields from "../../shields"; import { decisionSelected } from "../../state/onboard-checkpoint-decision"; import { deriveCheckpointFromSession } from "../../state/onboard-checkpoint-migrate"; @@ -162,6 +163,7 @@ function makeInput(overrides: Partial = {}): RebuildR mcpEntries: [], rebuildShieldsWindow: { relocked: false, wasLocked: false }, relockShieldsIfNeeded: vi.fn(() => true), + validatePolicyAuthority: vi.fn(async () => undefined), onCreated: vi.fn(), log: vi.fn(), bail: vi.fn((message: string): never => { @@ -511,6 +513,20 @@ describe("runRebuildRecreatePhase handoff", () => { expect(input.onCreated).not.toHaveBeenCalled(); expect(input.bail).toHaveBeenCalledWith("Recreate failed (stale-sandbox recovery).", 1); }); + + it("does not run recreate recovery after an inner policy authority refusal (#9833)", async () => { + const refusal = new PolicyAuthorityRefusalError("policy authority changed during recreate"); + vi.spyOn(rebuildOnboardDependencies, "onboard").mockRejectedValue(refusal); + const input = makeInput({ recoveryRecreate: true }); + + await expect(runRebuildRecreatePhase(input)).rejects.toBe(refusal); + + expect(input.validatePolicyAuthority).toHaveBeenCalledTimes(2); + expect(input.registryRollback.restoreForRetry).not.toHaveBeenCalled(); + expect(input.relockShieldsIfNeeded).not.toHaveBeenCalled(); + expect(input.onCreated).not.toHaveBeenCalled(); + expect(input.bail).not.toHaveBeenCalled(); + }); }); describe("rebuild recreate shields state", () => { diff --git a/src/lib/actions/sandbox/rebuild-recreate-phase.ts b/src/lib/actions/sandbox/rebuild-recreate-phase.ts index 146bf74f0c3..f29ed7f11c6 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-phase.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-phase.ts @@ -63,6 +63,7 @@ export interface RebuildRecreatePhaseInput { mcpEntries: McpRebuildPreparation["entries"]; rebuildShieldsWindow: RebuildShieldsWindow; relockShieldsIfNeeded: (sandboxStillExists: boolean) => boolean; + validatePolicyAuthority: () => Promise; onCreated: () => void; log: RebuildLog; bail: RebuildBail; @@ -98,6 +99,7 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): mcpEntries: rebuildMcpEntries, rebuildShieldsWindow, relockShieldsIfNeeded, + validatePolicyAuthority, onCreated, log, bail, @@ -156,6 +158,7 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): return bail("Authoritative rebuild journal authority changed before sandbox recreation."); } + await validatePolicyAuthority(); onboardSession.updateSession((s: Session) => { Object.assign( s, @@ -164,6 +167,7 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): hermesAuthMethod: rebuildDurableConfig.hermesAuthMethod, webSearchConfig: rebuildDurableConfig.webSearchConfig, toolDisclosure: rebuildDurableConfig.toolDisclosure, + policyAuthority: sb.policyAuthority ?? null, observabilityEnabled: recreateOptions.observabilityEnabled, observabilityRequestedExplicitly: recreateOptions.observabilityRequestedExplicitly, telegramConfig: sessionMatchesSandbox ? sessionBefore?.telegramConfig : null, @@ -207,6 +211,7 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): // bindings. Do not ask inner onboarding to resolve their stale preset names // as built-ins while the generated definitions are intentionally absent. s.policyPresets = recreatePolicyPresets; + s.policyAuthority = sb.policyAuthority ?? null; s.gpuPassthrough = rebuildGpuOverrides.sessionGpuPassthrough; s.metadata.fromDockerfile = storedFromDockerfile; s.provider = resumeConfig.provider; @@ -245,6 +250,7 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): // and durable retry state instead of terminating the outer transaction. let onboardFailed = false; let onboardExitCode = 1; + let onboardError: unknown; const savedExit = process.exit; process.exit = ((code) => { onboardFailed = true; @@ -296,6 +302,7 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): log("onboard() returned successfully"); } catch (error) { onboardFailed = true; + onboardError = error; const message = error instanceof Error ? error.message : String(error); const name = error instanceof Error ? error.name : ""; if (name !== "RebuildOnboardExit") { @@ -317,8 +324,14 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): } } - if (!onboardFailed) onCreated(); + if (!onboardFailed) { + await validatePolicyAuthority(); + onCreated(); + await validatePolicyAuthority(); + } if (onboardFailed) { + await validatePolicyAuthority(); + if (rebuildOnboardDependencies.isPolicyAuthorityRefusalError(onboardError)) throw onboardError; try { markLastStartedStepFailed(onboardSession, "Rebuild recreate failed"); } catch { @@ -372,12 +385,25 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): return false; } - if (recoveryRecreate) shields.clearShieldsState(sandboxName); + if ( + recoveryRecreate && + !( + rebuildShieldsWindow.policyAuthority === "externally-managed" && + rebuildShieldsWindow.wasLocked + ) + ) { + await validatePolicyAuthority(); + shields.clearShieldsState(sandboxName); + await validatePolicyAuthority(); + } const preservedRegistryFields = { ...(hasRebuildHermesToolGateways ? { hermesToolGateways: [...rebuildHermesToolGateways] } : {}), }; if (Object.keys(preservedRegistryFields).length > 0) { + await validatePolicyAuthority(); registry.updateSandbox(sandboxName, preservedRegistryFields); + await validatePolicyAuthority(); } + await validatePolicyAuthority(); return true; } diff --git a/src/lib/actions/sandbox/rebuild-recreate-reasoning.test.ts b/src/lib/actions/sandbox/rebuild-recreate-reasoning.test.ts index 55b1355942a..0a97f610f88 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-reasoning.test.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-reasoning.test.ts @@ -124,6 +124,7 @@ function makeInput(overrides: Partial = {}): RebuildR mcpEntries: [], rebuildShieldsWindow: { relocked: false, wasLocked: false }, relockShieldsIfNeeded: vi.fn(() => true), + validatePolicyAuthority: vi.fn(async () => undefined), onCreated: vi.fn(), log: vi.fn(), bail: vi.fn((message: string): never => { diff --git a/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts b/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts index 84b3e9a3369..3d711d08ee0 100644 --- a/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts +++ b/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts @@ -11,7 +11,7 @@ afterEach(() => { }); describe("rebuild restore target forwarding", () => { - it("forwards the recreated target identity and explicit custom-image capability", () => { + it("forwards the recreated target identity and explicit custom-image capability", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const restoreRecreatedSandboxState = vi .spyOn(snapshotRestore, "restoreRecreatedSandboxStateWithManagedAuthority") @@ -23,13 +23,15 @@ describe("rebuild restore target forwarding", () => { failedFiles: [], }); - runRebuildRestorePhase({ + await runRebuildRestorePhase({ sandboxName: "alpha", targetAgentType: "langchain-deepagents-code", targetImageIsCustom: true, backupManifest: { agentType: "openclaw", backupPath: "/tmp/rebuild-backup" } as never, policyPresets: [], customPolicies: [], + policyAuthority: "nemoclaw-managed", + validatePolicyAuthority: vi.fn(async () => undefined), reconcileManagedDcodeObservability: false, log: vi.fn(), }); diff --git a/src/lib/actions/sandbox/rebuild-restore-phase.test.ts b/src/lib/actions/sandbox/rebuild-restore-phase.test.ts index 6e38a5c9c0d..2e00fb7384a 100644 --- a/src/lib/actions/sandbox/rebuild-restore-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-restore-phase.test.ts @@ -21,14 +21,16 @@ const BUILTIN_OBSERVABILITY_CONTENT = type StandardRestoreOptions = Omit< Parameters[0], - "targetAgentType" | "targetImageIsCustom" + "policyAuthority" | "targetAgentType" | "targetImageIsCustom" | "validatePolicyAuthority" >; function runStandardRebuildRestorePhase(options: StandardRestoreOptions) { return runRebuildRestorePhase({ ...options, + policyAuthority: "nemoclaw-managed", targetAgentType: "openclaw", targetImageIsCustom: false, + validatePolicyAuthority: vi.fn(async () => undefined), }); } @@ -44,7 +46,7 @@ describe("rebuild policy restore fidelity", () => { vi.restoreAllMocks(); }); - it("migrates restored legacy Hermes dashboard state into its profile", () => { + it("migrates restored legacy Hermes dashboard state into its profile", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(snapshotRestore, "restoreRecreatedSandboxStateWithManagedAuthority").mockReturnValue({ success: true, @@ -67,13 +69,15 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValue("converged"); const log = vi.fn(); - const result = runRebuildRestorePhase({ + const result = await runRebuildRestorePhase({ sandboxName: "hermes", targetAgentType: "hermes", targetImageIsCustom: false, backupManifest: { agentType: "hermes", backupPath: "/tmp/rebuild-backup" } as never, policyPresets: [], customPolicies: [], + policyAuthority: "nemoclaw-managed", + validatePolicyAuthority: vi.fn(async () => undefined), reconcileManagedDcodeObservability: false, log, }); @@ -83,7 +87,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.restoreSucceeded).toBe(true); }); - it("reports a failed Hermes dashboard migration as an incomplete restore", () => { + it("reports a failed Hermes dashboard migration as an incomplete restore", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(snapshotRestore, "restoreRecreatedSandboxStateWithManagedAuthority").mockReturnValue({ @@ -103,13 +107,15 @@ describe("rebuild policy restore fidelity", () => { }); vi.spyOn(sandboxConfig, "restoreHermesDashboardConfig").mockReturnValue("failed"); - const result = runRebuildRestorePhase({ + const result = await runRebuildRestorePhase({ sandboxName: "hermes", targetAgentType: "hermes", targetImageIsCustom: false, backupManifest: { agentType: "hermes", backupPath: "/tmp/rebuild-backup" } as never, policyPresets: [], customPolicies: [], + policyAuthority: "nemoclaw-managed", + validatePolicyAuthority: vi.fn(async () => undefined), reconcileManagedDcodeObservability: false, log: vi.fn(), }); @@ -120,7 +126,7 @@ describe("rebuild policy restore fidelity", () => { ); }); - it("reports an unresolved Hermes target as an incomplete restore", () => { + it("reports an unresolved Hermes target as an incomplete restore", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(snapshotRestore, "restoreRecreatedSandboxStateWithManagedAuthority").mockReturnValue({ @@ -140,13 +146,15 @@ describe("rebuild policy restore fidelity", () => { }); const seedDashboard = vi.spyOn(sandboxConfig, "restoreHermesDashboardConfig"); - const result = runRebuildRestorePhase({ + const result = await runRebuildRestorePhase({ sandboxName: "hermes", targetAgentType: "hermes", targetImageIsCustom: false, backupManifest: { agentType: "hermes", backupPath: "/tmp/rebuild-backup" } as never, policyPresets: [], customPolicies: [], + policyAuthority: "nemoclaw-managed", + validatePolicyAuthority: vi.fn(async () => undefined), reconcileManagedDcodeObservability: false, log: vi.fn(), }); @@ -158,7 +166,7 @@ describe("rebuild policy restore fidelity", () => { ); }); - it("surfaces a fresh OpenClaw plugin registry precondition failure", () => { + it("surfaces a fresh OpenClaw plugin registry precondition failure", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined); const log = vi.fn(); @@ -171,7 +179,7 @@ describe("rebuild policy restore fidelity", () => { error: "could not read fresh OpenClaw plugin install registry", }); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: { agentType: "openclaw", backupPath: "/tmp/rebuild-backup" } as never, policyPresets: [], @@ -189,7 +197,7 @@ describe("rebuild policy restore fidelity", () => { ); }); - it("replays custom web-policy names from exact content instead of same-name built-ins", () => { + it("replays custom web-policy names from exact content instead of same-name built-ins", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); const parsePresetPolicyKeys = vi.spyOn(policies, "parsePresetPolicyKeys"); @@ -209,7 +217,7 @@ describe("rebuild policy restore fidelity", () => { content: `network_policies:\n ${name}-custom:\n name: ${name}-custom\n`, sourcePath: `/tmp/${name}.yaml`, })); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: { agentType: "openclaw", @@ -245,7 +253,7 @@ describe("rebuild policy restore fidelity", () => { expect(parsePresetPolicyKeys).not.toHaveBeenCalled(); }); - it("replays captured registry custom policies during stale recovery without a backup", () => { + it("replays captured registry custom policies during stale recovery without a backup", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(sandboxState, "restoreSandboxState").mockReturnValue({ success: true, @@ -268,7 +276,7 @@ describe("rebuild policy restore fidelity", () => { }, }, ]; - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -294,7 +302,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.finalPresets).toEqual(["custom-egress"]); }); - it("leaves generated MCP policy replay exclusively to MCP restoration", () => { + it("leaves generated MCP policy replay exclusively to MCP restoration", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const applyPresetContent = vi.spyOn(policies, "applyPresetContent").mockReturnValue(true); const genuineCustomPolicy = { @@ -308,7 +316,7 @@ describe("rebuild policy restore fidelity", () => { "network_policies:\n mcp-bridge-search:\n endpoints:\n - host: mcp.example.com\n allowed_ips: [203.0.113.10]\n", sourcePath: MCP_BRIDGE_POLICY_SOURCE, }; - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -328,7 +336,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.failedPresets).toEqual([]); }); - it("removes an observability preset introduced while rebuilding a restricted sandbox", () => { + it("removes an observability preset introduced while rebuilding a restricted sandbox", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset").mockReturnValue(true); @@ -337,7 +345,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce("absent"); const removePreset = vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["npm"], @@ -354,7 +362,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("retains an observed exact built-in when post-removal verification is unavailable", () => { + it("retains an observed exact built-in when post-removal verification is unavailable", async () => { vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset").mockReturnValue(true); vi.spyOn(policies, "getPresetContentGatewayState") @@ -362,7 +370,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce(null); vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["npm"], @@ -375,7 +383,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(false); }); - it("accounts for known failed additions without treating a narrower live set as unverified", () => { + it("accounts for known failed additions without treating a narrower live set as unverified", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset") @@ -392,7 +400,7 @@ describe("rebuild policy restore fidelity", () => { throw new Error("apply failed"); }); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["npm", "bad", "throw"], @@ -408,12 +416,12 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("keeps reconciliation unverified when a reported successful addition is missing live", () => { + it("keeps reconciliation unverified when a reported successful addition is missing live", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["observability-otlp-local"], @@ -428,13 +436,13 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(false); }); - it("retains target built-in attribution when exact post-apply verification is unavailable", () => { + it("retains target built-in attribution when exact post-apply verification is unavailable", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset").mockReturnValue(true); vi.spyOn(policies, "getPresetContentGatewayState").mockReturnValue(null); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["observability-otlp-local"], @@ -447,10 +455,10 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(false); }); - it("does not remove or persist DCode base-policy keys detected as broad presets", () => { + it("does not remove or persist DCode base-policy keys detected as broad presets", async () => { const removePreset = vi.spyOn(policies, "removePreset"); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -465,7 +473,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("leaves a same-name custom observability policy outside built-in narrowing", () => { + it("leaves a same-name custom observability policy outside built-in narrowing", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const applyPresetContent = vi.spyOn(policies, "applyPresetContent").mockReturnValue(true); const removePreset = vi.spyOn(policies, "removePreset"); @@ -475,7 +483,7 @@ describe("rebuild policy restore fidelity", () => { sourcePath: "/tmp/operator-collector.yaml", }; - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -495,7 +503,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("leaves a differently named custom policy owning observability egress outside built-in narrowing", () => { + it("leaves a differently named custom policy owning observability egress outside built-in narrowing", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const applyPresetContent = vi.spyOn(policies, "applyPresetContent").mockReturnValue(true); const exactState = vi.spyOn(policies, "getPresetContentGatewayState").mockReturnValue("match"); @@ -507,7 +515,7 @@ describe("rebuild policy restore fidelity", () => { sourcePath: "/tmp/corp-otel.yaml", }; - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -528,7 +536,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("removes an exact inner built-in behind a same-name custom with a different key", () => { + it("removes an exact inner built-in behind a same-name custom with a different key", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const customPolicy = { name: "observability-otlp-local", @@ -541,7 +549,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce("absent"); const removePreset = vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["observability-otlp-local"], @@ -557,7 +565,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("removes an exact inner built-in when overlapping custom replay fails", () => { + it("removes an exact inner built-in when overlapping custom replay fails", async () => { vi.spyOn(console, "error").mockImplementation(() => undefined); const customPolicy = { name: "corp-otel", @@ -570,7 +578,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce("absent"); const removePreset = vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -587,7 +595,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("leaves drift untouched and unverified when successful custom ownership is not exact", () => { + it("leaves drift untouched and unverified when successful custom ownership is not exact", async () => { vi.spyOn(console, "error").mockImplementation(() => undefined); const customPolicy = { name: "corp-otel", @@ -598,7 +606,7 @@ describe("rebuild policy restore fidelity", () => { vi.spyOn(policies, "getPresetContentGatewayState").mockReturnValue("drift"); const removePreset = vi.spyOn(policies, "removePreset"); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -612,7 +620,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(false); }); - it("retains separate built-in attribution when same-name custom removal is unverified", () => { + it("retains separate built-in attribution when same-name custom removal is unverified", async () => { vi.spyOn(console, "error").mockImplementation(() => undefined); const customPolicy = { name: "observability-otlp-local", @@ -625,7 +633,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce(null); vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["observability-otlp-local"], @@ -661,6 +669,37 @@ describe("rebuild policy restore fidelity", () => { ).toBeUndefined(); }); + it("does not replay or remove policy under external rebuild authority (#9833)", async () => { + const applyPreset = vi.spyOn(policies, "applyPreset"); + const applyPresetContent = vi.spyOn(policies, "applyPresetContent"); + const removePreset = vi.spyOn(policies, "removePreset"); + + const result = await runRebuildRestorePhase({ + sandboxName: "alpha", + targetAgentType: "openclaw", + targetImageIsCustom: false, + backupManifest: null, + policyPresets: ["npm", "observability-otlp-local"], + customPolicies: [ + { + name: "custom-api", + content: "network_policies:\n custom-api: {}\n", + sourcePath: "/tmp/custom-api.yaml", + }, + ], + policyAuthority: "externally-managed", + validatePolicyAuthority: vi.fn(async () => undefined), + reconcileManagedDcodeObservability: true, + log: vi.fn(), + }); + + expect(applyPreset).not.toHaveBeenCalled(); + expect(applyPresetContent).not.toHaveBeenCalled(); + expect(removePreset).not.toHaveBeenCalled(); + expect(result.finalBuiltinPresets).toEqual([]); + expect(result.finalPresets).toEqual([]); + }); + it("retains the force-skipped backup warning in the successful final summary", () => { const writeLine = vi.fn(); diff --git a/src/lib/actions/sandbox/rebuild-restore-phase.ts b/src/lib/actions/sandbox/rebuild-restore-phase.ts index 049c5f94f3d..48ea16226c5 100644 --- a/src/lib/actions/sandbox/rebuild-restore-phase.ts +++ b/src/lib/actions/sandbox/rebuild-restore-phase.ts @@ -3,6 +3,10 @@ import { CLI_NAME } from "../../cli/branding"; import { G, R, YW } from "../../cli/terminal-style"; +import { + isPolicyAuthorityRefusalError, + type SandboxPolicyAuthority, +} from "../../adapters/openshell/policy-authority"; import { OBSERVABILITY_OTLP_LOCAL_POLICY_PRESET, OBSERVABILITY_POLICY_BINDING, @@ -25,6 +29,8 @@ export interface RebuildRestorePhaseInput { backupManifest: RebuildBackupManifest; policyPresets: string[]; customPolicies: NonNullable; + policyAuthority: SandboxPolicyAuthority; + validatePolicyAuthority: () => Promise; reconcileManagedDcodeObservability: boolean; log: RebuildLog; } @@ -64,24 +70,44 @@ function finalRestoredPresetState( }; } -function reconcileFinalManagedObservability( +async function runPolicyAuthorityBoundOperation( + validatePolicyAuthority: () => Promise, + operation: () => T, +): Promise { + await validatePolicyAuthority(); + try { + return operation(); + } finally { + await validatePolicyAuthority(); + } +} + +async function reconcileFinalManagedObservability( sandboxName: string, targetManagedObservability: boolean, restoredBuiltinPresets: readonly string[], restoredCustomPresets: readonly string[], failedBuiltinPresets: readonly string[], successfulCustomObservabilityContents: readonly string[], + validatePolicyAuthority: () => Promise, log: RebuildLog, -): Pick< - RebuildRestorePhaseResult, - | "finalPresets" - | "finalBuiltinPresets" - | "failedPresetRemovals" - | "policyPresetReconciliationVerified" +): Promise< + Pick< + RebuildRestorePhaseResult, + | "finalPresets" + | "finalBuiltinPresets" + | "failedPresetRemovals" + | "policyPresetReconciliationVerified" + > > { - const customObservabilityStates = successfulCustomObservabilityContents.map((content) => - OBSERVABILITY_POLICY_BINDING.inspectContent(sandboxName, content, policies), - ); + const customObservabilityStates: Array<"match" | "absent" | "drift" | null> = []; + for (const content of successfulCustomObservabilityContents) { + customObservabilityStates.push( + await runPolicyAuthorityBoundOperation(validatePolicyAuthority, () => + OBSERVABILITY_POLICY_BINDING.inspectContent(sandboxName, content, policies), + ), + ); + } const customObservabilityExpected = successfulCustomObservabilityContents.length > 0; const customObservabilityVerified = customObservabilityStates.includes("match"); if (!targetManagedObservability && customObservabilityVerified) { @@ -92,7 +118,9 @@ function reconcileFinalManagedObservability( }; } - const loadedBinding = OBSERVABILITY_POLICY_BINDING.load(sandboxName, policies); + const loadedBinding = await runPolicyAuthorityBoundOperation(validatePolicyAuthority, () => + OBSERVABILITY_POLICY_BINDING.load(sandboxName, policies), + ); const builtinContent = loadedBinding.content; if (!builtinContent) { log("Could not load managed observability preset content after rebuild restore"); @@ -115,14 +143,11 @@ function reconcileFinalManagedObservability( let liveAfter = liveBefore; if (!targetManagedObservability && liveBefore === "match") { log(`Removing unexpected live preset: ${OBSERVABILITY_OTLP_LOCAL_POLICY_PRESET}`); - const removal = OBSERVABILITY_POLICY_BINDING.removeExact( - sandboxName, - builtinContent, - policies, - { + const removal = await runPolicyAuthorityBoundOperation(validatePolicyAuthority, () => + OBSERVABILITY_POLICY_BINDING.removeExact(sandboxName, builtinContent, policies, { knownBefore: liveBefore, removeOptions: { nonFatal: true }, - }, + }), ); if (removal.reportedSuccess !== true) { failedPresetRemovals.push(OBSERVABILITY_OTLP_LOCAL_POLICY_PRESET); @@ -179,7 +204,9 @@ function reconcileFinalManagedObservability( * Boundary coverage: rebuild-flow.test.ts exercises full/partial state restore, * stale recovery, successful presets, and incomplete preset recovery reporting. */ -export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): RebuildRestorePhaseResult { +export async function runRebuildRestorePhase( + input: RebuildRestorePhaseInput, +): Promise { const { sandboxName, targetAgentType, @@ -187,9 +214,12 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild backupManifest, policyPresets, customPolicies, + policyAuthority, + validatePolicyAuthority, reconcileManagedDcodeObservability, log, } = input; + await validatePolicyAuthority(); let restoreSucceeded = true; if (backupManifest) { console.log(""); @@ -206,6 +236,7 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild getSandbox: (name) => loadRegistry().sandboxes[name] ?? null, }, ); + await validatePolicyAuthority(); log( `Restore result: success=${restore.success}, restored=${restore.restoredDirs.join(",")}; files=${restore.restoredFiles.join(",")}, failed=${restore.failedDirs.join(",")}; failedFiles=${restore.failedFiles.join(",")}${restore.error ? `; error=${restore.error}` : ""}`, ); @@ -221,6 +252,7 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild dashboardTarget.agentName === "hermes" ? sandboxConfig.restoreHermesDashboardConfig(sandboxName, dashboardTarget) : "failed"; + await validatePolicyAuthority(); log(`Hermes dashboard state after restore: ${dashboardSeed}`); if (dashboardSeed === "failed") { restoreSucceeded = false; @@ -246,6 +278,20 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild } } + await validatePolicyAuthority(); + + if (policyAuthority === "externally-managed") { + return { + restoreSucceeded, + restoredPresets: [], + failedPresets: [], + finalPresets: [], + finalBuiltinPresets: [], + failedPresetRemovals: [], + policyPresetReconciliationVerified: true, + }; + } + const restoredBuiltinPresets: string[] = []; const restoredCustomPresets: string[] = []; const failedPresets: string[] = []; @@ -264,7 +310,9 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild for (const presetName of builtinPolicyPresets) { try { log(`Applying preset: ${presetName}`); - const applied = policies.applyPreset(sandboxName, presetName); + const applied = await runPolicyAuthorityBoundOperation(validatePolicyAuthority, () => + policies.applyPreset(sandboxName, presetName), + ); if (applied) { restoredBuiltinPresets.push(presetName); } else { @@ -272,6 +320,8 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild failedPresets.push(presetName); } } catch (error) { + if (isPolicyAuthorityRefusalError(error)) throw error; + await validatePolicyAuthority(); const message = error instanceof Error ? error.message : String(error); log(`Failed to apply preset '${presetName}': ${message}`); failedBuiltinPresets.push(presetName); @@ -284,12 +334,14 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild const trustedPrivatePinCapability = entry.trustedPrivatePins ? replayTrustedPrivatePolicyPinCapability(entry.content, entry.trustedPrivatePins) : undefined; - const applied = policies.applyPresetContent(sandboxName, entry.name, entry.content, { - custom: { - sourcePath: entry.sourcePath, - ...(trustedPrivatePinCapability ? { trustedPrivatePinCapability } : {}), - }, - }); + const applied = await runPolicyAuthorityBoundOperation(validatePolicyAuthority, () => + policies.applyPresetContent(sandboxName, entry.name, entry.content, { + custom: { + sourcePath: entry.sourcePath, + ...(trustedPrivatePinCapability ? { trustedPrivatePinCapability } : {}), + }, + }), + ); if (applied) { restoredCustomPresets.push(entry.name); if ( @@ -302,6 +354,8 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild failedPresets.push(entry.name); } } catch (error) { + if (isPolicyAuthorityRefusalError(error)) throw error; + await validatePolicyAuthority(); const message = error instanceof Error ? error.message : String(error); log(`Failed to apply custom preset '${entry.name}': ${message}`); failedPresets.push(entry.name); @@ -322,13 +376,14 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild const restoredPresets = uniquePresetNames([...restoredBuiltinPresets, ...restoredCustomPresets]); const finalPolicyState = reconcileManagedDcodeObservability - ? reconcileFinalManagedObservability( + ? await reconcileFinalManagedObservability( sandboxName, targetManagedObservability, restoredBuiltinPresets, restoredCustomPresets, failedBuiltinPresets, successfulCustomObservabilityContents, + validatePolicyAuthority, log, ) : { @@ -337,5 +392,6 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild failedPresetRemovals: [], policyPresetReconciliationVerified: true, }; + await validatePolicyAuthority(); return { restoreSucceeded, restoredPresets, failedPresets, ...finalPolicyState }; } diff --git a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts index fd41d7a4778..ff7c628c683 100644 --- a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts +++ b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; import * as gatewayDrift from "../../adapters/openshell/gateway-drift"; +import * as policyAuthority from "../../adapters/openshell/policy-authority"; import * as resolve from "../../adapters/openshell/resolve"; import * as openshellRuntime from "../../adapters/openshell/runtime"; import * as agentDefs from "../../agent/defs"; @@ -26,6 +27,10 @@ import { rebuildOnboardDependencies } from "./rebuild-onboard-dependencies"; import * as rebuildRoutePreflight from "./rebuild-preflight-guards"; import * as rebuildShields from "./rebuild-shields"; import * as rebuildUsageNotice from "./rebuild-usage-notice"; +import { + managedSandboxEntry, + SANDBOX_IDENTITY, +} from "../../../../test/helpers/managed-policy-receipt-fixture"; function cloneSession(session: Session): Session { return JSON.parse(JSON.stringify(session)); @@ -146,6 +151,10 @@ describe("rebuild resume snapshot repair", () => { vi.spyOn(onboardSession, "releaseOnboardLock").mockImplementation(() => undefined), vi.spyOn(onboardSession, "markStepFailed").mockImplementation(() => loadSession()), vi.spyOn(registry, "getSandbox").mockReturnValue({ + ...managedSandboxEntry("alpha", "openclaw", { + policyHash: "managed-policy", + policyVersion: 1, + }), name: "alpha", provider: "ollama-local", model: "nvidia/nemotron", @@ -158,6 +167,20 @@ describe("rebuild resume snapshot repair", () => { gatewayPort: 8080, } as never), vi.spyOn(registry, "updateSandbox").mockReturnValue(true), + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "owner-unknown", + effectivePolicy: {}, + policyIdentity: { hash: "managed-policy", activeVersion: 1 }, + }), + vi + .spyOn(policyAuthority, "inspectOpenShellSandboxIdentityFingerprint") + .mockReturnValue(SANDBOX_IDENTITY), + vi + .spyOn(policyAuthority, "assertOpenShellGatewayPortBinding") + .mockImplementation(() => undefined), + vi.spyOn(policyAuthority, "inspectActiveGlobalPolicy").mockReturnValue({ + state: "absent", + }), vi.spyOn(registry, "listSandboxes").mockReturnValue({ sandboxes: [] } as never), vi.spyOn(rebuildRoutePreflight, "commitRebuildRoutePreflight").mockReturnValue({ ok: true, diff --git a/src/lib/actions/sandbox/rebuild-shields-finally.test.ts b/src/lib/actions/sandbox/rebuild-shields-finally.test.ts index 732b22ee444..fea57162243 100644 --- a/src/lib/actions/sandbox/rebuild-shields-finally.test.ts +++ b/src/lib/actions/sandbox/rebuild-shields-finally.test.ts @@ -4,10 +4,15 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const phaseMocks = vi.hoisted(() => ({ + createRegistryRollback: vi.fn(), + recordRegistryRemoval: vi.fn(), + restoreRegistryForRetry: vi.fn(), runBackup: vi.fn(), runDestroy: vi.fn(), runPreflight: vi.fn(), + runRecreate: vi.fn(), runShields: vi.fn(), + revalidateAuthority: vi.fn(), openRecreateJournal: vi.fn(), })); @@ -22,6 +27,15 @@ const gatewayAuthority = { requiredCapabilities: [], } as const; +const policyAuthorityReceipt = { + authority: "nemoclaw-managed", + gatewayName: "nemoclaw", + managedMcpPolicies: [], + operation: "rebuild sandbox 'alpha'", + requiredPolicies: [], + sandboxName: "alpha", +} as const; + vi.mock("./rebuild-recreate-journal", () => ({ fingerprintRebuildRecreateTargetIntent: () => "intent-1", openRebuildRecreateJournal: phaseMocks.openRecreateJournal, @@ -32,6 +46,7 @@ vi.mock("./rebuild-backup-phase", () => ({ })); vi.mock("./rebuild-preflight-phase", () => ({ + revalidateRebuildPolicyAuthority: phaseMocks.revalidateAuthority, runHermesCronRestoreBackupPreflight: () => ({ plan: null }), runRebuildPreflightPhase: phaseMocks.runPreflight, })); @@ -40,6 +55,14 @@ vi.mock("./rebuild-destroy-phase", () => ({ runRebuildDestroyPhase: phaseMocks.runDestroy, })); +vi.mock("./rebuild-recreate-phase", () => ({ + runRebuildRecreatePhase: phaseMocks.runRecreate, +})); + +vi.mock("./rebuild-registry-rollback", () => ({ + createRebuildRegistryRollback: phaseMocks.createRegistryRollback, +})); + vi.mock("./rebuild-shields-phase", () => ({ runRebuildShieldsPhase: phaseMocks.runShields, })); @@ -48,8 +71,10 @@ import { rebuildSandbox } from "./rebuild"; describe("rebuild shields relock guard", () => { const rebuildWindow = { relocked: false, wasLocked: true }; + const applyDcodePatch = vi.fn(); const cleanupDcodePreflight = vi.fn(); const releaseOnboardLock = vi.fn(); + const restoreDcodePatch = vi.fn(); const revalidateDcodeBeforeDelete = vi.fn(async () => true); const relockShields = vi.fn(() => { rebuildWindow.relocked = true; @@ -59,6 +84,13 @@ describe("rebuild shields relock guard", () => { beforeEach(() => { vi.clearAllMocks(); rebuildWindow.relocked = false; + applyDcodePatch.mockReturnValue(restoreDcodePatch); + phaseMocks.createRegistryRollback.mockReturnValue({ + recordRemoval: phaseMocks.recordRegistryRemoval, + restoreForRetry: phaseMocks.restoreRegistryForRetry, + }); + phaseMocks.revalidateAuthority.mockResolvedValue(undefined); + phaseMocks.runRecreate.mockResolvedValue(true); phaseMocks.runPreflight.mockResolvedValue({ sandboxEntry: { name: "alpha", customPolicies: [] }, targetConfig: { durableConfig: { webSearchConfig: null } }, @@ -71,10 +103,13 @@ describe("rebuild shields relock guard", () => { liveState: { staleRecovery: false, staleRegistrySnapshot: null }, recoveryManifest: null, dcodePreflight: { + applyDockerGpuPatchNetwork: applyDcodePatch, + checkAtDeleteEdge: vi.fn(async () => ({ ok: true })), cleanup: cleanupDcodePreflight, revalidateBeforeDelete: revalidateDcodeBeforeDelete, }, preparedImage: null, + policyAuthorityReceipt, releaseOnboardLock, log: vi.fn(), bail: vi.fn(), @@ -154,6 +189,7 @@ describe("rebuild shields relock guard", () => { recoveryManifest: null, dcodePreflight: { cleanup: cleanupDcodePreflight }, preparedImage: null, + policyAuthorityReceipt, releaseOnboardLock, log: vi.fn(), bail, diff --git a/src/lib/actions/sandbox/rebuild-shields-phase.test.ts b/src/lib/actions/sandbox/rebuild-shields-phase.test.ts index 2b362610ae3..19f504e3246 100644 --- a/src/lib/actions/sandbox/rebuild-shields-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-shields-phase.test.ts @@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { RebuildBail } from "./rebuild-credential-preflight"; const phaseMocks = vi.hoisted(() => ({ + markSourceDeleted: vi.fn(), openWindow: vi.fn(), relockWindow: vi.fn(), })); @@ -14,6 +15,7 @@ vi.mock("./rebuild-flow-helpers", () => ({ })); vi.mock("./rebuild-shields", () => ({ + markRebuildShieldsSourceDeleted: phaseMocks.markSourceDeleted, relockRebuildShieldsWindow: phaseMocks.relockWindow, })); @@ -39,12 +41,15 @@ describe("rebuild Shields phase", () => { const phase = runRebuildShieldsPhase( "alpha", false, + "nemoclaw-managed", releaseOnboardLock, bail as unknown as RebuildBail, ); - expect(phaseMocks.openWindow).toHaveBeenCalledWith("alpha", false); + expect(phaseMocks.openWindow).toHaveBeenCalledWith("alpha", false, "nemoclaw-managed"); expect(phase).toMatchObject({ window, staleSandboxWasLocked: false }); + phase?.markSourceDeleted(); + expect(phaseMocks.markSourceDeleted).toHaveBeenCalledWith(window); expect(phase?.relock(true)).toBe(true); expect(phaseMocks.relockWindow).toHaveBeenCalledWith("alpha", window, true, "nemoclaw"); expect(releaseOnboardLock).not.toHaveBeenCalled(); @@ -60,7 +65,13 @@ describe("rebuild Shields phase", () => { const bail = vi.fn(); expect( - runRebuildShieldsPhase("alpha", false, releaseOnboardLock, bail as unknown as RebuildBail), + runRebuildShieldsPhase( + "alpha", + false, + "nemoclaw-managed", + releaseOnboardLock, + bail as unknown as RebuildBail, + ), ).toBeNull(); expect(releaseOnboardLock).toHaveBeenCalledOnce(); @@ -75,7 +86,13 @@ describe("rebuild Shields phase", () => { const releaseOnboardLock = vi.fn(); expect(() => - runRebuildShieldsPhase("alpha", false, releaseOnboardLock, vi.fn() as unknown as RebuildBail), + runRebuildShieldsPhase( + "alpha", + false, + "nemoclaw-managed", + releaseOnboardLock, + vi.fn() as unknown as RebuildBail, + ), ).toThrow("Shields state is unreadable"); expect(releaseOnboardLock).toHaveBeenCalledOnce(); diff --git a/src/lib/actions/sandbox/rebuild-shields-phase.ts b/src/lib/actions/sandbox/rebuild-shields-phase.ts index c96c54c07c0..6d717a7baf1 100644 --- a/src/lib/actions/sandbox/rebuild-shields-phase.ts +++ b/src/lib/actions/sandbox/rebuild-shields-phase.ts @@ -2,13 +2,19 @@ // SPDX-License-Identifier: Apache-2.0 import { CLI_NAME } from "../../cli/branding"; +import type { SandboxPolicyAuthority } from "../../adapters/openshell/policy-authority"; import type { RebuildBail } from "./rebuild-credential-preflight"; import { openRebuildShieldsWindowForState } from "./rebuild-flow-helpers"; -import { type RebuildShieldsWindow, relockRebuildShieldsWindow } from "./rebuild-shields"; +import { + markRebuildShieldsSourceDeleted, + type RebuildShieldsWindow, + relockRebuildShieldsWindow, +} from "./rebuild-shields"; export interface RebuildShieldsPhaseResult { window: RebuildShieldsWindow; staleSandboxWasLocked: boolean; + markSourceDeleted: () => void; relock: (sandboxStillExists: boolean) => boolean; } @@ -19,6 +25,7 @@ export interface RebuildShieldsPhaseResult { export function runRebuildShieldsPhase( sandboxName: string, recoveryRecreate: boolean, + policyAuthority: SandboxPolicyAuthority, releaseOnboardLock: () => void, bail: RebuildBail, ): RebuildShieldsPhaseResult | null { @@ -28,6 +35,7 @@ export function runRebuildShieldsPhase( ({ rebuildShieldsWindow: window, staleSandboxWasLocked } = openRebuildShieldsWindowForState( sandboxName, recoveryRecreate, + policyAuthority, )); } catch (error) { process.removeListener("exit", releaseOnboardLock); @@ -43,6 +51,7 @@ export function runRebuildShieldsPhase( return { window, staleSandboxWasLocked, + markSourceDeleted: () => markRebuildShieldsSourceDeleted(window), relock: (sandboxStillExists: boolean) => relockRebuildShieldsWindow(sandboxName, window, sandboxStillExists, CLI_NAME), }; diff --git a/src/lib/actions/sandbox/rebuild-shields.test.ts b/src/lib/actions/sandbox/rebuild-shields.test.ts new file mode 100644 index 00000000000..043f083c056 --- /dev/null +++ b/src/lib/actions/sandbox/rebuild-shields.test.ts @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + isShieldsDown: vi.fn(), + openBackupShieldsWindow: vi.fn(), + rebindReplacementConfigLock: vi.fn(), + relockBackupShieldsWindow: vi.fn(), +})); + +vi.mock("../../shields", () => ({ + isShieldsDown: mocks.isShieldsDown, + rebindReplacementConfigLock: mocks.rebindReplacementConfigLock, +})); + +vi.mock("./backup-shields-window", () => ({ + openBackupShieldsWindow: mocks.openBackupShieldsWindow, + relockBackupShieldsWindow: mocks.relockBackupShieldsWindow, +})); + +import { + markRebuildShieldsSourceDeleted, + openRebuildShieldsWindow, + relockRebuildShieldsWindow, +} from "./rebuild-shields"; + +describe("external-policy rebuild Shields window", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.isShieldsDown.mockReturnValue(false); + }); + + it("keeps policy untouched and rebinds only the replacement config lock (#9833)", () => { + const window = openRebuildShieldsWindow("alpha", "nemoclaw", "externally-managed"); + + expect(window).toEqual({ + policyAuthority: "externally-managed", + relocked: false, + sourceDeleted: false, + wasLocked: true, + }); + expect(mocks.openBackupShieldsWindow).not.toHaveBeenCalled(); + + markRebuildShieldsSourceDeleted(window!); + expect(relockRebuildShieldsWindow("alpha", window!, true, "nemoclaw")).toBe(true); + + expect(mocks.rebindReplacementConfigLock).toHaveBeenCalledWith("alpha", true); + expect(mocks.relockBackupShieldsWindow).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/rebuild-shields.ts b/src/lib/actions/sandbox/rebuild-shields.ts index e789938102d..53a4913cda6 100644 --- a/src/lib/actions/sandbox/rebuild-shields.ts +++ b/src/lib/actions/sandbox/rebuild-shields.ts @@ -6,8 +6,13 @@ import { openBackupShieldsWindow, relockBackupShieldsWindow, } from "./backup-shields-window"; +import type { SandboxPolicyAuthority } from "../../adapters/openshell/policy-authority"; +import * as shields from "../../shields"; -export type RebuildShieldsWindow = BackupShieldsWindow; +export type RebuildShieldsWindow = BackupShieldsWindow & { + policyAuthority?: SandboxPolicyAuthority; + sourceDeleted?: boolean; +}; function rebuildShieldsWindowOptions(sandboxName: string, cliName: string) { return { @@ -30,8 +35,42 @@ function rebuildShieldsWindowOptions(sandboxName: string, cliName: string) { export function openRebuildShieldsWindow( sandboxName: string, cliName: string, + policyAuthority: SandboxPolicyAuthority = "nemoclaw-managed", ): RebuildShieldsWindow | null { - return openBackupShieldsWindow(sandboxName, rebuildShieldsWindowOptions(sandboxName, cliName)); + if (policyAuthority === "externally-managed") { + return { + policyAuthority, + relocked: false, + sourceDeleted: false, + wasLocked: !shields.isShieldsDown(sandboxName), + }; + } + const window = openBackupShieldsWindow( + sandboxName, + rebuildShieldsWindowOptions(sandboxName, cliName), + ); + return window ? { ...window, policyAuthority, sourceDeleted: false } : null; +} + +export function openAbsentRebuildShieldsWindow( + sandboxName: string, + policyAuthority: SandboxPolicyAuthority, +): { staleSandboxWasLocked: boolean; window: RebuildShieldsWindow } { + const wasLocked = !shields.isShieldsDown(sandboxName); + if (policyAuthority === "externally-managed") { + return { + staleSandboxWasLocked: false, + window: { policyAuthority, relocked: false, sourceDeleted: true, wasLocked }, + }; + } + return { + staleSandboxWasLocked: wasLocked, + window: { policyAuthority, relocked: false, sourceDeleted: true, wasLocked: false }, + }; +} + +export function markRebuildShieldsSourceDeleted(window: RebuildShieldsWindow): void { + window.sourceDeleted = true; } export function printRebuildShieldsRecovery( @@ -40,6 +79,10 @@ export function printRebuildShieldsRecovery( cliName: string, ): void { if (!window.wasLocked) return; + if (window.policyAuthority === "externally-managed") { + console.error(" 4. Retry the rebuild to rebind the retained config lockdown."); + return; + } console.error(` 4. Restore shields lockdown:`); console.error(` ${cliName} ${sandboxName} shields up`); } @@ -50,6 +93,29 @@ export function relockRebuildShieldsWindow( sandboxStillExists: boolean, cliName: string, ): boolean { + if (window.policyAuthority === "externally-managed") { + if (window.relocked) return true; + if (!window.wasLocked || window.sourceDeleted !== true) { + window.relocked = true; + return true; + } + if (!sandboxStillExists) { + console.error( + ` Cannot rebind the retained config lockdown because sandbox '${sandboxName}' is absent.`, + ); + return false; + } + try { + shields.rebindReplacementConfigLock(sandboxName, true); + window.relocked = true; + return true; + } catch (error) { + console.error( + ` Failed to rebind the retained config lockdown: ${error instanceof Error ? error.message : String(error)}`, + ); + return false; + } + } return relockBackupShieldsWindow( sandboxName, window, diff --git a/src/lib/agent/definition-types.ts b/src/lib/agent/definition-types.ts index 663dc314835..eca8f361e4a 100644 --- a/src/lib/agent/definition-types.ts +++ b/src/lib/agent/definition-types.ts @@ -116,6 +116,10 @@ export interface AgentInference { export type AgentMcpSupport = "bridge" | "disabled"; export type AgentMcpAdapter = "mcporter" | "hermes-config" | "deepagents-config"; +export function isAgentMcpAdapter(value: unknown): value is AgentMcpAdapter { + return value === "mcporter" || value === "hermes-config" || value === "deepagents-config"; +} + export interface AgentMcpCapability { support: AgentMcpSupport; adapter?: AgentMcpAdapter; diff --git a/src/lib/onboard/credential-provider-registration.test.ts b/src/lib/onboard/credential-provider-registration.test.ts index 2316b8e5fca..e0b78938c67 100644 --- a/src/lib/onboard/credential-provider-registration.test.ts +++ b/src/lib/onboard/credential-provider-registration.test.ts @@ -824,10 +824,7 @@ describe("credential provider registration", () => { }, async () => ({ messagingTokenDefs: tokenDefs }), ), - ).rejects.toMatchObject({ - message: expect.stringMatching(/authority changed.*alpha-first.*inspect.*before retrying/isu), - mutatedProviderNames: ["alpha-first"], - }); + ).rejects.toThrow("authority changed"); expect( runOpenshell.mock.calls diff --git a/src/lib/onboard/credential-provider-registration.ts b/src/lib/onboard/credential-provider-registration.ts index 6f74183cc25..28eafb6e9c4 100644 --- a/src/lib/onboard/credential-provider-registration.ts +++ b/src/lib/onboard/credential-provider-registration.ts @@ -29,6 +29,18 @@ export interface MessagingProviderRegistrationOptions { revalidatePolicyRequirements?(operation: string): void; } +function policyAuthorityCheckedRunner( + runOpenshell: OpenshellCliHelpers["runOpenshell"], + revalidatePolicyRequirements: MessagingProviderRegistrationOptions["revalidatePolicyRequirements"], + operation: string, +): OpenshellCliHelpers["runOpenshell"] { + if (!revalidatePolicyRequirements) return runOpenshell; + return (...args) => { + revalidatePolicyRequirements(operation); + return runOpenshell(...args); + }; +} + type PreparedCredentialProviders = { messagingTokenDefs: MessagingTokenDef[]; }; @@ -218,7 +230,10 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg type: string, credentialEnv: string, ): boolean { - return credentialBindingMatchesGateway({ name, type, credentialEnv }, gatewayRunner()); + return credentialBindingMatchesGateway( + { name, type, credentialEnv }, + gatewayRunner(), + ); } function preflightRequiredCredentialProviderBindings( diff --git a/src/lib/onboard/hermes-dashboard.test.ts b/src/lib/onboard/hermes-dashboard.test.ts index 84f39a3c83b..224cb8e1991 100644 --- a/src/lib/onboard/hermes-dashboard.test.ts +++ b/src/lib/onboard/hermes-dashboard.test.ts @@ -290,35 +290,4 @@ describe("onboard Hermes dashboard helpers", () => { expect.anything(), ); }); - - it("leaves the sandbox running after Hermes dashboard rollback (#9833)", () => { - const runOpenshell = vi.fn(); - const forwarding = createHermesDashboardOnboardForwarding({ - agentName: "hermes", - env: { NEMOCLAW_HERMES_DASHBOARD: "1" }, - ensureForward: vi.fn(() => false), - note: vi.fn(), - runOpenshell, - getApiForwardPort: () => "8642", - fail: (message): never => { - throw new Error(message); - }, - }); - const state = forwarding.resolveStateForPort(18789); - - expect(() => forwarding.ensureForState(state, "my-hermes", true)).toThrow( - /left the sandbox running/u, - ); - expect(runOpenshell).toHaveBeenCalledWith(["forward", "stop", "8642", "my-hermes"], { - ignoreError: true, - }); - expect(runOpenshell).toHaveBeenCalledWith( - ["forward", "stop", "18789", "my-hermes"], - { ignoreError: true }, - ); - expect(runOpenshell).not.toHaveBeenCalledWith( - ["sandbox", "delete", "my-hermes"], - expect.anything(), - ); - }); }); diff --git a/src/lib/onboard/machine/handlers/policies.ts b/src/lib/onboard/machine/handlers/policies.ts index 1fcb49cdffd..9266f132136 100644 --- a/src/lib/onboard/machine/handlers/policies.ts +++ b/src/lib/onboard/machine/handlers/policies.ts @@ -244,13 +244,15 @@ export async function handlePoliciesState({ `verify the externally managed policy for sandbox '${sandboxName}'`, ); verifySandboxInferenceRoute(); - revalidatePolicyRequirements?.(`record verified external policy for sandbox '${sandboxName}'`); + revalidatePolicyRequirements?.( + `record verified external policy for sandbox '${sandboxName}'`, + ); deps.skippedStepMessage("policies", "externally managed"); await deps.recordStateSkipped("policies", { reason: "externally_managed", }); revalidatePolicyRequirements?.( - `complete externally managed policy setup for sandbox '${sandboxName}'`, + `record verified external policy for sandbox '${sandboxName}'`, ); const session = await deps.recordStepComplete( "policies", diff --git a/src/lib/onboard/machine/handlers/sandbox-policy-authority-completion.test.ts b/src/lib/onboard/machine/handlers/sandbox-policy-authority-completion.test.ts index d00af59cd8d..ea37b33227d 100644 --- a/src/lib/onboard/machine/handlers/sandbox-policy-authority-completion.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-policy-authority-completion.test.ts @@ -9,7 +9,6 @@ import { baseOptions, bindJournaledRecreate, createDeps } from "./sandbox-test-f vi.mock("../../messaging-channel-setup", () => ({ detectMessagingChannelsFromEnv: vi.fn(() => []), - detectUnconfiguredMessagingChannels: vi.fn(() => []), })); function refuseAt(targetOperation: string) { @@ -25,19 +24,6 @@ function refuseAt(targetOperation: string) { } describe("sandbox completion policy authority", () => { - it("rechecks immediately before sandbox creation (#9833)", async () => { - const preflightPolicyRequirements = refuseAt("create sandbox 'my-assistant'"); - const { deps, calls } = createDeps({ preflightPolicyRequirements }); - - await expect(handleSandboxState(baseOptions(deps))).rejects.toThrow( - /external policy authority must supply/u, - ); - - expect(calls.createSandbox).not.toHaveBeenCalled(); - expect(calls.updateSandbox).not.toHaveBeenCalled(); - expect(calls.complete).not.toHaveBeenCalled(); - }); - it("rechecks after the inner create before registry or session completion (#9833)", async () => { const preflightPolicyRequirements = refuseAt("complete the created sandbox"); const { deps, calls } = createDeps({ preflightPolicyRequirements }); @@ -81,42 +67,6 @@ describe("sandbox completion policy authority", () => { expect(calls.complete).not.toHaveBeenCalled(); }); - it("rechecks before recording reused sandbox state (#9833)", async () => { - const session = createSession({ sandboxName: "saved" }); - session.steps.sandbox.status = "complete"; - const preflightPolicyRequirements = refuseAt("record reused sandbox state for 'saved'"); - const { deps, calls } = createDeps( - { - getSandboxReuseState: () => "ready", - getSandboxRegistryEntry: () => ({ - name: "saved", - pendingRouteReservation: true, - reservationSessionId: session.sessionId, - provider: "provider", - model: "model", - endpointUrl: null, - preferredInferenceApi: "openai-completions", - toolDisclosure: "progressive", - fromDockerfile: null, - hermesAuthMethod: null, - }), - preflightPolicyRequirements, - }, - session, - ); - - await expect( - handleSandboxState({ - ...baseOptions(deps, session), - resume: true, - sandboxName: "saved", - }), - ).rejects.toThrow(/external policy authority must supply/u); - - expect(calls.createSandbox).not.toHaveBeenCalled(); - expect(calls.skipped).not.toHaveBeenCalled(); - }); - it.each([ { operation: "register the created sandbox", diff --git a/src/lib/onboard/policy-selection-host-local-route.test.ts b/src/lib/onboard/policy-selection-host-local-route.test.ts index 83f162f3277..7efe5cc7881 100644 --- a/src/lib/onboard/policy-selection-host-local-route.test.ts +++ b/src/lib/onboard/policy-selection-host-local-route.test.ts @@ -119,33 +119,6 @@ describe("host-local route-only policy selection", () => { expect(syncPresetSelection).not.toHaveBeenCalled(); }); - it("refuses interactive preset mutation when authority changes during the prompt (#9833)", async () => { - const { deps, syncPresetSelection } = createHarness(); - deps.isNonInteractive.mockReturnValue(false); - deps.selectTierPresetsAndAccess.mockResolvedValue([{ name: "npm", access: "read" }]); - const refusePresetMutation = () => { - throw new Error("policy authority changed"); - }; - const policyChecks = new Map([ - ["apply policy presets to sandbox 'alpha'", refusePresetMutation], - ]); - const revalidatePolicyRequirements = vi.fn((operation: string) => - policyChecks.get(operation)?.(), - ); - - await expect( - setupPoliciesWithSelection(deps, "alpha", { - selectedPresets: null, - provider: null, - excludedPresets: ["local-inference"], - revalidatePolicyRequirements, - }), - ).rejects.toThrow("policy authority changed"); - - expect(deps.selectTierPresetsAndAccess).toHaveBeenCalledOnce(); - expect(syncPresetSelection).not.toHaveBeenCalled(); - }); - it("does not attribute presets when the policy mutation is refused (#9833)", async () => { const { deps, syncPresetSelection } = createHarness(); const onSelection = vi.fn(); @@ -163,74 +136,6 @@ describe("host-local route-only policy selection", () => { expect(onSelection).not.toHaveBeenCalled(); }); - it("refuses resumed preset synchronization when authority changes (#9833)", async () => { - const { deps, syncPresetSelection } = createHarness(); - const revalidatePolicyRequirements = vi.fn(() => { - throw new Error("policy authority changed"); - }); - - await expect( - setupPoliciesWithSelection(deps, "alpha", { - selectedPresets: ["npm"], - revalidatePolicyRequirements, - }), - ).rejects.toThrow("policy authority changed"); - - expect(revalidatePolicyRequirements).toHaveBeenCalledWith( - "reapply recorded policy presets to sandbox 'alpha'", - ); - expect(syncPresetSelection).not.toHaveBeenCalled(); - }); - - it("refuses retained-preset synchronization when authority changes (#9833)", async () => { - const { deps, syncPresetSelection } = createHarness(); - deps.env.NEMOCLAW_POLICY_MODE = "skip"; - const revalidatePolicyRequirements = vi - .fn<() => void>() - .mockImplementationOnce(() => undefined) - .mockImplementationOnce(() => { - throw new Error("policy authority changed"); - }); - - await expect( - setupPoliciesWithSelection(deps, "alpha", { - selectedPresets: null, - provider: null, - excludedPresets: ["local-inference"], - revalidatePolicyRequirements, - }), - ).rejects.toThrow("policy authority changed"); - - expect(revalidatePolicyRequirements).toHaveBeenLastCalledWith( - "apply retained policy presets to sandbox 'alpha'", - ); - expect(syncPresetSelection).not.toHaveBeenCalled(); - }); - - it("refuses non-interactive preset synchronization when authority changes (#9833)", async () => { - const { deps, syncPresetSelection } = createHarness(); - const revalidatePolicyRequirements = vi - .fn<() => void>() - .mockImplementationOnce(() => undefined) - .mockImplementationOnce(() => { - throw new Error("policy authority changed"); - }); - - await expect( - setupPoliciesWithSelection(deps, "alpha", { - selectedPresets: null, - provider: null, - excludedPresets: ["local-inference"], - revalidatePolicyRequirements, - }), - ).rejects.toThrow("policy authority changed"); - - expect(revalidatePolicyRequirements).toHaveBeenLastCalledWith( - "apply non-interactive policy presets to sandbox 'alpha'", - ); - expect(syncPresetSelection).not.toHaveBeenCalled(); - }); - it("removes a live stale local-inference preset even when ordinary policy setup is skipped", async () => { const { deps, syncPresetSelection } = createHarness(); deps.env.NEMOCLAW_POLICY_MODE = "skip"; diff --git a/src/lib/onboard/providers.test.ts b/src/lib/onboard/providers.test.ts index 4301d10bc58..ee25d9c1efe 100644 --- a/src/lib/onboard/providers.test.ts +++ b/src/lib/onboard/providers.test.ts @@ -3,6 +3,8 @@ import { describe, expect, it, vi } from "vitest"; +import { PolicyAuthorityRefusalError } from "../adapters/openshell/policy-authority"; + type RunResult = { error?: unknown; output?: string; @@ -21,9 +23,8 @@ type RunOptions = { }; type RunOpenshell = (command: string[], opts?: RunOptions) => RunResult; -const messagingBridgeProvider = require( - "./messaging-bridge-provider" -) as typeof import("./messaging-bridge-provider"); +const messagingBridgeProvider = + require("./messaging-bridge-provider") as typeof import("./messaging-bridge-provider"); const DISCORD_STATIC_PROFILE_EXPORT = JSON.stringify({ id: "discord-hermes-static-v1", @@ -1056,7 +1057,6 @@ describe("onboard provider helpers", () => { ]); }); - it("throws instead of exiting when best-effort messaging provider upsert fails", () => { const originalExit = process.exit; process.exit = ((code?: number | string | null) => { @@ -1085,24 +1085,35 @@ describe("onboard provider helpers", () => { }); it("reports providers changed before bridge refresh throws (#9833)", () => { + const cause = new Error("receipt changed"); + const refusal = new PolicyAuthorityRefusalError( + "policy authority changed", + "externally-managed", + { cause }, + ); const configureRefreshes = vi .spyOn(messagingBridgeProvider, "configureMessagingBridgeRefreshes") .mockImplementation(() => { - throw new Error("policy authority changed"); + throw refusal; }); try { - expect(() => + let caught: unknown; + try { upsertMessagingProviders( [{ name: "alpha-bridge", envKey: "BRIDGE_TOKEN", token: "test-token" }], () => ({ status: 0, stdout: "", stderr: "" }), { bestEffort: true }, - ), - ).toThrow( - expect.objectContaining({ - message: expect.stringMatching(/policy authority changed.*alpha-bridge/isu), - mutatedProviderNames: ["alpha-bridge"], - }), - ); + ); + } catch (error) { + caught = error; + } + expect(caught).toBe(refusal); + expect(caught).toMatchObject({ + cause, + observedAuthority: "externally-managed", + message: expect.stringMatching(/policy authority changed.*alpha-bridge/isu), + mutatedProviderNames: ["alpha-bridge"], + }); } finally { configureRefreshes.mockRestore(); } diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index 80684e9302a..1c2fd810753 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -35,6 +35,7 @@ const { ensureWebSearchProviderProfiles } = require("./brave-provider-profile"); const MESSAGING_PROVIDER_BINDING_CONFLICT = "NEMOCLAW_MESSAGING_PROVIDER_BINDING_CONFLICT"; const MESSAGING_PROVIDER_MUTATION_FAILURE = "NEMOCLAW_MESSAGING_PROVIDER_MUTATION_FAILURE"; +const POLICY_AUTHORITY_REFUSAL = "NEMOCLAW_POLICY_AUTHORITY_REFUSAL"; class MessagingProviderMutationError extends Error { constructor(error, mutatedProviderNames, createdProviderNames) { @@ -73,7 +74,9 @@ function attachMutatedProviderNames(error, names, createdNames = []) { if (names.length === 0) return error; const original = error instanceof Error ? error : new Error(String(error)); const failure = - isMessagingProviderBindingConflict(original) || isMessagingProviderMutationFailure(original) + isMessagingProviderBindingConflict(original) || + isMessagingProviderMutationFailure(original) || + original.code === POLICY_AUTHORITY_REFUSAL ? original : new MessagingProviderMutationError(original, [], []); const existing = Array.isArray(failure.mutatedProviderNames) ? failure.mutatedProviderNames : []; diff --git a/src/lib/onboard/resume/locked-runtime.test.ts b/src/lib/onboard/resume/locked-runtime.test.ts index e282d6415f8..2354cd4da61 100644 --- a/src/lib/onboard/resume/locked-runtime.test.ts +++ b/src/lib/onboard/resume/locked-runtime.test.ts @@ -44,6 +44,19 @@ const portableCheckpointWithoutAuthority: OnboardCheckpoint = { }; describe("locked onboarding runtime preparation", () => { + it("stops an invalid saved authority before resume preparation effects (#9833)", async () => { + const preparePortableHost = vi.fn(); + const loadSession = vi.fn(() => { + throw new Error("saved policy authority is invalid"); + }); + + await expect( + prepare({ resume: true, preparePortableHost }, true, true, loadSession), + ).rejects.toThrow("saved policy authority is invalid"); + expect(loadSession).toHaveBeenCalledOnce(); + expect(preparePortableHost).not.toHaveBeenCalled(); + }); + it("rejects portable resume without selected authority before host preparation (#9035)", async () => { const preparePortableHost = vi.fn(); diff --git a/src/lib/onboard/sandbox-reuse.ts b/src/lib/onboard/sandbox-reuse.ts index 348a675854b..7145301e02c 100644 --- a/src/lib/onboard/sandbox-reuse.ts +++ b/src/lib/onboard/sandbox-reuse.ts @@ -142,7 +142,7 @@ export function applyReusedSandboxDashboardState( ); } input.revalidatePolicyRequirements?.( - `restore dashboard state for sandbox '${input.sandboxName}'`, + `restore dashboard state for sandbox ${JSON.stringify(input.sandboxName)}`, ); const dashboardPort = manageDashboard ? input.revalidatePolicyRequirements @@ -153,7 +153,9 @@ export function applyReusedSandboxDashboardState( : 0; const chatUiUrl = manageDashboard ? `http://127.0.0.1:${dashboardPort}` : input.chatUiUrl; if (manageDashboard) { - input.revalidatePolicyRequirements?.(`record dashboard URL for sandbox '${input.sandboxName}'`); + input.revalidatePolicyRequirements?.( + `record dashboard URL for sandbox ${JSON.stringify(input.sandboxName)}`, + ); input.env.CHAT_UI_URL = chatUiUrl; } const hermesDashboardState = manageDashboard @@ -161,7 +163,7 @@ export function applyReusedSandboxDashboardState( : { enabled: false, config: null }; if (manageDashboard) { input.revalidatePolicyRequirements?.( - `restore Hermes dashboard state for sandbox '${input.sandboxName}'`, + `restore Hermes dashboard state for sandbox ${JSON.stringify(input.sandboxName)}`, ); input.hermesDashboardForwarding.ensureForState( hermesDashboardState, @@ -170,7 +172,9 @@ export function applyReusedSandboxDashboardState( input.revalidatePolicyRequirements, ); } - input.revalidatePolicyRequirements?.(`update reused sandbox metadata for '${input.sandboxName}'`); + input.revalidatePolicyRequirements?.( + `update reused sandbox metadata for ${JSON.stringify(input.sandboxName)}`, + ); input.updateReusedSandboxMetadata( input.sandboxName, input.agent, @@ -182,7 +186,7 @@ export function applyReusedSandboxDashboardState( input.revalidatePolicyRequirements, ); input.revalidatePolicyRequirements?.( - `record reused dashboard state for sandbox '${input.sandboxName}'`, + `record reused dashboard state for sandbox ${JSON.stringify(input.sandboxName)}`, ); (input.updateSandbox ?? registry.updateSandbox)(input.sandboxName, { ...getHermesDashboardRegistryFields(hermesDashboardState), diff --git a/src/lib/policy/gateway-state.ts b/src/lib/policy/gateway-state.ts index 79c23ddf64e..f8410b65bef 100644 --- a/src/lib/policy/gateway-state.ts +++ b/src/lib/policy/gateway-state.ts @@ -2,6 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 import { isDeepStrictEqual } from "node:util"; + +export function policyValuesEqual(left: unknown, right: unknown): boolean { + return isDeepStrictEqual(left, right); +} + import YAML from "yaml"; export type PresetContentSource = { name: string; content: string | null }; diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index ce1bb499d1d..0cbe28d86f7 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -4542,6 +4542,40 @@ function lockAgentConfig( }); } +/** Rebind a replacement sandbox's config lock without changing its external policy. */ +function rebindReplacementConfigLock(sandboxName: string, allowLegacyHermesProtocol = false): void { + validateName(sandboxName, "sandbox name"); + return withShieldsTransitionLock(sandboxName, "rebind replacement config lock", () => { + const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + const protocol = requireHermesShieldsProtocol(sandboxName, target, allowLegacyHermesProtocol); + const relock = relockAndReconfirm(() => + lockAgentConfigWithoutHostLock( + sandboxName, + target, + false, + allowLegacyHermesProtocol, + protocol, + ), + ); + if (!relock.ok || !relock.lastResult) { + throw new Error( + relock.error ?? "Replacement config lock did not re-confirm after the settle window", + ); + } + saveShieldsState(sandboxName, { + shieldsDown: false, + shieldsDownAt: null, + shieldsDownTimeout: null, + shieldsDownReason: null, + shieldsDownPolicy: null, + shieldsPolicySnapshotPath: null, + shieldsManagedMcpPolicyKeys: [], + chattrApplied: relock.lastResult.chattrApplied, + fileHashes: relock.lastResult.fileHashes, + }); + }); +} + type ShieldsDownRollbackOutcome = | "mutable_default_restored" | "lockdown_restored" @@ -6969,6 +7003,7 @@ export { MAX_TIMEOUT_SECONDS, parseDuration, prepareAutoRestoreTransitionTakeover, + rebindReplacementConfigLock, repairMutableConfigPerms, resolvePersistedAutoRestoreTarget, restoreLockedStateDirStartupAccess, diff --git a/test/credentials/rebuild-credential-preflight.test.ts b/test/credentials/rebuild-credential-preflight.test.ts index c662c4d1bd2..43c2534ded1 100644 --- a/test/credentials/rebuild-credential-preflight.test.ts +++ b/test/credentials/rebuild-credential-preflight.test.ts @@ -15,6 +15,11 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { + managedPolicyMetadata, + managedSandboxEntry, + SANDBOX_ID, +} from "../helpers/managed-policy-receipt-fixture"; import { execTimeout, testTimeoutOptions } from "../helpers/timeouts"; const REPO_ROOT = path.join(import.meta.dirname, "../.."); @@ -86,6 +91,10 @@ wait();`, const gatewayPort = Number(gatewayPortText); expect(gatewayPort).toBeLessThanOrEqual(65_535); const gatewayName = `nemoclaw-${gatewayPort}`; + const managedPolicyState = managedSandboxEntry(sandboxName, agent ?? "openclaw", { + gatewayName, + gatewayPort, + }); fs.writeFileSync( path.join(nemoclawDir, "sandboxes.json"), @@ -103,6 +112,10 @@ wait();`, dashboardPort: agent === "langchain-deepagents-code" ? 0 : 18789, fromDockerfile: null, policies: [], + lifecycleGeneration: managedPolicyState.lifecycleGeneration, + lifecycleLiveIdentityFingerprint: managedPolicyState.lifecycleLiveIdentityFingerprint, + policyAuthority: managedPolicyState.policyAuthority, + policyCreationReceipt: managedPolicyState.policyCreationReceipt, agent, ...(agent === "langchain-deepagents-code" ? { @@ -187,12 +200,20 @@ const requiredFeatures = "request-body-credential-rewrite websocket-credential-r if (a[0] === "-V" || a[0] === "--version") { process.stdout.write("openshell 0.0.106\\n"); process.exit(0); } if (a[0] === "sandbox" && a[1] === "list") { process.stdout.write("${sandboxName} Ready\\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] === "get") { +if (a.includes("sandbox") && a.includes("get")) { if (fs.existsSync(${JSON.stringify(deleteMarker)})) { process.stderr.write("sandbox ${sandboxName} not found\\n"); process.exit(1); } - process.stdout.write("Sandbox: ${sandboxName}\\nPhase: Ready\\n"); + process.stdout.write("Sandbox: ${sandboxName}\\nId: ${SANDBOX_ID}\\nPhase: Ready\\n"); + process.exit(0); +} +if (a[0] === "policy" && a[1] === "list" && a.includes("--global")) { + process.stderr.write("No global policy history found\\n"); + process.exit(0); +} +if (a[0] === "policy" && a[1] === "get" && a.includes("--output") && a.includes("json")) { + process.stdout.write(${JSON.stringify(managedPolicyMetadata(sandboxName))} + "\\n"); process.exit(0); } if (a[0] === "sandbox" && a[1] === "delete") { fs.writeFileSync(${JSON.stringify(deleteMarker)}, "deleted\\n"); process.exit(0); } diff --git a/test/e2e/README.md b/test/e2e/README.md index 6228a43c926..0056be2c389 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -157,7 +157,7 @@ The historical fixtures retain these version boundaries: | Fixture | Required boundary | | --- | --- | | `openshell-gateway-upgrade` | Retain the historical installer commit and SHA-256 digest, sandbox image digest, and reviewed OpenClaw npm URL and SHA-512 integrity. Install the historical package before testing the candidate upgrade path. | -| `rebuild-openclaw` | Retain the reviewed old-base build in the target. Build and create the old sandbox before testing the candidate rebuild path. | +| `rebuild-openclaw` | Retain the reviewed historical OpenClaw runtime build in the target. Resolve the current trusted sandbox base, create the legacy runtime through real onboarding, and verify it before testing the candidate rebuild path. | These targets may restore the shared artifact for the candidate CLI. They must not replace a historical installer, package, image, or version boundary with that artifact. diff --git a/test/e2e/live/rebuild-openclaw-legacy-context.ts b/test/e2e/live/rebuild-openclaw-legacy-context.ts new file mode 100644 index 00000000000..0dc669c00db --- /dev/null +++ b/test/e2e/live/rebuild-openclaw-legacy-context.ts @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import { stageOptimizedSandboxBuildContext } from "../../../src/lib/sandbox/build-context"; + +export interface LegacyOpenClawSandboxContext { + buildCtx: string; + dockerfile: string; + blueprint: string; + restoreCurrent(): void; + cleanup(): void; +} + +function replaceExactlyOne( + source: string, + pattern: RegExp, + replacement: string, + label: string, +): string { + const matches = [...source.matchAll(pattern)]; + if (matches.length !== 1) { + throw new Error(`Expected one ${label}; found ${matches.length}`); + } + return source.replace(pattern, replacement); +} + +function writePreservingMode(filePath: string, contents: string, mode: number): void { + fs.chmodSync(filePath, mode | 0o200); + fs.writeFileSync(filePath, contents, "utf8"); + fs.chmodSync(filePath, mode); +} + +/** + * Stage the complete trusted OpenClaw Docker build context, then lower only + * the runtime inputs needed to create the historical sandbox exercised by this + * E2E. The base image remains under the real onboard resolver's authority. The + * caller restores the current trusted recipe before invoking rebuild. + */ +export function createLegacyOpenClawSandboxContext(options: { + rootDir: string; + openClawVersion: string; +}): LegacyOpenClawSandboxContext { + const staged = stageOptimizedSandboxBuildContext(options.rootDir); + const dockerfile = staged.stagedDockerfile; + const blueprint = path.join(staged.buildCtx, "nemoclaw-blueprint", "blueprint.yaml"); + const currentDockerfile = fs.readFileSync(dockerfile, "utf8"); + const currentBlueprint = fs.readFileSync(blueprint, "utf8"); + const dockerfileMode = fs.statSync(dockerfile).mode & 0o777; + const blueprintMode = fs.statSync(blueprint).mode & 0o777; + + try { + let legacyDockerfile = replaceExactlyOne( + currentDockerfile, + /^ARG OPENCLAW_VERSION=.*$/gm, + `ARG OPENCLAW_VERSION=${options.openClawVersion}`, + "Dockerfile OPENCLAW_VERSION default", + ); + legacyDockerfile = replaceExactlyOne( + legacyDockerfile, + /^ARG NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=.*$/gm, + "ARG NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", + "Dockerfile legacy OpenClaw fixture flag", + ); + const legacyBlueprint = replaceExactlyOne( + currentBlueprint, + /^(\s*)min_openclaw_version:.*$/gm, + `$1min_openclaw_version: "${options.openClawVersion}"`, + "blueprint min_openclaw_version", + ); + writePreservingMode(dockerfile, legacyDockerfile, dockerfileMode); + writePreservingMode(blueprint, legacyBlueprint, blueprintMode); + } catch (error) { + fs.rmSync(staged.buildCtx, { recursive: true, force: true }); + throw error; + } + + return { + buildCtx: staged.buildCtx, + dockerfile, + blueprint, + restoreCurrent() { + writePreservingMode(dockerfile, currentDockerfile, dockerfileMode); + writePreservingMode(blueprint, currentBlueprint, blueprintMode); + }, + cleanup() { + fs.rmSync(staged.buildCtx, { recursive: true, force: true }); + }, + }; +} diff --git a/test/e2e/live/rebuild-openclaw-old-base-context.ts b/test/e2e/live/rebuild-openclaw-old-base-context.ts deleted file mode 100644 index cdeb476d2b8..00000000000 --- a/test/e2e/live/rebuild-openclaw-old-base-context.ts +++ /dev/null @@ -1,118 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { directDockerfileCopySources } from "../../../scripts/lib/dockerfile-copy-sources.mts"; -import { REPO_ROOT } from "../fixtures/paths.ts"; - -const DOCKERFILE_BASE = path.join(REPO_ROOT, "Dockerfile.base"); -const DOCKERIGNORE = path.join(REPO_ROOT, ".dockerignore"); -const OLD_OPENCLAW_VERSION = "2026.3.11"; -const BLUEPRINT_RELPATH = "nemoclaw-blueprint/blueprint.yaml"; - -export function oldBaseContextSources(): string[] { - return [BLUEPRINT_RELPATH, ...directDockerfileBaseCopySources()]; -} - -export function directDockerfileBaseCopySources(dockerfilePath = DOCKERFILE_BASE): string[] { - return directDockerfileCopySources(dockerfilePath, "Dockerfile.base").map(({ source }) => { - validateOldBaseContextSource(source); - return source; - }); -} - -export function dockerignoreSecretPatterns(dockerignorePath = DOCKERIGNORE): string[] { - const patterns: string[] = []; - let inSecuritySection = false; - - for (const rawLine of fs.readFileSync(dockerignorePath, "utf8").split(/\r?\n/)) { - const line = rawLine.trim(); - if (/^#\s*Security:/i.test(line)) { - inSecuritySection = true; - continue; - } - if (!inSecuritySection || !line || line.startsWith("#")) continue; - if (line.startsWith("!")) { - throw new Error(`Unsupported negated .dockerignore security pattern: ${line}`); - } - patterns.push(line.replace(/^\.\//, "")); - } - - if (patterns.length === 0) { - throw new Error("No .dockerignore security patterns found"); - } - return patterns; -} - -function dockerignorePatternMatchesPath(pattern: string, relativePath: string): boolean { - const normalizedPattern = pattern.replace(/^\/+/, ""); - const parts = relativePath.split("/"); - const fileName = parts.at(-1) ?? ""; - - if (normalizedPattern.endsWith("/")) { - const dirName = normalizedPattern.replace(/\/+$/, ""); - return parts.includes(dirName); - } - - const target = normalizedPattern.includes("/") ? relativePath : fileName; - const escaped = normalizedPattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*"); - return new RegExp(`^${escaped}$`).test(target); -} - -function matchesDockerignoreSecretPattern(relativePath: string): boolean { - return dockerignoreSecretPatterns().some((pattern) => - dockerignorePatternMatchesPath(pattern, relativePath), - ); -} - -function validateOldBaseContextSource(relativePath: string): string { - const parts = relativePath.split("/"); - const resolved = path.resolve(REPO_ROOT, relativePath); - const repoPrefix = `${REPO_ROOT}${path.sep}`; - const invalidSource = - path.isAbsolute(relativePath) || - relativePath.includes("\\") || - /[$*?[\]"']/.test(relativePath) || - relativePath.startsWith("--") || - parts.some((part) => !part || part === "." || part === "..") || - (resolved !== REPO_ROOT && !resolved.startsWith(repoPrefix)); - if (invalidSource) { - throw new Error(`Unsupported direct Dockerfile.base COPY source: ${relativePath}`); - } - if (matchesDockerignoreSecretPattern(relativePath)) { - throw new Error( - `Unsupported .dockerignore-secret Dockerfile.base COPY source: ${relativePath}`, - ); - } - return resolved; -} - -function copyOldBaseContextFile(buildContext: string, relativePath: string): void { - const source = validateOldBaseContextSource(relativePath); - const target = path.join(buildContext, ...relativePath.split("/")); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.copyFileSync(source, target); -} - -export function createOldBaseBuildContext(): string { - const buildContext = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-base-")); - // The legacy bash test builds Dockerfile.base with the full repository as - // context after temporarily lowering blueprint.yaml in-place. Keep the - // trusted checkout read-only while staging every current Dockerfile.base - // direct COPY dependency needed by that old-base build. - for (const relativePath of oldBaseContextSources()) { - copyOldBaseContextFile(buildContext, relativePath); - } - - const stagedBlueprint = path.join(buildContext, ...BLUEPRINT_RELPATH.split("/")); - const original = fs.readFileSync(stagedBlueprint, "utf8"); - const minOpenClawVersion = /^(\s*min_openclaw_version:\s*).*/m; - if (!minOpenClawVersion.test(original)) { - throw new Error("blueprint min_openclaw_version line was not found"); - } - const lowered = original.replace(minOpenClawVersion, `$1"${OLD_OPENCLAW_VERSION}"`); - fs.writeFileSync(stagedBlueprint, lowered, "utf8"); - return buildContext; -} diff --git a/test/e2e/live/rebuild-openclaw.test.ts b/test/e2e/live/rebuild-openclaw.test.ts index 27e4414149f..fe054967653 100644 --- a/test/e2e/live/rebuild-openclaw.test.ts +++ b/test/e2e/live/rebuild-openclaw.test.ts @@ -11,21 +11,16 @@ import { assertExitZero as expectExitZero, resultText } from "../fixtures/client import type { HostCliClient } from "../fixtures/clients/host.ts"; import { validateSandboxName } from "../fixtures/clients/sandbox.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; -import { - readJsonFile, - readJsonFileOr, - restoreFile, - snapshotFile, - writeJsonFile, -} from "../fixtures/file-state.ts"; +import { readJsonFile, readJsonFileOr, restoreFile, snapshotFile } from "../fixtures/file-state.ts"; import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; -import { createOldBaseBuildContext } from "./rebuild-openclaw-old-base-context.ts"; +import { createLegacyOpenClawSandboxContext } from "./rebuild-openclaw-legacy-context.ts"; -// The contract stays intentionally local to this live test: build an older -// OpenClaw base image, create a sandbox from it through the real OpenShell CLI, -// seed workspace/policy/gateway-token state, run the real `nemoclaw rebuild`, -// and verify the rebuilt sandbox preserved state while rotating secrets. +// The contract stays intentionally local to this live test: use NemoClaw's +// current trusted base-image resolver to build a reviewed historical OpenClaw +// runtime, seed workspace/policy/gateway-token state, run the real +// `nemoclaw rebuild`, and verify the rebuilt sandbox preserved state while +// rotating secrets. // // Simplicity boundary: no new registry, fixture family, or migration ledger. @@ -53,10 +48,8 @@ const POLICY_PRESETS = ["npm", "pypi", "telegram"] as const; const MARKER_CONTENT = `REBUILD_OC_E2E_${Date.now()}`; const PRE_REBUILD_GATEWAY_TOKEN = `nemoclaw-e2e-old-gateway-token-${MARKER_CONTENT}`; -const OLD_BASE_TAG = `nemoclaw-old-base:${SANDBOX_NAME.toLowerCase().replace(/[^a-z0-9_.-]+/g, "-")}`; const ONBOARD_TIMEOUT_MS = 20 * 60_000; -const DOCKER_BUILD_TIMEOUT_MS = 35 * 60_000; const REBUILD_TIMEOUT_MS = 30 * 60_000; const OPENSHELL_TIMEOUT_MS = 2 * 60_000; @@ -147,19 +140,6 @@ async function cleanupRebuiltNemoClawSandbox(host: HostCliClient, apiKey: string ); } -async function cleanupOldOpenClawBaseImage(host: HostCliClient): Promise { - const result = await host.command("docker", ["rmi", OLD_BASE_TAG], { - artifactName: "cleanup-docker-rmi-old-base", - env: dockerContextEnv(), - timeoutMs: OPENSHELL_TIMEOUT_MS, - }); - assertCleanupSucceededOrAbsent( - result, - /No such image|image .* not found/iu, - `cleanup old OpenClaw base image ${OLD_BASE_TAG}`, - ); -} - function pythonExecArgs(script: string): string[] { return ["python3", "-c", script]; } @@ -207,67 +187,6 @@ async function configureGatewayInferenceRoute( ); } -function seedRegistryAndSession(dashboardPort: number): void { - // The legacy rebuild regression requires an intentionally old OpenClaw sandbox - // that NemoClaw cannot create through the normal onboard path because current - // blueprints reject versions below min_openclaw_version. Create that sandbox - // through OpenShell, then upsert only this test-owned registry/session entry - // so `nemoclaw rebuild --yes` exercises the user-visible rebuild - // boundary. Remove this local seeding once a first-class old-version lifecycle - // fixture/profile exists. - const registry = readJsonFileOr<{ - sandboxes?: Record>; - defaultSandbox?: string; - }>(REGISTRY_FILE, {}); - registry.sandboxes = registry.sandboxes ?? {}; - registry.sandboxes[SANDBOX_NAME] = { - name: SANDBOX_NAME, - createdAt: new Date().toISOString(), - model: DEFAULT_MODEL, - provider: "compatible-endpoint", - gpuEnabled: false, - policies: [], - policyTier: null, - agent: null, - agentVersion: OLD_OPENCLAW_VERSION, - dashboardPort, - // This test creates an old NemoClaw-managed runtime directly through - // OpenShell. Record the managed-image provenance explicitly so rebuild - // does not have to guess whether an omitted legacy value meant `--from`. - fromDockerfile: null, - }; - registry.defaultSandbox = SANDBOX_NAME; - writeJsonFile(REGISTRY_FILE, registry); - - const now = new Date().toISOString(); - const complete = { status: "complete", startedAt: now, completedAt: now, error: null }; - const pending = { status: "pending", startedAt: null, completedAt: null, error: null }; - const session = readJsonFileOr>(SESSION_FILE, {}); - Object.assign(session, { - sandboxName: SANDBOX_NAME, - status: "complete", - resumable: true, - lastCompletedStep: "inference", - failure: null, - provider: "compatible-endpoint", - model: DEFAULT_MODEL, - credentialEnv: "COMPATIBLE_API_KEY", - endpointUrl: HOSTED_ENDPOINT_URL, - agent: null, - steps: { - preflight: complete, - gateway: complete, - sandbox: pending, - provider_selection: complete, - inference: complete, - openclaw: pending, - agent_setup: pending, - policies: pending, - }, - }); - writeJsonFile(SESSION_FILE, session); -} - function registrySandbox(): Record { const data = readJsonFileOr<{ sandboxes?: Record> }>( REGISTRY_FILE, @@ -339,15 +258,13 @@ function backupCredentialLeakPaths(backupDir: string, oldGatewayToken: string): test( "rebuild-openclaw: old OpenClaw sandbox rebuild preserves state and rotates gateway token", { - timeout: REBUILD_TIMEOUT_MS + 2 * DOCKER_BUILD_TIMEOUT_MS + ONBOARD_TIMEOUT_MS, + timeout: REBUILD_TIMEOUT_MS + 2 * ONBOARD_TIMEOUT_MS, meta: { e2ePhases: [ "confirm Docker and prepare OpenClaw rebuild resources", "onboard the current OpenClaw sandbox", - "build the old OpenClaw base image", - "create the old OpenClaw sandbox", + "create the legacy OpenClaw runtime on the current trusted base", "seed persistent state policy and registry metadata", - "restore the current OpenClaw base image", "rebuild the OpenClaw sandbox", "validate upgraded state policy inference and backup hygiene", ], @@ -378,9 +295,10 @@ test( oldOpenClawVersion: OLD_OPENCLAW_VERSION, sandboxName: SANDBOX_NAME, markerFile: MARKER_FILE, - oldBaseTag: OLD_BASE_TAG, preservedBoundaries: [ - "docker build Dockerfile.base with old OPENCLAW_VERSION", + "current trusted base image resolved and pinned by real NemoClaw onboard", + "test-only --from context lowers only the OpenClaw runtime and is restored before rebuild", + "real NemoClaw and OpenShell binaries remain authoritative", "openshell sandbox create/exec/policy", "real nemoclaw onboard and rebuild CLI", "workspace marker, registry/session files, backup manifest, config hash", @@ -407,11 +325,6 @@ test( ["gateway", "destroy", "-g", "nemoclaw"], "pre-cleanup-openshell-gateway-destroy", ); - await host.command("docker", ["rmi", OLD_BASE_TAG], { - artifactName: "pre-cleanup-docker-rmi-old-base", - env: dockerContextEnv(), - timeoutMs: OPENSHELL_TIMEOUT_MS, - }); const registrySnapshot = snapshotFile(REGISTRY_FILE); const sessionSnapshot = snapshotFile(SESSION_FILE); @@ -421,9 +334,6 @@ test( restoreFile(SESSION_FILE, sessionSnapshot); fs.rmSync(sandboxBackupRoot, { recursive: true, force: true }); }); - cleanup.trackDisposable(`remove old OpenClaw base image ${OLD_BASE_TAG}`, () => - cleanupOldOpenClawBaseImage(host), - ); cleanup.trackGateway(host, "nemoclaw", { artifactName: "cleanup-openshell-gateway-destroy", env: dockerContextEnv(), @@ -481,79 +391,29 @@ test( "phase-1-delete-current-sandbox", ); - // Phase 2: build the old base image with a temporary build context that - // lowers only the blueprint minimum-version gate consumed by Dockerfile.base. - // The trusted checkout stays read-only. - progress.phase("build the old OpenClaw base image"); - const oldBaseBuildContext = createOldBaseBuildContext(); - try { - const buildOldBase = await host.command( - "docker", - [ - "build", - "--build-arg", - `OPENCLAW_VERSION=${OLD_OPENCLAW_VERSION}`, - "--build-arg", - "NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", - "-f", - path.join(REPO_ROOT, "Dockerfile.base"), - "-t", - OLD_BASE_TAG, - oldBaseBuildContext, - ], - { - artifactName: "phase-2-docker-build-old-openclaw-base", - env: dockerContextEnv(), - timeoutMs: DOCKER_BUILD_TIMEOUT_MS, - }, - ); - expectExitZero(buildOldBase, `docker build old OpenClaw ${OLD_OPENCLAW_VERSION}`); - } finally { - fs.rmSync(oldBaseBuildContext, { recursive: true, force: true }); - } - - // Phase 3: create an OpenShell sandbox from the old base image. - progress.phase("create the old OpenClaw sandbox"); - const oldDockerfileDir = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-")); - const oldDockerfile = path.join(oldDockerfileDir, "Dockerfile"); - fs.writeFileSync( - oldDockerfile, - [ - `FROM ${OLD_BASE_TAG}`, - "USER sandbox", - "WORKDIR /sandbox", - "RUN mkdir -p /sandbox/.openclaw/workspace /sandbox/.openclaw && echo '{}' > /sandbox/.openclaw/openclaw.json", - '["/bin/bash"]', - ] - .map((line, index) => (index === 4 ? `CMD ${line}` : line)) - .join("\n"), - "utf8", + // Phase 2: recreate the sandbox through NemoClaw so its current trusted + // base-image resolver remains authoritative while the explicit E2E fixture + // installs the reviewed historical OpenClaw runtime. Direct OpenShell + // creation cannot truthfully establish NemoClaw policy ownership. + progress.phase("create the legacy OpenClaw runtime on the current trusted base"); + const legacyContext = createLegacyOpenClawSandboxContext({ + rootDir: REPO_ROOT, + openClawVersion: OLD_OPENCLAW_VERSION, + }); + cleanup.trackDisposable("remove legacy OpenClaw sandbox context", () => + legacyContext.cleanup(), ); - try { - const createOldSandbox = await sandbox.openshell( - [ - "sandbox", - "create", - "--name", - SANDBOX_NAME, - "--from", - oldDockerfile, - "--gateway", - "nemoclaw", - "--no-tty", - "--", - "true", - ], - { - artifactName: "phase-3-create-old-openclaw-sandbox", - env: dockerContextEnv(), - timeoutMs: 10 * 60_000, - }, - ); - expectExitZero(createOldSandbox, "openshell sandbox create old OpenClaw sandbox"); - } finally { - fs.rmSync(oldDockerfileDir, { recursive: true, force: true }); - } + const createOldSandbox = await host.command( + "node", + [CLI_ENTRYPOINT, "onboard", "--non-interactive", "--from", legacyContext.dockerfile], + { + artifactName: "phase-3-onboard-old-openclaw-sandbox", + env: cliEnv(apiKey, { NEMOCLAW_RECREATE_SANDBOX: "1" }), + redactionValues: [apiKey], + timeoutMs: ONBOARD_TIMEOUT_MS, + }, + ); + expectExitZero(createOldSandbox, "nemoclaw onboard old OpenClaw sandbox"); await waitForSandboxReady(sandbox); const oldVersion = await sandbox.exec(SANDBOX_NAME, ["openclaw", "--version"], { @@ -563,10 +423,15 @@ test( }); expectExitZero(oldVersion, "old openclaw --version"); expect(resultText(oldVersion)).toContain(OLD_OPENCLAW_VERSION); + expect(registrySandbox().fromDockerfile).toBe(legacyContext.dockerfile); - // Phase 4: seed workspace state, an existing gateway token, and registry / - // resume-session state so `nemoclaw rebuild --yes` drives the same - // user-visible rebuild path as the former shell test. + // Rebuild reuses the recorded --from path. Restore the current trusted + // recipe at that exact path so the next lifecycle creates the upgrade, + // while the existing sandbox remains on the verified historical runtime. + legacyContext.restoreCurrent(); + + // Phase 4: seed workspace state and an existing gateway token while keeping + // the registry and resume-session state written by the old-image onboard. progress.phase("seed persistent state policy and registry metadata"); const markerWrite = await sandbox.exec( SANDBOX_NAME, @@ -627,16 +492,24 @@ print(json.dumps({'seeded': saved == os.environ['PRE_REBUILD_GATEWAY_TOKEN'], 'h const preRebuildConfigHash = preHashResult.stdout.trim(); expect(preRebuildConfigHash).toContain("openclaw.json"); - seedRegistryAndSession(phase1DashboardPort as number); const sessionAfterSeed = readJsonFileOr>(SESSION_FILE, {}); const seededSteps = sessionAfterSeed.steps as Record | undefined; const seededSandbox = registrySandbox(); + expect(seededSandbox.dashboardPort).toBe(phase1DashboardPort); + expect(seededSandbox.policyAuthority).toBe("nemoclaw-managed"); + expect(seededSandbox.policyCreationReceipt).toMatchObject({ + schemaVersion: 1, + origin: "sandbox-create", + sandboxName: SANDBOX_NAME, + }); await artifacts.writeJson("phase-4-registry-session-summary.json", { registry: { name: seededSandbox.name, provider: seededSandbox.provider, agentVersion: seededSandbox.agentVersion, dashboardPort: seededSandbox.dashboardPort, + policyAuthority: seededSandbox.policyAuthority, + hasPolicyCreationReceipt: seededSandbox.policyCreationReceipt !== undefined, policyCount: Array.isArray(seededSandbox.policies) ? seededSandbox.policies.length : 0, }, session: { @@ -693,27 +566,7 @@ print(json.dumps({'seeded': saved == os.environ['PRE_REBUILD_GATEWAY_TOKEN'], 'h expectExitZero(prePolicyList, "nemoclaw policy-list before rebuild"); expect(prePolicyList.stdout).toMatch(/●\s+telegram/i); - // Phase 5: restore the current base image tag that rebuild consumes. - progress.phase("restore the current OpenClaw base image"); - const buildCurrentBase = await host.command( - "docker", - [ - "build", - "-f", - path.join(REPO_ROOT, "Dockerfile.base"), - "-t", - "ghcr.io/nvidia/nemoclaw/sandbox-base:latest", - REPO_ROOT, - ], - { - artifactName: "phase-5-docker-build-current-base", - env: dockerContextEnv(), - timeoutMs: DOCKER_BUILD_TIMEOUT_MS, - }, - ); - expectExitZero(buildCurrentBase, "docker build current base image"); - - // Phase 6: run the real rebuild CLI. + // Phase 5: run the real rebuild CLI. progress.phase("rebuild the OpenClaw sandbox"); const rebuild = await host.command( "node", diff --git a/test/e2e/support/rebuild-openclaw-legacy-context.test.ts b/test/e2e/support/rebuild-openclaw-legacy-context.test.ts new file mode 100644 index 00000000000..e5257ead0be --- /dev/null +++ b/test/e2e/support/rebuild-openclaw-legacy-context.test.ts @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { REPO_ROOT } from "../fixtures/paths.ts"; +import { createLegacyOpenClawSandboxContext } from "../live/rebuild-openclaw-legacy-context.ts"; + +const copiedContexts: string[] = []; + +describe("rebuild-openclaw legacy runtime context", () => { + afterEach(() => { + for (const contextPath of copiedContexts.splice(0)) { + fs.rmSync(contextPath, { recursive: true, force: true }); + } + }); + + it("lowers only the OpenClaw runtime inputs and restores the current trusted recipe", () => { + const sourceDockerfile = fs.readFileSync(path.join(REPO_ROOT, "Dockerfile"), "utf8"); + const sourceBlueprint = fs.readFileSync( + path.join(REPO_ROOT, "nemoclaw-blueprint", "blueprint.yaml"), + "utf8", + ); + const sourceBaseImage = sourceDockerfile.match(/^ARG BASE_IMAGE=.*$/gm); + const legacyContext = createLegacyOpenClawSandboxContext({ + rootDir: REPO_ROOT, + openClawVersion: "2026.3.11", + }); + copiedContexts.push(legacyContext.buildCtx); + + const patchedDockerfile = fs.readFileSync(legacyContext.dockerfile, "utf8"); + expect(sourceBaseImage).toHaveLength(1); + expect(patchedDockerfile.match(/^ARG BASE_IMAGE=.*$/gm)).toEqual(sourceBaseImage); + expect(patchedDockerfile.match(/^ARG OPENCLAW_VERSION=.*$/gm)).toEqual([ + "ARG OPENCLAW_VERSION=2026.3.11", + ]); + expect(patchedDockerfile.match(/^ARG NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=.*$/gm)).toEqual([ + "ARG NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", + ]); + expect(fs.readFileSync(legacyContext.blueprint, "utf8")).toMatch( + /^\s*min_openclaw_version: "2026\.3\.11"$/m, + ); + const requiredPaths = ["agents/openclaw", "nemoclaw", "nemoclaw-blueprint", "scripts", "src"]; + expect( + requiredPaths.every((requiredPath) => + fs.existsSync(path.join(legacyContext.buildCtx, requiredPath)), + ), + ).toBe(true); + + legacyContext.restoreCurrent(); + + expect(fs.readFileSync(legacyContext.dockerfile, "utf8")).toBe(sourceDockerfile); + expect(fs.readFileSync(legacyContext.blueprint, "utf8")).toBe(sourceBlueprint); + expect(fs.readFileSync(path.join(REPO_ROOT, "Dockerfile"), "utf8")).toBe(sourceDockerfile); + expect( + fs.readFileSync(path.join(REPO_ROOT, "nemoclaw-blueprint", "blueprint.yaml"), "utf8"), + ).toBe(sourceBlueprint); + }); +}); diff --git a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts b/test/e2e/support/rebuild-openclaw-old-base-context.test.ts deleted file mode 100644 index 7b74f4e63b5..00000000000 --- a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts +++ /dev/null @@ -1,248 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; - -import { - createOldBaseBuildContext, - directDockerfileBaseCopySources, - dockerignoreSecretPatterns, -} from "../live/rebuild-openclaw-old-base-context.ts"; - -const copiedContexts: string[] = []; -const testFiles: string[] = []; -const MULTILINE_COPY_SOURCES = [ - "agents/openclaw/openclaw-runtime/package-lock.json", - "agents/openclaw/mcporter-runtime/package-lock.json", - "scripts/lib/reviewed-npm-audit.mts", - "scripts/lib/openclaw-npm-remediation.mts", -]; - -describe("rebuild-openclaw old-base build context", () => { - afterEach(() => { - for (const contextPath of copiedContexts.splice(0)) { - fs.rmSync(contextPath, { recursive: true, force: true }); - } - for (const filePath of testFiles.splice(0)) { - fs.rmSync(filePath, { recursive: true, force: true }); - } - }); - - it("stages every direct Dockerfile.base COPY dependency", () => { - const buildContext = createOldBaseBuildContext(); - copiedContexts.push(buildContext); - - const stagedSources = directDockerfileBaseCopySources().map((source) => - path.join(buildContext, ...source.split("/")), - ); - - expect(stagedSources).not.toHaveLength(0); - expect(directDockerfileBaseCopySources()).toEqual( - expect.arrayContaining(MULTILINE_COPY_SOURCES), - ); - expect(stagedSources.every((source) => fs.existsSync(source))).toBe(true); - }); - - it("parses direct Dockerfile.base COPY syntax without silently ignoring variants", () => { - const dockerfilePath = path.join( - fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-dockerfile-")), - "Dockerfile.base", - ); - testFiles.push(path.dirname(dockerfilePath)); - fs.writeFileSync( - dockerfilePath, - [ - "FROM base AS build", - "copy scripts/lib/sandbox-rlimits.sh /tmp/lowercase", - "COPY\tnemoclaw-blueprint/blueprint.yaml /tmp/tabbed", - "COPY --chown=sandbox:sandbox \\", - " agents/openclaw/openclaw-runtime/package.json \\", - " agents/openclaw/openclaw-runtime/package-lock.json \\", - " /tmp/openclaw/", - "COPY scripts/lib/reviewed-npm-archive.mts scripts/lib/reviewed-npm-audit.mts /tmp/lib/", - "COPY --from=build \\", - " /tmp/ignored-one \\", - " /tmp/ignored-two \\", - " /tmp/ignored/", - ].join("\r\n"), - "utf8", - ); - - expect(directDockerfileBaseCopySources(dockerfilePath)).toEqual([ - "scripts/lib/sandbox-rlimits.sh", - "nemoclaw-blueprint/blueprint.yaml", - "agents/openclaw/openclaw-runtime/package.json", - "agents/openclaw/openclaw-runtime/package-lock.json", - "scripts/lib/reviewed-npm-archive.mts", - "scripts/lib/reviewed-npm-audit.mts", - ]); - }); - - it("returns every source from a multiline direct COPY instruction", () => { - const dockerfilePath = path.join( - fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-dockerfile-")), - "Dockerfile.base", - ); - testFiles.push(path.dirname(dockerfilePath)); - fs.writeFileSync( - dockerfilePath, - [ - "COPY agents/openclaw/openclaw-runtime/package.json \\", - " agents/openclaw/openclaw-runtime/package-lock.json \\", - " /usr/local/lib/nemoclaw/openclaw-runtime/", - ].join("\n"), - "utf8", - ); - - expect(directDockerfileBaseCopySources(dockerfilePath)).toEqual([ - "agents/openclaw/openclaw-runtime/package.json", - "agents/openclaw/openclaw-runtime/package-lock.json", - ]); - }); - - it.each([ - { - dockerfile: 'COPY ["scripts/lib/sandbox-rlimits.sh", "/tmp/"]', - expectedError: "Unsupported direct Dockerfile.base COPY form at line 1", - }, - { - dockerfile: "COPY < { - const dockerfilePath = path.join( - fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-dockerfile-")), - "Dockerfile.base", - ); - testFiles.push(path.dirname(dockerfilePath)); - fs.writeFileSync(dockerfilePath, dockerfile, "utf8"); - - expect(() => directDockerfileBaseCopySources(dockerfilePath), dockerfile).toThrow( - expectedError, - ); - }, - ); - - it("rejects out-of-context direct Dockerfile.base COPY sources before staging", () => { - const parentRelativeDockerfilePath = path.join( - fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-dockerfile-")), - "Dockerfile.base", - ); - const absoluteDockerfilePath = path.join( - fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-dockerfile-")), - "Dockerfile.base", - ); - testFiles.push( - path.dirname(parentRelativeDockerfilePath), - path.dirname(absoluteDockerfilePath), - ); - fs.writeFileSync(parentRelativeDockerfilePath, "COPY ../outside /tmp/outside\n", "utf8"); - fs.writeFileSync( - absoluteDockerfilePath, - ["COPY scripts/lib/sandbox-rlimits.sh \\", " /etc/passwd \\", " /tmp/passwd"].join("\n"), - "utf8", - ); - - expect(() => directDockerfileBaseCopySources(parentRelativeDockerfilePath)).toThrow( - "Unsupported direct Dockerfile.base COPY source", - ); - expect(() => directDockerfileBaseCopySources(absoluteDockerfilePath)).toThrow( - "Unsupported direct Dockerfile.base COPY source", - ); - }); - - it("rejects every current .dockerignore secret COPY pattern before staging", () => { - const representativeSourceByPattern = new Map([ - [".env", ".env"], - [".env.*", ".env.prod"], - [".envrc", ".envrc"], - [".npmrc", ".npmrc"], - [".netrc", ".netrc"], - [".pypirc", ".pypirc"], - [".direnv/", ".direnv/config"], - [".ssh/", ".ssh/id_rsa.pub"], - ["secrets/", "secrets/token.json"], - [".credentials", ".credentials"], - ["*.key", "private.key"], - ["*.pem", "private.pem"], - ["*.pfx", "private.pfx"], - ["*.p12", "private.p12"], - ["*.jks", "private.jks"], - ["*.keystore", "private.keystore"], - ["*.tfvars", "terraform.tfvars"], - ["*_ecdsa", "id_ecdsa"], - ["*_ed25519", "id_ed25519"], - ["*_rsa", "id_rsa"], - ["credentials.json", "credentials.json"], - ["key.json", "key.json"], - ["secrets.json", "secrets.json"], - ["secrets.yaml", "secrets.yaml"], - ["service-account*.json", "service-account-prod.json"], - ["token.json", "token.json"], - ]); - - const securityPatterns = dockerignoreSecretPatterns(); - expect(securityPatterns).not.toHaveLength(0); - expect(securityPatterns).toEqual([...representativeSourceByPattern.keys()]); - - securityPatterns.forEach((pattern) => { - const dockerfilePath = path.join( - fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-dockerfile-")), - "Dockerfile.base", - ); - testFiles.push(path.dirname(dockerfilePath)); - const source = representativeSourceByPattern.get(pattern); - expect( - source, - `missing representative source for .dockerignore pattern ${pattern}`, - ).toBeDefined(); - fs.writeFileSync(dockerfilePath, `COPY ${source} /tmp/secret\n`, "utf8"); - - expect( - () => directDockerfileBaseCopySources(dockerfilePath), - `.dockerignore pattern ${pattern} should reject representative source ${source}`, - ).toThrow("Unsupported .dockerignore-secret Dockerfile.base COPY source"); - }); - }); -}); diff --git a/test/helpers/rebuild-dcode-flow-helpers.ts b/test/helpers/rebuild-dcode-flow-helpers.ts index 77891a20370..2bc257ec8df 100644 --- a/test/helpers/rebuild-dcode-flow-helpers.ts +++ b/test/helpers/rebuild-dcode-flow-helpers.ts @@ -5,9 +5,11 @@ import { expect } from "vitest"; import { expectNoSandboxDelete } from "./rebuild-delete-assertions"; import type { RebuildFlowHarness } from "./rebuild-flow-dcode-harness"; +import { managedSandboxEntry } from "./managed-policy-receipt-fixture"; export function makeDcodeSandboxEntry(): Record { return { + ...managedSandboxEntry("alpha", "langchain-deepagents-code"), name: "alpha", agent: "langchain-deepagents-code", agentVersion: "0.1.12", diff --git a/test/helpers/rebuild-flow-dcode-harness.ts b/test/helpers/rebuild-flow-dcode-harness.ts index c1097ac7e13..78e839b4a74 100644 --- a/test/helpers/rebuild-flow-dcode-harness.ts +++ b/test/helpers/rebuild-flow-dcode-harness.ts @@ -2,9 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 import { type MockInstance, vi } from "vitest"; +import type { SandboxPolicyAuthorityInspection } from "../../src/lib/adapters/openshell/policy-authority"; import type { GatewayRestartResult } from "../../src/lib/actions/sandbox/gateway-restart"; import type { OpenShellSandboxInventory } from "../../src/lib/adapters/openshell/sandbox-observer"; import { makePreparedRecoveryManifest } from "../../src/lib/actions/sandbox/rebuild-flow-test-fixtures"; +import { managedPolicyInspection } from "./managed-policy-receipt-fixture"; import { agentDefs, agentOnboard, @@ -26,6 +28,7 @@ import { onboardCredentialEnv, onboardSession, openshellRuntime, + policyAuthority, policies, processRecovery, purgeRebuildModule, @@ -43,12 +46,14 @@ import { registryPersistence, resolve, sandboxList, + sandboxRecreateProbe, sandboxSession, sandboxState, sandboxVersion, shields, snapshotEnv, sourceSandboxGateway, + withManagedRebuildPolicyReceipt, } from "./rebuild-flow-harness"; export { installRebuildFlowTestHooks } from "./rebuild-flow-harness"; @@ -93,6 +98,7 @@ export type RebuildFlowOverrides = { }; buildMessagingRebuildPlan?: () => Promise | unknown; sandboxEntry?: Record; + policyAuthorityInspection?: SandboxPolicyAuthorityInspection; sandboxEntryReads?: Array | null>; sessionSandboxName?: string; sandboxInventory?: OpenShellSandboxInventory; @@ -147,6 +153,8 @@ export type RebuildFlowHarness = { checkAndRecoverSandboxProcessesSpy: MockInstance; restartSandboxGatewaySpy: MockInstance; ensureMessagingHostForwardAfterRebuildSpy: MockInstance; + inspectGlobalPolicyAuthoritySpy: MockInstance; + inspectSandboxPolicyAuthoritySpy: MockInstance; logSpy: MockInstance; finalizeIncompleteOnboardStepSpy: MockInstance; openShieldsSpy: MockInstance; @@ -345,7 +353,7 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): .mockImplementation(() => undefined); const finalizeIncompleteOnboardStepSpy = installTerminalStepFailureMock(onboardSession, session); session.sandboxName = overrides.sessionSandboxName ?? session.sandboxName; - const sandboxEntry = { + const sandboxEntry = withManagedRebuildPolicyReceipt({ name: "alpha", provider: "ollama-local", model: "nvidia/nemotron", @@ -356,18 +364,62 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): // Tests that exercise the legacy ambiguous-image path override this explicitly. nemoclawVersion: "0.0.71", nimContainer: null, + policyAuthority: "nemoclaw-managed" as const, ...(overrides.sandboxEntry ?? {}), - }; + }); + const recordedPolicyAuthority = (sandboxEntry as Record).policyAuthority; + const policyAuthorityInspection = + overrides.policyAuthorityInspection ?? + (recordedPolicyAuthority === "externally-managed" + ? ({ + authority: "externally-managed", + effectivePolicy: {}, + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + } as const) + : managedPolicyInspection()); + const inspectGlobalPolicyAuthoritySpy = vi + .spyOn(policyAuthority, "inspectActiveGlobalPolicy") + .mockReturnValue( + policyAuthorityInspection.authority === "externally-managed" + ? { state: "active", inspection: policyAuthorityInspection } + : { state: "absent" }, + ); + const inspectSandboxPolicyAuthoritySpy = vi + .spyOn(policyAuthority, "inspectSandboxPolicyAuthority") + .mockReturnValue(policyAuthorityInspection); + vi.spyOn(policyAuthority, "assertOpenShellGatewayPortBinding").mockImplementation( + () => undefined, + ); + vi.spyOn(policyAuthority, "inspectOpenShellSandboxIdentityFingerprint").mockImplementation( + () => + String((sandboxEntry as Record).lifecycleLiveIdentityFingerprint ?? ""), + ); + vi.spyOn(sandboxRecreateProbe, "observeSandboxPresenceOnGateway").mockReturnValue( + overrides.sandboxInventory?.sandboxes.length === 0 || + overrides.reconciledSandboxGatewayState?.state === "missing" + ? "missing" + : "present", + ); const preDeleteDefaultSandbox = overrides.preDeleteDefaultSandbox === undefined ? "alpha" : overrides.preDeleteDefaultSandbox; let sandboxEntryReadCount = 0; vi.spyOn(registry, "getSandbox").mockImplementation(() => { const configuredReads = overrides.sandboxEntryReads ?? []; - return ( + const configured = sandboxEntryReadCount < configuredReads.length ? configuredReads[sandboxEntryReadCount++] - : sandboxEntry - ) as never; + : sandboxEntry; + const persistedPolicyAuthority = ( + sandboxEntry as typeof sandboxEntry & { policyAuthority?: unknown } + ).policyAuthority; + if ( + configured && + !("policyAuthority" in configured) && + persistedPolicyAuthority !== undefined + ) { + return { ...configured, policyAuthority: persistedPolicyAuthority } as never; + } + return configured as never; }); let registryLoadCount = 0; vi.spyOn(registryPersistence, "load").mockImplementation(() => { @@ -384,7 +436,12 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): }; }); vi.spyOn(registry, "listSandboxes").mockReturnValue({ sandboxes: [] }); - const registryUpdateSpy = vi.spyOn(registry, "updateSandbox").mockReturnValue(true); + const registryUpdateSpy = vi + .spyOn(registry, "updateSandbox") + .mockImplementation((_name, updates) => { + Object.assign(sandboxEntry, updates); + return true; + }); vi.spyOn(rebuildRoutePreflight, "commitRebuildRoutePreflight").mockImplementation( (...args: unknown[]) => { const input = args[0] as { @@ -525,7 +582,10 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): } const probedGateway = sourceSandboxGateway(argv, "get"); const liveSource = "Name: alpha\nId: sbx-alpha-source\nPhase: Ready\n"; - return probedGateway && !deletedSourceGateways.has(probedGateway) + const sourceInitiallyMissing = + overrides.sandboxInventory?.sandboxes.length === 0 || + overrides.reconciledSandboxGatewayState?.state === "missing"; + return probedGateway && !sourceInitiallyMissing && !deletedSourceGateways.has(probedGateway) ? { status: 0, output: liveSource, stdout: liveSource, stderr: "" } : { status: 1, @@ -759,6 +819,8 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): checkAndRecoverSandboxProcessesSpy, restartSandboxGatewaySpy, ensureMessagingHostForwardAfterRebuildSpy, + inspectGlobalPolicyAuthoritySpy, + inspectSandboxPolicyAuthoritySpy, logSpy, finalizeIncompleteOnboardStepSpy, openShieldsSpy, diff --git a/test/helpers/rebuild-flow-generic-harness.ts b/test/helpers/rebuild-flow-generic-harness.ts index b68923d638a..adae440a18d 100644 --- a/test/helpers/rebuild-flow-generic-harness.ts +++ b/test/helpers/rebuild-flow-generic-harness.ts @@ -6,6 +6,7 @@ import path from "node:path"; import { vi } from "vitest"; import { makePreparedRecoveryManifest } from "../../src/lib/actions/sandbox/rebuild-flow-test-fixtures"; import type { RebuildRecreateOnboardOpts } from "../../src/lib/actions/sandbox/rebuild-gpu-opt-out"; +import { managedPolicyInspection } from "./managed-policy-receipt-fixture"; import { agentDefs, agentRuntime, @@ -27,6 +28,7 @@ import { onboardCredentialEnv, onboardSession, openshellRuntime, + policyAuthority, policies, processRecovery, purgeRebuildModule, @@ -43,11 +45,13 @@ import { registryPersistence, resolve, sandboxList, + sandboxRecreateProbe, sandboxSession, sandboxState, sandboxVersion, shields, sourceSandboxGateway, + withManagedRebuildPolicyReceipt, } from "./rebuild-flow-harness"; export { @@ -246,7 +250,7 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): const customOpenClawPluginProvenance = modelsCustomOpenClawImage ? { openclawImagePluginInstalls: [] } : {}; - const currentSandboxEntry = { + const currentSandboxEntry = withManagedRebuildPolicyReceipt({ name: "alpha", provider: "ollama-local", model: "nvidia/nemotron", @@ -258,9 +262,45 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): dashboardPort: 18789, gatewayName: "nemoclaw", gatewayPort: 8080, + policyAuthority: "nemoclaw-managed" as const, ...customOpenClawPluginProvenance, ...(overrides.sandboxEntry ?? {}), - }; + }); + const recordedPolicyAuthority = (currentSandboxEntry as Record) + .policyAuthority; + const policyAuthorityInspection = + overrides.policyAuthorityInspection ?? + (recordedPolicyAuthority === "externally-managed" + ? ({ + authority: "externally-managed", + effectivePolicy: {}, + policyIdentity: { hash: "external-policy", activeVersion: 1 }, + } as const) + : managedPolicyInspection()); + const inspectGlobalPolicyAuthoritySpy = vi + .spyOn(policyAuthority, "inspectActiveGlobalPolicy") + .mockReturnValue( + policyAuthorityInspection.authority === "externally-managed" + ? { state: "active", inspection: policyAuthorityInspection } + : { state: "absent" }, + ); + const inspectSandboxPolicyAuthoritySpy = vi + .spyOn(policyAuthority, "inspectSandboxPolicyAuthority") + .mockReturnValue(policyAuthorityInspection); + vi.spyOn(policyAuthority, "assertOpenShellGatewayPortBinding").mockImplementation( + () => undefined, + ); + vi.spyOn(policyAuthority, "inspectOpenShellSandboxIdentityFingerprint").mockImplementation( + () => + String( + (currentSandboxEntry as Record).lifecycleLiveIdentityFingerprint ?? "", + ), + ); + vi.spyOn(sandboxRecreateProbe, "observeSandboxPresenceOnGateway").mockReturnValue( + overrides.staleRecovery || overrides.sandboxInventory?.sandboxes.length === 0 + ? "missing" + : "present", + ); const readCurrentSandboxEntry = () => structuredClone(currentSandboxEntry); vi.spyOn(registry, "getSandbox").mockImplementation(readCurrentSandboxEntry); const initialDefaultSandbox = overrides.defaultSandbox ?? null; @@ -400,7 +440,9 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): } ); }); - vi.spyOn(rebuildShields, "openRebuildShieldsWindow").mockReturnValue(rebuildShieldsWindow); + const openRebuildShieldsWindowSpy = vi + .spyOn(rebuildShields, "openRebuildShieldsWindow") + .mockReturnValue(rebuildShieldsWindow); const relockSpy = vi .spyOn(rebuildShields, "relockRebuildShieldsWindow") .mockImplementation((...args: unknown[]) => { @@ -678,9 +720,12 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): ensureTargetGatewaySpy, ensureValidatedBraveSearchCredentialSpy, hydrateCredentialEnvSpy, + inspectGlobalPolicyAuthoritySpy, + inspectSandboxPolicyAuthoritySpy, logSpy, finalizeIncompleteOnboardStepSpy, onboardSpy, + openRebuildShieldsWindowSpy, registryUpdateSpy, setDefaultSpy, setDefault: (name: string) => registry.setDefault(name), diff --git a/test/helpers/rebuild-flow-harness.ts b/test/helpers/rebuild-flow-harness.ts index 071594096bc..b630739b358 100644 --- a/test/helpers/rebuild-flow-harness.ts +++ b/test/helpers/rebuild-flow-harness.ts @@ -45,6 +45,7 @@ export const nim = requireDist("../../inference/nim.js"); export const onboardCredentialEnv = requireDist("../../onboard/credential-env.js"); export const onboardSession = requireDist("../../state/onboard-session.js"); export const openshellRuntime = requireDist("../../adapters/openshell/runtime.js"); +export const policyAuthority = requireDist("../../adapters/openshell/policy-authority.js"); export const policies = requireDist("../../policy/index.js"); export const portableAgentLifecycle = requireDist( "../../onboard/experimental/portable-agent-lifecycle.js", @@ -64,6 +65,7 @@ export const registry = requireDist("../../state/registry.js"); export const registryPersistence = requireDist("../../state/registry/persistence.js"); export const resolve = requireDist("../../adapters/openshell/resolve.js"); export const sandboxList = requireDist("../../openshell-sandbox-list.js"); +export const sandboxRecreateProbe = requireDist("../../onboard/sandbox-recreate-probe.js"); export const sandboxSession = requireDist("../../state/sandbox-session.js"); export const sandboxState = requireDist("../../state/sandbox.js"); export const sandboxVersion = requireDist("../../sandbox/version.js"); diff --git a/test/helpers/rebuild-flow-test-support.ts b/test/helpers/rebuild-flow-test-support.ts index cab63d41c99..793e8adaf82 100644 --- a/test/helpers/rebuild-flow-test-support.ts +++ b/test/helpers/rebuild-flow-test-support.ts @@ -4,6 +4,7 @@ import { type MockInstance, vi } from "vitest"; import type { GatewayRestartResult } from "../../src/lib/actions/sandbox/gateway-restart"; import type { SandboxGatewayState } from "../../src/lib/actions/sandbox/gateway-state"; +import type { SandboxPolicyAuthorityInspection } from "../../src/lib/adapters/openshell/policy-authority"; import type { OpenShellSandboxInventory } from "../../src/lib/adapters/openshell/sandbox-observer"; import type { finalizePreparedRebuildImageMessagingPlan, @@ -13,6 +14,12 @@ import type { RebuildRecreateOnboardOpts } from "../../src/lib/actions/sandbox/r import type { VersionCheckResult } from "../../src/lib/sandbox/version"; import type { PreservedEnvFile } from "../../src/lib/state/preserved-env"; import type { SandboxRemovalReceipt } from "../../src/lib/state/registry"; +import { + LIFECYCLE_GENERATION, + POLICY_HASH, + POLICY_VERSION, + SANDBOX_IDENTITY, +} from "./managed-policy-receipt-fixture"; export type RebuildSandbox = (typeof import("../../src/lib/actions/sandbox/rebuild"))["rebuildSandbox"]; @@ -75,6 +82,7 @@ export type RebuildFlowOverrides = { agentPolicyAdditionsContent?: string; preflightWithProductionBaselineResolver?: boolean; preflightAuthoritativeRebuildTarget?: (options: Record) => Promise | void; + policyAuthorityInspection?: SandboxPolicyAuthorityInspection; revalidateRebuildRouteBeforeDelete?: ( receipt: Record, ) => { ok: true; receipt: Record } | { ok: false; message: string }; @@ -145,9 +153,12 @@ export type RebuildFlowHarness = { ensureTargetGatewaySpy: MockInstance; ensureValidatedBraveSearchCredentialSpy: MockInstance; hydrateCredentialEnvSpy: MockInstance; + inspectGlobalPolicyAuthoritySpy: MockInstance; + inspectSandboxPolicyAuthoritySpy: MockInstance; logSpy: MockInstance; finalizeIncompleteOnboardStepSpy: MockInstance; onboardSpy: MockInstance; + openRebuildShieldsWindowSpy: MockInstance; registryUpdateSpy: MockInstance; setDefaultSpy: MockInstance; setDefault: (name: string) => boolean; @@ -174,6 +185,44 @@ export type RebuildFlowHarness = { finalizePreparedImageSpy: MockInstance; session: RebuildFlowSession; }; + +export function withManagedRebuildPolicyReceipt>( + entry: T, +): T { + if ( + entry.policyAuthority !== "nemoclaw-managed" || + Object.hasOwn(entry, "policyCreationReceipt") + ) { + return entry; + } + const gatewayName = entry.gatewayName === undefined ? "nemoclaw" : entry.gatewayName; + const gatewayPort = entry.gatewayPort === undefined ? 8080 : entry.gatewayPort; + const lifecycleGeneration = + entry.lifecycleGeneration === undefined ? LIFECYCLE_GENERATION : entry.lifecycleGeneration; + const sandboxIdentityFingerprint = + entry.lifecycleLiveIdentityFingerprint === undefined + ? SANDBOX_IDENTITY + : entry.lifecycleLiveIdentityFingerprint; + return { + ...entry, + gatewayName, + gatewayPort, + lifecycleGeneration, + lifecycleLiveIdentityFingerprint: sandboxIdentityFingerprint, + policyCreationReceipt: { + schemaVersion: 1, + origin: "sandbox-create", + gatewayName, + gatewayPort, + sandboxName: entry.name, + lifecycleGeneration, + sandboxIdentityFingerprint, + policyHash: POLICY_HASH, + policyVersion: POLICY_VERSION, + }, + }; +} + export const originalSandboxName = process.env.NEMOCLAW_SANDBOX_NAME; export function snapshotEnv(names: readonly string[]): () => void { const saved = names.map((name) => [name, process.env[name]] as const); diff --git a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts index 62f2bb837a4..af17df60837 100644 --- a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts +++ b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts @@ -17,6 +17,7 @@ import { createServer } from "node:net"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, it } from "vitest"; +import { managedSandboxEntry } from "../../helpers/managed-policy-receipt-fixture"; import { testTimeout } from "../../helpers/timeouts"; const TIMEOUT_MS = testTimeout(60_000); @@ -66,6 +67,10 @@ let dockerInvocationsFile: string; let gatewayListener: ReturnType | null; function writeDefaultRegistry(gatewayName: string, gatewayPort: number) { + const managedPolicyState = managedSandboxEntry(SANDBOX_NAME, "openclaw", { + gatewayName, + gatewayPort, + }); fs.writeFileSync( path.join(registryDir, "sandboxes.json"), JSON.stringify({ @@ -82,6 +87,10 @@ function writeDefaultRegistry(gatewayName: string, gatewayPort: number) { dashboardPort: 28790, fromDockerfile: null, policies: [], + lifecycleGeneration: managedPolicyState.lifecycleGeneration, + lifecycleLiveIdentityFingerprint: managedPolicyState.lifecycleLiveIdentityFingerprint, + policyAuthority: managedPolicyState.policyAuthority, + policyCreationReceipt: managedPolicyState.policyCreationReceipt, }, }, }), @@ -155,11 +164,16 @@ if (args[0] === "gateway" && args[1] === "select") { emit(script.gatewaySelect); } -if (args[0] === "sandbox" && args[1] === "get") { +if (args.includes("sandbox") && args.includes("get")) { // Use a separate key so retries after select advance properly. emit(cycle("sandboxGet", script.sandboxGet)); } +if (args[0] === "policy" && args[1] === "list" && args.includes("--global")) { + process.stderr.write("No global policy history found\\n"); + process.exit(0); +} + if (args[0] === "policy" && args[1] === "get") { process.stdout.write("version: 1\\nnetwork_policies:\\n"); process.exit(0); @@ -354,140 +368,144 @@ afterEach(async () => { // at "Cannot back up state", and (c) reports the stale state and proceeds to // recreate from the preserved registry metadata instead of aborting. describe("connect preserves the registry so rebuild can recover in scenario 14 (#4497)", () => { - it("after a non-destructive connect, `rebuild --yes` recovers the stale sandbox", { - timeout: TIMEOUT_MS, - }, async () => { - gatewayListener = createServer(); - await new Promise((resolve, reject) => { - gatewayListener?.once("error", reject); - gatewayListener?.listen(0, "127.0.0.1", resolve); - }); - const gatewayAddress = gatewayListener.address(); - assert.ok(gatewayAddress && typeof gatewayAddress !== "string"); - const gatewayPort = gatewayAddress.port; - const gatewayName = `nemoclaw-${gatewayPort}`; - writeDefaultRegistry(gatewayName, gatewayPort); - writeDefaultSession(gatewayName); - writeDockerStub(gatewayName, gatewayPort); - writeStubOpenshell({ - sandboxGet: [{ output: SANDBOX_GET_NOT_FOUND, exit: 1 }], - status: [{ output: statusConnectedNemoclaw(gatewayName, gatewayPort), exit: 0 }], - gatewayInfo: [{ output: gatewayInfoNemoclaw(gatewayName, gatewayPort), exit: 0 }], - gatewaySelect: { output: "", exit: 0 }, - selectFlipsActive: false, - sandboxList: "", - }); - - // Step 3: routine connect must preserve the registry entry. - const connect = runCli("connect"); - assert.equal(connect.status, 1, `connect expected exit 1, got ${connect.status}`); - assert.equal( - registrySandboxPresent(connect), - true, - `connect must preserve the registry entry, got: ${JSON.stringify(connect.registry)}`, - ); - assert.equal(connect.sessionSandboxName, SANDBOX_NAME, "session must survive connect"); - assert.doesNotMatch(connect.stderr, /Removed stale local registry entry/); - - // Step 4: the previously-suggested rebuild must RECOVER the stale sandbox. - // The live `sandbox list` does not report it, so rebuild enters its - // stale-recovery path: it locates the preserved registry entry, skips the - // impossible backup (instead of dead-ending at "Cannot back up state"), - // and proceeds to recreate from the preserved metadata. - const repoRoot = path.join(import.meta.dirname, "../../.."); - const nodeBinDir = path.dirname(process.execPath); - const rebuild = spawnSync( - process.execPath, - [path.join(repoRoot, "bin", "nemoclaw.js"), SANDBOX_NAME, "rebuild", "--yes"], - { - cwd: repoRoot, - encoding: "utf-8", - timeout: TIMEOUT_MS, - env: { - ...process.env, - HOME: tmpDir, - PATH: `${homeLocalBin}:${nodeBinDir}:/usr/bin:/bin`, - NO_COLOR: "1", - NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", - NEMOCLAW_SKIP_HOST_DNS_PREFLIGHT: "1", - NEMOCLAW_NON_INTERACTIVE: "1", - // The recreate handoff (onboard --resume) fails fast in this stubbed - // HOME — fine: the assertions below target the recovery markers that - // are emitted BEFORE the recreate, proving rebuild crossed the - // backup gate that previously blocked it. - NVIDIA_INFERENCE_API_KEY: "nvapi-test-key-for-rebuild", - NEMOCLAW_PROVIDER_KEY: "", + it( + "after a non-destructive connect, `rebuild --yes` recovers the stale sandbox", + { + timeout: TIMEOUT_MS, + }, + async () => { + gatewayListener = createServer(); + await new Promise((resolve, reject) => { + gatewayListener?.once("error", reject); + gatewayListener?.listen(0, "127.0.0.1", resolve); + }); + const gatewayAddress = gatewayListener.address(); + assert.ok(gatewayAddress && typeof gatewayAddress !== "string"); + const gatewayPort = gatewayAddress.port; + const gatewayName = `nemoclaw-${gatewayPort}`; + writeDefaultRegistry(gatewayName, gatewayPort); + writeDefaultSession(gatewayName); + writeDockerStub(gatewayName, gatewayPort); + writeStubOpenshell({ + sandboxGet: [{ output: SANDBOX_GET_NOT_FOUND, exit: 1 }], + status: [{ output: statusConnectedNemoclaw(gatewayName, gatewayPort), exit: 0 }], + gatewayInfo: [{ output: gatewayInfoNemoclaw(gatewayName, gatewayPort), exit: 0 }], + gatewaySelect: { output: "", exit: 0 }, + selectFlipsActive: false, + sandboxList: "", + }); + + // Step 3: routine connect must preserve the registry entry. + const connect = runCli("connect"); + assert.equal(connect.status, 1, `connect expected exit 1, got ${connect.status}`); + assert.equal( + registrySandboxPresent(connect), + true, + `connect must preserve the registry entry, got: ${JSON.stringify(connect.registry)}`, + ); + assert.equal(connect.sessionSandboxName, SANDBOX_NAME, "session must survive connect"); + assert.doesNotMatch(connect.stderr, /Removed stale local registry entry/); + + // Step 4: the previously-suggested rebuild must RECOVER the stale sandbox. + // The live `sandbox list` does not report it, so rebuild enters its + // stale-recovery path: it locates the preserved registry entry, skips the + // impossible backup (instead of dead-ending at "Cannot back up state"), + // and proceeds to recreate from the preserved metadata. + const repoRoot = path.join(import.meta.dirname, "../../.."); + const nodeBinDir = path.dirname(process.execPath); + const rebuild = spawnSync( + process.execPath, + [path.join(repoRoot, "bin", "nemoclaw.js"), SANDBOX_NAME, "rebuild", "--yes"], + { + cwd: repoRoot, + encoding: "utf-8", + timeout: TIMEOUT_MS, + env: { + ...process.env, + HOME: tmpDir, + PATH: `${homeLocalBin}:${nodeBinDir}:/usr/bin:/bin`, + NO_COLOR: "1", + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", + NEMOCLAW_SKIP_HOST_DNS_PREFLIGHT: "1", + NEMOCLAW_NON_INTERACTIVE: "1", + // The recreate handoff (onboard --resume) fails fast in this stubbed + // HOME — fine: the assertions below target the recovery markers that + // are emitted BEFORE the recreate, proving rebuild crossed the + // backup gate that previously blocked it. + NVIDIA_INFERENCE_API_KEY: "nvapi-test-key-for-rebuild", + NEMOCLAW_PROVIDER_KEY: "", + }, }, - }, - ); - const rebuildOut = `${rebuild.stdout || ""}\n${rebuild.stderr || ""}`; - const installerInvocations = fs - .readFileSync(installerInvocationsFile, "utf8") - .split("\n") - .filter(Boolean); - const dockerInvocations = fs - .readFileSync(dockerInvocationsFile, "utf8") - .split("\n") - .filter(Boolean); - - assert.equal( - installerInvocations.length, - 0, - `rebuild must not invoke the OpenShell installer, got ${installerInvocations.length} invocation(s)`, - ); - assert.doesNotMatch( - rebuildOut, - /below minimum required version|Installing OpenShell/, - `rebuild must use the fixture OpenShell binaries, got:\n${rebuildOut}`, - ); - assert.doesNotMatch( - rebuildOut, - /below minimum.*upgrading|missing provider credential rewrite or MCP L7 policy support.*reinstalling/i, - `rebuild must not enter the OpenShell upgrade or repair path, got:\n${rebuildOut}`, - ); - assert.doesNotMatch( - rebuildOut, - /Installing OpenShell from release/, - `rebuild must not enter the OpenShell install path, got:\n${rebuildOut}`, - ); - assert.doesNotMatch( - rebuildOut, - /does not exist/, - `rebuild must locate the preserved sandbox, got:\n${rebuildOut}`, - ); - // The reopened-issue dead-end must be gone. - assert.doesNotMatch( - rebuildOut, - /Cannot back up state/, - `rebuild must not dead-end on the stale sandbox (#4497), got:\n${rebuildOut}`, - ); - assert.match( - rebuildOut, - new RegExp(`Rebuild sandbox '${SANDBOX_NAME}'`), - `rebuild must enter the rebuild flow, got:\n${rebuildOut}`, - ); - // It must recognize the stale state and skip the impossible backup. - assert.match( - rebuildOut, - /absent from the live OpenShell gateway/, - `rebuild must report the stale-recovery state (#4497), got:\n${rebuildOut}\nDocker invocations:\n${dockerInvocations.join("\n")}`, - ); - assert.match( - rebuildOut, - /No live workspace state to back up/, - `rebuild must skip backup on stale recovery (#4497), got:\n${rebuildOut}`, - ); - assert.doesNotMatch( - rebuildOut, - /Backing up sandbox state/, - `rebuild must not attempt backup on a stale sandbox (#4497), got:\n${rebuildOut}`, - ); - // And it must proceed to recreate from the preserved metadata — this line - // is printed right before the onboard --resume handoff. - assert.match( - rebuildOut, - /Creating new sandbox with current image/, - `rebuild must proceed to recreate the sandbox (#4497), got:\n${rebuildOut}`, - ); - }); + ); + const rebuildOut = `${rebuild.stdout || ""}\n${rebuild.stderr || ""}`; + const installerInvocations = fs + .readFileSync(installerInvocationsFile, "utf8") + .split("\n") + .filter(Boolean); + const dockerInvocations = fs + .readFileSync(dockerInvocationsFile, "utf8") + .split("\n") + .filter(Boolean); + + assert.equal( + installerInvocations.length, + 0, + `rebuild must not invoke the OpenShell installer, got ${installerInvocations.length} invocation(s)`, + ); + assert.doesNotMatch( + rebuildOut, + /below minimum required version|Installing OpenShell/, + `rebuild must use the fixture OpenShell binaries, got:\n${rebuildOut}`, + ); + assert.doesNotMatch( + rebuildOut, + /below minimum.*upgrading|missing provider credential rewrite or MCP L7 policy support.*reinstalling/i, + `rebuild must not enter the OpenShell upgrade or repair path, got:\n${rebuildOut}`, + ); + assert.doesNotMatch( + rebuildOut, + /Installing OpenShell from release/, + `rebuild must not enter the OpenShell install path, got:\n${rebuildOut}`, + ); + assert.doesNotMatch( + rebuildOut, + /does not exist/, + `rebuild must locate the preserved sandbox, got:\n${rebuildOut}`, + ); + // The reopened-issue dead-end must be gone. + assert.doesNotMatch( + rebuildOut, + /Cannot back up state/, + `rebuild must not dead-end on the stale sandbox (#4497), got:\n${rebuildOut}`, + ); + assert.match( + rebuildOut, + new RegExp(`Rebuild sandbox '${SANDBOX_NAME}'`), + `rebuild must enter the rebuild flow, got:\n${rebuildOut}`, + ); + // It must recognize the stale state and skip the impossible backup. + assert.match( + rebuildOut, + /absent from the live OpenShell gateway/, + `rebuild must report the stale-recovery state (#4497), got:\n${rebuildOut}\nDocker invocations:\n${dockerInvocations.join("\n")}`, + ); + assert.match( + rebuildOut, + /No live workspace state to back up/, + `rebuild must skip backup on stale recovery (#4497), got:\n${rebuildOut}`, + ); + assert.doesNotMatch( + rebuildOut, + /Backing up sandbox state/, + `rebuild must not attempt backup on a stale sandbox (#4497), got:\n${rebuildOut}`, + ); + // And it must proceed to recreate from the preserved metadata — this line + // is printed right before the onboard --resume handoff. + assert.match( + rebuildOut, + /Creating new sandbox with current image/, + `rebuild must proceed to recreate the sandbox (#4497), got:\n${rebuildOut}`, + ); + }, + ); }); diff --git a/test/runtime/messaging/rebuild-messaging-conflict-preflight.test.ts b/test/runtime/messaging/rebuild-messaging-conflict-preflight.test.ts index 0d05dee21c2..5fd287377be 100644 --- a/test/runtime/messaging/rebuild-messaging-conflict-preflight.test.ts +++ b/test/runtime/messaging/rebuild-messaging-conflict-preflight.test.ts @@ -13,6 +13,11 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { + managedPolicyMetadata, + managedSandboxEntry, + SANDBOX_ID, +} from "../../helpers/managed-policy-receipt-fixture"; const REPO_ROOT = path.join(import.meta.dirname, "../../.."); const NODE_BIN = path.dirname(process.execPath); @@ -116,20 +121,30 @@ function createConflictFixture() { const nemoclawDir = path.join(tmpDir, ".nemoclaw"); fs.mkdirSync(nemoclawDir, { recursive: true, mode: 0o700 }); - const sandboxEntry = (name: string) => ({ - name, - model: "meta/llama-3.3-70b-instruct", - provider: "nvidia-prod", - gpuEnabled: false, - sandboxGpuMode: "0", - gatewayName: "nemoclaw", - gatewayPort: 8080, - dashboardPort: 18789, - fromDockerfile: null, - policies: [], - agent: null, - messaging: { schemaVersion: 1, plan: teamsPlan(name, "shared-teams-hash") }, - }); + const sandboxEntry = (name: string) => { + const managedPolicyState = managedSandboxEntry(name, "openclaw", { + gatewayName: "nemoclaw", + gatewayPort: 8080, + }); + return { + name, + model: "meta/llama-3.3-70b-instruct", + provider: "nvidia-prod", + gpuEnabled: false, + sandboxGpuMode: "0", + gatewayName: "nemoclaw", + gatewayPort: 8080, + dashboardPort: 18789, + fromDockerfile: null, + policies: [], + lifecycleGeneration: managedPolicyState.lifecycleGeneration, + lifecycleLiveIdentityFingerprint: managedPolicyState.lifecycleLiveIdentityFingerprint, + policyAuthority: managedPolicyState.policyAuthority, + policyCreationReceipt: managedPolicyState.policyCreationReceipt, + agent: null, + messaging: { schemaVersion: 1, plan: teamsPlan(name, "shared-teams-hash") }, + }; + }; fs.writeFileSync( path.join(nemoclawDir, "sandboxes.json"), @@ -163,10 +178,19 @@ function createConflictFixture() { `#!/usr/bin/env node const a = process.argv.slice(2); if (a[0]==="sandbox" && a[1]==="list") { process.stdout.write("my-assistant\\n"); process.exit(0); } +if (a.includes("sandbox") && a.includes("get")) { process.stdout.write("Name: " + a.at(-1) + "\\nId: ${SANDBOX_ID}\\nPhase: Ready\\n"); process.exit(0); } if (a[0]==="sandbox" && a[1]==="ssh-config") { process.stdout.write("${sshConfig}\\n"); process.exit(0); } +if (a[0]==="policy" && a[1]==="list" && a.includes("--global")) { + process.stderr.write("No global policy history found\\n"); + process.exit(0); +} +if (a[0]==="policy" && a[1]==="get" && a.includes("--output") && a.includes("json")) { + process.stdout.write(${JSON.stringify(managedPolicyMetadata("my-assistant"))} + "\\n"); + process.exit(0); +} if (a[0]==="sandbox" && a[1]==="delete") { process.exit(0); } if (a[0]==="status") { process.stdout.write("Status: Connected\\nGateway: nemoclaw\\n"); process.exit(0); } -if (a[0]==="gateway" && a[1]==="info") { process.stdout.write("Gateway: nemoclaw\\n"); process.exit(0); } +if (a[0]==="gateway" && a[1]==="info") { process.stdout.write("Gateway: nemoclaw\\nGateway endpoint: https://127.0.0.1:8080/\\n"); process.exit(0); } if (a[0]==="gateway" && a[1]==="select") { process.exit(0); } if (a[0]==="inference" && a[1]==="get") { process.stdout.write('{"provider":"nvidia-prod","model":"meta/llama-3.3-70b-instruct"}\\n'); process.exit(0); } if (a[0]==="inference") { process.exit(0); } @@ -234,22 +258,26 @@ function registryHasSandbox(nemoclawDir: string, name: string): boolean { } describe("rebuild messaging credential conflict preflight (#5954)", () => { - it("aborts BEFORE backup/delete when another sandbox shares the Teams credential", { - timeout: 90_000, - }, () => { - const f = createConflictFixture(); - const result = runRebuild(f.tmpDir); - const output = `${result.stderr || ""}${result.stdout || ""}`; - - // Aborted, with the actionable conflict explanation. - expect(result.status).not.toBe(0); - expect(output).toContain("uses the same teams credential"); - expect(output).toContain("Aborting"); - - // Nothing destructive ran: the sandbox is untouched and still registered. - expect(output).not.toContain("Backing up sandbox state"); - expect(output).not.toContain("Old sandbox deleted"); - expect(output).not.toContain("must not run before the conflict preflight"); - expect(registryHasSandbox(f.nemoclawDir, "my-assistant")).toBe(true); - }); + it( + "aborts BEFORE backup/delete when another sandbox shares the Teams credential", + { + timeout: 90_000, + }, + () => { + const f = createConflictFixture(); + const result = runRebuild(f.tmpDir); + const output = `${result.stderr || ""}${result.stdout || ""}`; + + // Aborted, with the actionable conflict explanation. + expect(result.status).not.toBe(0); + expect(output).toContain("uses the same teams credential"); + expect(output).toContain("Aborting"); + + // Nothing destructive ran: the sandbox is untouched and still registered. + expect(output).not.toContain("Backing up sandbox state"); + expect(output).not.toContain("Old sandbox deleted"); + expect(output).not.toContain("must not run before the conflict preflight"); + expect(registryHasSandbox(f.nemoclawDir, "my-assistant")).toBe(true); + }, + ); }); diff --git a/test/runtime/policy/policy-mutation-read-failure.test.ts b/test/runtime/policy/policy-mutation-read-failure.test.ts index 81560f7761a..db8ef24155f 100644 --- a/test/runtime/policy/policy-mutation-read-failure.test.ts +++ b/test/runtime/policy/policy-mutation-read-failure.test.ts @@ -16,13 +16,12 @@ import { const requireForTest = createRequire(import.meta.url); const policies = requireForTest( - path.join(import.meta.dirname, "..", "../..", "src", "lib", "policy", "index.ts"), + path.join(import.meta.dirname, "../../..", "src", "lib", "policy", "index.ts"), ) as typeof import("../../../src/lib/policy"); const policyAuthority = requireForTest( path.join( import.meta.dirname, - "..", - "../..", + "../../..", "src", "lib", "adapters", @@ -31,7 +30,7 @@ const policyAuthority = requireForTest( ), ) as typeof import("../../../src/lib/adapters/openshell/policy-authority"); const registry = requireForTest( - path.join(import.meta.dirname, "..", "../..", "src", "lib", "state", "registry.ts"), + path.join(import.meta.dirname, "../../..", "src", "lib", "state", "registry.ts"), ) as typeof import("../../../src/lib/state/registry"); const CUSTOM_PRESET = "network_policies:\n example:\n host: example.com\n"; const MALFORMED_BASE_POLICIES = [ diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index eccefc8d086..d02a51b8a09 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1229,7 +1229,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ restoreCli: true, exposeCliBin: true, owningPaths: [ - "test/e2e/live/rebuild-openclaw-old-base-context.ts", + "test/e2e/live/rebuild-openclaw-legacy-context.ts", "src/lib/core/shell-quote.ts", ], environment: hostedInference,