From dfa9376b097e94a3730f23c92c36da10e69a64c2 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 17:48:15 -0700 Subject: [PATCH 01/40] fix(policy): enforce external policy authority --- .../checks/openshell-policy-mutation-read.mts | 18 +- .../openshell/policy-authority.test.ts | 368 ++++++++++++++ .../adapters/openshell/policy-authority.ts | 373 ++++++++++++++ src/lib/policy/README.md | 21 + ...line-exclusion-journal-integration.test.ts | 11 + .../baseline-exclusion-persistence.test.ts | 103 +++- src/lib/policy/commands.ts | 42 ++ src/lib/policy/context-builder.ts | 75 ++- src/lib/policy/context.test.ts | 210 +++++--- src/lib/policy/index.ts | 464 +++++++++++++++--- src/lib/policy/policy-apply-finality.test.ts | 67 ++- .../policy-authority-integration.test.ts | 243 +++++++++ src/lib/policy/policy-registry.ts | 38 ++ src/lib/state/registry-normalization.test.ts | 172 +++++++ src/lib/state/registry-normalization.ts | 50 +- src/lib/state/registry.ts | 80 ++- src/lib/state/registry/persistence.ts | 32 +- src/lib/state/registry/types.ts | 3 + test/policies.test.ts | 92 +++- test/policy-mutation-read-discovery.test.ts | 21 + test/policy-mutation-read-failure.test.ts | 28 +- test/policy-preset-noop-disclosure.test.ts | 12 + test/portable-policy-failure-finality.test.ts | 30 +- 23 files changed, 2302 insertions(+), 251 deletions(-) create mode 100644 src/lib/adapters/openshell/policy-authority.test.ts create mode 100644 src/lib/adapters/openshell/policy-authority.ts create mode 100644 src/lib/policy/policy-authority-integration.test.ts create mode 100644 src/lib/policy/policy-registry.ts diff --git a/scripts/checks/openshell-policy-mutation-read.mts b/scripts/checks/openshell-policy-mutation-read.mts index e1943578549..330d390c216 100644 --- a/scripts/checks/openshell-policy-mutation-read.mts +++ b/scripts/checks/openshell-policy-mutation-read.mts @@ -52,6 +52,10 @@ function unclassifiedBase(site: string): DiscoveredPolicyRead { return { site, view: "base", failureHandling: "unclassified" }; } +function unclassifiedFull(site: string): DiscoveredPolicyRead { + return { site, view: "full", failureHandling: "unclassified" }; +} + function ignoredFull(site: string): DiscoveredPolicyRead { return { site, view: "full", failureHandling: "ignore-error" }; } @@ -95,6 +99,10 @@ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ ignoredFull("getSandboxGatewayStateForStatus"), ], }, + { + relativePath: "src/lib/actions/sandbox/launch-readiness.ts", + expectedReads: [unclassifiedFull("captureLivePolicy")], + }, { relativePath: "src/lib/policy/commands.ts", expectedReads: [ @@ -108,6 +116,8 @@ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ view: "full", failureHandling: "unclassified", }, + unclassifiedFull("buildPolicyGetFullJsonCommand"), + unclassifiedFull("buildGlobalPolicyGetFullJsonCommand"), ], }, ] as const; @@ -418,8 +428,12 @@ function directPolicyReadView( ts.isExpression(element) ? literalText(element) : null, ); if (values[offset] !== "policy" || values[offset + 1] !== "get") return null; - if (values[offset + 2] === "--base") return "base"; - if (values[offset + 2] === "--full") return "full"; + const readArguments = values.slice(offset + 2); + const hasBase = readArguments.includes("--base"); + const hasFull = readArguments.includes("--full"); + if (hasBase === hasFull) return null; + if (hasBase) return "base"; + if (hasFull) return "full"; return null; } diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts new file mode 100644 index 00000000000..d5425315de6 --- /dev/null +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -0,0 +1,368 @@ +// 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 openshellResolveModule from "./resolve"; +import { + assertExternalPolicyRequirements, + assertRecordedPolicyAuthority, + inspectGlobalPolicyAuthority, + inspectSandboxPolicyAuthority, + type PolicyAuthorityCapture, + policyAuthorityInternals, + type SandboxPolicyAuthorityInspection, +} from "./policy-authority"; + +function captureResult( + stdout: string, + overrides: Partial<{ + stderr: string; + exitCode: number | null; + timedOut: boolean; + }> = {}, +) { + return { + stdout, + stderr: overrides.stderr ?? "", + exitCode: overrides.exitCode ?? 0, + timedOut: overrides.timedOut ?? false, + }; +} + +function sandboxMetadata(overrides: Record = {}): Record { + return { + scope: "sandbox", + sandbox: "alpha", + status: "effective", + policy_source: "sandbox", + policy: { version: 1, network_policies: { baseline: { endpoints: ["base.test"] } } }, + ...overrides, + }; +} + +function globalMetadata(overrides: Record = {}): Record { + return { + scope: "global", + status: "loaded", + policy: { version: 1, network_policies: { baseline: { endpoints: ["base.test"] } } }, + ...overrides, + }; +} + +function errorFrom(action: () => unknown): Error { + try { + action(); + } catch (error) { + expect(error).toBeInstanceOf(Error); + return error as Error; + } + throw new Error("expected the action to throw"); +} + +describe("OpenShell policy authority inspection", () => { + beforeEach(() => { + vi.restoreAllMocks(); + vi.spyOn(openshellResolveModule, "resolveOpenshell").mockReturnValue(null); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("recognizes a sandbox-scoped effective policy as NemoClaw-managed (#9833)", () => { + const runCaptureEx = vi.fn(() => + captureResult(JSON.stringify(sandboxMetadata())), + ); + + expect(inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx })).toEqual({ + authority: "nemoclaw-managed", + effectivePolicy: { + version: 1, + network_policies: { baseline: { endpoints: ["base.test"] } }, + }, + }); + expect(runCaptureEx).toHaveBeenCalledWith( + ["openshell", "policy", "get", "--full", "--output", "json", "alpha"], + { + maxBuffer: policyAuthorityInternals.captureMaxBytes, + timeout: policyAuthorityInternals.captureTimeoutMs, + }, + ); + }); + + it("recognizes a global policy source as externally managed on the recorded gateway (#9833)", () => { + const policy = { version: 1, network_policies: { required: { endpoints: ["api.test"] } } }; + const runCaptureEx = vi.fn(() => + captureResult(JSON.stringify(sandboxMetadata({ policy_source: "global", policy }))), + ); + + expect( + inspectSandboxPolicyAuthority({ + sandboxName: "alpha", + gatewayName: "nemoclaw-18080", + runCaptureEx, + }), + ).toEqual({ authority: "externally-managed", effectivePolicy: policy }); + expect(runCaptureEx.mock.calls[0]?.[0]).toEqual([ + "openshell", + "policy", + "get", + "-g", + "nemoclaw-18080", + "--full", + "--output", + "json", + "alpha", + ]); + }); + + it("recognizes NemoClaw-managed authority when global history is absent (#9833)", () => { + const runCaptureEx = vi.fn(() => captureResult("")); + + expect(inspectGlobalPolicyAuthority({ runCaptureEx })).toEqual({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); + expect(runCaptureEx.mock.calls[0]?.[0]).toEqual([ + "openshell", + "policy", + "list", + "--global", + "--limit", + "1", + ]); + }); + + it.each([ + [ + "loaded", + globalMetadata({ + policy: { version: 1, network_policies: { required: { endpoints: ["api.test"] } } }, + }), + "externally-managed", + ], + ["superseded", globalMetadata({ status: "superseded", policy: undefined }), "nemoclaw-managed"], + ] as const)("classifies %s global policy metadata (#9833)", (_case, metadata, authority) => { + const runCaptureEx = vi + .fn() + .mockReturnValueOnce(captureResult("policy revision history")) + .mockReturnValueOnce(captureResult(JSON.stringify(metadata))); + + expect(inspectGlobalPolicyAuthority({ gatewayName: "nemoclaw-18080", runCaptureEx })).toEqual({ + authority, + effectivePolicy: authority === "externally-managed" ? metadata.policy : {}, + }); + expect(runCaptureEx.mock.calls.map(([argv]) => argv)).toEqual([ + ["openshell", "policy", "list", "-g", "nemoclaw-18080", "--global", "--limit", "1"], + [ + "openshell", + "policy", + "get", + "-g", + "nemoclaw-18080", + "--global", + "--full", + "--output", + "json", + ], + ]); + }); + + it("rejects invalid sandbox and gateway identities before querying policy (#9833)", () => { + const runCaptureEx = vi.fn(() => + captureResult(JSON.stringify(sandboxMetadata())), + ); + + expect(() => inspectSandboxPolicyAuthority({ sandboxName: "--global", runCaptureEx })).toThrow( + /Invalid sandbox name/, + ); + expect(() => + inspectGlobalPolicyAuthority({ gatewayName: "invalid gateway", runCaptureEx }), + ).toThrow(/Invalid gateway name/); + expect(() => inspectGlobalPolicyAuthority({ gatewayName: "", runCaptureEx })).toThrow( + /gateway name is required/, + ); + expect(runCaptureEx).not.toHaveBeenCalled(); + }); + + it.each([ + ["another scope", sandboxMetadata({ scope: "global" })], + ["another sandbox", sandboxMetadata({ sandbox: "beta" })], + ["an unknown source", sandboxMetadata({ policy_source: "unknown" })], + ])("rejects sandbox metadata with %s (#9833)", (_caseName, metadata) => { + const secret = "captured-policy-secret"; + const runCaptureEx = vi.fn(() => + captureResult(JSON.stringify({ ...metadata, diagnostic: secret })), + ); + + const error = errorFrom(() => + inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx }), + ); + expect(error.message).toContain("inspection failed"); + expect(error.message).not.toContain(secret); + }); + + it.each([ + ["empty", captureResult("")], + ["malformed", captureResult('{"secret":"captured-global-secret"')], + ["another scope", captureResult(JSON.stringify(globalMetadata({ scope: "sandbox" })))], + ["another source", captureResult(JSON.stringify(globalMetadata({ policy_source: "sandbox" })))], + ["a pending status", captureResult(JSON.stringify(globalMetadata({ status: "pending" })))], + ["a failed status", captureResult(JSON.stringify(globalMetadata({ status: "failed" })))], + ])("rejects global policy metadata that is %s (#9833)", (_case, result) => { + const runCaptureEx = vi + .fn() + .mockReturnValueOnce(captureResult("policy revision history")) + .mockReturnValueOnce(result); + + const error = errorFrom(() => inspectGlobalPolicyAuthority({ runCaptureEx })); + expect(error.message).toContain("inspection failed"); + expect(error.message).not.toContain("captured-global-secret"); + }); + + it.each([ + ["a nonzero exit", { exitCode: 7 }], + ["a timeout", { timedOut: true }], + ])( + "fails closed without reading global metadata after history query has %s (#9833)", + (_case, overrides) => { + const runCaptureEx = vi.fn(() => + captureResult("captured-history-secret", { + ...overrides, + stderr: "captured-history-stderr-secret", + }), + ); + + const error = errorFrom(() => inspectGlobalPolicyAuthority({ runCaptureEx })); + expect(error.message).toContain("inspection failed"); + expect(error.message).not.toContain("captured-history-secret"); + expect(error.message).not.toContain("captured-history-stderr-secret"); + expect(runCaptureEx).toHaveBeenCalledOnce(); + }, + ); + + it("recognizes NemoClaw-managed authority when sandbox policy output is empty (#9833)", () => { + const runCaptureEx = vi.fn(() => captureResult("")); + + expect(inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx })).toEqual({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); + }); + + it.each([ + ["a nonzero exit", { exitCode: 7 }], + ["a timeout", { timedOut: true }], + ["malformed JSON", {}], + ])("fails closed without exposing output after %s (#9833)", (_caseName, overrides) => { + const runCaptureEx = vi.fn(() => + captureResult('{"secret":"captured-stdout-secret"', { + ...overrides, + stderr: "captured-stderr-secret", + }), + ); + + const error = errorFrom(() => + inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx }), + ); + expect(error.message).not.toContain("captured-stdout-secret"); + expect(error.message).not.toContain("captured-stderr-secret"); + }); + + it("replaces a thrown capture diagnostic instead of exposing command output (#9833)", () => { + const runCaptureEx = vi.fn(() => { + throw new Error("captured-policy-secret"); + }); + + const error = errorFrom(() => + inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx }), + ); + expect(error.message).toContain("could not run"); + expect(error.message).not.toContain("captured-policy-secret"); + }); + + it("rejects a captured policy response that exceeds the byte limit (#9833)", () => { + const oversized = "x".repeat(policyAuthorityInternals.captureMaxBytes + 1); + const runCaptureEx = vi.fn(() => captureResult(oversized)); + + const error = errorFrom(() => + inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx }), + ); + expect(error.message).toContain("capture limit"); + expect(error.message).not.toContain(oversized.slice(0, 32)); + }); +}); + +describe("recorded policy authority", () => { + it("accepts unchanged authority and refuses missing or changed authority (#9833)", () => { + expect(() => + assertRecordedPolicyAuthority("externally-managed", "externally-managed", "rebuild"), + ).not.toThrow(); + expect(() => + assertRecordedPolicyAuthority(undefined, "externally-managed", "restore the snapshot"), + ).toThrow(/recorded policy authority is unavailable or invalid/); + expect(() => + assertRecordedPolicyAuthority( + "nemoclaw-managed", + "externally-managed", + "restore the snapshot", + ), + ).toThrow(/changed from nemoclaw-managed to externally-managed/); + expect(() => + assertRecordedPolicyAuthority("externally-managed", "unknown", "restore the snapshot"), + ).toThrow(/observed OpenShell policy authority is unavailable or invalid/); + }); +}); + +describe("externally managed policy requirements", () => { + it("compares exact requirements and redacts missing or drifted contents (#9833)", () => { + const requiredPolicy = { + version: 1, + filesystem_policy: { read_only: ["/required-secret"] }, + process: { run_as_user: 1000 }, + network_policies: { + exact: { endpoints: [{ host: "api.test", port: 443 }], mode: "allow" }, + missing: { endpoints: [{ host: "missing-secret.test", port: 443 }] }, + drifted: { endpoints: [{ host: "required-secret.test", port: 443 }] }, + }, + }; + const inspection: SandboxPolicyAuthorityInspection = { + authority: "externally-managed", + effectivePolicy: { + version: 9, + filesystem_policy: { read_only: ["/observed-secret"] }, + network_policies: { + exact: { mode: "allow", endpoints: [{ port: 443, host: "api.test" }] }, + drifted: { endpoints: [{ host: "observed-secret.test", port: 443 }] }, + }, + }, + }; + + const error = errorFrom(() => + assertExternalPolicyRequirements({ + inspection, + requiredPolicy, + operation: "enable messaging", + sandboxName: "alpha", + }), + ); + expect(error.message).toContain('missing sections "process"'); + expect(error.message).toContain('drifted sections "filesystem_policy"'); + expect(error.message).toContain('missing entries "missing"'); + expect(error.message).toContain('drifted entries "drifted"'); + expect(error.message).not.toMatch( + /required-secret|observed-secret|missing-secret\.test|observed-secret\.test/u, + ); + }); + + it("leaves NemoClaw-managed requirements to the mutation path (#9833)", () => { + expect(() => + assertExternalPolicyRequirements({ + inspection: { authority: "nemoclaw-managed", effectivePolicy: {} }, + requiredPolicy: { network_policies: { required: { endpoints: ["api.test"] } } }, + operation: "apply a preset", + }), + ).not.toThrow(); + }); +}); diff --git a/src/lib/adapters/openshell/policy-authority.ts b/src/lib/adapters/openshell/policy-authority.ts new file mode 100644 index 00000000000..fad057dba2c --- /dev/null +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -0,0 +1,373 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isDeepStrictEqual } from "node:util"; + +import { + diagnosticPreview, + isValidName, + NAME_ALLOWED_FORMAT, + NAME_MAX_LENGTH, +} from "../../sandbox-name-contract"; +import { + buildGlobalPolicyGetFullJsonCommand, + buildGlobalPolicyListCommand, + buildPolicyGetFullJsonCommand, +} from "../../policy/commands"; +const POLICY_AUTHORITY_CAPTURE_MAX_BYTES = 1024 * 1024; +const POLICY_AUTHORITY_CAPTURE_TIMEOUT_MS = 30_000; + +type JsonObject = Record; + +export type SandboxPolicyAuthority = "nemoclaw-managed" | "externally-managed"; + +export interface SandboxPolicyAuthorityInspection { + readonly authority: SandboxPolicyAuthority; + readonly effectivePolicy: JsonObject; +} + +const POLICY_AUTHORITY_REFUSAL_CODE = "NEMOCLAW_POLICY_AUTHORITY_REFUSAL"; + +/** A final refusal at the OpenShell policy authority boundary. */ +export class PolicyAuthorityRefusalError extends Error { + readonly code = POLICY_AUTHORITY_REFUSAL_CODE; + + constructor(message: string) { + super(message); + this.name = "PolicyAuthorityRefusalError"; + } +} + +/** Recognize policy-authority refusals across CommonJS and ESM module boundaries. */ +export function isPolicyAuthorityRefusalError(error: unknown): boolean { + return ( + error instanceof PolicyAuthorityRefusalError || + (isObject(error) && error.code === POLICY_AUTHORITY_REFUSAL_CODE) + ); +} + +interface PolicyAuthorityCaptureResult { + readonly stdout: string; + readonly stderr?: string; + readonly exitCode: number | null; + readonly timedOut: boolean; +} + +export type PolicyAuthorityCapture = ( + command: readonly string[], + options?: { readonly maxBuffer?: number; readonly timeout?: number }, +) => PolicyAuthorityCaptureResult; + +interface PolicyAuthorityInspectionOptions { + readonly gatewayName?: string; + readonly runCaptureEx: PolicyAuthorityCapture; +} + +interface SandboxPolicyAuthorityInspectionOptions extends PolicyAuthorityInspectionOptions { + readonly sandboxName: string; +} + +function validatePolicyAuthorityName(name: string, label: string): string { + if (!name || typeof name !== "string") { + throw new PolicyAuthorityRefusalError( + `${label} is required. Allowed format: ${NAME_ALLOWED_FORMAT}.`, + ); + } + if (name.length > NAME_MAX_LENGTH) { + throw new PolicyAuthorityRefusalError( + `${label} too long (max ${NAME_MAX_LENGTH} chars): ${diagnosticPreview(name)}. Allowed format: ${NAME_ALLOWED_FORMAT}.`, + ); + } + if (isValidName(name)) return name; + throw new PolicyAuthorityRefusalError( + `Invalid ${label}: ${diagnosticPreview(name)}. Allowed format: ${NAME_ALLOWED_FORMAT}.`, + ); +} + +function isObject(value: unknown): value is JsonObject { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isPolicyAuthority(value: unknown): value is SandboxPolicyAuthority { + return value === "nemoclaw-managed" || value === "externally-managed"; +} + +function failInspection(subject: "sandbox" | "global", reason: string): never { + throw new PolicyAuthorityRefusalError( + `OpenShell ${subject} policy authority inspection failed: ${reason}. Policy-dependent operations must stop.`, + ); +} + +function capturePolicyQuery( + command: readonly string[], + capture: PolicyAuthorityCapture, + subject: "sandbox" | "global", + queryKind: "machine-readable policy" | "policy history", +): { readonly stdout: string; readonly stderr: string } { + let result: PolicyAuthorityCaptureResult; + try { + result = capture(command, { + maxBuffer: POLICY_AUTHORITY_CAPTURE_MAX_BYTES, + timeout: POLICY_AUTHORITY_CAPTURE_TIMEOUT_MS, + }); + } catch { + failInspection(subject, `the ${queryKind} query could not run`); + } + + if ( + !isObject(result) || + typeof result.stdout !== "string" || + (result.stderr !== undefined && typeof result.stderr !== "string") + ) { + failInspection(subject, `the ${queryKind} query returned an invalid capture result`); + } + const stderr = result.stderr ?? ""; + if ( + Buffer.byteLength(result.stdout, "utf8") + Buffer.byteLength(stderr, "utf8") > + POLICY_AUTHORITY_CAPTURE_MAX_BYTES + ) { + failInspection(subject, `the ${queryKind} response exceeded the capture limit`); + } + if (result.timedOut === true) { + failInspection(subject, `the ${queryKind} query timed out`); + } + if (result.timedOut !== false || result.exitCode !== 0) { + failInspection(subject, `the ${queryKind} query did not complete successfully`); + } + return { stdout: result.stdout, stderr }; +} + +function parsePolicyMetadata(raw: string, subject: "sandbox" | "global"): JsonObject { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + failInspection(subject, "OpenShell returned malformed machine-readable policy metadata"); + } + if (!isObject(parsed)) { + failInspection(subject, "OpenShell returned an invalid policy metadata object"); + } + return parsed; +} + +function policyObject(metadata: JsonObject, subject: "sandbox" | "global"): JsonObject { + if (!isObject(metadata.policy)) { + failInspection(subject, "OpenShell did not return an effective policy object"); + } + return metadata.policy; +} + +/** Inspect the effective policy source for one live sandbox. */ +export function inspectSandboxPolicyAuthority({ + sandboxName, + gatewayName, + runCaptureEx, +}: SandboxPolicyAuthorityInspectionOptions): SandboxPolicyAuthorityInspection { + const validatedSandboxName = validatePolicyAuthorityName(sandboxName, "sandbox name"); + const validatedGatewayName = + gatewayName === undefined + ? undefined + : validatePolicyAuthorityName(gatewayName, "gateway name"); + const { stdout: raw } = capturePolicyQuery( + buildPolicyGetFullJsonCommand(validatedSandboxName, validatedGatewayName), + runCaptureEx, + "sandbox", + "machine-readable policy", + ); + if (raw.trim().length === 0) { + return { authority: "nemoclaw-managed", effectivePolicy: {} }; + } + const metadata = parsePolicyMetadata(raw, "sandbox"); + if (metadata.scope !== "sandbox") { + failInspection("sandbox", "OpenShell returned policy metadata for another scope"); + } + if (metadata.sandbox !== validatedSandboxName) { + failInspection("sandbox", "OpenShell returned policy metadata for another sandbox"); + } + if (metadata.status !== "effective") { + failInspection("sandbox", "OpenShell did not report an effective sandbox policy"); + } + if (metadata.policy_source !== "sandbox" && metadata.policy_source !== "global") { + failInspection("sandbox", "OpenShell returned an unknown policy source"); + } + return { + authority: metadata.policy_source === "sandbox" ? "nemoclaw-managed" : "externally-managed", + effectivePolicy: policyObject(metadata, "sandbox"), + }; +} + +/** Inspect whether a global policy will manage sandboxes created next. */ +export function inspectGlobalPolicyAuthority({ + gatewayName, + runCaptureEx, +}: PolicyAuthorityInspectionOptions): SandboxPolicyAuthorityInspection { + const validatedGatewayName = + gatewayName === undefined + ? undefined + : validatePolicyAuthorityName(gatewayName, "gateway name"); + const { stdout: history } = capturePolicyQuery( + buildGlobalPolicyListCommand(validatedGatewayName), + runCaptureEx, + "global", + "policy history", + ); + if (history.trim().length === 0) { + return { authority: "nemoclaw-managed", effectivePolicy: {} }; + } + const { stdout: raw } = capturePolicyQuery( + buildGlobalPolicyGetFullJsonCommand(validatedGatewayName), + runCaptureEx, + "global", + "machine-readable policy", + ); + if (raw.trim().length === 0) { + failInspection("global", "OpenShell returned empty policy metadata"); + } + const metadata = parsePolicyMetadata(raw, "global"); + if (metadata.scope !== "global") { + failInspection("global", "OpenShell returned policy metadata for another scope"); + } + if (Object.hasOwn(metadata, "sandbox")) { + failInspection("global", "OpenShell returned an unexpected sandbox identity"); + } + if (metadata.policy_source !== undefined && metadata.policy_source !== "global") { + failInspection("global", "OpenShell returned an unknown global policy source"); + } + if (metadata.status === "superseded") { + return { authority: "nemoclaw-managed", effectivePolicy: {} }; + } + if (metadata.status !== "loaded") { + failInspection( + "global", + "OpenShell returned a global policy status that cannot determine authority", + ); + } + return { + authority: "externally-managed", + effectivePolicy: policyObject(metadata, "global"), + }; +} + +function operationLabel(operation: string): string { + return typeof operation === "string" && operation.trim().length > 0 + ? operation.trim() + : "continue the policy-dependent operation"; +} + +/** Refuse a lifecycle operation when its durable and observed authority disagree. */ +export function assertRecordedPolicyAuthority( + recorded: unknown, + observed: unknown, + operation: string, +): void { + const label = operationLabel(operation); + if (!isPolicyAuthority(recorded)) { + throw new PolicyAuthorityRefusalError( + `Refusing to ${label}: the recorded policy authority is unavailable or invalid.`, + ); + } + if (!isPolicyAuthority(observed)) { + throw new PolicyAuthorityRefusalError( + `Refusing to ${label}: the observed OpenShell policy authority is unavailable or invalid.`, + ); + } + if (recorded !== observed) { + throw new PolicyAuthorityRefusalError( + `Refusing to ${label}: OpenShell policy authority changed from ${recorded} to ${observed}.`, + ); + } +} + +function networkPolicies(policy: JsonObject, label: string): JsonObject { + const value = policy.network_policies; + if (value === undefined) return {}; + if (!isObject(value)) { + throw new PolicyAuthorityRefusalError( + `Refusing to ${label}: the required network policy input is invalid.`, + ); + } + return value; +} + +function formatPolicyKeys(keys: readonly string[]): string { + return keys.map((key) => JSON.stringify(key)).join(", "); +} + +/** Verify externally supplied policy requirements without claiming ownership. */ +export function assertExternalPolicyRequirements({ + inspection, + requiredPolicy, + operation, + sandboxName, +}: { + readonly inspection: SandboxPolicyAuthorityInspection; + readonly requiredPolicy: JsonObject; + readonly operation: string; + readonly sandboxName?: string; +}): void { + const label = operationLabel(operation); + if (!isPolicyAuthority(inspection.authority)) { + throw new PolicyAuthorityRefusalError( + `Refusing to ${label}: the observed OpenShell policy authority is invalid.`, + ); + } + if (inspection.authority === "nemoclaw-managed") return; + if (!isObject(requiredPolicy) || !isObject(inspection.effectivePolicy)) { + throw new PolicyAuthorityRefusalError( + `Refusing to ${label}: the policy requirement input is invalid.`, + ); + } + + const required = networkPolicies(requiredPolicy, label); + const observedValue = inspection.effectivePolicy.network_policies; + const observed = isObject(observedValue) ? observedValue : null; + const missing: string[] = []; + const drifted: string[] = []; + for (const key of Object.keys(required).sort()) { + if (!observed || !Object.hasOwn(observed, key)) { + missing.push(key); + } else if (!isDeepStrictEqual(observed[key], required[key])) { + drifted.push(key); + } + } + const requiredSections = Object.keys(requiredPolicy) + .filter((key) => key !== "network_policies" && key !== "version") + .sort(); + const missingSections: string[] = []; + const driftedSections: string[] = []; + for (const key of requiredSections) { + if (!Object.hasOwn(inspection.effectivePolicy, key)) { + missingSections.push(key); + } else if (!isDeepStrictEqual(inspection.effectivePolicy[key], requiredPolicy[key])) { + driftedSections.push(key); + } + } + if ( + missing.length === 0 && + drifted.length === 0 && + missingSections.length === 0 && + driftedSections.length === 0 + ) { + return; + } + + const target = sandboxName ? ` for sandbox ${JSON.stringify(sandboxName)}` : ""; + const differences = [ + ...(missing.length > 0 ? [`missing entries ${formatPolicyKeys(missing)}`] : []), + ...(drifted.length > 0 ? [`drifted entries ${formatPolicyKeys(drifted)}`] : []), + ...(missingSections.length > 0 + ? [`missing sections ${formatPolicyKeys(missingSections)}`] + : []), + ...(driftedSections.length > 0 + ? [`drifted sections ${formatPolicyKeys(driftedSections)}`] + : []), + ].join("; "); + throw new PolicyAuthorityRefusalError( + `Refusing to ${label}${target}: the externally managed policy has ${differences}. Ask the external policy authority to supply the exact required entries.`, + ); +} + +export const policyAuthorityInternals = { + captureMaxBytes: POLICY_AUTHORITY_CAPTURE_MAX_BYTES, + captureTimeoutMs: POLICY_AUTHORITY_CAPTURE_TIMEOUT_MS, +}; diff --git a/src/lib/policy/README.md b/src/lib/policy/README.md index ab44d0ef086..cf0e9bd6ec7 100644 --- a/src/lib/policy/README.md +++ b/src/lib/policy/README.md @@ -7,3 +7,24 @@ Policy modules own sandbox network-policy preset loading, tier resolution, and policy application helpers. They may orchestrate OpenShell policy commands while legacy flows are being migrated, but pure selection/planning helpers should move under `src/lib/domain/**` when they can be isolated. + +## Policy authority + +The policy module reads the effective OpenShell policy through the sandbox's recorded gateway. +NemoClaw records the first qualified authority before another policy read or set. +NemoClaw refuses the operation when it cannot write that record. + +Immediately before each policy set, NemoClaw reads authority again and compares it with the record. +NemoClaw refuses the policy set when: + +- NemoClaw cannot determine authority. +- Recorded and observed authority differ. +- An external authority owns the policy. + +For external authority, preset requests only verify the effective policy. +NemoClaw requires the exact preset entries before it reports success. +NemoClaw does not set policy or record preset or custom-policy attribution. +The external authority must supply a missing or changed entry. + +A legacy sandbox record retains the first qualified `policyAuthority` after a later operation fails. +An inspection that cannot determine authority does not change the record. diff --git a/src/lib/policy/baseline-exclusion-journal-integration.test.ts b/src/lib/policy/baseline-exclusion-journal-integration.test.ts index d92c36c1455..cfbea706568 100644 --- a/src/lib/policy/baseline-exclusion-journal-integration.test.ts +++ b/src/lib/policy/baseline-exclusion-journal-integration.test.ts @@ -8,11 +8,20 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; const harness = vi.hoisted(() => ({ + inspectSandboxPolicyAuthority: vi.fn(() => ({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + })), livePolicy: "", run: vi.fn(), runCapture: vi.fn(), })); +vi.mock("../adapters/openshell/policy-authority", async (importOriginal) => ({ + ...(await importOriginal()), + inspectSandboxPolicyAuthority: harness.inspectSandboxPolicyAuthority, +})); + vi.mock("../runner", async (importOriginal) => ({ ...(await importOriginal()), run: harness.run, @@ -83,6 +92,7 @@ network_policies: }), ); expect(registry.getBaselineExclusions("alpha")).toEqual([]); + expect(registry.getSandbox("alpha")?.policyAuthority).toBe("nemoclaw-managed"); interruptedCommit.mockRestore(); // Simulate a new CLI process: reload both the registry and policy modules @@ -95,5 +105,6 @@ network_policies: expect(reloadedRegistry.getBaselineExclusions("alpha")).toEqual([ expect.objectContaining({ key: "nous_research", digest }), ]); + expect(reloadedRegistry.getSandbox("alpha")?.policyAuthority).toBe("nemoclaw-managed"); }); }); diff --git a/src/lib/policy/baseline-exclusion-persistence.test.ts b/src/lib/policy/baseline-exclusion-persistence.test.ts index 2ce24a84f7d..431e79caa22 100644 --- a/src/lib/policy/baseline-exclusion-persistence.test.ts +++ b/src/lib/policy/baseline-exclusion-persistence.test.ts @@ -14,11 +14,17 @@ const mocks = vi.hoisted(() => ({ getBaselineExclusions: vi.fn(), getBaselineExclusionTransition: vi.fn(), getSandbox: vi.fn(), + inspectSandboxPolicyAuthority: vi.fn(), removeBaselineExclusion: vi.fn(), run: vi.fn(), runCapture: vi.fn(), })); +vi.mock("../adapters/openshell/policy-authority", async (importOriginal) => ({ + ...(await importOriginal()), + inspectSandboxPolicyAuthority: mocks.inspectSandboxPolicyAuthority, +})); + vi.mock("../runner", async (importOriginal) => ({ ...(await importOriginal()), run: mocks.run, @@ -76,16 +82,30 @@ const OPENCLAW_RESTORED_POLICY = YAML.stringify({ network_policies: { managed_inference: OPENCLAW_BASELINE_ENTRY }, }); +function expectNoBaselineMutation(): void { + expect(mocks.addBaselineExclusion).not.toHaveBeenCalled(); + expect(mocks.beginBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(mocks.clearBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(mocks.commitBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(mocks.removeBaselineExclusion).not.toHaveBeenCalled(); + expect(mocks.run).not.toHaveBeenCalled(); +} + describe("excludeBaselineEntry persistence boundary (#7178)", () => { beforeEach(() => { vi.spyOn(openshellResolveModule, "resolveOpenshell").mockReturnValue("/usr/bin/openshell"); vi.spyOn(console, "error").mockImplementation(() => undefined); mocks.runCapture.mockReturnValue(LIVE_POLICY); mocks.run.mockReturnValue({ status: 0 }); + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); mocks.getSandbox.mockReturnValue({ name: "alpha", agent: "hermes", agentVersion: "1.2.3", + policyAuthority: "nemoclaw-managed", }); mocks.getBaselineExclusions.mockReturnValue([]); mocks.getBaselineExclusionTransition.mockReturnValue(null); @@ -125,6 +145,37 @@ describe("excludeBaselineEntry persistence boundary (#7178)", () => { expect(console.error).toHaveBeenCalledWith(expect.stringContaining("no live policy changes")); }); + it("refuses exclusion journal changes when authority changes during the live read (#9833)", () => { + mocks.inspectSandboxPolicyAuthority + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "externally-managed", effectivePolicy: {} }); + + expect(excludeBaselineEntry("alpha", "nous_research", LIVE_DIGEST, { nonFatal: true })).toBe( + false, + ); + + expectNoBaselineMutation(); + expect(console.error).toHaveBeenCalledWith(expect.stringContaining("policy authority changed")); + }); + + it("preserves a pending exclusion when authority changes at the policy-set edge (#9833)", () => { + mocks.beginBaselineExclusionTransition.mockReturnValue(true); + mocks.inspectSandboxPolicyAuthority + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValue({ authority: "externally-managed", effectivePolicy: {} }); + + expect(excludeBaselineEntry("alpha", "nous_research", LIVE_DIGEST, { nonFatal: true })).toBe( + false, + ); + + expect(mocks.beginBaselineExclusionTransition).toHaveBeenCalledOnce(); + expect(mocks.run).not.toHaveBeenCalled(); + expect(mocks.clearBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(mocks.commitBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(console.error).toHaveBeenCalledWith(expect.stringContaining("policy authority changed")); + }); + it("clears a fresh transaction when live narrowing fails", () => { mocks.beginBaselineExclusionTransition.mockReturnValue(true); mocks.run.mockReturnValue({ status: 19 }); @@ -217,6 +268,7 @@ describe("excludeBaselineEntry persistence boundary (#7178)", () => { agentVersion: "1.2.3", gatewayName: "nemoclaw-18080", gatewayPort: 18080, + policyAuthority: "nemoclaw-managed", }); mocks.beginBaselineExclusionTransition.mockReturnValue(true); mocks.runCapture @@ -360,10 +412,15 @@ describe("restoreBaselineEntry persistence boundary (#7178)", () => { vi.spyOn(console, "error").mockImplementation(() => undefined); mocks.runCapture.mockReturnValue("version: 1\nnetwork_policies: {}\n"); mocks.run.mockReturnValue({ status: 0 }); + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); mocks.getSandbox.mockReturnValue({ name: "alpha", agent: "hermes", agentVersion: "1.2.3", + policyAuthority: "nemoclaw-managed", }); mocks.getBaselineExclusions.mockReturnValue([RECORDED]); mocks.getBaselineExclusionTransition.mockReturnValue(null); @@ -384,21 +441,24 @@ describe("restoreBaselineEntry persistence boundary (#7178)", () => { ["changes", "nous_research", "stale-preview-digest", [RECORDED]], ["appears", "nous_research", null, [RECORDED]], ["disappears", "legacy_entry", LIVE_DIGEST, [{ ...RECORDED, key: "legacy_entry" }]], - ] as const)("does not mutate when the baseline entry %s after the operator preview", (_change, key, expectedTargetDigest, exclusions) => { - mocks.getBaselineExclusions.mockReturnValue([...exclusions]); - - expect(restoreBaselineEntry("alpha", key, { nonFatal: true, expectedTargetDigest })).toBe( - false, - ); - - expect(mocks.runCapture).not.toHaveBeenCalled(); - expect(mocks.run).not.toHaveBeenCalled(); - expect(mocks.beginBaselineExclusionTransition).not.toHaveBeenCalled(); - expect(mocks.clearBaselineExclusionTransition).not.toHaveBeenCalled(); - expect(mocks.commitBaselineExclusionTransition).not.toHaveBeenCalled(); - expect(mocks.removeBaselineExclusion).not.toHaveBeenCalled(); - expect(console.error).toHaveBeenCalledWith(expect.stringContaining("changed after preview")); - }); + ] as const)( + "does not mutate when the baseline entry %s after the operator preview", + (_change, key, expectedTargetDigest, exclusions) => { + mocks.getBaselineExclusions.mockReturnValue([...exclusions]); + + expect(restoreBaselineEntry("alpha", key, { nonFatal: true, expectedTargetDigest })).toBe( + false, + ); + + expect(mocks.runCapture).not.toHaveBeenCalled(); + expect(mocks.run).not.toHaveBeenCalled(); + expect(mocks.beginBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(mocks.clearBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(mocks.commitBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(mocks.removeBaselineExclusion).not.toHaveBeenCalled(); + expect(console.error).toHaveBeenCalledWith(expect.stringContaining("changed after preview")); + }, + ); it("does not widen live egress when its durable transaction cannot be recorded", () => { mocks.beginBaselineExclusionTransition.mockReturnValue(false); @@ -409,6 +469,17 @@ describe("restoreBaselineEntry persistence boundary (#7178)", () => { expect(console.error).toHaveBeenCalledWith(expect.stringContaining("no live policy changes")); }); + it("refuses restore journal changes when authority changes during the live read (#9833)", () => { + mocks.inspectSandboxPolicyAuthority + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "externally-managed", effectivePolicy: {} }); + + expect(restoreBaselineEntry("alpha", "nous_research", { nonFatal: true })).toBe(false); + + expectNoBaselineMutation(); + expect(console.error).toHaveBeenCalledWith(expect.stringContaining("policy authority changed")); + }); + it("clears the restore transaction when live policy restoration fails", () => { mocks.run.mockReturnValue({ status: 19 }); @@ -443,6 +514,7 @@ describe("restoreBaselineEntry persistence boundary (#7178)", () => { name: "alpha", agent: "openclaw", agentVersion: "2.0.0", + policyAuthority: "nemoclaw-managed", }); mocks.getBaselineExclusions.mockReturnValue([staleExclusion]); mocks.runCapture @@ -556,6 +628,7 @@ describe("restoreBaselineEntry persistence boundary (#7178)", () => { name: "alpha", agent: "agent-without-a-readable-baseline", agentVersion: "1.2.3", + policyAuthority: "nemoclaw-managed", }); mocks.runCapture.mockReturnValue(LIVE_POLICY); mocks.getBaselineExclusionTransition.mockReturnValue({ diff --git a/src/lib/policy/commands.ts b/src/lib/policy/commands.ts index bcad4ef7eee..eb1780b3a51 100644 --- a/src/lib/policy/commands.ts +++ b/src/lib/policy/commands.ts @@ -16,3 +16,45 @@ export function buildPolicyGetCommand(sandboxName: string): string[] { export function buildPolicyGetFullCommand(sandboxName: string): string[] { return buildOpenshellCommand(["policy", "get", "--full", sandboxName]); } + +function policyGetGatewayArgs(gatewayName?: string): string[] { + return gatewayName ? ["-g", gatewayName] : []; +} + +/** Read effective sandbox policy and its authority metadata as JSON. */ +export function buildPolicyGetFullJsonCommand(sandboxName: string, gatewayName?: string): string[] { + return buildOpenshellCommand([ + "policy", + "get", + ...policyGetGatewayArgs(gatewayName), + "--full", + "--output", + "json", + sandboxName, + ]); +} + +/** Read the global policy and its authority metadata as JSON. */ +export function buildGlobalPolicyGetFullJsonCommand(gatewayName?: string): string[] { + return buildOpenshellCommand([ + "policy", + "get", + ...policyGetGatewayArgs(gatewayName), + "--global", + "--full", + "--output", + "json", + ]); +} + +/** Check whether the global policy has revision history. */ +export function buildGlobalPolicyListCommand(gatewayName?: string): string[] { + return buildOpenshellCommand([ + "policy", + "list", + ...policyGetGatewayArgs(gatewayName), + "--global", + "--limit", + "1", + ]); +} diff --git a/src/lib/policy/context-builder.ts b/src/lib/policy/context-builder.ts index 7c2ba5e0013..3a68e4e30cb 100644 --- a/src/lib/policy/context-builder.ts +++ b/src/lib/policy/context-builder.ts @@ -111,6 +111,7 @@ export interface PolicyContext { } const POLICY_DOC_URL = "docs/network-policy/customize-network-policy.mdx"; +const EXTERNAL_POLICY_CHANGE_PATH = "Ask the external policy authority to supply a changed entry."; function hostStemsFromContent(content: string | null | undefined): { public: string[]; @@ -191,7 +192,11 @@ function partitionPresets( // would record the preset as operator-applied (#9079). Sibling base additions // with no catalog entry are never iterated here, so this only corrects the // incidental name-collision case. - if (!isApplied && verification === "gateway-only" && isAgentBasePreset(sandboxName, info.name)) { + if ( + !isApplied && + verification === "gateway-only" && + isAgentBasePreset(sandboxName, info.name) + ) { verification = "agent-base"; } const enforcedNotApplied = @@ -255,23 +260,39 @@ function buildBaselineExclusions( return [...byKey.values()].sort((a, b) => a.key.localeCompare(b.key)); } -function buildApprovalPath(sandboxName: string): PolicyContextApprovalPath { +function buildApprovalPath( + sandboxName: string, + externallyManaged: boolean, +): PolicyContextApprovalPath { return { inspect: `nemoclaw ${sandboxName} policy list`, - add: `nemoclaw ${sandboxName} policy add `, - remove: `nemoclaw ${sandboxName} policy remove `, + add: externallyManaged + ? EXTERNAL_POLICY_CHANGE_PATH + : `nemoclaw ${sandboxName} policy add `, + remove: externallyManaged + ? EXTERNAL_POLICY_CHANGE_PATH + : `nemoclaw ${sandboxName} policy remove `, excludeBaseline: `nemoclaw ${sandboxName} policy exclude --dry-run`, - restoreBaseline: `nemoclaw ${sandboxName} policy restore `, + restoreBaseline: externallyManaged + ? EXTERNAL_POLICY_CHANGE_PATH + : `nemoclaw ${sandboxName} policy restore `, documentation: POLICY_DOC_URL, }; } -function buildSupportBoundaries(tier: PolicyContextTier | null): PolicyContextSupportBoundary[] { +function buildSupportBoundaries( + tier: PolicyContextTier | null, + externallyManaged: boolean, +): PolicyContextSupportBoundary[] { return [ { capability: "preset selection", - owner: "nemoclaw", - note: tier ? `tier: ${tier.label}` : "no tier recorded", + owner: externallyManaged ? "external" : "nemoclaw", + note: externallyManaged + ? "the external policy authority must supply a changed entry" + : tier + ? `tier: ${tier.label}` + : "no tier recorded", }, { capability: "host allowlist enforcement", @@ -280,8 +301,10 @@ function buildSupportBoundaries(tier: PolicyContextTier | null): PolicyContextSu }, { capability: "shields toggle", - owner: "nemoclaw", - note: "shields up locks down mutable config", + owner: externallyManaged ? "external" : "nemoclaw", + note: externallyManaged + ? "the external authority controls live policy changes; restrictive NemoClaw-owned configuration protection and cleanup may still proceed" + : "shields up locks down mutable config", }, { capability: "credential storage", @@ -363,7 +386,8 @@ export function buildPolicyContext( options: BuildPolicyContextOptions = {}, ): PolicyContext { const sandbox = registry.getSandbox(sandboxName); - const tierName = sandbox?.policyTier ?? null; + const externallyManaged = sandbox?.policyAuthority === "externally-managed"; + const tierName = externallyManaged ? null : (sandbox?.policyTier ?? null); const tierDef = tierName ? getTier(tierName) : null; const tier: PolicyContextTier | null = tierDef ? { name: tierDef.name, label: tierDef.label, description: tierDef.description } @@ -386,8 +410,8 @@ export function buildPolicyContext( sandboxName, sandbox?.baselineExclusionTransition ?? null, ), - approvalPath: buildApprovalPath(sandboxName), - supportBoundaries: buildSupportBoundaries(tier), + approvalPath: buildApprovalPath(sandboxName, externallyManaged), + supportBoundaries: buildSupportBoundaries(tier, externallyManaged), generatedAt: new Date().toISOString(), }; } @@ -430,12 +454,19 @@ function exclusionStatusTag(status: PolicyContextExclusionStatus): string { } } -function formatExclusionLine(exclusion: PolicyContextExclusion, sandboxName: string): string { +function formatExclusionLine( + exclusion: PolicyContextExclusion, + sandboxName: string, + restoreAction: string, +): string { + const restore = restoreAction.startsWith("nemoclaw ") + ? `\`nemoclaw ${sandboxName} policy restore ${exclusion.key}\`` + : restoreAction; return [ `- \`${exclusion.key}\` — status: ${exclusionStatusTag(exclusion.status)}`, ` acknowledged: ${exclusion.acknowledgedAt ?? "(unknown)"}`, ` impact: ${exclusion.supportImpact}`, - ` restore: \`nemoclaw ${sandboxName} policy restore ${exclusion.key}\``, + ` restore: ${restore}`, ].join("\n"); } @@ -456,6 +487,10 @@ function formatPresetLine(preset: PolicyContextPreset): string { ].join("\n"); } +function formatApprovalAction(action: string): string { + return action.startsWith("nemoclaw ") ? `\`${action}\`` : action; +} + export function renderPolicyContextMarkdown(ctx: PolicyContext): string { const lines: string[] = []; lines.push(`# Sandbox policy context: ${ctx.sandboxName}`); @@ -497,16 +532,18 @@ export function renderPolicyContextMarkdown(ctx: PolicyContext): string { lines.push("- none"); } else { for (const exclusion of ctx.baselineExclusions) { - lines.push(formatExclusionLine(exclusion, ctx.sandboxName)); + lines.push(formatExclusionLine(exclusion, ctx.sandboxName, ctx.approvalPath.restoreBaseline)); } } lines.push(""); lines.push("## Approval and remediation"); lines.push(`- inspect: \`${ctx.approvalPath.inspect}\``); - lines.push(`- add a preset: \`${ctx.approvalPath.add}\``); - lines.push(`- remove a preset: \`${ctx.approvalPath.remove}\``); + lines.push(`- add a preset: ${formatApprovalAction(ctx.approvalPath.add)}`); + lines.push(`- remove a preset: ${formatApprovalAction(ctx.approvalPath.remove)}`); lines.push(`- preview a baseline exclusion: \`${ctx.approvalPath.excludeBaseline}\``); - lines.push(`- restore a baseline entry: \`${ctx.approvalPath.restoreBaseline}\``); + lines.push( + `- restore a baseline entry: ${formatApprovalAction(ctx.approvalPath.restoreBaseline)}`, + ); lines.push(`- documentation: ${ctx.approvalPath.documentation}`); lines.push(""); lines.push("## Support boundaries"); diff --git a/src/lib/policy/context.test.ts b/src/lib/policy/context.test.ts index 02120c14319..1b4316ce554 100644 --- a/src/lib/policy/context.test.ts +++ b/src/lib/policy/context.test.ts @@ -76,11 +76,18 @@ function mockBuiltinPresets() { }); } -function stubRegistry(entry: Partial<{ policies: string[]; policyTier: string }>) { +function stubRegistry( + entry: Partial<{ + policies: string[]; + policyTier: string; + policyAuthority: "nemoclaw-managed" | "externally-managed"; + }>, +) { vi.mocked(registry.getSandbox).mockReturnValue({ name: SANDBOX, policies: entry.policies, policyTier: entry.policyTier ?? null, + policyAuthority: entry.policyAuthority, } as ReturnType); } @@ -144,6 +151,67 @@ describe("buildPolicyContext", () => { expect(ctx.supportBoundaries.some((b) => b.capability === "host allowlist enforcement")).toBe( true, ); + expect(ctx.supportBoundaries).toContainEqual({ + capability: "shields toggle", + owner: "nemoclaw", + note: "shields up locks down mutable config", + }); + }); + + it("attributes externally managed policy changes only to the external authority (#9833)", () => { + resetMocks(); + mockBuiltinPresets(); + stubTier(); + stubRegistry({ + policies: [], + policyTier: "balanced", + policyAuthority: "externally-managed", + }); + vi.mocked(registry.getBaselineExclusions).mockReturnValue([ + { + version: 1, + agent: "openclaw", + key: "nous_research", + digest: "digest-1", + acknowledgedAt: "2026-07-19T00:00:00.000Z", + }, + ]); + vi.mocked(policies.getBaselineExclusionRuntimeStatus).mockReturnValue("excluded"); + + const context = buildPolicyContext(SANDBOX); + const markdown = renderPolicyContextMarkdown(context); + + expect(context.tier).toBeNull(); + expect(getTier).not.toHaveBeenCalled(); + expect(context.supportBoundaries).toContainEqual({ + capability: "preset selection", + owner: "external", + note: "the external policy authority must supply a changed entry", + }); + expect(context.supportBoundaries).toContainEqual({ + capability: "shields toggle", + owner: "external", + note: "the external authority controls live policy changes; restrictive NemoClaw-owned configuration protection and cleanup may still proceed", + }); + expect(context.approvalPath).toEqual({ + inspect: "nemoclaw alpha policy list", + add: "Ask the external policy authority to supply a changed entry.", + remove: "Ask the external policy authority to supply a changed entry.", + excludeBaseline: "nemoclaw alpha policy exclude --dry-run", + restoreBaseline: "Ask the external policy authority to supply a changed entry.", + documentation: "docs/network-policy/customize-network-policy.mdx", + }); + expect(markdown).toContain( + "restore: Ask the external policy authority to supply a changed entry.", + ); + expect(markdown).toContain( + "- restore a baseline entry: Ask the external policy authority to supply a changed entry.", + ); + expect(markdown).toContain( + "- shields toggle (owner: external) — the external authority controls live policy changes; restrictive NemoClaw-owned configuration protection and cleanup may still proceed", + ); + expect(markdown).toContain("`nemoclaw alpha policy exclude --dry-run`"); + expect(markdown).not.toMatch(/nemoclaw alpha policy (?:add|remove|restore)(?:\s|`)/u); }); it("marks active presets as `verified` when the gateway agrees and `registry-only` when it disagrees", () => { @@ -396,66 +464,66 @@ describe("buildPolicyContext", () => { expect(markdown).toContain("rebuild blocked"); }); - it.each([ - "exclude", - "restore", - ] as const)("surfaces pending %s repair even when the release baseline is unreadable (#7194)", (operation) => { - resetMocks(); - mockBuiltinPresets(); - vi.mocked(getTier).mockReturnValue(null); - vi.mocked(registry.getBaselineExclusions).mockReturnValue([ - { - version: 1, - agent: "openclaw", - key: "another_entry", - digest: "c".repeat(64), - acknowledgedAt: "2026-07-18T00:00:00.000Z", - }, - { - version: 1, - agent: "openclaw", - key: "nous_research", - digest: "a".repeat(64), - acknowledgedAt: "2026-07-19T00:00:00.000Z", - }, - ]); - vi.mocked(registry.getSandbox).mockReturnValue({ - name: SANDBOX, - policies: [], - baselineExclusionTransition: { - id: "00000000-0000-4000-8000-000000000001", - operation, - exclusion: { + it.each(["exclude", "restore"] as const)( + "surfaces pending %s repair even when the release baseline is unreadable (#7194)", + (operation) => { + resetMocks(); + mockBuiltinPresets(); + vi.mocked(getTier).mockReturnValue(null); + vi.mocked(registry.getBaselineExclusions).mockReturnValue([ + { + version: 1, + agent: "openclaw", + key: "another_entry", + digest: "c".repeat(64), + acknowledgedAt: "2026-07-18T00:00:00.000Z", + }, + { version: 1, agent: "openclaw", key: "nous_research", digest: "a".repeat(64), acknowledgedAt: "2026-07-19T00:00:00.000Z", }, - targetLiveDigest: operation === "restore" ? "b".repeat(64) : null, - startedAt: "2026-07-19T00:00:00.000Z", - }, - }); - vi.mocked(policies.getBaselineExclusionRuntimeStatus).mockReturnValue("baseline-unreadable"); - - const ctx = buildPolicyContext(SANDBOX); - - expect(ctx.baselineExclusions).toEqual( - expect.arrayContaining([ - expect.objectContaining({ key: "another_entry", status: "baseline-unreadable" }), - expect.objectContaining({ - key: "nous_research", - status: operation === "exclude" ? "pending-exclude-repair" : "pending-restore-repair", - }), - ]), - ); - expect(ctx.baselineExclusions).toHaveLength(2); - expect(policies.getBaselineExclusionRuntimeStatus).toHaveBeenCalledOnce(); - expect(policies.getBaselineExclusionRuntimeStatus).toHaveBeenCalledWith( - SANDBOX, - expect.objectContaining({ key: "another_entry" }), - ); - }); + ]); + vi.mocked(registry.getSandbox).mockReturnValue({ + name: SANDBOX, + policies: [], + baselineExclusionTransition: { + id: "00000000-0000-4000-8000-000000000001", + operation, + exclusion: { + version: 1, + agent: "openclaw", + key: "nous_research", + digest: "a".repeat(64), + acknowledgedAt: "2026-07-19T00:00:00.000Z", + }, + targetLiveDigest: operation === "restore" ? "b".repeat(64) : null, + startedAt: "2026-07-19T00:00:00.000Z", + }, + }); + vi.mocked(policies.getBaselineExclusionRuntimeStatus).mockReturnValue("baseline-unreadable"); + + const ctx = buildPolicyContext(SANDBOX); + + expect(ctx.baselineExclusions).toEqual( + expect.arrayContaining([ + expect.objectContaining({ key: "another_entry", status: "baseline-unreadable" }), + expect.objectContaining({ + key: "nous_research", + status: operation === "exclude" ? "pending-exclude-repair" : "pending-restore-repair", + }), + ]), + ); + expect(ctx.baselineExclusions).toHaveLength(2); + expect(policies.getBaselineExclusionRuntimeStatus).toHaveBeenCalledOnce(); + expect(policies.getBaselineExclusionRuntimeStatus).toHaveBeenCalledWith( + SANDBOX, + expect.objectContaining({ key: "another_entry" }), + ); + }, + ); }); describe("renderPolicyContextMarkdown", () => { @@ -508,24 +576,20 @@ describe("renderPolicyContextMarkdown", () => { gatewayPresets: null, agentBase: false, }, - ])("renders the $status verification status (#9079)", ({ - status, - applied, - gatewayPresets, - agentBase, - }) => { - resetMocks(); - mockBuiltinPresets(); - stubTier(); - stubRegistry({ policies: applied, policyTier: "balanced" }); - vi.mocked(policies.isAgentBasePreset).mockReturnValue(agentBase); - - const md = renderPolicyContextMarkdown( - buildPolicyContext(SANDBOX, { gatewayPresets }), - ); - - expect(md).toContain(`status: ${status}`); - }); + ])( + "renders the $status verification status (#9079)", + ({ status, applied, gatewayPresets, agentBase }) => { + resetMocks(); + mockBuiltinPresets(); + stubTier(); + stubRegistry({ policies: applied, policyTier: "balanced" }); + vi.mocked(policies.isAgentBasePreset).mockReturnValue(agentBase); + + const md = renderPolicyContextMarkdown(buildPolicyContext(SANDBOX, { gatewayPresets })); + + expect(md).toContain(`status: ${status}`); + }, + ); it("states which verification statuses confirm gateway enforcement (#9079)", () => { resetMocks(); diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index b028fd0ea9f..60a639a5a5f 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -28,10 +28,10 @@ import { import { resolveSandboxGatewayName } from "../onboard/gateway-binding"; import { assertNoOpenShellGatewayEndpointOverride } from "../openshell-gateway-endpoint-guard"; import { OPENSHELL_SANDBOX_HOST_BRIDGE } from "../private-networks"; -import { ROOT, run, runCapture } from "../runner"; +import { ROOT, run, runCapture, runCaptureEx } from "../runner"; import { diagnosticPreview, isValidName, NAME_ALLOWED_FORMAT } from "../sandbox-name-contract"; import { redact } from "../security/redact"; -import * as registry from "../state/registry"; +import * as registry from "./policy-registry"; import type { BaselineExclusionRuntimeStatus } from "./baseline-exclusion"; import { digestBaselineEntry, @@ -570,6 +570,136 @@ interface PolicySetSubmission { readonly status: number | null; } +interface PolicyAuthorityContext { + readonly authority: registry.SandboxPolicyAuthority; + readonly authorityRecordedNow: boolean; + readonly gatewayName: string; + readonly inspection: registry.SandboxPolicyAuthorityInspection; +} + +function policyAuthorityError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** Inspect live authority through the gateway recorded for this sandbox. */ +function inspectPolicyAuthority( + sandboxName: string, + operation: string, + requestedGatewayName?: string, + requireRecordedAuthority = false, +): PolicyAuthorityContext { + const sandbox = registry.getSandbox(sandboxName); + const recordedGatewayName = sandbox ? resolveSandboxGatewayName(sandbox) : null; + if (recordedGatewayName && requestedGatewayName && requestedGatewayName !== recordedGatewayName) { + throw new Error( + `Refusing to ${operation}: sandbox '${sandboxName}' is recorded on gateway ` + + `'${recordedGatewayName}', not '${requestedGatewayName}'.`, + ); + } + const gatewayName = + recordedGatewayName ?? requestedGatewayName ?? resolveSandboxGatewayName(undefined); + const inspection = registry.inspectSandboxPolicyAuthority({ + sandboxName, + gatewayName, + runCaptureEx, + }); + if (sandbox?.policyAuthority !== undefined) { + try { + registry.assertRecordedPolicyAuthority( + sandbox.policyAuthority, + inspection.authority, + operation, + ); + } catch (error) { + if ( + sandbox.policyAuthority === "externally-managed" || + inspection.authority === "externally-managed" + ) { + throw new Error( + `${policyAuthorityError(error)} Ask the external policy authority to change the required entry.`, + ); + } + throw error; + } + return { + authority: inspection.authority, + authorityRecordedNow: false, + gatewayName, + inspection, + }; + } + + if (requireRecordedAuthority) { + throw new Error( + `Refusing to ${operation}: policy authority is not recorded for sandbox '${sandboxName}'.`, + ); + } + if ( + !sandbox || + !registry.updateSandbox(sandboxName, { + policyAuthority: inspection.authority, + }) + ) { + throw new Error( + `Refusing to ${operation}: NemoClaw could not record policy authority for sandbox '${sandboxName}'.`, + ); + } + return { + authority: inspection.authority, + authorityRecordedNow: true, + gatewayName, + inspection, + }; +} + +function assertNemoClawManagedPolicy(context: PolicyAuthorityContext, operation: string): void { + if (context.authority === "nemoclaw-managed") return; + throw new Error( + `Refusing to ${operation}: this sandbox policy is externally managed. ` + + "Ask the external policy authority to change the required entry.", + ); +} + +function reportPolicyAuthorityFailure(error: unknown): false { + console.error(` ${policyAuthorityError(error)}`); + return false; +} + +function inspectNemoClawManagedPolicy( + sandboxName: string, + operation: string, + gatewayName?: string, +): PolicyAuthorityContext | null { + try { + const context = inspectPolicyAuthority(sandboxName, operation, gatewayName); + assertNemoClawManagedPolicy(context, operation); + return context; + } catch (error) { + reportPolicyAuthorityFailure(error); + return null; + } +} + +/** Recheck the original managed receipt immediately before a local state mutation. */ +function recheckNemoClawManagedPolicy( + sandboxName: string, + operation: string, + authority: PolicyAuthorityContext, +): boolean { + try { + const observed = inspectPolicyAuthority(sandboxName, operation, authority.gatewayName, true); + registry.assertRecordedPolicyAuthority( + authority.authority, + observed.authority, + operation, + ); + assertNemoClawManagedPolicy(observed, operation); + return true; + } catch (error) { + return reportPolicyAuthorityFailure(error); + } +} + /** * Submit a composed policy document through a private temp file and classify * what OpenShell did with it. @@ -652,12 +782,34 @@ function policySetFailure( function setPolicyDocument( sandboxName: string, policyDocument: string, - options: { nonFatal?: boolean; gatewayName?: string } = {}, + options: { + nonFatal?: boolean; + gatewayName?: string; + } = {}, ): boolean { + let authority: PolicyAuthorityContext; + try { + authority = inspectPolicyAuthority(sandboxName, "set the sandbox policy", options.gatewayName); + assertNemoClawManagedPolicy(authority, "set the sandbox policy"); + if (authority.authorityRecordedNow) { + authority = inspectPolicyAuthority( + sandboxName, + "set the sandbox policy", + authority.gatewayName, + true, + ); + assertNemoClawManagedPolicy(authority, "set the sandbox policy"); + } + } catch (error) { + console.error(` ${policyAuthorityError(error)}`); + if (options.nonFatal) return false; + process.exit(1); + } + const { outcome, status } = submitComposedPolicy( sandboxName, policyDocument, - options.gatewayName, + authority.gatewayName, ); if (outcome.kind === "applied") return true; @@ -1339,11 +1491,17 @@ function removePreset( return false; } + const operation = `remove policy preset '${presetName}'`; + const authority = inspectNemoClawManagedPolicy(sandboxName, operation); + if (!authority) return false; + // Get current policy YAML from sandbox let rawPolicy = ""; try { // Mutations start from round-trippable --base, never provider-composed --full. - rawPolicy = runCapture(buildPolicyGetCommand(sandboxName)); + rawPolicy = runCapture(buildPolicyGetCommand(sandboxName), { + env: { OPENSHELL_GATEWAY: authority.gatewayName }, + }); } catch { /* ignored */ } @@ -1385,6 +1543,7 @@ function removePreset( return false; } if (sandbox) { + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; const attributionRemoved = isCustom ? registry.removeCustomPolicyByName(sandboxName, presetName) : registry.updateSandbox(sandboxName, { @@ -1426,12 +1585,21 @@ function removePreset( // Run before submitting so a missing-binary exit doesn't orphan files in // $TMPDIR (the cleanup doesn't run on process.exit). if (!assertOpenshellResolvable(options)) return false; + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; - if (!setPolicyDocument(sandboxName, updated, options)) return false; - console.log(` Removed preset: ${presetName}`); + if ( + !setPolicyDocument(sandboxName, updated, { + nonFatal: options.nonFatal, + gatewayName: authority.gatewayName, + }) + ) { + return false; + } + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; const sandbox = options.skipRegistryUpdate ? undefined : registry.getSandbox(sandboxName); if (sandbox) { + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; if (isCustom) { registry.removeCustomPolicyByName(sandboxName, presetName); } else { @@ -1440,6 +1608,7 @@ function removePreset( } } + console.log(` Removed preset: ${presetName}`); return true; } @@ -1595,6 +1764,17 @@ type LiveBaselineEntryState = | { state: "present"; digest: string } | { state: "invalid"; digest: null }; +type RecheckManagedPolicyAuthority = () => boolean; + +function authorityBoundRegistryStep( + recheckAuthority: RecheckManagedPolicyAuthority, + operation: () => boolean, + failureMessage: string, +): boolean { + if (!recheckAuthority()) return false; + return registryTransitionStep(operation, failureMessage); +} + function inspectLiveBaselineEntry(policy: string, key: string): LiveBaselineEntryState { try { const document = YAML.parse(policy); @@ -1626,6 +1806,7 @@ function reconcileBaselineExclusionTransition( sandboxName: string, requestedKey: string, gatewayName: string, + recheckAuthority: RecheckManagedPolicyAuthority, ): BaselineTransitionReconciliation | null { const transition = registry.getBaselineExclusionTransition(sandboxName); if (!transition) return { state: "none" }; @@ -1660,7 +1841,9 @@ function reconcileBaselineExclusionTransition( ? live.state === "absent" : live.state === "present" && live.digest === transition.targetLiveDigest; if (atTarget) { - if (!finalizeBaselineExclusionTransition(sandboxName, transition)) return null; + if (!finalizeBaselineExclusionTransition(sandboxName, transition, recheckAuthority)) { + return null; + } return { state: transition.operation === "exclude" ? "excluded" : "restored" }; } @@ -1679,7 +1862,8 @@ function reconcileBaselineExclusionTransition( return { state: "resume", transition }; } if ( - !registryTransitionStep( + !authorityBoundRegistryStep( + recheckAuthority, () => registry.clearBaselineExclusionTransition(sandboxName, transition.id), `The live policy remains at the pre-${transition.operation} state for '${key}', but the durable journal could not be rolled back. Re-run the same command; rebuild remains blocked.`, ) @@ -1700,6 +1884,7 @@ function beginBaselineExclusionTransition( operation: registry.BaselineExclusionTransitionOperation, exclusion: registry.BaselineExclusionEntry, targetLiveDigest: string | null, + recheckAuthority: RecheckManagedPolicyAuthority, ): registry.BaselineExclusionTransition | null { const transition: registry.BaselineExclusionTransition = { id: randomUUID(), @@ -1708,7 +1893,8 @@ function beginBaselineExclusionTransition( targetLiveDigest, startedAt: new Date().toISOString(), }; - return registryTransitionStep( + return authorityBoundRegistryStep( + recheckAuthority, () => registry.beginBaselineExclusionTransition(sandboxName, transition), `Could not record the pending baseline '${operation}' for '${sandboxName}'; no live policy changes were made.`, ) @@ -1751,9 +1937,11 @@ function restoreTransitionCanFinalize( function finalizeBaselineExclusionTransition( sandboxName: string, transition: registry.BaselineExclusionTransition, + recheckAuthority: RecheckManagedPolicyAuthority, ): boolean { if (!restoreTransitionCanFinalize(sandboxName, transition)) return false; - return registryTransitionStep( + return authorityBoundRegistryStep( + recheckAuthority, () => registry.commitBaselineExclusionTransition(sandboxName, transition.id), `The live policy was updated for '${transition.exclusion.key}', but the durable journal could not be finalized. Re-run 'policy ${transition.operation} ${transition.exclusion.key}' to reconcile it; rebuild remains blocked.`, ); @@ -1762,8 +1950,10 @@ function finalizeBaselineExclusionTransition( function compensateBaselineExclusionTransition( sandboxName: string, transition: registry.BaselineExclusionTransition, + recheckAuthority: RecheckManagedPolicyAuthority, ): boolean { - return registryTransitionStep( + return authorityBoundRegistryStep( + recheckAuthority, () => registry.clearBaselineExclusionTransition(sandboxName, transition.id), `Failed to roll back the pending baseline '${transition.operation}' for '${transition.exclusion.key}'. The durable journal was preserved; re-run the same command before rebuilding '${sandboxName}'.`, ); @@ -1775,6 +1965,7 @@ function settleBaselineExclusionTransitionAfterPush( pushSucceeded: boolean, canRollbackAtSource: boolean, gatewayName: string, + recheckAuthority: RecheckManagedPolicyAuthority, ): boolean { const currentPolicy = readCurrentSandboxPolicy(sandboxName, gatewayName); if (!currentPolicy) { @@ -1789,14 +1980,14 @@ function settleBaselineExclusionTransitionAfterPush( ? live.state === "absent" : live.state === "present" && live.digest === transition.targetLiveDigest; if (atTarget) { - return finalizeBaselineExclusionTransition(sandboxName, transition); + return finalizeBaselineExclusionTransition(sandboxName, transition, recheckAuthority); } const atSource = transition.operation === "exclude" ? live.state === "present" && live.digest === transition.exclusion.digest : live.state === "absent"; if (!pushSucceeded && atSource && canRollbackAtSource) { - compensateBaselineExclusionTransition(sandboxName, transition); + compensateBaselineExclusionTransition(sandboxName, transition, recheckAuthority); return false; } const state = atSource ? "the pre-mutation state" : "an unexpected third state"; @@ -1811,8 +2002,10 @@ function attemptBaselineTransitionPolicyPush( updatedPolicy: string, options: { nonFatal?: boolean }, gatewayName: string, + recheckAuthority: RecheckManagedPolicyAuthority, ): boolean { try { + if (!recheckAuthority()) return false; return pushPolicyYaml(sandboxName, updatedPolicy, { ...options, nonFatal: true, @@ -1836,9 +2029,20 @@ function excludeBaselineEntry( digest: string, options: { nonFatal?: boolean } = {}, ): boolean { - return withRecordedSandboxGateway(sandboxName, (gatewayName) => - excludeBaselineEntryOnGateway(sandboxName, key, digest, options, gatewayName), - ); + return withRecordedSandboxGateway(sandboxName, (gatewayName) => { + const operation = `exclude baseline policy entry '${key}'`; + const authority = inspectNemoClawManagedPolicy(sandboxName, operation, gatewayName); + if (!authority) return false; + const recheckAuthority = () => recheckNemoClawManagedPolicy(sandboxName, operation, authority); + return excludeBaselineEntryOnGateway( + sandboxName, + key, + digest, + options, + gatewayName, + recheckAuthority, + ); + }); } function excludeBaselineEntryOnGateway( @@ -1847,8 +2051,14 @@ function excludeBaselineEntryOnGateway( digest: string, options: { nonFatal?: boolean }, gatewayName: string, + recheckAuthority: RecheckManagedPolicyAuthority, ): boolean { - const reconciled = reconcileBaselineExclusionTransition(sandboxName, key, gatewayName); + const reconciled = reconcileBaselineExclusionTransition( + sandboxName, + key, + gatewayName, + recheckAuthority, + ); if (!reconciled) return false; if (reconciled.state === "excluded") return true; if (reconciled.state === "resume" && reconciled.transition.operation !== "exclude") { @@ -1896,9 +2106,14 @@ function excludeBaselineEntryOnGateway( }; if (!removed) { if (reconciled.state === "resume") { - return finalizeBaselineExclusionTransition(sandboxName, reconciled.transition); + return finalizeBaselineExclusionTransition( + sandboxName, + reconciled.transition, + recheckAuthority, + ); } - return registryTransitionStep( + return authorityBoundRegistryStep( + recheckAuthority, () => registry.addBaselineExclusion(sandboxName, exclusion), `The already-narrow live policy could not be recorded for '${sandboxName}'.`, ); @@ -1906,13 +2121,14 @@ function excludeBaselineEntryOnGateway( const transition = reconciled.state === "resume" ? reconciled.transition - : beginBaselineExclusionTransition(sandboxName, "exclude", exclusion, null); + : beginBaselineExclusionTransition(sandboxName, "exclude", exclusion, null, recheckAuthority); if (!transition) return false; const pushSucceeded = attemptBaselineTransitionPolicyPush( sandboxName, updated, options, gatewayName, + recheckAuthority, ); // When this was a fresh exclusion, a failed push that verifies at the exact // source can clear the journal. A re-exclude that began with committed/live @@ -1923,6 +2139,7 @@ function excludeBaselineEntryOnGateway( pushSucceeded, !previousExclusion, gatewayName, + recheckAuthority, ); } @@ -1941,9 +2158,13 @@ function restoreBaselineEntry( key: string, options: RestoreBaselineEntryOptions = {}, ): boolean { - return withRecordedSandboxGateway(sandboxName, (gatewayName) => - restoreBaselineEntryOnGateway(sandboxName, key, options, gatewayName), - ); + return withRecordedSandboxGateway(sandboxName, (gatewayName) => { + const operation = `restore baseline policy entry '${key}'`; + const authority = inspectNemoClawManagedPolicy(sandboxName, operation, gatewayName); + if (!authority) return false; + const recheckAuthority = () => recheckNemoClawManagedPolicy(sandboxName, operation, authority); + return restoreBaselineEntryOnGateway(sandboxName, key, options, gatewayName, recheckAuthority); + }); } function restoreBaselineEntryOnGateway( @@ -1951,6 +2172,7 @@ function restoreBaselineEntryOnGateway( key: string, options: RestoreBaselineEntryOptions, gatewayName: string, + recheckAuthority: RecheckManagedPolicyAuthority, ): boolean { // Resolve the current agent baseline before changing either durable or live // state. A missing non-OpenClaw baseline must not be mistaken for a release @@ -1979,7 +2201,12 @@ function restoreBaselineEntryOnGateway( return false; } - const reconciled = reconcileBaselineExclusionTransition(sandboxName, key, gatewayName); + const reconciled = reconcileBaselineExclusionTransition( + sandboxName, + key, + gatewayName, + recheckAuthority, + ); if (!reconciled) return false; if (reconciled.state === "restored") return true; if (reconciled.state === "resume" && reconciled.transition.operation !== "restore") { @@ -2001,7 +2228,8 @@ function restoreBaselineEntryOnGateway( return false; } if (!target) { - return registryTransitionStep( + return authorityBoundRegistryStep( + recheckAuthority, () => registry.removeBaselineExclusion(sandboxName, key), `The obsolete exclusion for '${key}' could not be cleared; no live policy changes were made.`, ); @@ -2021,9 +2249,14 @@ function restoreBaselineEntryOnGateway( } if (live.state === "present" && live.digest === targetDigest) { if (reconciled.state === "resume") { - return finalizeBaselineExclusionTransition(sandboxName, reconciled.transition); + return finalizeBaselineExclusionTransition( + sandboxName, + reconciled.transition, + recheckAuthority, + ); } - return registryTransitionStep( + return authorityBoundRegistryStep( + recheckAuthority, () => registry.removeBaselineExclusion(sandboxName, key), `The restored live policy could not be recorded for '${sandboxName}'.`, ); @@ -2031,7 +2264,13 @@ function restoreBaselineEntryOnGateway( const transition = reconciled.state === "resume" ? reconciled.transition - : beginBaselineExclusionTransition(sandboxName, "restore", recordedExclusion, targetDigest); + : beginBaselineExclusionTransition( + sandboxName, + "restore", + recordedExclusion, + targetDigest, + recheckAuthority, + ); if (!transition) return false; const updated = mergeBaselineEntryIntoPolicy(currentPolicy, key, target.entry); const pushSucceeded = attemptBaselineTransitionPolicyPush( @@ -2039,6 +2278,7 @@ function restoreBaselineEntryOnGateway( updated, options, gatewayName, + recheckAuthority, ); return settleBaselineExclusionTransitionAfterPush( sandboxName, @@ -2046,6 +2286,7 @@ function restoreBaselineEntryOnGateway( pushSucceeded, true, gatewayName, + recheckAuthority, ); } @@ -2232,11 +2473,35 @@ function applyPresetContent( return false; } + const requiredNetworkPolicies = parseNetworkPolicies(presetContent); + if (!requiredNetworkPolicies) { + console.error(` Preset ${presetName} has invalid network_policies.`); + return false; + } + const operation = `apply policy preset '${presetName}'`; + let authority: PolicyAuthorityContext; + try { + authority = inspectPolicyAuthority(sandboxName, operation); + if (authority.authority === "externally-managed") { + registry.assertExternalPolicyRequirements({ + inspection: authority.inspection, + requiredPolicy: { network_policies: requiredNetworkPolicies }, + operation, + sandboxName, + }); + return true; + } + } catch (error) { + return reportPolicyAuthorityFailure(error); + } + // Get current policy YAML from sandbox let rawPolicy: string | null = null; try { // Mutations start from round-trippable --base, never provider-composed --full. - rawPolicy = runCapture(buildPolicyGetCommand(sandboxName)); + rawPolicy = runCapture(buildPolicyGetCommand(sandboxName), { + env: { OPENSHELL_GATEWAY: authority.gatewayName }, + }); } catch { /* Refused below. */ } @@ -2343,15 +2608,27 @@ function applyPresetContent( if (policyChanged && !assertOpenshellResolvable(options)) return false; if (policyChanged) { - if (!setPolicyDocument(sandboxName, merged, options)) return false; - console.log(` Applied preset: ${presetName}`); + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; + if ( + !setPolicyDocument(sandboxName, merged, { + nonFatal: options.nonFatal, + gatewayName: authority.gatewayName, + }) + ) { + return false; + } + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; } // Some multi-resource lifecycle callers reserve ownership in the registry // before mutating the live gateway. That ordering prevents a successful // policy set followed by a registry-write failure from leaving an unowned // live key. They explicitly request no second registry write here. - if (options.skipRegistryUpdate) return true; + if (options.skipRegistryUpdate) { + if (policyChanged) console.log(` Applied preset: ${presetName}`); + return true; + } + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; const sandbox = registry.getSandbox(sandboxName); if (sandbox) { @@ -2399,6 +2676,7 @@ function applyPresetContent( ); } + if (policyChanged) console.log(` Applied preset: ${presetName}`); return true; } @@ -2438,29 +2716,12 @@ function applyPresets(sandboxName: string, presetNames: string[]): boolean { const uniquePresetNames = [...new Set(presetNames)].filter(Boolean); if (uniquePresetNames.length === 0) return true; - let rawPolicy: string | null = null; - try { - // Mutations start from round-trippable --base, never provider-composed --full. - rawPolicy = runCapture(buildPolicyGetCommand(sandboxName)); - } catch { - /* Refused below. */ - } - - let merged = parseCurrentPolicyOrEmpty(rawPolicy); - // Keep the batch entrypoint on the same fail-closed source boundary as - // applyPresetContent: an unusable successful read is still a failed read. - if (!merged) { - console.error( - ` Could not read the current policy for sandbox '${sandboxName}'; refusing to apply presets to avoid overwriting it.`, - ); - return false; - } - const presetContents: Array<{ + const preparedPresets: Array<{ content: string; + entries: string; name: string; - state: PresetPolicyState; }> = []; - const originalPolicy = merged; + const requiredNetworkPolicies: PolicyObject = {}; for (const presetName of uniquePresetNames) { const presetContent = loadPresetForSandbox(sandboxName, presetName); @@ -2481,10 +2742,68 @@ function applyPresets(sandboxName: string, presetNames: string[]): boolean { ); return false; } + const networkPolicies = parseNetworkPolicies(presetContent); + if (!networkPolicies) { + console.error(` Preset ${presetName} has invalid network_policies.`); + return false; + } + for (const [key, value] of Object.entries(networkPolicies)) { + requiredNetworkPolicies[key] = value; + } + preparedPresets.push({ + content: presetContent, + entries: presetEntries, + name: presetName, + }); + } + + const operation = "apply policy presets"; + let authority: PolicyAuthorityContext; + try { + authority = inspectPolicyAuthority(sandboxName, operation); + if (authority.authority === "externally-managed") { + registry.assertExternalPolicyRequirements({ + inspection: authority.inspection, + requiredPolicy: { network_policies: requiredNetworkPolicies }, + operation, + sandboxName, + }); + return true; + } + } catch (error) { + return reportPolicyAuthorityFailure(error); + } - const state = classifyPresetEntries(merged, presetEntries); - presetContents.push({ content: presetContent, name: presetName, state }); - merged = mergePresetIntoPolicy(merged, presetEntries); + let rawPolicy: string | null = null; + try { + // Mutations start from round-trippable --base, never provider-composed --full. + rawPolicy = runCapture(buildPolicyGetCommand(sandboxName), { + env: { OPENSHELL_GATEWAY: authority.gatewayName }, + }); + } catch { + /* Refused below. */ + } + + let merged = parseCurrentPolicyOrEmpty(rawPolicy); + // Keep the batch entrypoint on the same fail-closed source boundary as + // applyPresetContent: an unusable successful read is still a failed read. + if (!merged) { + console.error( + ` Could not read the current policy for sandbox '${sandboxName}'; refusing to apply presets to avoid overwriting it.`, + ); + return false; + } + const presetContents: Array<{ + content: string; + name: string; + state: PresetPolicyState; + }> = []; + const originalPolicy = merged; + + for (const preset of preparedPresets) { + const state = classifyPresetEntries(merged, preset.entries); + presetContents.push({ content: preset.content, name: preset.name, state }); + merged = mergePresetIntoPolicy(merged, preset.entries); } let npmBaselineWidened = false; @@ -2534,13 +2853,13 @@ function applyPresets(sandboxName: string, presetNames: string[]): boolean { // The shared fatal path preserves OpenShell's status after it removes the // temporary policy. Onboarding defers that exit until its recovery state // and outer cleanup have finished. - setPolicyDocument(sandboxName, merged); - - for (const preset of presetContents.filter((entry) => entry.state !== "match")) { - console.log(` Applied preset: ${preset.name}`); - } + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; + setPolicyDocument(sandboxName, merged, { gatewayName: authority.gatewayName }); + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; } + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return false; + const sandbox = registry.getSandbox(sandboxName); if (sandbox) { const pols = sandbox.policies || []; @@ -2552,6 +2871,12 @@ function applyPresets(sandboxName: string, presetNames: string[]): boolean { registry.updateSandbox(sandboxName, { policies: pols }); } + if (policyChanged) { + for (const preset of presetContents.filter((entry) => entry.state !== "match")) { + console.log(` Applied preset: ${preset.name}`); + } + } + return true; } @@ -2916,6 +3241,10 @@ function applyPermissivePolicy(sandboxName: string): void { ); } + const operation = "apply the permissive sandbox policy"; + const authority = inspectPolicyAuthority(sandboxName, operation); + assertNemoClawManagedPolicy(authority, operation); + const policyPath = resolvePermissivePolicyPath(sandboxName); if (!fs.existsSync(policyPath)) { throw new Error(`Permissive policy not found: ${policyPath}`); @@ -2928,11 +3257,14 @@ function applyPermissivePolicy(sandboxName: string): void { console.log(" Applying permissive policy..."); assertOpenshellResolvable(); - if (materializedPolicy === policyDocument) { - run(buildPolicySetCommand(policyPath, sandboxName)); - } else { - setPolicyDocument(sandboxName, materializedPolicy); - } + setPolicyDocument(sandboxName, materializedPolicy, { gatewayName: authority.gatewayName }); + const observed = inspectPolicyAuthority(sandboxName, operation, authority.gatewayName, true); + registry.assertRecordedPolicyAuthority( + authority.authority, + observed.authority, + operation, + ); + assertNemoClawManagedPolicy(observed, operation); console.log(" Applied permissive policy."); } diff --git a/src/lib/policy/policy-apply-finality.test.ts b/src/lib/policy/policy-apply-finality.test.ts index 687d7231799..60a5207530b 100644 --- a/src/lib/policy/policy-apply-finality.test.ts +++ b/src/lib/policy/policy-apply-finality.test.ts @@ -7,15 +7,28 @@ import os from "node:os"; import path from "node:path"; import { beforeEach, describe, expect, it, vi } from "vitest"; -const { addCustomPolicy, getSandbox, resolveOpenshell, run, runCapture, updateSandbox } = - vi.hoisted(() => ({ - addCustomPolicy: vi.fn(), - getSandbox: vi.fn(), - resolveOpenshell: vi.fn(), - run: vi.fn(), - runCapture: vi.fn(), - updateSandbox: vi.fn(), - })); +const { + addCustomPolicy, + getSandbox, + inspectSandboxPolicyAuthority, + resolveOpenshell, + run, + runCapture, + updateSandbox, +} = vi.hoisted(() => ({ + addCustomPolicy: vi.fn(), + getSandbox: vi.fn(), + inspectSandboxPolicyAuthority: vi.fn(), + resolveOpenshell: vi.fn(), + run: vi.fn(), + runCapture: vi.fn(), + updateSandbox: vi.fn(), +})); + +vi.mock("../adapters/openshell/policy-authority", async (importOriginal) => ({ + ...(await importOriginal()), + inspectSandboxPolicyAuthority, +})); vi.mock("../runner", async (importOriginal) => ({ ...(await importOriginal()), @@ -139,13 +152,23 @@ describe("applyPresets finality when openshell rejects the composed policy", () run.mockReset(); runCapture.mockReset(); getSandbox.mockReset(); + inspectSandboxPolicyAuthority.mockReset(); updateSandbox.mockReset(); addCustomPolicy.mockReset(); resolveOpenshell.mockReset(); resolveOpenshell.mockReturnValue("/usr/local/bin/openshell"); + inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); runCapture.mockReturnValue(BASE_POLICY); - getSandbox.mockReturnValue({ name: SANDBOX, agent: "openclaw", policies: [] }); + getSandbox.mockReturnValue({ + name: SANDBOX, + agent: "openclaw", + policies: [], + policyAuthority: "nemoclaw-managed", + }); vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {}); }); @@ -212,12 +235,22 @@ describe("single-preset mutations when openshell rejects the composed policy", ( run.mockReset(); runCapture.mockReset(); getSandbox.mockReset(); + inspectSandboxPolicyAuthority.mockReset(); updateSandbox.mockReset(); addCustomPolicy.mockReset(); resolveOpenshell.mockReset(); resolveOpenshell.mockReturnValue("/usr/local/bin/openshell"); - getSandbox.mockReturnValue({ name: SANDBOX, agent: "openclaw", policies: ["weather"] }); + inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); + getSandbox.mockReturnValue({ + name: SANDBOX, + agent: "openclaw", + policies: ["weather"], + policyAuthority: "nemoclaw-managed", + }); run.mockReturnValue(policySetResult(openshellRejection(REJECTION_MESSAGE))); vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {}); @@ -261,12 +294,22 @@ describe("applyPresets temporary policy material under local I/O failure", () => run.mockReset(); runCapture.mockReset(); getSandbox.mockReset(); + inspectSandboxPolicyAuthority.mockReset(); updateSandbox.mockReset(); resolveOpenshell.mockReset(); resolveOpenshell.mockReturnValue("/usr/local/bin/openshell"); + inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); runCapture.mockReturnValue(BASE_POLICY); - getSandbox.mockReturnValue({ name: SANDBOX, agent: "openclaw", policies: [] }); + getSandbox.mockReturnValue({ + name: SANDBOX, + agent: "openclaw", + policies: [], + policyAuthority: "nemoclaw-managed", + }); run.mockReturnValue(policySetResult(openshellRejection("refused"))); vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {}); diff --git a/src/lib/policy/policy-authority-integration.test.ts b/src/lib/policy/policy-authority-integration.test.ts new file mode 100644 index 00000000000..5a29c646b62 --- /dev/null +++ b/src/lib/policy/policy-authority-integration.test.ts @@ -0,0 +1,243 @@ +// 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 YAML from "yaml"; + +const mocks = vi.hoisted(() => ({ + addCustomPolicy: vi.fn(), + beginBaselineExclusionTransition: vi.fn(), + getBaselineExclusions: vi.fn(), + getBaselineExclusionTransition: vi.fn(), + getSandbox: vi.fn(), + inspectSandboxPolicyAuthority: vi.fn(), + resolveOpenshell: vi.fn(), + run: vi.fn(), + runCapture: vi.fn(), + updateSandbox: vi.fn(), +})); + +vi.mock("../adapters/openshell/policy-authority", async (importOriginal) => ({ + ...(await importOriginal()), + inspectSandboxPolicyAuthority: mocks.inspectSandboxPolicyAuthority, +})); + +vi.mock("../adapters/openshell/resolve", async (importOriginal) => ({ + ...(await importOriginal()), + resolveOpenshell: mocks.resolveOpenshell, +})); + +vi.mock("../runner", async (importOriginal) => ({ + ...(await importOriginal()), + run: mocks.run, + runCapture: mocks.runCapture, +})); + +vi.mock("../state/registry", async (importOriginal) => ({ + ...(await importOriginal()), + addCustomPolicy: mocks.addCustomPolicy, + beginBaselineExclusionTransition: mocks.beginBaselineExclusionTransition, + getBaselineExclusions: mocks.getBaselineExclusions, + getBaselineExclusionTransition: mocks.getBaselineExclusionTransition, + getSandbox: mocks.getSandbox, + updateSandbox: mocks.updateSandbox, +})); + +import { + applyPermissivePolicy, + applyPresetContent, + excludeBaselineEntry, + removePreset, + restoreBaselineEntry, +} from "./index"; + +const SANDBOX = "authority-9833"; +const BASE_POLICY = `version: 1 +network_policies: + existing: + endpoints: + - host: existing.example.com + port: 443 +`; +const WEATHER_PRESET = `preset: + name: weather + description: Read-only weather +network_policies: + weather: + name: weather + endpoints: + - host: wttr.in + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } +`; +const WEATHER_POLICY = YAML.parse(WEATHER_PRESET).network_policies.weather; + +function reportedErrors(): string { + return vi + .mocked(console.error) + .mock.calls.flat() + .map((entry) => String(entry)) + .join("\n"); +} + +describe("sandbox policy authority ownership", () => { + let sandbox: Record; + + beforeEach(() => { + for (const mock of Object.values(mocks)) mock.mockReset(); + sandbox = { + name: SANDBOX, + gatewayName: "nemoclaw", + policies: [], + }; + mocks.getSandbox.mockImplementation(() => sandbox); + mocks.getBaselineExclusions.mockReturnValue([]); + mocks.getBaselineExclusionTransition.mockReturnValue(null); + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); + mocks.resolveOpenshell.mockReturnValue("/usr/local/bin/openshell"); + mocks.runCapture.mockReturnValue(BASE_POLICY); + mocks.run.mockReturnValue({ status: 0 }); + mocks.updateSandbox.mockImplementation((_name, updates) => { + sandbox = { ...sandbox, ...updates }; + return true; + }); + vi.spyOn(console, "error").mockImplementation(() => undefined); + vi.spyOn(console, "log").mockImplementation(() => undefined); + vi.spyOn(console, "warn").mockImplementation(() => undefined); + }); + + it("accepts an externally supplied custom preset without setting or attributing it (#9833)", () => { + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { network_policies: { weather: WEATHER_POLICY } }, + }); + + expect( + applyPresetContent(SANDBOX, "weather", WEATHER_PRESET, { + custom: { sourcePath: "/tmp/weather.yaml" }, + }), + ).toBe(true); + + expect(mocks.runCapture).not.toHaveBeenCalled(); + expect(mocks.run).not.toHaveBeenCalled(); + expect(mocks.addCustomPolicy).not.toHaveBeenCalled(); + expect(mocks.updateSandbox).toHaveBeenCalledTimes(1); + expect(mocks.updateSandbox).toHaveBeenCalledWith(SANDBOX, { + policyAuthority: "externally-managed", + }); + }); + + it("records external authority before refusing a missing preset requirement (#9833)", () => { + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { network_policies: {} }, + }); + + expect(applyPresetContent(SANDBOX, "weather", WEATHER_PRESET)).toBe(false); + + expect(reportedErrors()).toContain("external policy authority"); + expect(reportedErrors()).toContain('"weather"'); + expect(reportedErrors()).not.toContain("wttr.in"); + expect(reportedErrors()).not.toContain("network_policies:"); + expect(mocks.runCapture).not.toHaveBeenCalled(); + expect(mocks.run).not.toHaveBeenCalled(); + expect(mocks.updateSandbox).toHaveBeenCalledOnce(); + expect(sandbox).toEqual( + expect.objectContaining({ policyAuthority: "externally-managed", policies: [] }), + ); + }); + + it("rechecks authority before policy set and refuses an ownership change (#9833)", () => { + mocks.inspectSandboxPolicyAuthority + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "externally-managed", effectivePolicy: {} }); + + expect(applyPresetContent(SANDBOX, "weather", WEATHER_PRESET, { nonFatal: true })).toBe(false); + + expect(mocks.inspectSandboxPolicyAuthority).toHaveBeenCalledTimes(2); + expect(mocks.runCapture).toHaveBeenCalledTimes(1); + expect(mocks.run).not.toHaveBeenCalled(); + expect(mocks.updateSandbox).toHaveBeenCalledOnce(); + expect(sandbox).toEqual( + expect.objectContaining({ policyAuthority: "nemoclaw-managed", policies: [] }), + ); + expect(reportedErrors()).toContain("policy authority changed"); + expect(reportedErrors()).toContain("external policy authority"); + }); + + it("withholds single-preset success when the final registry check changes authority (#9833)", () => { + sandbox = { ...sandbox, policyAuthority: "nemoclaw-managed" }; + mocks.inspectSandboxPolicyAuthority + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "externally-managed", effectivePolicy: {} }); + + expect( + applyPresetContent(SANDBOX, "weather", WEATHER_PRESET, { + custom: { sourcePath: "/tmp/weather.yaml" }, + }), + ).toBe(false); + + expect(mocks.run).toHaveBeenCalledOnce(); + expect(mocks.addCustomPolicy).not.toHaveBeenCalled(); + expect(mocks.updateSandbox).not.toHaveBeenCalled(); + expect(console.log).not.toHaveBeenCalledWith(" Applied preset: weather"); + expect(reportedErrors()).toContain("policy authority changed"); + }); + + it("refuses external removal before reading or changing policy state (#9833)", () => { + sandbox = { ...sandbox, policyAuthority: "externally-managed", policies: ["weather"] }; + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { network_policies: { weather: WEATHER_POLICY } }, + }); + + expect(removePreset(SANDBOX, "weather", { nonFatal: true })).toBe(false); + + expect(mocks.runCapture).not.toHaveBeenCalled(); + expect(mocks.run).not.toHaveBeenCalled(); + expect(mocks.updateSandbox).not.toHaveBeenCalled(); + expect(reportedErrors()).toContain("external policy authority"); + }); + + it("refuses external baseline and permissive changes before side effects (#9833)", () => { + sandbox = { ...sandbox, policyAuthority: "externally-managed" }; + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "externally-managed", + effectivePolicy: {}, + }); + + expect(excludeBaselineEntry(SANDBOX, "existing", "reviewed-digest", { nonFatal: true })).toBe( + false, + ); + expect(restoreBaselineEntry(SANDBOX, "existing", { nonFatal: true })).toBe(false); + expect(() => applyPermissivePolicy(SANDBOX)).toThrow(/external policy authority/); + + expect(mocks.getBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(mocks.beginBaselineExclusionTransition).not.toHaveBeenCalled(); + expect(mocks.runCapture).not.toHaveBeenCalled(); + expect(mocks.run).not.toHaveBeenCalled(); + expect(mocks.updateSandbox).not.toHaveBeenCalled(); + }); + + it("throws when permissive policy authority changes after the policy set (#9833)", () => { + sandbox = { ...sandbox, policyAuthority: "nemoclaw-managed" }; + mocks.inspectSandboxPolicyAuthority + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "externally-managed", effectivePolicy: {} }); + + expect(() => applyPermissivePolicy(SANDBOX)).toThrow(/policy authority changed/u); + + expect(mocks.run).toHaveBeenCalledOnce(); + expect(console.log).not.toHaveBeenCalledWith(" Applied permissive policy."); + }); +}); diff --git a/src/lib/policy/policy-registry.ts b/src/lib/policy/policy-registry.ts new file mode 100644 index 00000000000..13d030ba228 --- /dev/null +++ b/src/lib/policy/policy-registry.ts @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** Registry operations owned by policy authority and attribution flows. */ +export { + addBaselineExclusion, + addCustomPolicy, + beginBaselineExclusionTransition, + clearBaselineExclusionTransition, + commitBaselineExclusionTransition, + getBaselineExclusions, + getBaselineExclusionTransition, + getConfiguredMessagingChannelsFromEntry, + getCustomPolicies, + getDisabledMessagingChannelsFromEntry, + getSandbox, + normalizeSandboxPolicyAttribution, + removeBaselineExclusion, + removeCustomPolicyByName, + updateSandbox, +} from "../state/registry"; + +export type { + BaselineExclusionEntry, + BaselineExclusionTransition, + BaselineExclusionTransitionOperation, + SandboxEntry, +} from "../state/registry"; + +export { + assertExternalPolicyRequirements, + assertRecordedPolicyAuthority, + inspectSandboxPolicyAuthority, +} from "../adapters/openshell/policy-authority"; +export type { + SandboxPolicyAuthority, + SandboxPolicyAuthorityInspection, +} from "../adapters/openshell/policy-authority"; diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index f62a8128756..9b4772b740f 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -12,6 +12,7 @@ import { normalizeBaselineExclusions, normalizeBaselineExclusionTransition, normalizeCustomPolicyEntries, + normalizeSandboxPolicyAuthority, } from "./registry-normalization"; const originalHome = process.env.HOME; @@ -67,6 +68,29 @@ describe("sandbox registry normalization", () => { estimatedModelDownloadBytes: null, } as const; + const createPolicyAttribution = () => { + const exclusion = { + version: 1 as const, + agent: "hermes", + key: "nous_research", + digest: "a".repeat(64), + acknowledgedAt: "2026-08-20T00:00:00.000Z", + }; + return { + policies: ["weather"], + customPolicies: [{ name: "private-api", content: "network_policies: {}" }], + baselineExclusions: [exclusion], + baselineExclusionTransition: { + id: "123e4567-e89b-42d3-a456-426614174983", + operation: "exclude" as const, + exclusion, + targetLiveDigest: null, + startedAt: "2026-08-20T00:00:01.000Z", + }, + policyPresetsFinalized: true, + }; + }; + it.each([null, [], 42, "invalid"])( "treats a non-object top-level registry document as empty: %j", async (document) => { @@ -273,6 +297,154 @@ describe("sandbox registry normalization", () => { }); expect(() => registry.getSandbox("profile")).toThrow("invalid serving profile provenance"); }); + + function expectExternalAttributionCleared(entry: unknown, name: string): void { + expect(entry).toMatchObject({ + name, + policies: [], + policyAuthority: "externally-managed", + }); + expect(entry).not.toHaveProperty("customPolicies"); + expect(entry).not.toHaveProperty("baselineExclusions"); + expect(entry).not.toHaveProperty("baselineExclusionTransition"); + expect(entry).not.toHaveProperty("policyPresetsFinalized"); + expect(entry).not.toHaveProperty("policyTier"); + } + + it("round-trips known policy authority while leaving legacy authority unknown (#9833)", async () => { + const registry = await loadRegistryWith({ + legacy: { name: "legacy" }, + managed: { name: "managed", policyAuthority: "nemoclaw-managed" }, + external: { name: "external", policyAuthority: "externally-managed" }, + }); + registry.save(registry.load()); + const persisted = JSON.parse( + fs.readFileSync(path.join(process.env.HOME!, ".nemoclaw", "sandboxes.json"), "utf8"), + ) as { sandboxes: Record> }; + expect(registry.getSandbox("legacy")?.policyAuthority).toBeUndefined(); + expect(registry.getSandbox("managed")?.policyAuthority).toBe("nemoclaw-managed"); + expect(registry.getSandbox("external")?.policyAuthority).toBe("externally-managed"); + expect(persisted.sandboxes.legacy).not.toHaveProperty("policyAuthority"); + expect(persisted.sandboxes.managed?.policyAuthority).toBe("nemoclaw-managed"); + expect(persisted.sandboxes.external?.policyAuthority).toBe("externally-managed"); + }); + + it("clears NemoClaw policy attribution from externally managed rows (#9833)", async () => { + const attribution = createPolicyAttribution(); + const registry = await loadRegistryWith({ + legacy: { name: "legacy", ...attribution, policyTier: "strict" }, + managed: { + name: "managed", + ...attribution, + policyAuthority: "nemoclaw-managed", + policyTier: "strict", + }, + external: { + name: "external", + ...attribution, + policyAuthority: "externally-managed", + policyTier: "strict", + }, + }); + + expect(registry.getSandbox("legacy")).toMatchObject(attribution); + expect(registry.getSandbox("managed")).toMatchObject(attribution); + expectExternalAttributionCleared(registry.getSandbox("external"), "external"); + }); + + it.each([null, "sandbox", {}])( + "fails closed on malformed persisted policy authority %j (#9833)", + async (policyAuthority) => { + const registry = await loadRegistryWith({ + alpha: { name: "alpha", policyAuthority }, + }); + + expect(() => registry.getSandbox("alpha")).toThrow(/invalid policy authority/i); + }, + ); + + it("backfills policy authority once without allowing later changes or removal (#9833)", async () => { + const registry = await loadRegistryWith({ legacy: { name: "legacy" } }); + + expect(() => registry.updateSandbox("legacy", { policyAuthority: "global" as never })).toThrow( + /invalid policy authority/i, + ); + expect(registry.updateSandbox("legacy", { policyAuthority: "nemoclaw-managed" })).toBe(true); + expect(() => + registry.updateSandbox("legacy", { policyAuthority: "externally-managed" }), + ).toThrow(/policy authority changed/u); + expect(() => registry.updateSandbox("legacy", { policyAuthority: undefined })).toThrow( + /policy authority changed/u, + ); + expect(registry.getSandbox("legacy")?.policyAuthority).toBe("nemoclaw-managed"); + + expect(() => + registry.registerSandbox({ name: "legacy", policyAuthority: "externally-managed" }), + ).toThrow(/policy authority changed/u); + }); + + it("canonicalizes external attribution across registry mutations and recovery (#9833)", async () => { + const registry = await loadRegistryWith({ + updated: { name: "updated", ...createPolicyAttribution(), policyTier: "strict" }, + }); + const externalEntry = (name: string) => ({ + name, + ...createPolicyAttribution(), + policyAuthority: "externally-managed" as const, + policyTier: "strict", + }); + + expectExternalAttributionCleared( + registry.registerSandbox(externalEntry("registered")), + "registered", + ); + expect(registry.updateSandbox("updated", { policyAuthority: "externally-managed" })).toBe(true); + expectExternalAttributionCleared(registry.getSandbox("updated"), "updated"); + + registry.restoreSandboxEntry(externalEntry("recovered")); + expectExternalAttributionCleared(registry.getSandbox("recovered"), "recovered"); + const receipt = registry.removeSandboxWithReceipt("recovered")!; + expect( + registry.restoreSandboxEntryIfMissing({ ...receipt, entry: externalEntry("recovered") }), + ).toBe(true); + expectExternalAttributionCleared(registry.getSandbox("recovered"), "recovered"); + }); + + it("preserves a replacement row when recovery has a different policy authority (#9833)", async () => { + const registry = await loadRegistryWith({ + alpha: { + name: "alpha", + model: "current", + policyAuthority: "externally-managed", + }, + }); + + expect(() => + registry.restoreSandboxEntry({ + name: "alpha", + model: "recovered", + policyAuthority: "nemoclaw-managed", + }), + ).toThrow(/policy authority changed during recovery/u); + expect(registry.getSandbox("alpha")).toMatchObject({ + model: "current", + policyAuthority: "externally-managed", + }); + }); +}); + +describe("sandbox policy authority normalization", () => { + it.each([ + [undefined, undefined], + ["nemoclaw-managed", "nemoclaw-managed"], + ["externally-managed", "externally-managed"], + ])("normalizes known policy authority %j (#9833)", (input, expected) => { + expect(normalizeSandboxPolicyAuthority(input)).toBe(expected); + }); + + it.each(["sandbox", null, {}])("rejects invalid policy authority %j (#9833)", (input) => { + expect(() => normalizeSandboxPolicyAuthority(input)).toThrow(/invalid policy authority/i); + }); }); describe("custom policy pin receipt normalization (#8176)", () => { diff --git a/src/lib/state/registry-normalization.ts b/src/lib/state/registry-normalization.ts index 7381b9c8381..8888e5c62fb 100644 --- a/src/lib/state/registry-normalization.ts +++ b/src/lib/state/registry-normalization.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { SandboxPolicyAuthority } from "../adapters/openshell/policy-authority"; import { isObjectRecord } from "../core/json-types"; import { normalizeTrustedPrivatePolicyPinReceipt } from "../policy/trusted-private-endpoints"; import type { @@ -8,13 +9,60 @@ import type { BaselineExclusionTransition, CustomPolicyEntry, SandboxEntry, -} from "./registry"; +} from "./registry/types"; const BASELINE_TRANSITION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; const BASELINE_TRANSITION_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/; const SHA256_DIGEST_PATTERN = /^[a-f0-9]{64}$/; +/** Keep legacy absence unknown and reject every unrecognized authority value. */ +export function normalizeSandboxPolicyAuthority( + value: unknown, +): SandboxPolicyAuthority | undefined { + if (value === undefined) return undefined; + if (value === "nemoclaw-managed" || value === "externally-managed") return value; + throw new Error( + "Sandbox registry contains an invalid policy authority; repair the registry before continuing", + ); +} + +/** Remove policy attribution that an external authority owns and normalize managed state. */ +export function normalizeSandboxPolicyAttribution(entry: SandboxEntry): SandboxEntry { + const policyAuthority = normalizeSandboxPolicyAuthority(entry.policyAuthority); + const { + policies: _policies, + customPolicies: _customPolicies, + baselineExclusions: _baselineExclusions, + baselineExclusionTransition: _baselineExclusionTransition, + policyPresetsFinalized: _policyPresetsFinalized, + policyTier: _policyTier, + policyAuthority: _policyAuthority, + ...rest + } = entry; + if (policyAuthority === "externally-managed") { + return { ...rest, policies: [], policyAuthority }; + } + + const baselineExclusions = normalizeBaselineExclusions(entry.baselineExclusions); + const baselineExclusionTransition = normalizeBaselineExclusionTransition( + entry.baselineExclusionTransition, + ); + const customPolicies = normalizeCustomPolicyEntries(entry.customPolicies); + return { + ...rest, + ...(entry.policies !== undefined ? { policies: entry.policies } : {}), + ...(customPolicies ? { customPolicies } : {}), + ...(baselineExclusions ? { baselineExclusions } : {}), + ...(baselineExclusionTransition ? { baselineExclusionTransition } : {}), + ...(entry.policyPresetsFinalized !== undefined + ? { policyPresetsFinalized: entry.policyPresetsFinalized } + : {}), + ...(entry.policyTier !== undefined ? { policyTier: entry.policyTier } : {}), + ...(policyAuthority !== undefined ? { policyAuthority } : {}), + }; +} + /** Normalize persisted custom policy content and its generated-pin authority. */ export function normalizeCustomPolicyEntries(value: unknown): CustomPolicyEntry[] | undefined { if (value === undefined) return undefined; diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 233ccafcd81..3173526a60e 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { isDeepStrictEqual } from "node:util"; +import { PolicyAuthorityRefusalError } from "../adapters/openshell/policy-authority"; import type { InferenceSelection } from "../inference/selection"; import { inferenceSelectionRegistryFields, @@ -39,6 +40,8 @@ import { normalizeBaselineExclusions, normalizeBaselineExclusionTransition, normalizeCustomPolicyEntries, + normalizeSandboxPolicyAttribution, + normalizeSandboxPolicyAuthority, retainedDefaultSandbox, } from "./registry-normalization"; import * as reversibleRemoval from "./registry-reversible-removal"; @@ -115,7 +118,11 @@ export { getMessagingPlanFromEntry, type SandboxMessagingState, } from "./registry-messaging"; -export { hasUnsafeHostMountTerminalText, normalizeCustomPolicyEntries }; +export { + hasUnsafeHostMountTerminalText, + normalizeCustomPolicyEntries, + normalizeSandboxPolicyAttribution, +}; export type SandboxRemovalReceipt = reversibleRemoval.RegistryRemovalReceipt; @@ -159,6 +166,20 @@ export function registerSandbox( if (entry.servingProfileProvenance !== undefined && !servingProfileProvenance) { throw new Error("Cannot register a sandbox with invalid serving profile provenance"); } + const requestedPolicyAuthority = normalizeSandboxPolicyAuthority(entry.policyAuthority); + const recordedPolicyAuthority = normalizeSandboxPolicyAuthority( + data.sandboxes[entry.name]?.policyAuthority, + ); + if ( + recordedPolicyAuthority !== undefined && + requestedPolicyAuthority !== undefined && + recordedPolicyAuthority !== requestedPolicyAuthority + ) { + throw new PolicyAuthorityRefusalError( + "Cannot register a sandbox after its policy authority changed", + ); + } + const policyAuthority = requestedPolicyAuthority ?? recordedPolicyAuthority; if (retainedDefaultSandbox(data.defaultSandbox, data.sandboxes) === null) { data.defaultSandbox = null; } @@ -219,12 +240,17 @@ export function registerSandbox( : undefined, openshellDriver: entry.openshellDriver || null, openshellVersion: entry.openshellVersion || null, - policies: entry.policies || [], - baselineExclusions: normalizeBaselineExclusions(entry.baselineExclusions), - baselineExclusionTransition: normalizeBaselineExclusionTransition( - entry.baselineExclusionTransition, - ), - policyTier: entry.policyTier || null, + ...(policyAuthority !== undefined ? { policyAuthority } : {}), + ...(policyAuthority === "externally-managed" + ? { policies: [] } + : { + policies: entry.policies || [], + baselineExclusions: normalizeBaselineExclusions(entry.baselineExclusions), + baselineExclusionTransition: normalizeBaselineExclusionTransition( + entry.baselineExclusionTransition, + ), + policyTier: entry.policyTier || null, + }), webSearchEnabled: typeof entry.webSearchEnabled === "boolean" ? entry.webSearchEnabled : undefined, // Preserve absence on reconstructed legacy rows. Only a freshly built @@ -417,6 +443,19 @@ function changesHostLocalInferenceLifecycleAuthority( ); } +function assertRecordedPolicyAuthorityUnchanged( + current: SandboxEntry, + updates: Partial, +): void { + if (!Object.prototype.hasOwnProperty.call(updates, "policyAuthority")) return; + const requested = normalizeSandboxPolicyAuthority(updates.policyAuthority); + if (current.policyAuthority === undefined || requested === current.policyAuthority) return; + throw new PolicyAuthorityRefusalError( + `Refusing to update sandbox '${current.name}' because its policy authority changed ` + + `from ${current.policyAuthority} to ${requested ?? "unrecorded"}.`, + ); +} + export function updateSandbox(name: string, updates: Partial): boolean { return withLock(() => { const data = load(); @@ -426,7 +465,8 @@ export function updateSandbox(name: string, updates: Partial): boo return false; } if (changesHostLocalInferenceLifecycleAuthority(current, updates)) return false; - data.sandboxes[name] = { ...current, ...updates }; + assertRecordedPolicyAuthorityUnchanged(current, updates); + data.sandboxes[name] = normalizeSandboxPolicyAttribution({ ...current, ...updates }); save(data); return true; }); @@ -471,7 +511,24 @@ export function restoreSandboxEntry( ): void { withLock(() => { const data = load(); - save(reversibleRemoval.restoreSandboxEntryInRegistry(data, entry, options.defaultTransition)); + const normalizedEntry = normalizeSandboxPolicyAttribution(entry); + const current = data.sandboxes[normalizedEntry.name]; + if ( + current && + normalizeSandboxPolicyAuthority(current.policyAuthority) !== + normalizeSandboxPolicyAuthority(normalizedEntry.policyAuthority) + ) { + throw new PolicyAuthorityRefusalError( + `Refusing to restore sandbox '${normalizedEntry.name}' because its policy authority changed during recovery.`, + ); + } + save( + reversibleRemoval.restoreSandboxEntryInRegistry( + data, + normalizedEntry, + options.defaultTransition, + ), + ); }); } @@ -479,7 +536,10 @@ export function restoreSandboxEntry( export function restoreSandboxEntryIfMissing(receipt: SandboxRemovalReceipt): boolean { return withLock(() => { const data = load(); - const result = reversibleRemoval.restoreSandboxIfMissingInRegistry(data, receipt); + const result = reversibleRemoval.restoreSandboxIfMissingInRegistry(data, { + ...receipt, + entry: normalizeSandboxPolicyAttribution(receipt.entry), + }); if (!result.restored) return false; save(result.registry); return result.restored; diff --git a/src/lib/state/registry/persistence.ts b/src/lib/state/registry/persistence.ts index 85e0c02d3d3..5e81706532d 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -13,9 +13,7 @@ import { serializeSandboxMessagingStateForDisk, } from "../registry-messaging"; import { - normalizeBaselineExclusions, - normalizeBaselineExclusionTransition, - normalizeCustomPolicyEntries, + normalizeSandboxPolicyAttribution, parseSandboxRegistryEntries, retainedDefaultSandbox, } from "../registry-normalization"; @@ -162,11 +160,7 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { "load", ); const mcp = normalizeSandboxMcpState(entry.mcp); - const baselineExclusions = normalizeBaselineExclusions(entry.baselineExclusions); - const baselineExclusionTransition = normalizeBaselineExclusionTransition( - entry.baselineExclusionTransition, - ); - const customPolicies = normalizeCustomPolicyEntries(entry.customPolicies); + const policyEntry = normalizeSandboxPolicyAttribution(entry); const { cuaRuntimeReadiness: _legacyCuaRuntimeReadiness, messaging: _messaging, @@ -175,11 +169,8 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { hostLocalInferenceProvenance: _hostLocalInferenceProvenance, servingProfileProvenance: _servingProfileProvenance, mcp: _mcp, - baselineExclusions: _baselineExclusions, - baselineExclusionTransition: _baselineExclusionTransition, - customPolicies: _customPolicies, ...rest - } = entry as SandboxEntry & { cuaRuntimeReadiness?: unknown }; + } = policyEntry as SandboxEntry & { cuaRuntimeReadiness?: unknown }; return { ...rest, ...(workload ? { workload } : {}), @@ -188,9 +179,6 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { ...(servingProfileProvenance ? { servingProfileProvenance } : {}), ...(messaging ? { messaging } : {}), ...(mcp ? { mcp } : {}), - ...(baselineExclusions ? { baselineExclusions } : {}), - ...(baselineExclusionTransition ? { baselineExclusionTransition } : {}), - ...(customPolicies ? { customPolicies } : {}), }; } @@ -230,11 +218,7 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { "save", ); const mcp = serializeSandboxMcpStateForDisk(durable.mcp); - const baselineExclusions = normalizeBaselineExclusions(durable.baselineExclusions); - const baselineExclusionTransition = normalizeBaselineExclusionTransition( - durable.baselineExclusionTransition, - ); - const customPolicies = normalizeCustomPolicyEntries(durable.customPolicies); + const policyEntry = normalizeSandboxPolicyAttribution(durable); const { cuaRuntimeReadiness: _legacyCuaRuntimeReadiness, messaging: _messaging, @@ -243,11 +227,8 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { hostLocalInferenceProvenance: _hostLocalInferenceProvenance, servingProfileProvenance: _servingProfileProvenance, mcp: _mcp, - baselineExclusions: _baselineExclusions, - baselineExclusionTransition: _baselineExclusionTransition, - customPolicies: _customPolicies, ...rest - } = durable as SandboxEntry & { cuaRuntimeReadiness?: unknown }; + } = policyEntry as SandboxEntry & { cuaRuntimeReadiness?: unknown }; return { ...rest, ...(rest.dashboardPort === 0 ? { dashboardPort: null } : {}), @@ -257,8 +238,5 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { ...(servingProfileProvenance ? { servingProfileProvenance } : {}), ...(messaging ? { messaging } : {}), ...(mcp ? { mcp } : {}), - ...(baselineExclusions ? { baselineExclusions } : {}), - ...(baselineExclusionTransition ? { baselineExclusionTransition } : {}), - ...(customPolicies ? { customPolicies } : {}), }; } diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index 578104a2ecb..5c23bf7c241 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { SandboxPolicyAuthority } from "../../adapters/openshell/policy-authority"; import type { InferenceSelection } from "../../inference/selection"; import type { ServingProfileProvenance } from "../../inference/serving/types"; import type { WebSearchProvider } from "../../inference/web-search"; @@ -119,6 +120,8 @@ export interface SandboxEntry extends Partial { hostMounts?: SandboxHostMount[]; openshellDriver?: string | null; openshellVersion?: string | null; + /** Policy authority for a completed sandbox; absence means unknown. */ + policyAuthority?: SandboxPolicyAuthority; policies?: string[]; customPolicies?: CustomPolicyEntry[]; /** Operator exclusions from the agent baseline policy, replayed on rebuild. */ diff --git a/test/policies.test.ts b/test/policies.test.ts index e194f4894b5..395ae521a48 100644 --- a/test/policies.test.ts +++ b/test/policies.test.ts @@ -17,6 +17,12 @@ const policies = requireForTest( const resolveOpenshellModule = requireForTest( path.join(REPO_ROOT, "src", "lib", "adapters", "openshell", "resolve.ts"), ) as { resolveOpenshell: (...args: unknown[]) => string | null }; +const policyAuthorityModule = requireForTest( + path.join(REPO_ROOT, "src", "lib", "adapters", "openshell", "policy-authority.ts"), +) as typeof import("../src/lib/adapters/openshell/policy-authority"); +const registryForTest = requireForTest( + path.join(REPO_ROOT, "src", "lib", "state", "registry.ts"), +) as typeof import("../src/lib/state/registry"); const POLICIES_PATH = JSON.stringify(path.join(REPO_ROOT, "src", "lib", "policy", "index.ts")); const REGISTRY_PATH = JSON.stringify(path.join(REPO_ROOT, "src", "lib", "state", "registry.ts")); const SOURCE_NODE_ARGS = ["--import", "tsx"]; @@ -36,7 +42,28 @@ function parseResultPayload(stdout: string): any { return JSON.parse(stdout.slice(markerIndex + marker.length)); } +function managedPolicyMetadata(sandboxName: string): string { + return JSON.stringify({ + scope: "sandbox", + sandbox: sandboxName, + status: "effective", + policy_source: "sandbox", + policy: { version: 1, network_policies: {} }, + }); +} + describe("policies", () => { + beforeEach(() => { + vi.spyOn(policyAuthorityModule, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + describe("listPresets", () => { it.each(Array.from(policies.listPresets(), (value) => [value]))( "$name has a name and description", @@ -162,6 +189,10 @@ process.stdout.write("\n__RESULT__" + JSON.stringify({ set -euo pipefail printf '%s\n' "$*" >> ${JSON.stringify(callsPath)} if [ "$1 $2" = "policy get" ]; then + if [[ " $* " == *" --output json "* ]]; then + printf '%s\n' ${JSON.stringify(managedPolicyMetadata("test-sandbox"))} + exit 0 + fi printf 'Version: 1\nHash: test\n---\nversion: 1\n\nnetwork_policies: {}\n' exit 0 fi @@ -199,9 +230,9 @@ exit 1 expect(result.status).toBe(0); const payload = parseResultPayload(result.stdout); expect(payload.result).toBe(true); - expect(payload.calls.filter((call: string) => call.startsWith("policy get "))).toHaveLength( - 1, - ); + const policyGets = payload.calls.filter((call: string) => call.startsWith("policy get ")); + expect(policyGets.some((call: string) => call.includes("--output json"))).toBe(true); + expect(policyGets.some((call: string) => !call.includes("--output json"))).toBe(true); expect(payload.calls.filter((call: string) => call.startsWith("policy set "))).toHaveLength( 1, ); @@ -234,6 +265,10 @@ process.stdout.write("\n__RESULT__" + JSON.stringify({ `#!/usr/bin/env bash set -euo pipefail if [ "$1 $2" = "policy get" ]; then + if [[ " $* " == *" --output json "* ]]; then + printf '%s\n' ${JSON.stringify(managedPolicyMetadata("hermes-sandbox"))} + exit 0 + fi printf 'Version: 1\nHash: test\n---\nversion: 1\n\nnetwork_policies: {}\n' exit 0 fi @@ -314,6 +349,10 @@ process.stdout.write("\n__RESULT__" + JSON.stringify({ `#!/usr/bin/env bash set -euo pipefail if [ "$1 $2" = "policy get" ]; then + if [[ " $* " == *" --output json "* ]]; then + printf '%s\n' ${JSON.stringify(managedPolicyMetadata("hermes-sandbox"))} + exit 0 + fi printf 'Version: 1\nHash: test\n---\nversion: 1\n\nnetwork_policies: {}\n' exit 0 fi @@ -376,6 +415,12 @@ exit 1 ); const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); const errSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + const sandboxSpy = vi.spyOn(registryForTest, "getSandbox").mockReturnValue({ + name: "test-sandbox", + agent: "openclaw", + policies: [], + policyAuthority: "nemoclaw-managed", + }); vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", fakeOpenshell); try { try { @@ -390,6 +435,7 @@ exit 1 } finally { logSpy.mockRestore(); errSpy.mockRestore(); + sandboxSpy.mockRestore(); vi.unstubAllEnvs(); fs.rmSync(tmpDir, { recursive: true, force: true }); } @@ -634,6 +680,12 @@ exit 1 const mkdtempSpy = vi.spyOn(fs, "mkdtempSync"); const errSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); + const sandboxSpy = vi.spyOn(registryForTest, "getSandbox").mockReturnValue({ + name: "my-assistant", + agent: "openclaw", + policies: [], + policyAuthority: "nemoclaw-managed", + }); const exitSpy = vi.spyOn(process, "exit").mockImplementation(((_code?: number) => { throw new Error("__test_exit__"); }) as never); @@ -651,6 +703,7 @@ exit 1 mkdtempSpy.mockRestore(); errSpy.mockRestore(); logSpy.mockRestore(); + sandboxSpy.mockRestore(); exitSpy.mockRestore(); } }); @@ -683,7 +736,10 @@ exit 1 .mockReturnValue(fakeOpenshell); savedGetSandbox = registryModule.getSandbox; savedAddCustomPolicy = registryModule.addCustomPolicy; - registryModule.getSandbox = (name: string) => ({ name }); + registryModule.getSandbox = (name: string) => ({ + name, + policyAuthority: "nemoclaw-managed", + }); registryModule.addCustomPolicy = () => true; }); @@ -789,9 +845,9 @@ network_policies: fs.rmSync(tmpHome, { recursive: true, force: true }); }); - it("returns false and warns when a custom preset cannot be recorded locally", () => { - // Sandbox is Ready on the gateway but missing from the local registry - // (e.g. after stale-registry pruning), so addCustomPolicy cannot persist. + it("refuses a custom preset when policy authority cannot be recorded (#9833)", () => { + // The sandbox is ready on the gateway but missing from the local + // registry, so the first observed authority cannot be persisted. registryModule.getSandbox = () => null; const addSpy = vi.fn(() => false); registryModule.addCustomPolicy = addSpy; @@ -807,21 +863,18 @@ network_policies: CUSTOM_CONTENT, { custom: { sourcePath: SOURCE_PATH } }, ); - // Pre-fix this returned true (silent exit 0) while policy-list/status - // never showed the preset. The command must not claim success. expect(result).toBe(false); expect(addSpy).not.toHaveBeenCalled(); const combined = errors.join("\n"); expect(combined).toContain("my-assistant"); - expect(combined).toMatch(/could not be\s+recorded locally/); - expect(combined).toMatch(/policy list or status/); + expect(combined).toContain("could not record policy authority"); } finally { errSpy.mockRestore(); logSpy.mockRestore(); } }); - it("warns but keeps the mutation when a built-in preset cannot be recorded locally (#9295)", () => { + it("refuses a built-in preset when policy authority cannot be recorded (#9833)", () => { registryModule.getSandbox = () => null; const updateSpy = vi.fn(() => true); registryModule.updateSandbox = updateSpy; @@ -831,16 +884,12 @@ network_policies: }); const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); try { - // A built-in preset stays discoverable from the gateway, so the applied - // policy stands. The warning is what tells the operator why policy list - // will report it without local state behind it. const result = policies.applyPresetContent("my-assistant", "github", BUILTIN_CONTENT, {}); - expect(result).toBe(true); + expect(result).toBe(false); expect(updateSpy).not.toHaveBeenCalled(); const combined = errors.join("\n"); expect(combined).toContain("my-assistant"); - expect(combined).toMatch(/could not be\s+recorded locally/); - expect(combined).toMatch(/active on gateway, missing\s+from local state/); + expect(combined).toContain("could not record policy authority"); } finally { errSpy.mockRestore(); logSpy.mockRestore(); @@ -848,7 +897,12 @@ network_policies: }); it("applies a well-formed custom preset and records it verbatim (#9406)", () => { - registryModule.getSandbox = (name: string) => ({ name }); + let sandbox: Record = { name: "my-assistant" }; + registryModule.getSandbox = () => sandbox; + registryModule.updateSandbox = (_name: string, updates: Record) => { + sandbox = { ...sandbox, ...updates }; + return true; + }; const addSpy = vi.fn(() => true); registryModule.addCustomPolicy = addSpy; const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); diff --git a/test/policy-mutation-read-discovery.test.ts b/test/policy-mutation-read-discovery.test.ts index 94c580ecc4a..6a2a2f1e5cb 100644 --- a/test/policy-mutation-read-discovery.test.ts +++ b/test/policy-mutation-read-discovery.test.ts @@ -71,6 +71,27 @@ describe("OpenShell policy mutation read discovery (#6921)", () => { expect(countPolicyReadCalls(source, "/repo/src/lib/fixture.ts", "/repo")).toBe(7); }); + it("classifies gateway-pinned direct policy reads", () => { + const source = [ + "function actionApply(gateway: string, sandboxName: string) {", + ' return runCmd(["openshell", "policy", "get", "-g", gateway, "--base", sandboxName], { reject: false });', + "}", + "function inspectAuthority(gateway: string, sandboxName: string) {", + ' return runCmd(["openshell", "policy", "get", "-g", gateway, "--full", "--output", "json", sandboxName]);', + "}", + ].join("\n"); + + expect(classifyPolicyReadCalls(source, "/repo/nemoclaw/src/blueprint/runner.ts", "/repo")) + .toEqual([ + { site: "actionApply", view: "base", failureHandling: "error-preserving" }, + { + site: "inspectAuthority", + view: "full", + failureHandling: "error-preserving", + }, + ]); + }); + it("classifies each read by function, policy view, and failure handling", () => { const source = [ 'import { buildPolicyGetCommand as buildBase, buildPolicyGetFullCommand as buildFull } from "./policy/commands";', diff --git a/test/policy-mutation-read-failure.test.ts b/test/policy-mutation-read-failure.test.ts index b8e5bd6f679..974a1c13e55 100644 --- a/test/policy-mutation-read-failure.test.ts +++ b/test/policy-mutation-read-failure.test.ts @@ -5,12 +5,26 @@ import fs from "node:fs"; import { createRequire } from "node:module"; import os from "node:os"; import path from "node:path"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const requireForTest = createRequire(import.meta.url); const policies = requireForTest( 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", + "openshell", + "policy-authority.ts", + ), +) as typeof import("../src/lib/adapters/openshell/policy-authority"); +const registry = requireForTest( + 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 = [ ["network_policies string", "version: 1\nnetwork_policies: invalid\n"], @@ -28,6 +42,18 @@ const UNMARKED_NON_POLICY_MAPPINGS = [ describe("OpenShell policy mutation read failures", () => { const tempDirs: string[] = []; + beforeEach(() => { + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + agent: "openclaw", + policyAuthority: "nemoclaw-managed", + }); + }); + afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); diff --git a/test/policy-preset-noop-disclosure.test.ts b/test/policy-preset-noop-disclosure.test.ts index 4e69cbe5fbc..07fe9aca4fb 100644 --- a/test/policy-preset-noop-disclosure.test.ts +++ b/test/policy-preset-noop-disclosure.test.ts @@ -6,6 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import YAML from "yaml"; import * as policies from "../src/lib/policy"; @@ -38,11 +39,22 @@ function runScenario({ const openshell = path.join(root, "openshell"); fs.writeFileSync(currentPolicyPath, currentPolicy); fs.writeFileSync(callsPath, ""); + const policyMetadata = JSON.stringify({ + scope: "sandbox", + sandbox: "alpha", + status: "effective", + policy_source: "sandbox", + policy: YAML.parse(currentPolicy), + }); fs.writeFileSync( openshell, `#!/usr/bin/env bash set -euo pipefail if [ "$1 $2" = "policy get" ]; then + if [[ " $* " == *" --output json "* ]]; then + printf '%s\n' ${JSON.stringify(policyMetadata)} + exit 0 + fi printf 'Version: 1\nHash: test\n---\n' cat ${JSON.stringify(currentPolicyPath)} exit 0 diff --git a/test/portable-policy-failure-finality.test.ts b/test/portable-policy-failure-finality.test.ts index 6c6ec8dab7c..ff6d8fdad66 100644 --- a/test/portable-policy-failure-finality.test.ts +++ b/test/portable-policy-failure-finality.test.ts @@ -6,6 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import YAML from "yaml"; const repoRoot = path.join(import.meta.dirname, ".."); const policyModulePath = path.join(repoRoot, "src", "lib", "policy", "index.ts"); @@ -97,8 +98,23 @@ interface PolicySetBehavior { * the `policy set --wait` result is what each scenario varies. */ function buildOpenshellStub(policySet: PolicySetBehavior, basePolicy: string): string { + const policyMetadata = JSON.stringify({ + scope: "sandbox", + sandbox: SANDBOX_NAME, + status: "effective", + policy_source: "sandbox", + policy: YAML.parse(basePolicy), + }); return `#!/bin/sh if [ "$1" = "policy" ] && [ "$2" = "get" ]; then + case " $* " in + *" --output json "*) + cat <<'JSON' +${policyMetadata} +JSON + exit 0 + ;; + esac cat <<'YAML' ${basePolicy} YAML @@ -136,12 +152,14 @@ const APPLY_PRESETS_DRIVER = * `removePreset` and `applyPreset` bypass the batch path that `applyPresets` * takes, and each composes its own policy document through its own temp file. */ -const REMOVE_PRESET_DRIVER = buildDriver( - `removePreset(${JSON.stringify(SANDBOX_NAME)}, ${JSON.stringify(PRESET_NAME)})`, -); -const APPLY_PRESET_DRIVER = buildDriver( - `applyPreset(${JSON.stringify(SANDBOX_NAME)}, ${JSON.stringify(PRESET_NAME)})`, -); +const REMOVE_PRESET_DRIVER = + `const registry = require(${JSON.stringify(registryModulePath)});\n` + + `registry.registerSandbox({ name: ${JSON.stringify(SANDBOX_NAME)}, agent: "openclaw", policies: [${JSON.stringify(PRESET_NAME)}] });\n` + + buildDriver(`removePreset(${JSON.stringify(SANDBOX_NAME)}, ${JSON.stringify(PRESET_NAME)})`); +const APPLY_PRESET_DRIVER = + `const registry = require(${JSON.stringify(registryModulePath)});\n` + + `registry.registerSandbox({ name: ${JSON.stringify(SANDBOX_NAME)}, agent: "openclaw", policies: [] });\n` + + buildDriver(`applyPreset(${JSON.stringify(SANDBOX_NAME)}, ${JSON.stringify(PRESET_NAME)})`); interface ChildRun { readonly result: SpawnSyncReturns; From ad1c8f7dcec2db4941927dfa18c55dff8c4bd15b Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 18:28:08 -0700 Subject: [PATCH 02/40] test(policy): model managed authority preflight --- test/policies-permissive-policy.test.ts | 4 +++ ...policy-semantic-validation-runtime.test.ts | 30 ++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/test/policies-permissive-policy.test.ts b/test/policies-permissive-policy.test.ts index d631ce40040..5c8d8e97e62 100644 --- a/test/policies-permissive-policy.test.ts +++ b/test/policies-permissive-policy.test.ts @@ -42,6 +42,10 @@ policies.applyPermissivePolicy("hermes-sandbox"); fakeOpenshell, `#!/usr/bin/env bash set -euo pipefail +if [ "$1 $2" = "policy get" ]; then + printf '%s\n' '{"scope":"sandbox","sandbox":"hermes-sandbox","status":"effective","policy_source":"sandbox","policy":{}}' + exit 0 +fi if [ "$1 $2" = "policy set" ]; then policy_file="" while [ "$#" -gt 0 ]; do diff --git a/test/policy-semantic-validation-runtime.test.ts b/test/policy-semantic-validation-runtime.test.ts index 6ab0ae3606c..1092d09d89d 100644 --- a/test/policy-semantic-validation-runtime.test.ts +++ b/test/policy-semantic-validation-runtime.test.ts @@ -6,13 +6,29 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const { runCapture } = vi.hoisted(() => ({ runCapture: vi.fn() })); +const { getSandbox, inspectSandboxPolicyAuthority, runCapture } = vi.hoisted(() => ({ + getSandbox: vi.fn(), + inspectSandboxPolicyAuthority: vi.fn(), + runCapture: vi.fn(), +})); + +vi.mock("../src/lib/adapters/openshell/policy-authority", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../src/lib/adapters/openshell/policy-authority") + >()), + inspectSandboxPolicyAuthority, +})); vi.mock("../src/lib/runner", async (importOriginal) => ({ ...(await importOriginal()), runCapture, })); +vi.mock("../src/lib/state/registry", async (importOriginal) => ({ + ...(await importOriginal()), + getSandbox, +})); + import { applyPresetContent, loadPreset, loadPresetFromFile } from "../src/lib/policy"; const tempDirs: string[] = []; @@ -28,6 +44,18 @@ network_policies: `; beforeEach(() => { + getSandbox.mockReset(); + getSandbox.mockImplementation((name: string) => ({ + name, + agent: "openclaw", + policies: [], + policyAuthority: "nemoclaw-managed", + })); + inspectSandboxPolicyAuthority.mockReset(); + inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); runCapture.mockReset(); }); From 58d9477850960da408b92542ef16e778faad4393 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 18:55:27 -0700 Subject: [PATCH 03/40] fix(policy): fail closed on empty authority --- scripts/checks/openshell-policy-mutation-read.mts | 9 +++++++++ src/lib/adapters/openshell/policy-authority.test.ts | 9 ++++----- src/lib/adapters/openshell/policy-authority.ts | 7 +++++-- test/policy-mutation-read-discovery.test.ts | 13 +++++++++++++ 4 files changed, 31 insertions(+), 7 deletions(-) diff --git a/scripts/checks/openshell-policy-mutation-read.mts b/scripts/checks/openshell-policy-mutation-read.mts index 330d390c216..a32eb3d7474 100644 --- a/scripts/checks/openshell-policy-mutation-read.mts +++ b/scripts/checks/openshell-policy-mutation-read.mts @@ -92,6 +92,13 @@ export const MUTATION_READS: readonly AuditedPolicyReadFile[] = [ ]; const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ + { + relativePath: "src/lib/adapters/openshell/policy-authority.ts", + expectedReads: [ + unclassifiedFull("inspectSandboxPolicyAuthority"), + unclassifiedFull("inspectGlobalPolicyAuthority"), + ], + }, { relativePath: "src/lib/actions/sandbox/gateway-state.ts", expectedReads: [ @@ -131,6 +138,8 @@ export interface DiscoveredPolicyReadSite { const POLICY_GET_BUILDERS = new Map([ ["buildPolicyGetCommand", "base"], ["buildPolicyGetFullCommand", "full"], + ["buildPolicyGetFullJsonCommand", "full"], + ["buildGlobalPolicyGetFullJsonCommand", "full"], ]); interface PolicyBuilderBindings { diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts index d5425315de6..996c371dbc3 100644 --- a/src/lib/adapters/openshell/policy-authority.test.ts +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -242,13 +242,12 @@ describe("OpenShell policy authority inspection", () => { }, ); - it("recognizes NemoClaw-managed authority when sandbox policy output is empty (#9833)", () => { + it("fails closed when sandbox policy output is empty (#9833)", () => { const runCaptureEx = vi.fn(() => captureResult("")); - expect(inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx })).toEqual({ - authority: "nemoclaw-managed", - effectivePolicy: {}, - }); + expect(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx })).toThrow( + /empty policy metadata/u, + ); }); it.each([ diff --git a/src/lib/adapters/openshell/policy-authority.ts b/src/lib/adapters/openshell/policy-authority.ts index fad057dba2c..0d03d11970c 100644 --- a/src/lib/adapters/openshell/policy-authority.ts +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -175,7 +175,7 @@ export function inspectSandboxPolicyAuthority({ "machine-readable policy", ); if (raw.trim().length === 0) { - return { authority: "nemoclaw-managed", effectivePolicy: {} }; + failInspection("sandbox", "OpenShell returned empty policy metadata"); } const metadata = parsePolicyMetadata(raw, "sandbox"); if (metadata.scope !== "sandbox") { @@ -293,7 +293,10 @@ function formatPolicyKeys(keys: readonly string[]): string { return keys.map((key) => JSON.stringify(key)).join(", "); } -/** Verify externally supplied policy requirements without claiming ownership. */ +/** + * Verify that an externally supplied policy contains each required entry and + * section without claiming ownership. Unrelated external entries are allowed. + */ export function assertExternalPolicyRequirements({ inspection, requiredPolicy, diff --git a/test/policy-mutation-read-discovery.test.ts b/test/policy-mutation-read-discovery.test.ts index 6a2a2f1e5cb..c38f45752e7 100644 --- a/test/policy-mutation-read-discovery.test.ts +++ b/test/policy-mutation-read-discovery.test.ts @@ -92,6 +92,19 @@ describe("OpenShell policy mutation read discovery (#6921)", () => { ]); }); + it("ignores direct policy reads with ambiguous view flags (#9833)", () => { + const source = [ + "function both(sandboxName: string) {", + ' return runCmd(["openshell", "policy", "get", "--base", "--full", sandboxName]);', + "}", + "function neither(sandboxName: string) {", + ' return runCmd(["openshell", "policy", "get", sandboxName]);', + "}", + ].join("\n"); + + expect(classifyPolicyReadCalls(source, "/repo/src/lib/fixture.ts", "/repo")).toEqual([]); + }); + it("classifies each read by function, policy view, and failure handling", () => { const source = [ 'import { buildPolicyGetCommand as buildBase, buildPolicyGetFullCommand as buildFull } from "./policy/commands";', From 864145b4cf988a9926c65ab0b14b7c8a0adff3cb Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 21:26:19 -0700 Subject: [PATCH 04/40] fix(policy): guard blueprint and Shields mutations --- .../runner-openshell-072-policy.test.ts | 209 ++++++++--- .../src/blueprint/runner-test-fixtures.ts | 77 +++- nemoclaw/src/blueprint/runner.test.ts | 83 +++-- nemoclaw/src/blueprint/runner.ts | 329 ++++++++++++++++-- .../checks/openshell-policy-mutation-read.mts | 13 +- .../openshell/policy-authority.test.ts | 113 +----- .../adapters/openshell/policy-authority.ts | 65 +--- src/lib/policy/commands.ts | 65 ++-- src/lib/policy/index.ts | 127 +++++-- src/lib/policy/policy-registry.ts | 2 + src/lib/shields/flow.test.ts | 12 +- src/lib/shields/index.test.ts | 54 ++- src/lib/shields/index.ts | 144 +++++++- src/lib/shields/policy-transition.test.ts | 138 ++++++++ test/helpers/shields-flow-harness.ts | 70 +++- test/policies.test.ts | 25 ++ 16 files changed, 1118 insertions(+), 408 deletions(-) diff --git a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts index 752e0c0930b..12d95ec40b5 100644 --- a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts +++ b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts @@ -13,6 +13,13 @@ import { inMemoryFsMethods, resolvedEndpointFor, } from "./runner-mock-fixtures.js"; +import { + gatewayStatusResult, + globalPolicyAuthorityResult, + minimalBlueprint, + resultWithBlueprintPolicyAuthority, + sandboxPolicyAuthorityResult, +} from "./runner-test-fixtures.js"; const { store } = createRunnerFsStore(); const mockExeca = vi.fn(); @@ -108,6 +115,14 @@ function policySetCalls(): unknown[][] { ); } +function defaultCommandResult(args: string[]) { + return resultWithBlueprintPolicyAuthority(args, { + exitCode: 0, + stdout: "", + stderr: "", + }); +} + function mergedPolicy(): Record { const key = [...store.keys()].find((candidate) => candidate.endsWith("/merged-policy.yaml")); expect(key).toBeDefined(); @@ -152,14 +167,15 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { mockExeca.mockReset(); vi.spyOn(process.stdout, "write").mockImplementation(() => true); const policyByCommand = new Map([ - ["policy get --base test-sandbox", policyOutput(BASE_POLICY)], - ["policy get --full test-sandbox", policyOutput(FULL_POLICY)], + ["policy get -g test-gateway --base test-sandbox", policyOutput(BASE_POLICY)], + ["policy get -g test-gateway --full test-sandbox", policyOutput(FULL_POLICY)], ]); - mockExeca.mockImplementation(async (_cmd: string, args: string[]) => ({ - exitCode: 0, - stdout: policyByCommand.get(args.slice(0, 4).join(" ")) ?? "", - stderr: "", - })); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => { + const policy = policyByCommand.get(args.join(" ")); + return policy === undefined + ? defaultCommandResult(args) + : { exitCode: 0, stdout: policy, stderr: "" }; + }); }); afterEach(() => { @@ -171,12 +187,12 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { expect(mockExeca).toHaveBeenCalledWith( "openshell", - ["policy", "get", "--base", "test-sandbox"], + ["policy", "get", "-g", "test-gateway", "--base", "test-sandbox"], expect.objectContaining({ reject: false }), ); expect(mockExeca).not.toHaveBeenCalledWith( "openshell", - ["policy", "get", "--full", "test-sandbox"], + ["policy", "get", "-g", "test-gateway", "--full", "test-sandbox"], expect.anything(), ); @@ -200,14 +216,11 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { ["scalar", "future_mode", "future_mode: strict\n"], ["sequence", "future_features", "future_features: [audit, attribution]\n"], ])("fails closed for an unknown top-level %s", async (_shape, key, fragment) => { - mockExeca.mockImplementation(async (_cmd: string, args: string[]) => ({ - exitCode: 0, - stdout: - args.slice(0, 4).join(" ") === "policy get --base test-sandbox" - ? policyOutput(`${fragment}${BASE_POLICY}`) - : "", - stderr: "", - })); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "policy get -g test-gateway --base test-sandbox" + ? { exitCode: 0, stdout: policyOutput(`${fragment}${BASE_POLICY}`), stderr: "" } + : defaultCommandResult(args), + ); await expect(actionApply("default", blueprint())).rejects.toThrow( `Current policy top-level field "${key}" must be a YAML mapping`, @@ -217,9 +230,9 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { it("fails closed when policy get --base fails", async () => { mockExeca.mockImplementation(async (_cmd: string, args: string[]) => - args.slice(0, 4).join(" ") === "policy get --base test-sandbox" + args.join(" ") === "policy get -g test-gateway --base test-sandbox" ? { exitCode: 1, stdout: "", stderr: "gateway unavailable" } - : { exitCode: 0, stdout: "", stderr: "" }, + : defaultCommandResult(args), ); await expect(actionApply("default", blueprint())).rejects.toThrow( @@ -229,14 +242,11 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { }); it("fails closed when policy get --base returns metadata without a policy document", async () => { - mockExeca.mockImplementation(async (_cmd: string, args: string[]) => ({ - exitCode: 0, - stdout: - args.slice(0, 4).join(" ") === "policy get --base test-sandbox" - ? "Version: 1\nHash: sha256:test\n" - : "", - stderr: "", - })); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "policy get -g test-gateway --base test-sandbox" + ? { exitCode: 0, stdout: "Version: 1\nHash: sha256:test\n", stderr: "" } + : defaultCommandResult(args), + ); await expect(actionApply("default", blueprint())).rejects.toThrow( /does not contain a policy YAML document/, @@ -249,14 +259,11 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { malformedBase.network_policies["_provider_unexpected"] = { endpoints: [{ host: "provider.invalid", port: 443, access: "full" }], }; - mockExeca.mockImplementation(async (_cmd: string, args: string[]) => ({ - exitCode: 0, - stdout: - args.slice(0, 4).join(" ") === "policy get --base test-sandbox" - ? policyOutput(YAML.stringify(malformedBase)) - : "", - stderr: "", - })); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "policy get -g test-gateway --base test-sandbox" + ? { exitCode: 0, stdout: policyOutput(YAML.stringify(malformedBase)), stderr: "" } + : defaultCommandResult(args), + ); await actionApply("default", blueprint()); const merged = mergedPolicy() as { @@ -284,18 +291,134 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { }); it("fails closed for a legacy network_policies array instead of dropping it", async () => { - mockExeca.mockImplementation(async (_cmd: string, args: string[]) => ({ - exitCode: 0, - stdout: - args.slice(0, 4).join(" ") === "policy get --base test-sandbox" - ? policyOutput("version: 1\nnetwork_policies:\n - name: legacy\n") - : "", - stderr: "", - })); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "policy get -g test-gateway --base test-sandbox" + ? { + exitCode: 0, + stdout: policyOutput("version: 1\nnetwork_policies:\n - name: legacy\n"), + stderr: "", + } + : defaultCommandResult(args), + ); await expect(actionApply("default", blueprint())).rejects.toThrow( /network_policies must be a YAML mapping/, ); expect(policySetCalls()).toEqual([]); }); + + it("uses exact external additions without mutating policy (#9833)", async () => { + const bp = blueprint(); + const additions = bp.components!.policy!.additions!; + vi.stubEnv("OPENSHELL_SANDBOX_POLICY", "/tmp/caller-policy.yaml"); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "status" + ? gatewayStatusResult("recorded-gateway") + : args.join(" ") === "policy list -g recorded-gateway --global --limit 1" + ? { exitCode: 0, stdout: "VERSION STATUS\n1 loaded\n", stderr: "" } + : args.join(" ") === "policy get -g recorded-gateway --global --full --output json" + ? globalPolicyAuthorityResult(additions) + : args.join(" ") === + "policy get -g recorded-gateway --full --output json test-sandbox" + ? sandboxPolicyAuthorityResult("test-sandbox", "externally-managed", additions) + : { exitCode: 0, stdout: "", stderr: "" }, + ); + + await actionApply("default", bp); + + const policyCalls = mockExeca.mock.calls.filter( + (call) => Array.isArray(call[1]) && call[1][0] === "policy", + ); + expect(policyCalls.every((call) => call[1].includes("recorded-gateway"))).toBe(true); + expect(policySetCalls()).toEqual([]); + const sandboxCreate = mockExeca.mock.calls.find( + (call) => Array.isArray(call[1]) && call[1][0] === "sandbox" && call[1][1] === "create", + ); + expect(sandboxCreate?.[2].env).not.toHaveProperty("OPENSHELL_SANDBOX_POLICY"); + }); + + it("refuses missing external additions before creating a sandbox (#9833)", async () => { + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "status" + ? gatewayStatusResult() + : args.join(" ") === "policy list -g test-gateway --global --limit 1" + ? { exitCode: 0, stdout: "VERSION STATUS\n1 loaded\n", stderr: "" } + : args.join(" ") === "policy get -g test-gateway --global --full --output json" + ? globalPolicyAuthorityResult() + : { exitCode: 0, stdout: "", stderr: "" }, + ); + + await expect(actionApply("default", blueprint())).rejects.toThrow( + /missing entries "nim_service"/, + ); + expect( + mockExeca.mock.calls.some( + (call) => Array.isArray(call[1]) && call[1][0] === "sandbox" && call[1][1] === "create", + ), + ).toBe(false); + }); + + it("fails closed on malformed global authority before sandbox creation (#9833)", async () => { + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "status" + ? gatewayStatusResult() + : args.join(" ") === "policy list -g test-gateway --global --limit 1" + ? { exitCode: 0, stdout: "VERSION STATUS\n1 loaded\n", stderr: "" } + : args.join(" ") === "policy get -g test-gateway --global --full --output json" + ? { exitCode: 0, stdout: "{", stderr: "" } + : { exitCode: 0, stdout: "", stderr: "" }, + ); + + await expect(actionApply("default", minimalBlueprint())).rejects.toThrow( + /malformed global policy authority metadata/, + ); + expect( + mockExeca.mock.calls.some( + (call) => Array.isArray(call[1]) && call[1][0] === "sandbox" && call[1][1] === "create", + ), + ).toBe(false); + }); + + it("stops before provider and policy mutation when sandbox authority is malformed (#9833)", async () => { + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "policy get -g test-gateway --full --output json test-sandbox" + ? { exitCode: 0, stdout: "{", stderr: "" } + : defaultCommandResult(args), + ); + + await expect(actionApply("default", minimalBlueprint())).rejects.toThrow( + /malformed sandbox policy authority metadata/, + ); + expect( + mockExeca.mock.calls.some( + (call) => Array.isArray(call[1]) && call[1][0] === "provider" && call[1][1] === "create", + ), + ).toBe(false); + expect(policySetCalls()).toEqual([]); + }); + + it("rechecks authority immediately before a managed policy mutation (#9833)", async () => { + let sandboxAuthorityReads = 0; + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => { + switch (args.join(" ")) { + case "policy get -g test-gateway --base test-sandbox": + return { + exitCode: 0, + stdout: "Version: 1\nHash: sha256:test\n---\nversion: 1\nnetwork_policies: {}\n", + stderr: "", + }; + case "policy get -g test-gateway --full --output json test-sandbox": + sandboxAuthorityReads += 1; + return sandboxPolicyAuthorityResult( + "test-sandbox", + sandboxAuthorityReads < 3 ? "nemoclaw-managed" : "externally-managed", + ); + default: + return defaultCommandResult(args); + } + }); + + await expect(actionApply("default", blueprint())).rejects.toThrow(/policy authority changed/); + expect(policySetCalls()).toEqual([]); + }); }); diff --git a/nemoclaw/src/blueprint/runner-test-fixtures.ts b/nemoclaw/src/blueprint/runner-test-fixtures.ts index 5096c501e01..1c577538096 100644 --- a/nemoclaw/src/blueprint/runner-test-fixtures.ts +++ b/nemoclaw/src/blueprint/runner-test-fixtures.ts @@ -82,9 +82,12 @@ export function resultForCommandFailure( command: readonly [string, string], stderr: string, ): { exitCode: number; stdout: string; stderr: string } { - return args[0] === command[0] && args[1] === command[1] - ? { exitCode: 1, stdout: "", stderr } - : { exitCode: 0, stdout: "", stderr: "" }; + return resultWithBlueprintPolicyAuthority( + args, + args[0] === command[0] && args[1] === command[1] + ? { exitCode: 1, stdout: "", stderr } + : { exitCode: 0, stdout: "", stderr: "" }, + ); } /** An empty successful command result. */ @@ -96,6 +99,74 @@ export function successResult(): { return { exitCode: 0, stdout: "", stderr: "" }; } +type CommandResult = { exitCode: number; stdout: string; stderr: string }; + +/** The connected gateway identity reported by `openshell status`. */ +export function gatewayStatusResult(gateway = "test-gateway"): CommandResult { + return { + exitCode: 0, + stdout: ["Gateway Status", "", " Status: Connected", ` Gateway: ${gateway}`, ""].join("\n"), + stderr: "", + }; +} + +/** Machine-readable effective policy metadata for one sandbox. */ +export function sandboxPolicyAuthorityResult( + sandboxName: string, + authority: "nemoclaw-managed" | "externally-managed" = "nemoclaw-managed", + networkPolicies: Record = {}, +): CommandResult { + return { + exitCode: 0, + stdout: JSON.stringify({ + scope: "sandbox", + sandbox: sandboxName, + status: "effective", + policy_source: authority === "nemoclaw-managed" ? "sandbox" : "global", + policy: { version: 1, network_policies: networkPolicies }, + }), + stderr: "", + }; +} + +/** Machine-readable external global policy metadata. */ +export function globalPolicyAuthorityResult( + networkPolicies: Record = {}, +): CommandResult { + return { + exitCode: 0, + stdout: JSON.stringify({ + scope: "global", + status: "loaded", + policy_source: "global", + policy: { version: 1, network_policies: networkPolicies }, + }), + stderr: "", + }; +} + +/** Standard gateway and policy-authority responses for blueprint apply tests. */ +export function resultWithBlueprintPolicyAuthority( + args: readonly string[], + fallback: CommandResult, + gateway = "test-gateway", +): CommandResult { + return args.join(" ") === "status" + ? gatewayStatusResult(gateway) + : args.join(" ") === `policy list -g ${gateway} --global --limit 1` + ? successResult() + : args[0] === "policy" && + args[1] === "get" && + args[2] === "-g" && + args[3] === gateway && + args[4] === "--full" && + args[5] === "--output" && + args[6] === "json" && + typeof args[7] === "string" + ? sandboxPolicyAuthorityResult(args[7]) + : fallback; +} + /** A failed command result carrying only stderr. */ export function failureResult(stderr: string): { exitCode: number; diff --git a/nemoclaw/src/blueprint/runner.test.ts b/nemoclaw/src/blueprint/runner.test.ts index 9aea233a2e9..7e76bcda490 100644 --- a/nemoclaw/src/blueprint/runner.test.ts +++ b/nemoclaw/src/blueprint/runner.test.ts @@ -14,9 +14,9 @@ import { } from "./runner-mock-fixtures.js"; import { blueprintWithPolicyAdditions, - failureResult, minimalBlueprint, resultForCommandFailure, + resultWithBlueprintPolicyAuthority, routedBlueprint, } from "./runner-test-fixtures.js"; @@ -80,15 +80,14 @@ function seedBlueprintFile(bp?: Record): void { function mockCurrentPolicy(stdout: string): void { mockExeca.mockImplementation(async (_cmd: string, args: string[]) => { - if ( - args[0] === "policy" && - args[1] === "get" && - args[2] === "--base" && - args[3] === "test-sandbox" - ) { + if (args.join(" ") === "policy get -g test-gateway --base test-sandbox") { return { exitCode: 0, stdout, stderr: "" }; } - return { exitCode: 0, stdout: "", stderr: "" }; + return resultWithBlueprintPolicyAuthority(args, { + exitCode: 0, + stdout: "", + stderr: "", + }); }); } @@ -104,6 +103,7 @@ describe("runner", () => { afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); }); describe("emitRunId", () => { @@ -409,17 +409,15 @@ describe("runner", () => { expect(plan.dry_run).toBe(false); }); - it.each( - [ - "credential_env", - "credential_default", - "SECRET_KEY", - "default-secret-value", - "real-secret-value", - "future-token-value", - "future-authorization", - ], - )( + it.each([ + "credential_env", + "credential_default", + "SECRET_KEY", + "default-secret-value", + "real-secret-value", + "future-token-value", + "future-authorization", + ])( "does not expose credential field names or secret values in public plan output [%s]", async (leaked) => { captureStdout(); @@ -535,8 +533,13 @@ describe("runner", () => { describe("actionApply", () => { beforeEach(() => { captureStdout(); - // Default: all subprocess calls succeed - mockExeca.mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + resultWithBlueprintPolicyAuthority(args, { + exitCode: 0, + stdout: "", + stderr: "", + }), + ); }); it("creates sandbox with correct arguments", async () => { @@ -655,12 +658,7 @@ describe("runner", () => { }, }); mockExeca.mockImplementation(async (_cmd: string, args: string[]) => { - if ( - args[0] === "policy" && - args[1] === "get" && - args[2] === "--base" && - args[3] === "test-sandbox" - ) { + if (args.join(" ") === "policy get -g test-gateway --base test-sandbox") { return { exitCode: 0, stdout: [ @@ -678,7 +676,11 @@ describe("runner", () => { stderr: "", }; } - return { exitCode: 0, stdout: "", stderr: "" }; + return resultWithBlueprintPolicyAuthority(args, { + exitCode: 0, + stdout: "", + stderr: "", + }); }); await actionApply("default", bp); @@ -688,6 +690,8 @@ describe("runner", () => { [ "policy", "set", + "-g", + "test-gateway", "--policy", expect.stringContaining("merged-policy.yaml"), "--wait", @@ -790,25 +794,27 @@ describe("runner", () => { expect(policySetCalls).toEqual([]); }); - it("skips policy commands when policy additions are empty", async () => { + it("skips policy mutation when policy additions are empty", async () => { await actionApply("default", minimalBlueprint()); const policyCalls = mockExeca.mock.calls.filter( (c) => Array.isArray(c[1]) && c[1][0] === "policy", ); - expect(policyCalls).toEqual([]); + expect(policyCalls.some((call) => call[1][1] === "set")).toBe(false); }); it("reuses sandbox when 'already exists' error", async () => { - mockExeca.mockResolvedValueOnce(failureResult("already exists")); - // Subsequent calls succeed - mockExeca.mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + resultForCommandFailure(args, ["sandbox", "create"], "already exists"), + ); await actionApply("default", minimalBlueprint()); expect(stdoutText()).toContain("already exists, reusing"); }); it("throws when sandbox creation fails with other error", async () => { - mockExeca.mockResolvedValueOnce(failureResult("disk full")); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + resultForCommandFailure(args, ["sandbox", "create"], "disk full"), + ); await expect(actionApply("default", minimalBlueprint())).rejects.toThrow( /Failed to create sandbox.*disk full/, @@ -898,6 +904,7 @@ describe("runner", () => { "inference", "inference_provider_created_by_apply", "policy_additions", + "policy_authority", "profile", "run_id", "sandbox_created_by_apply", @@ -1377,7 +1384,13 @@ describe("runner", () => { describe("main (CLI)", () => { beforeEach(() => { captureStdout(); - mockExeca.mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + resultWithBlueprintPolicyAuthority(args, { + exitCode: 0, + stdout: "", + stderr: "", + }), + ); seedBlueprintFile(); }); diff --git a/nemoclaw/src/blueprint/runner.ts b/nemoclaw/src/blueprint/runner.ts index ec9e53170df..d645b84332e 100644 --- a/nemoclaw/src/blueprint/runner.ts +++ b/nemoclaw/src/blueprint/runner.ts @@ -16,6 +16,7 @@ import { randomUUID } from "node:crypto"; import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join, sep } from "node:path"; +import { isDeepStrictEqual } from "node:util"; import { execa } from "execa"; import YAML from "yaml"; @@ -60,7 +61,7 @@ const { parseOpenShellPolicy, withoutProviderComposedPolicies } = const sourceOrGeneratedSandboxName = importedSandboxName as typeof importedSandboxName & { default?: typeof importedSandboxName; }; -const { assertValidName, assertValidProviderName } = +const { assertValidName, assertValidProviderName, isValidName } = sourceOrGeneratedSandboxName.default ?? sourceOrGeneratedSandboxName; type Action = "plan" | "apply" | "status" | "rollback"; @@ -71,6 +72,7 @@ type RollbackPlanSource = { inference_provider_created_by_apply?: unknown; inference?: unknown; identity?: unknown; + policy_authority?: unknown; }; type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"; type RestProtocol = "rest"; @@ -101,6 +103,18 @@ interface PolicyAddition { type PolicyAdditions = { [name: string]: PolicyAddition }; +type BlueprintPolicyAuthorityInspection = { + authority: "nemoclaw-managed" | "externally-managed"; + effectivePolicy: UnknownRecord; +}; + +type BlueprintPolicyAuthorityReceipt = { + authority: BlueprintPolicyAuthorityInspection["authority"]; + gateway: string; + scope: "global" | "sandbox"; + sandbox_name?: string; +}; + const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]); const REST_PROTOCOLS = new Set(["rest"]); const ENDPOINT_ENFORCEMENT_MODES = new Set(["enforce", "audit"]); @@ -110,6 +124,8 @@ const MISSING_SANDBOX_INSPECTION_PATTERN = /(?:\bsandbox\b[^\r\n]*\b(?:not found|does not exist)\b|\b(?:not found|does not exist)\b[^\r\n]*\bsandbox\b)/i; const MISSING_PROVIDER_INSPECTION_PATTERN = /(?:\bprovider\b[^\r\n]*\b(?:not found|does not exist)\b|\b(?:not found|does not exist)\b[^\r\n]*\bprovider\b|\bunknown provider\b)/i; +const POLICY_AUTHORITY_MAX_BYTES = 1024 * 1024; +const POLICY_AUTHORITY_TIMEOUT_MS = 30_000; interface InferenceRouteBinding { provider: string; @@ -538,14 +554,25 @@ export function loadBlueprint(): Blueprint { async function runCmd( args: string[], - options?: { reject?: boolean }, + options?: { + maxBuffer?: number; + omitSandboxPolicy?: boolean; + reject?: boolean; + timeout?: number; + }, ): Promise<{ exitCode: number; stdout: string; stderr: string }> { + const env = buildSubprocessEnv(); + if (options?.omitSandboxPolicy) { + delete env.OPENSHELL_SANDBOX_POLICY; + } const result = await execa(args[0], args.slice(1), { reject: options?.reject ?? true, stdout: "pipe", stderr: "pipe", - env: buildSubprocessEnv(), + env, extendEnv: false, + ...(options?.maxBuffer !== undefined ? { maxBuffer: options.maxBuffer } : {}), + ...(options?.timeout !== undefined ? { timeout: options.timeout } : {}), }); return { exitCode: result.exitCode ?? 1, @@ -554,6 +581,172 @@ async function runCmd( }; } +async function inspectActiveGatewayIdentity(): Promise { + const result = await runCmd(["openshell", "status"], { reject: false }); + const output = `${result.stderr}\n${result.stdout}`; + if (result.exitCode !== 0) { + throw new Error( + `Failed to inspect the active OpenShell gateway: ${boundedCommandError(output)}`, + ); + } + const lines = output.replace(/\u001b\[[0-9;]*m/g, "").split(/\r?\n/); + const gateways = lines + .map((line) => /^\s*Gateway:\s*(.+?)\s*$/i.exec(line)?.[1]?.trim()) + .filter((gateway): gateway is string => Boolean(gateway)); + const connected = lines.some((line) => /^\s*Status:\s*Connected\b/i.test(line)); + if (!connected || gateways.length !== 1) { + throw new Error( + `Failed to prove the active OpenShell gateway identity: ${boundedCommandError(output)}`, + ); + } + return assertValidName(gateways[0], "OpenShell gateway name"); +} + +async function runBlueprintPolicyAuthorityCommand( + command: string[], + subject: "global" | "sandbox", +): Promise>> { + let result: Awaited>; + try { + result = await runCmd(command, { + maxBuffer: POLICY_AUTHORITY_MAX_BYTES, + reject: false, + timeout: POLICY_AUTHORITY_TIMEOUT_MS, + }); + } catch { + throw new Error( + `OpenShell ${subject} policy authority inspection failed. Policy-dependent operations must stop.`, + ); + } + if ( + result.exitCode !== 0 || + Buffer.byteLength(result.stdout, "utf8") + Buffer.byteLength(result.stderr, "utf8") > + POLICY_AUTHORITY_MAX_BYTES + ) { + throw new Error( + `OpenShell ${subject} policy authority inspection failed. Policy-dependent operations must stop.`, + ); + } + return result; +} + +async function inspectBlueprintPolicyAuthority( + gateway: string, + sandboxName?: string, +): Promise { + const subject = sandboxName === undefined ? "global" : "sandbox"; + if (sandboxName === undefined) { + const history = await runBlueprintPolicyAuthorityCommand( + ["openshell", "policy", "list", "-g", gateway, "--global", "--limit", "1"], + subject, + ); + if (history.stdout.trim().length === 0) { + return { authority: "nemoclaw-managed", effectivePolicy: {} }; + } + } + const command = + sandboxName === undefined + ? ["openshell", "policy", "get", "-g", gateway, "--global", "--full", "--output", "json"] + : ["openshell", "policy", "get", "-g", gateway, "--full", "--output", "json", sandboxName]; + const result = await runBlueprintPolicyAuthorityCommand(command, subject); + if (result.stdout.trim().length === 0) { + throw new Error( + `OpenShell returned empty ${subject} policy authority metadata. Policy-dependent operations must stop.`, + ); + } + + let metadata: unknown; + try { + metadata = JSON.parse(result.stdout); + } catch { + throw new Error( + `OpenShell returned malformed ${subject} policy authority metadata. Policy-dependent operations must stop.`, + ); + } + if (!isPlainObject(metadata)) { + throw new Error( + `OpenShell returned invalid ${subject} policy authority metadata. Policy-dependent operations must stop.`, + ); + } + if (sandboxName === undefined) { + if ( + metadata.scope !== "global" || + (metadata.status !== "loaded" && metadata.status !== "superseded") || + (metadata.policy_source !== undefined && metadata.policy_source !== "global") || + Object.hasOwn(metadata, "sandbox") + ) { + throw new Error( + "OpenShell returned invalid global policy authority metadata. Policy-dependent operations must stop.", + ); + } + if (metadata.status === "superseded") { + return { authority: "nemoclaw-managed", effectivePolicy: {} }; + } + if (!isPlainObject(metadata.policy)) { + throw new Error( + "OpenShell returned invalid global policy authority metadata. Policy-dependent operations must stop.", + ); + } + return { authority: "externally-managed", effectivePolicy: metadata.policy }; + } + if ( + metadata.scope !== "sandbox" || + metadata.sandbox !== sandboxName || + metadata.status !== "effective" || + (metadata.policy_source !== "sandbox" && metadata.policy_source !== "global") || + !isPlainObject(metadata.policy) + ) { + throw new Error( + "OpenShell returned invalid sandbox policy authority metadata. Policy-dependent operations must stop.", + ); + } + return { + authority: metadata.policy_source === "sandbox" ? "nemoclaw-managed" : "externally-managed", + effectivePolicy: metadata.policy, + }; +} + +function assertBlueprintPolicyAuthorityMatches( + recorded: BlueprintPolicyAuthorityInspection, + observed: BlueprintPolicyAuthorityInspection, +): void { + if (recorded.authority !== observed.authority) { + throw new Error( + `Refusing to apply blueprint policy additions because OpenShell policy authority changed from ${recorded.authority} to ${observed.authority}.`, + ); + } +} + +function assertBlueprintExternalPolicyRequirements( + inspection: BlueprintPolicyAuthorityInspection, + additions: PolicyAdditions, +): void { + if (inspection.authority !== "externally-managed") return; + const observed = inspection.effectivePolicy.network_policies; + const observedPolicies = isPlainObject(observed) ? observed : null; + const missing: string[] = []; + const drifted: string[] = []; + for (const key of Object.keys(additions).sort()) { + if (!observedPolicies || !Object.hasOwn(observedPolicies, key)) { + missing.push(key); + } else if (!isDeepStrictEqual(observedPolicies[key], additions[key])) { + drifted.push(key); + } + } + if (missing.length === 0 && drifted.length === 0) return; + const differences = [ + ...(missing.length > 0 + ? [`missing entries ${missing.map((key) => JSON.stringify(key)).join(", ")}`] + : []), + ...(drifted.length > 0 + ? [`drifted entries ${drifted.map((key) => JSON.stringify(key)).join(", ")}`] + : []), + ].join("; "); + throw new Error( + `Refusing to apply the blueprint: the externally managed policy has ${differences}. Ask the external policy authority to supply the exact required entries.`, + ); +} + async function runRuntimeIdentityCommand( args: string[], options?: RuntimeIdentityCommandOptions, @@ -694,6 +887,7 @@ interface PersistedRunPlan { sandbox_created_by_apply: boolean; inference_provider_created_by_apply: boolean; policy_additions: PolicyAdditions; + policy_authority: BlueprintPolicyAuthorityReceipt; inference: SafeInferencePlan; identity?: RuntimeIdentityReceipt; timestamp: string; @@ -711,6 +905,7 @@ type StatusRunPlan = { sandbox_created_by_apply?: boolean; inference_provider_created_by_apply?: boolean; policy_additions?: PolicyAdditions; + policy_authority?: BlueprintPolicyAuthorityReceipt; inference?: SafeInferencePlan; identity?: RuntimeIdentityReceipt; router?: { @@ -726,6 +921,22 @@ function optionalString(value: unknown): string | undefined { return typeof value === "string" ? value : undefined; } +function isBlueprintPolicyAuthorityReceipt( + value: unknown, +): value is BlueprintPolicyAuthorityReceipt { + if (!isPlainObject(value)) return false; + if ( + (value.authority !== "nemoclaw-managed" && value.authority !== "externally-managed") || + (value.scope !== "global" && value.scope !== "sandbox") || + !isValidName(value.gateway) + ) { + return false; + } + return value.scope === "global" + ? value.sandbox_name === undefined + : isValidName(value.sandbox_name); +} + function buildSafeInferencePlan(source: InferenceProfile | UnknownRecord): SafeInferencePlan { return { provider_type: optionalString(source.provider_type), @@ -778,6 +989,7 @@ function buildPersistedRunPlan(args: { sandboxCreatedByApply: boolean; inferenceProviderCreatedByApply: boolean; policyAdditions: PolicyAdditions; + policyAuthorityReceipt: BlueprintPolicyAuthorityReceipt; inferenceCfg: InferenceProfile; runtimeIdentityReceipt?: RuntimeIdentityReceipt; timestamp: string; @@ -789,6 +1001,7 @@ function buildPersistedRunPlan(args: { sandbox_created_by_apply: args.sandboxCreatedByApply, inference_provider_created_by_apply: args.inferenceProviderCreatedByApply, policy_additions: args.policyAdditions, + policy_authority: args.policyAuthorityReceipt, inference: buildSafeInferencePlan(args.inferenceCfg), timestamp: args.timestamp, }; @@ -847,6 +1060,9 @@ function buildStatusRunPlan(source: unknown, fallbackRunId: string): StatusRunPl if (isPolicyAdditions(source.policy_additions)) { safePlan.policy_additions = source.policy_additions; } + if (isBlueprintPolicyAuthorityReceipt(source.policy_authority)) { + safePlan.policy_authority = source.policy_authority; + } if (isPlainObject(source.inference)) { safePlan.inference = buildSafeInferencePlan(source.inference); @@ -960,10 +1176,18 @@ export async function actionApply( if (credentialEnv) { credential = process.env[credentialEnv] ?? credentialDefault; } + const policyGateway = await inspectActiveGatewayIdentity(); + const initialPolicyAuthority = await inspectBlueprintPolicyAuthority(policyGateway); const stateDir = join(homedir(), ".nemoclaw", "state", "runs", rid); mkdirSync(stateDir, { recursive: true }); let runtimeIdentityReceipt: RuntimeIdentityReceipt | undefined; + let policyAuthorityReceipt: BlueprintPolicyAuthorityReceipt = { + authority: initialPolicyAuthority.authority, + gateway: policyGateway, + scope: "global", + }; + let sandboxPolicyAuthority: BlueprintPolicyAuthorityInspection | null = null; let sandboxCreatedByApply = false; let inferenceProviderCreatedByApply = false; const persistRunPlan = (): void => { @@ -977,6 +1201,7 @@ export async function actionApply( sandboxCreatedByApply, inferenceProviderCreatedByApply, policyAdditions, + policyAuthorityReceipt, inferenceCfg, runtimeIdentityReceipt, timestamp: new Date().toISOString(), @@ -990,6 +1215,8 @@ export async function actionApply( runtimeIdentityReceipt = receipt; persistRunPlan(); }, options?.runtimeIdentityProfilePolicy); + persistRunPlan(); + assertBlueprintExternalPolicyRequirements(initialPolicyAuthority, policyAdditions); try { let reuseExistingSandbox = false; @@ -1075,7 +1302,10 @@ export async function actionApply( createArgs.push("--forward", String(port)); } - const createResult = await runCmd(createArgs, { reject: false }); + const createResult = await runCmd(createArgs, { + omitSandboxPolicy: initialPolicyAuthority.authority === "externally-managed", + reject: false, + }); sandboxCreatedByApply = createResult.exitCode === 0; if (sandboxCreatedByApply) { // Persist ownership immediately so a later-process rollback stays safe @@ -1102,6 +1332,25 @@ export async function actionApply( } } + { + const observedPolicyAuthority = await inspectBlueprintPolicyAuthority( + policyGateway, + sandboxName, + ); + if (sandboxCreatedByApply) { + assertBlueprintPolicyAuthorityMatches(initialPolicyAuthority, observedPolicyAuthority); + } + sandboxPolicyAuthority = observedPolicyAuthority; + policyAuthorityReceipt = { + authority: observedPolicyAuthority.authority, + gateway: policyGateway, + scope: "sandbox", + sandbox_name: sandboxName, + }; + persistRunPlan(); + assertBlueprintExternalPolicyRequirements(observedPolicyAuthority, policyAdditions); + } + // Keep runtime credentials unattached until OpenShell accepts the // sandbox's requested inference route. progress(50, "Configuring inference provider"); @@ -1222,32 +1471,66 @@ export async function actionApply( } if (Object.keys(policyAdditions).length > 0) { - progress(78, "Applying policy additions"); - const currentPolicy = await runCmd(["openshell", "policy", "get", "--base", sandboxName], { - reject: false, - }); - if (currentPolicy.exitCode !== 0) { - throw new Error( - `Failed to read current policy before applying additions: ${currentPolicy.stderr}`, - ); + if (!sandboxPolicyAuthority) { + throw new Error("Sandbox policy authority is unavailable before applying additions."); } + const observedPolicyAuthority = await inspectBlueprintPolicyAuthority( + policyGateway, + sandboxName, + ); + assertBlueprintPolicyAuthorityMatches(sandboxPolicyAuthority, observedPolicyAuthority); + assertBlueprintExternalPolicyRequirements(observedPolicyAuthority, policyAdditions); + if (observedPolicyAuthority.authority === "nemoclaw-managed") { + progress(78, "Applying policy additions"); + const currentPolicy = await runCmd( + ["openshell", "policy", "get", "-g", policyGateway, "--base", sandboxName], + { reject: false }, + ); + if (currentPolicy.exitCode !== 0) { + throw new Error( + `Failed to read current policy before applying additions: ${currentPolicy.stderr}`, + ); + } - const mergedPolicyFile = join(stateDir, "merged-policy.yaml"); - writeFileSync(mergedPolicyFile, mergePolicyAdditions(currentPolicy.stdout, policyAdditions), { - encoding: "utf-8", - mode: 0o600, - }); + const mergedPolicyFile = join(stateDir, "merged-policy.yaml"); + writeFileSync( + mergedPolicyFile, + mergePolicyAdditions(currentPolicy.stdout, policyAdditions), + { + encoding: "utf-8", + mode: 0o600, + }, + ); - const policySet = await runCmd( - ["openshell", "policy", "set", "--policy", mergedPolicyFile, "--wait", sandboxName], - { reject: false }, - ); - if (policySet.exitCode !== 0) { - throw new Error(`Failed to apply policy additions: ${policySet.stderr}`); + const beforeMutation = await inspectBlueprintPolicyAuthority(policyGateway, sandboxName); + assertBlueprintPolicyAuthorityMatches(sandboxPolicyAuthority, beforeMutation); + const policySet = await runCmd( + [ + "openshell", + "policy", + "set", + "-g", + policyGateway, + "--policy", + mergedPolicyFile, + "--wait", + sandboxName, + ], + { reject: false }, + ); + if (policySet.exitCode !== 0) { + throw new Error(`Failed to apply policy additions: ${policySet.stderr}`); + } } } progress(85, "Saving run state"); + if (!sandboxPolicyAuthority) { + throw new Error("Sandbox policy authority is unavailable before saving run state."); + } + const finalPolicyAuthority = await inspectBlueprintPolicyAuthority(policyGateway, sandboxName); + assertBlueprintPolicyAuthorityMatches(sandboxPolicyAuthority, finalPolicyAuthority); + assertBlueprintExternalPolicyRequirements(finalPolicyAuthority, policyAdditions); persistRunPlan(); progress(100, "Apply complete"); diff --git a/scripts/checks/openshell-policy-mutation-read.mts b/scripts/checks/openshell-policy-mutation-read.mts index a32eb3d7474..bfa1ffb494a 100644 --- a/scripts/checks/openshell-policy-mutation-read.mts +++ b/scripts/checks/openshell-policy-mutation-read.mts @@ -79,7 +79,11 @@ export const MUTATION_READS: readonly AuditedPolicyReadFile[] = [ }, { relativePath: "nemoclaw/src/blueprint/runner.ts", - expectedReads: [unclassifiedBase("actionApply")], + expectedReads: [ + unclassifiedBase("actionApply"), + unclassifiedFull("inspectBlueprintPolicyAuthority"), + unclassifiedFull("inspectBlueprintPolicyAuthority"), + ], }, { relativePath: "src/lib/shields/index.ts", @@ -94,10 +98,7 @@ export const MUTATION_READS: readonly AuditedPolicyReadFile[] = [ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ { relativePath: "src/lib/adapters/openshell/policy-authority.ts", - expectedReads: [ - unclassifiedFull("inspectSandboxPolicyAuthority"), - unclassifiedFull("inspectGlobalPolicyAuthority"), - ], + expectedReads: [unclassifiedFull("inspectSandboxPolicyAuthority")], }, { relativePath: "src/lib/actions/sandbox/gateway-state.ts", @@ -124,7 +125,6 @@ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ failureHandling: "unclassified", }, unclassifiedFull("buildPolicyGetFullJsonCommand"), - unclassifiedFull("buildGlobalPolicyGetFullJsonCommand"), ], }, ] as const; @@ -139,7 +139,6 @@ const POLICY_GET_BUILDERS = new Map([ ["buildPolicyGetCommand", "base"], ["buildPolicyGetFullCommand", "full"], ["buildPolicyGetFullJsonCommand", "full"], - ["buildGlobalPolicyGetFullJsonCommand", "full"], ]); interface PolicyBuilderBindings { diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts index 996c371dbc3..39bf04a09a3 100644 --- a/src/lib/adapters/openshell/policy-authority.test.ts +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -7,7 +7,6 @@ import * as openshellResolveModule from "./resolve"; import { assertExternalPolicyRequirements, assertRecordedPolicyAuthority, - inspectGlobalPolicyAuthority, inspectSandboxPolicyAuthority, type PolicyAuthorityCapture, policyAuthorityInternals, @@ -41,15 +40,6 @@ function sandboxMetadata(overrides: Record = {}): Record = {}): Record { - return { - scope: "global", - status: "loaded", - policy: { version: 1, network_policies: { baseline: { endpoints: ["base.test"] } } }, - ...overrides, - }; -} - function errorFrom(action: () => unknown): Error { try { action(); @@ -117,58 +107,6 @@ describe("OpenShell policy authority inspection", () => { ]); }); - it("recognizes NemoClaw-managed authority when global history is absent (#9833)", () => { - const runCaptureEx = vi.fn(() => captureResult("")); - - expect(inspectGlobalPolicyAuthority({ runCaptureEx })).toEqual({ - authority: "nemoclaw-managed", - effectivePolicy: {}, - }); - expect(runCaptureEx.mock.calls[0]?.[0]).toEqual([ - "openshell", - "policy", - "list", - "--global", - "--limit", - "1", - ]); - }); - - it.each([ - [ - "loaded", - globalMetadata({ - policy: { version: 1, network_policies: { required: { endpoints: ["api.test"] } } }, - }), - "externally-managed", - ], - ["superseded", globalMetadata({ status: "superseded", policy: undefined }), "nemoclaw-managed"], - ] as const)("classifies %s global policy metadata (#9833)", (_case, metadata, authority) => { - const runCaptureEx = vi - .fn() - .mockReturnValueOnce(captureResult("policy revision history")) - .mockReturnValueOnce(captureResult(JSON.stringify(metadata))); - - expect(inspectGlobalPolicyAuthority({ gatewayName: "nemoclaw-18080", runCaptureEx })).toEqual({ - authority, - effectivePolicy: authority === "externally-managed" ? metadata.policy : {}, - }); - expect(runCaptureEx.mock.calls.map(([argv]) => argv)).toEqual([ - ["openshell", "policy", "list", "-g", "nemoclaw-18080", "--global", "--limit", "1"], - [ - "openshell", - "policy", - "get", - "-g", - "nemoclaw-18080", - "--global", - "--full", - "--output", - "json", - ], - ]); - }); - it("rejects invalid sandbox and gateway identities before querying policy (#9833)", () => { const runCaptureEx = vi.fn(() => captureResult(JSON.stringify(sandboxMetadata())), @@ -178,11 +116,15 @@ describe("OpenShell policy authority inspection", () => { /Invalid sandbox name/, ); expect(() => - inspectGlobalPolicyAuthority({ gatewayName: "invalid gateway", runCaptureEx }), + inspectSandboxPolicyAuthority({ + sandboxName: "alpha", + gatewayName: "invalid gateway", + runCaptureEx, + }), ).toThrow(/Invalid gateway name/); - expect(() => inspectGlobalPolicyAuthority({ gatewayName: "", runCaptureEx })).toThrow( - /gateway name is required/, - ); + expect(() => + inspectSandboxPolicyAuthority({ sandboxName: "alpha", gatewayName: "", runCaptureEx }), + ).toThrow(/gateway name is required/); expect(runCaptureEx).not.toHaveBeenCalled(); }); @@ -203,45 +145,6 @@ describe("OpenShell policy authority inspection", () => { expect(error.message).not.toContain(secret); }); - it.each([ - ["empty", captureResult("")], - ["malformed", captureResult('{"secret":"captured-global-secret"')], - ["another scope", captureResult(JSON.stringify(globalMetadata({ scope: "sandbox" })))], - ["another source", captureResult(JSON.stringify(globalMetadata({ policy_source: "sandbox" })))], - ["a pending status", captureResult(JSON.stringify(globalMetadata({ status: "pending" })))], - ["a failed status", captureResult(JSON.stringify(globalMetadata({ status: "failed" })))], - ])("rejects global policy metadata that is %s (#9833)", (_case, result) => { - const runCaptureEx = vi - .fn() - .mockReturnValueOnce(captureResult("policy revision history")) - .mockReturnValueOnce(result); - - const error = errorFrom(() => inspectGlobalPolicyAuthority({ runCaptureEx })); - expect(error.message).toContain("inspection failed"); - expect(error.message).not.toContain("captured-global-secret"); - }); - - it.each([ - ["a nonzero exit", { exitCode: 7 }], - ["a timeout", { timedOut: true }], - ])( - "fails closed without reading global metadata after history query has %s (#9833)", - (_case, overrides) => { - const runCaptureEx = vi.fn(() => - captureResult("captured-history-secret", { - ...overrides, - stderr: "captured-history-stderr-secret", - }), - ); - - const error = errorFrom(() => inspectGlobalPolicyAuthority({ runCaptureEx })); - expect(error.message).toContain("inspection failed"); - expect(error.message).not.toContain("captured-history-secret"); - expect(error.message).not.toContain("captured-history-stderr-secret"); - expect(runCaptureEx).toHaveBeenCalledOnce(); - }, - ); - it("fails closed when sandbox policy output is empty (#9833)", () => { const runCaptureEx = vi.fn(() => captureResult("")); diff --git a/src/lib/adapters/openshell/policy-authority.ts b/src/lib/adapters/openshell/policy-authority.ts index 0d03d11970c..d6e59e3cfc5 100644 --- a/src/lib/adapters/openshell/policy-authority.ts +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -9,11 +9,7 @@ import { NAME_ALLOWED_FORMAT, NAME_MAX_LENGTH, } from "../../sandbox-name-contract"; -import { - buildGlobalPolicyGetFullJsonCommand, - buildGlobalPolicyListCommand, - buildPolicyGetFullJsonCommand, -} from "../../policy/commands"; +import { buildPolicyGetFullJsonCommand } from "../../policy/commands"; const POLICY_AUTHORITY_CAPTURE_MAX_BYTES = 1024 * 1024; const POLICY_AUTHORITY_CAPTURE_TIMEOUT_MS = 30_000; @@ -58,15 +54,12 @@ export type PolicyAuthorityCapture = ( options?: { readonly maxBuffer?: number; readonly timeout?: number }, ) => PolicyAuthorityCaptureResult; -interface PolicyAuthorityInspectionOptions { +interface SandboxPolicyAuthorityInspectionOptions { + readonly sandboxName: string; readonly gatewayName?: string; readonly runCaptureEx: PolicyAuthorityCapture; } -interface SandboxPolicyAuthorityInspectionOptions extends PolicyAuthorityInspectionOptions { - readonly sandboxName: string; -} - function validatePolicyAuthorityName(name: string, label: string): string { if (!name || typeof name !== "string") { throw new PolicyAuthorityRefusalError( @@ -196,58 +189,6 @@ export function inspectSandboxPolicyAuthority({ }; } -/** Inspect whether a global policy will manage sandboxes created next. */ -export function inspectGlobalPolicyAuthority({ - gatewayName, - runCaptureEx, -}: PolicyAuthorityInspectionOptions): SandboxPolicyAuthorityInspection { - const validatedGatewayName = - gatewayName === undefined - ? undefined - : validatePolicyAuthorityName(gatewayName, "gateway name"); - const { stdout: history } = capturePolicyQuery( - buildGlobalPolicyListCommand(validatedGatewayName), - runCaptureEx, - "global", - "policy history", - ); - if (history.trim().length === 0) { - return { authority: "nemoclaw-managed", effectivePolicy: {} }; - } - const { stdout: raw } = capturePolicyQuery( - buildGlobalPolicyGetFullJsonCommand(validatedGatewayName), - runCaptureEx, - "global", - "machine-readable policy", - ); - if (raw.trim().length === 0) { - failInspection("global", "OpenShell returned empty policy metadata"); - } - const metadata = parsePolicyMetadata(raw, "global"); - if (metadata.scope !== "global") { - failInspection("global", "OpenShell returned policy metadata for another scope"); - } - if (Object.hasOwn(metadata, "sandbox")) { - failInspection("global", "OpenShell returned an unexpected sandbox identity"); - } - if (metadata.policy_source !== undefined && metadata.policy_source !== "global") { - failInspection("global", "OpenShell returned an unknown global policy source"); - } - if (metadata.status === "superseded") { - return { authority: "nemoclaw-managed", effectivePolicy: {} }; - } - if (metadata.status !== "loaded") { - failInspection( - "global", - "OpenShell returned a global policy status that cannot determine authority", - ); - } - return { - authority: "externally-managed", - effectivePolicy: policyObject(metadata, "global"), - }; -} - function operationLabel(operation: string): string { return typeof operation === "string" && operation.trim().length > 0 ? operation.trim() diff --git a/src/lib/policy/commands.ts b/src/lib/policy/commands.ts index eb1780b3a51..a042bbecb24 100644 --- a/src/lib/policy/commands.ts +++ b/src/lib/policy/commands.ts @@ -3,58 +3,57 @@ import { buildOpenshellCommand } from "../adapters/openshell/command-argv"; -export function buildPolicySetCommand(policyFile: string, sandboxName: string): string[] { - return buildOpenshellCommand(["policy", "set", "--policy", policyFile, "--wait", sandboxName]); +export function buildPolicySetCommand( + policyFile: string, + sandboxName: string, + gatewayName?: string, +): string[] { + return buildOpenshellCommand([ + "policy", + "set", + ...policyGatewayArgs(gatewayName), + "--policy", + policyFile, + "--wait", + sandboxName, + ]); } /** Read the round-trippable base policy before a mutation. */ -export function buildPolicyGetCommand(sandboxName: string): string[] { - return buildOpenshellCommand(["policy", "get", "--base", sandboxName]); +export function buildPolicyGetCommand(sandboxName: string, gatewayName?: string): string[] { + return buildOpenshellCommand([ + "policy", + "get", + ...policyGatewayArgs(gatewayName), + "--base", + sandboxName, + ]); } /** Read the effective policy for status and other diagnostics. */ -export function buildPolicyGetFullCommand(sandboxName: string): string[] { - return buildOpenshellCommand(["policy", "get", "--full", sandboxName]); -} - -function policyGetGatewayArgs(gatewayName?: string): string[] { - return gatewayName ? ["-g", gatewayName] : []; -} - -/** Read effective sandbox policy and its authority metadata as JSON. */ -export function buildPolicyGetFullJsonCommand(sandboxName: string, gatewayName?: string): string[] { +export function buildPolicyGetFullCommand(sandboxName: string, gatewayName?: string): string[] { return buildOpenshellCommand([ "policy", "get", - ...policyGetGatewayArgs(gatewayName), + ...policyGatewayArgs(gatewayName), "--full", - "--output", - "json", sandboxName, ]); } -/** Read the global policy and its authority metadata as JSON. */ -export function buildGlobalPolicyGetFullJsonCommand(gatewayName?: string): string[] { +function policyGatewayArgs(gatewayName?: string): string[] { + return gatewayName ? ["-g", gatewayName] : []; +} + +/** Read effective sandbox policy and its authority metadata as JSON. */ +export function buildPolicyGetFullJsonCommand(sandboxName: string, gatewayName?: string): string[] { return buildOpenshellCommand([ "policy", "get", - ...policyGetGatewayArgs(gatewayName), - "--global", + ...policyGatewayArgs(gatewayName), "--full", "--output", "json", - ]); -} - -/** Check whether the global policy has revision history. */ -export function buildGlobalPolicyListCommand(gatewayName?: string): string[] { - return buildOpenshellCommand([ - "policy", - "list", - ...policyGetGatewayArgs(gatewayName), - "--global", - "--limit", - "1", + sandboxName, ]); } diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index 60a639a5a5f..385bc20a781 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -570,34 +570,56 @@ interface PolicySetSubmission { readonly status: number | null; } -interface PolicyAuthorityContext { +function policyAuthorityError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +export interface PolicyMutationAuthority { readonly authority: registry.SandboxPolicyAuthority; readonly authorityRecordedNow: boolean; readonly gatewayName: string; readonly inspection: registry.SandboxPolicyAuthorityInspection; } -function policyAuthorityError(error: unknown): string { - return error instanceof Error ? error.message : String(error); -} +export const isPolicyAuthorityRefusalError = registry.isPolicyAuthorityRefusalError; -/** Inspect live authority through the gateway recorded for this sandbox. */ -function inspectPolicyAuthority( +/** Inspect and, when needed, persist the authority that owns one sandbox policy. */ +export function inspectPolicyMutationAuthority( sandboxName: string, operation: string, requestedGatewayName?: string, requireRecordedAuthority = false, -): PolicyAuthorityContext { - const sandbox = registry.getSandbox(sandboxName); - const recordedGatewayName = sandbox ? resolveSandboxGatewayName(sandbox) : null; +): PolicyMutationAuthority { + let sandbox: ReturnType; + try { + sandbox = registry.getSandbox(sandboxName); + } catch { + throw new registry.PolicyAuthorityRefusalError( + `Refusing to ${operation}: sandbox policy authority is unavailable.`, + ); + } + let recordedGatewayName: string | null; + try { + recordedGatewayName = sandbox ? resolveSandboxGatewayName(sandbox) : null; + } catch { + throw new registry.PolicyAuthorityRefusalError( + `Refusing to ${operation}: the recorded sandbox gateway is unavailable or invalid.`, + ); + } if (recordedGatewayName && requestedGatewayName && requestedGatewayName !== recordedGatewayName) { throw new Error( `Refusing to ${operation}: sandbox '${sandboxName}' is recorded on gateway ` + `'${recordedGatewayName}', not '${requestedGatewayName}'.`, ); } - const gatewayName = - recordedGatewayName ?? requestedGatewayName ?? resolveSandboxGatewayName(undefined); + let gatewayName: string; + try { + gatewayName = recordedGatewayName ?? requestedGatewayName ?? resolveSandboxGatewayName(undefined); + } catch { + throw new registry.PolicyAuthorityRefusalError( + `Refusing to ${operation}: the sandbox gateway is unavailable or invalid.`, + ); + } const inspection = registry.inspectSandboxPolicyAuthority({ sandboxName, gatewayName, @@ -634,12 +656,18 @@ function inspectPolicyAuthority( `Refusing to ${operation}: policy authority is not recorded for sandbox '${sandboxName}'.`, ); } - if ( - !sandbox || - !registry.updateSandbox(sandboxName, { - policyAuthority: inspection.authority, - }) - ) { + let authorityRecorded: boolean; + try { + authorityRecorded = Boolean( + sandbox && + registry.updateSandbox(sandboxName, { + policyAuthority: inspection.authority, + }), + ); + } catch { + authorityRecorded = false; + } + if (!authorityRecorded) { throw new Error( `Refusing to ${operation}: NemoClaw could not record policy authority for sandbox '${sandboxName}'.`, ); @@ -652,14 +680,61 @@ function inspectPolicyAuthority( }; } -function assertNemoClawManagedPolicy(context: PolicyAuthorityContext, operation: string): void { - if (context.authority === "nemoclaw-managed") return; +/** Require NemoClaw ownership before a local policy mutation. */ +export function assertNemoClawManagedPolicy( + authority: PolicyMutationAuthority, + operation: string, +): void { + if (authority.authority === "nemoclaw-managed") return; throw new Error( `Refusing to ${operation}: this sandbox policy is externally managed. ` + "Ask the external policy authority to change the required entry.", ); } +/** Recheck one recorded receipt immediately before a policy mutation. */ +export function recheckPolicyMutationAuthority( + sandboxName: string, + operation: string, + recorded: PolicyMutationAuthority, +): PolicyMutationAuthority { + const observed = inspectPolicyMutationAuthority( + sandboxName, + operation, + recorded.gatewayName, + true, + ); + registry.assertRecordedPolicyAuthority(recorded.authority, observed.authority, operation); + assertNemoClawManagedPolicy(observed, operation); + return observed; +} + +/** Reject a final OpenShell policy refusal without exposing raw diagnostics. */ +export function rejectFinalPolicySetResult( + result: ReturnType, + operation: string, +): void { + const captured = result as ReturnType & { + error?: Error; + stderr?: string | Buffer | null; + }; + const outcome = classifyPolicySetResult({ + status: typeof captured.status === "number" ? captured.status : null, + ...(captured.error ? { error: captured.error } : {}), + stderr: Buffer.isBuffer(captured.stderr) + ? captured.stderr.toString("utf8") + : (captured.stderr ?? null), + }); + if (outcome.kind === "rejected") { + throw new registry.PolicyAuthorityRefusalError( + `Refusing to ${operation}: OpenShell rejected the policy change: ${redact(outcome.message)}`, + ); + } +} + +const inspectPolicyAuthority = inspectPolicyMutationAuthority; +type PolicyAuthorityContext = PolicyMutationAuthority; + function reportPolicyAuthorityFailure(error: unknown): false { console.error(` ${policyAuthorityError(error)}`); return false; @@ -687,13 +762,7 @@ function recheckNemoClawManagedPolicy( authority: PolicyAuthorityContext, ): boolean { try { - const observed = inspectPolicyAuthority(sandboxName, operation, authority.gatewayName, true); - registry.assertRecordedPolicyAuthority( - authority.authority, - observed.authority, - operation, - ); - assertNemoClawManagedPolicy(observed, operation); + recheckPolicyMutationAuthority(sandboxName, operation, authority); return true; } catch (error) { return reportPolicyAuthorityFailure(error); @@ -3259,11 +3328,7 @@ function applyPermissivePolicy(sandboxName: string): void { assertOpenshellResolvable(); setPolicyDocument(sandboxName, materializedPolicy, { gatewayName: authority.gatewayName }); const observed = inspectPolicyAuthority(sandboxName, operation, authority.gatewayName, true); - registry.assertRecordedPolicyAuthority( - authority.authority, - observed.authority, - operation, - ); + registry.assertRecordedPolicyAuthority(authority.authority, observed.authority, operation); assertNemoClawManagedPolicy(observed, operation); console.log(" Applied permissive policy."); } diff --git a/src/lib/policy/policy-registry.ts b/src/lib/policy/policy-registry.ts index 13d030ba228..16f96284dfe 100644 --- a/src/lib/policy/policy-registry.ts +++ b/src/lib/policy/policy-registry.ts @@ -31,6 +31,8 @@ export { assertExternalPolicyRequirements, assertRecordedPolicyAuthority, inspectSandboxPolicyAuthority, + isPolicyAuthorityRefusalError, + PolicyAuthorityRefusalError, } from "../adapters/openshell/policy-authority"; export type { SandboxPolicyAuthority, diff --git a/src/lib/shields/flow.test.ts b/src/lib/shields/flow.test.ts index 50743597c1b..33923017e3b 100644 --- a/src/lib/shields/flow.test.ts +++ b/src/lib/shields/flow.test.ts @@ -686,7 +686,7 @@ describe("shields command flow", () => { expect(Date.now() - startedAt).toBeGreaterThanOrEqual(100); expect(fs.existsSync(transitionPath)).toBe(true); expect(harness.runSpy).toHaveBeenCalledWith( - ["openshell", "policy", "set"], + ["openshell", "policy", "set", "-g", "nemoclaw"], expect.objectContaining({ ignoreError: true }), ); }); @@ -946,7 +946,7 @@ describe("shields command flow", () => { }); expect(fs.existsSync(markerPath)).toBe(false); expect(harness.runSpy).toHaveBeenCalledWith( - ["openshell", "policy", "set"], + ["openshell", "policy", "set", "-g", "nemoclaw"], expect.objectContaining({ ignoreError: true }), ); expect(harness.logSpy).toHaveBeenCalledWith(" Shields: UP (lockdown active)"); @@ -1211,7 +1211,7 @@ describe("shields command flow", () => { ).toMatchObject({ shieldsDown: false, shieldsDownAt: null }); expect(fs.existsSync(markerPath)).toBe(false); expect(harness.runSpy).toHaveBeenCalledWith( - ["openshell", "policy", "set"], + ["openshell", "policy", "set", "-g", "nemoclaw"], expect.objectContaining({ ignoreError: true }), ); expect(harness.logSpy).toHaveBeenCalledWith(" Shields: UP (lockdown active)"); @@ -1246,7 +1246,7 @@ describe("shields command flow", () => { ).toMatchObject({ shieldsDown: false, shieldsDownAt: null }); expect(fs.existsSync(markerPath)).toBe(false); expect(harness.runSpy).toHaveBeenCalledWith( - ["openshell", "policy", "set"], + ["openshell", "policy", "set", "-g", "nemoclaw"], expect.objectContaining({ ignoreError: true }), ); }); @@ -1332,7 +1332,7 @@ describe("shields command flow", () => { expect(fs.existsSync(containmentPath)).toBe(true); expect(fs.existsSync(sandboxMutationLockPath)).toBe(false); expect(harness.runSpy).not.toHaveBeenCalledWith( - ["openshell", "policy", "set"], + ["openshell", "policy", "set", "-g", "nemoclaw"], expect.anything(), ); }); @@ -1385,7 +1385,7 @@ describe("shields command flow", () => { expect(fs.existsSync(timerMarkerPath)).toBe(true); expect(fs.existsSync(transitionLockPath)).toBe(true); expect(harness.runSpy).not.toHaveBeenCalledWith( - ["openshell", "policy", "set"], + ["openshell", "policy", "set", "-g", "nemoclaw"], expect.anything(), ); }); diff --git a/src/lib/shields/index.test.ts b/src/lib/shields/index.test.ts index df79f091573..02363c4353c 100644 --- a/src/lib/shields/index.test.ts +++ b/src/lib/shields/index.test.ts @@ -565,7 +565,7 @@ describe("shields — unit logic", () => { expect(composition.yaml).not.toContain("mcp_bridge_beta"); }); - it("deadline restore removes saved MCP keys when the registry cannot be read", async () => { + it("deadline restore refuses policy mutation when authority cannot be read (#9833)", async () => { const sandboxName = "openclaw"; const processToken = "b".repeat(32); const snapshotPath = path.join(stateDir(), "policy-snapshot-unreadable-registry.yaml"); @@ -600,25 +600,21 @@ describe("shields — unit logic", () => { originalRmSync(target, options); }); const { applyShieldsPolicySnapshot } = await loadShieldsModule(); + const { run } = await import("../runner"); - const result = applyShieldsPolicySnapshot(sandboxName, snapshotPath, { - transitionProcessToken: processToken, - deadlineAuthoritative: true, - expiredTimerRecovery: true, - }); - - expect(result.managedMcpOmissions).toEqual([ - expect.objectContaining({ - reason: expect.stringMatching( - /Managed MCP registry inspection failed at the auto-restore deadline/, - ), + expect(() => + applyShieldsPolicySnapshot(sandboxName, snapshotPath, { + transitionProcessToken: processToken, + deadlineAuthoritative: true, + expiredTimerRecovery: true, }), - ]); - expect(appliedPolicy).toContain("restrictive_baseline"); - expect(appliedPolicy).not.toContain("mcp_bridge_alpha"); + ).toThrow(/policy authority/i); + + expect(run).not.toHaveBeenCalled(); + expect(appliedPolicy).toBe(""); }); - it("auto-restore applies a snapshot with no managed MCP entries when policy staging is unavailable (#7952)", async () => { + it("auto-restore refuses before policy staging when authority is unavailable (#9833)", async () => { const sandboxName = "openclaw"; const processToken = "d".repeat(32); const snapshotPath = path.join(stateDir(), "policy-snapshot-no-managed-mcp.yaml"); @@ -645,26 +641,16 @@ describe("shields — unit logic", () => { }); }); - const result = applyShieldsPolicySnapshot(sandboxName, snapshotPath, { - transitionProcessToken: processToken, - deadlineAuthoritative: true, - expiredTimerRecovery: true, - }); + expect(() => + applyShieldsPolicySnapshot(sandboxName, snapshotPath, { + transitionProcessToken: processToken, + deadlineAuthoritative: true, + expiredTimerRecovery: true, + }), + ).toThrow(/policy authority inspection failed/i); - expect(result.status).toBe(0); expect(createTempDirectory).not.toHaveBeenCalled(); - expect(run).toHaveBeenCalledWith( - [ - expect.stringMatching(/(?:^|\/)openshell$/), - "policy", - "set", - "--policy", - snapshotPath, - "--wait", - sandboxName, - ], - { ignoreError: true }, - ); + expect(run).not.toHaveBeenCalled(); }); it("reuses the snapshot without staging when the snapshot and current policy have no managed MCP entries (#7952)", async () => { diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index 83d7964270a..1ac4349bdb6 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -41,6 +41,11 @@ const { buildPolicySetCommand, parseCurrentPolicy, resolvePermissivePolicyPath, + assertNemoClawManagedPolicy, + inspectPolicyMutationAuthority, + isPolicyAuthorityRefusalError, + recheckPolicyMutationAuthority, + rejectFinalPolicySetResult: rejectFinalShieldsPolicySetResult, } = require("../policy"); const { parseDuration, MAX_SECONDS, DEFAULT_SECONDS } = require("../domain/duration"); const { @@ -132,6 +137,21 @@ type MutableConfigRepairResult = import("./mutable-config-perms").MutableConfigR type AgentStateLockPlan = import("../agent/definition-types").AgentStateLockPlan; type ManagedMcpPolicyOmission = import("./permissive-runtime").ManagedMcpPolicyOmission; type TimerMarker = import("./timer-control").TimerMarker; +type PolicyMutationAuthority = ReturnType; + +/** Require the registry-bound live authority before a Shields-owned policy mutation. */ +function assertShieldsPolicyMutationAuthority( + sandboxName: string, + operation: string, + recorded?: PolicyMutationAuthority, +): PolicyMutationAuthority { + const authority = recorded + ? recheckPolicyMutationAuthority(sandboxName, operation, recorded) + : inspectPolicyMutationAuthority(sandboxName, operation); + assertNemoClawManagedPolicy(authority, operation); + return authority; +} + const STATE_DIR = resolveShieldsStateDir(); const SHIELDS_TRANSITION_POLL_MS = 50; const SHIELDS_TRANSITION_HANDOFF_GRACE_MS = 500; @@ -4004,12 +4024,13 @@ function describeRollbackTimerAuthority( function resolveExactManagedMcpPolicies( sandboxName: string, livePolicyYaml?: string, + gatewayName?: string, ): ReturnType { let effectiveLivePolicy = livePolicyYaml; if (!effectiveLivePolicy) { let rawPolicy: string; try { - rawPolicy = runCapture(buildPolicyGetCommand(sandboxName)); + rawPolicy = runCapture(buildPolicyGetCommand(sandboxName, gatewayName)); } catch (error) { throw new Error("Cannot read the live gateway policy for managed MCP reconciliation", { cause: error, @@ -4025,11 +4046,14 @@ function resolveExactManagedMcpPolicies( function resolveProvableManagedMcpPoliciesForDeadline( sandboxName: string, + gatewayName?: string, ): ReturnType { try { let effectiveLivePolicy = ""; try { - effectiveLivePolicy = parseCurrentPolicy(runCapture(buildPolicyGetCommand(sandboxName))); + effectiveLivePolicy = parseCurrentPolicy( + runCapture(buildPolicyGetCommand(sandboxName, gatewayName)), + ); } catch { // The tolerant deadline inspector records exact omissions for every claim // when the live policy cannot be parsed or read. @@ -4071,6 +4095,10 @@ function applyShieldsPolicySnapshot( snapshotPath: string, options: ShieldsPolicySnapshotRestoreOptions = {}, ): ShieldsPolicySnapshotRestoreResult { + const policyAuthority = assertShieldsPolicyMutationAuthority( + sandboxName, + "restore the Shields policy snapshot", + ); const buildPolicySet = options.buildPolicySet ?? buildPolicySetCommand; const runPolicySet = options.runPolicySet ?? run; const state = loadShieldsState(sandboxName); @@ -4158,15 +4186,28 @@ function applyShieldsPolicySnapshot( fs.readFileSync(snapshotPath, "utf-8"), hasManagedMcpPolicyClaims(sandboxName), ); - return runPolicySet(buildPolicySet(snapshotPath, sandboxName), { - ignoreError: true, - }); + assertShieldsPolicyMutationAuthority( + sandboxName, + "restore the Shields policy snapshot", + policyAuthority, + ); + const result = runPolicySet( + buildPolicySet(snapshotPath, sandboxName, policyAuthority.gatewayName), + { + ignoreError: true, + }, + ); + rejectFinalShieldsPolicySetResult(result, "restore the Shields policy snapshot"); + return result; } } let managedMcpOmissions: ManagedMcpPolicyOmission[] = []; let runtimePolicyPath: string; if (options.deadlineAuthoritative) { - const inspection = resolveProvableManagedMcpPoliciesForDeadline(sandboxName); + const inspection = resolveProvableManagedMcpPoliciesForDeadline( + sandboxName, + policyAuthority.gatewayName, + ); const runtime = buildDeadlineRuntimeManagedMcpPolicy(snapshotPath, { managedMcpPolicies: inspection.policies, snapshotManagedPolicyKeys, @@ -4175,7 +4216,11 @@ function applyShieldsPolicySnapshot( runtimePolicyPath = runtime.path; managedMcpOmissions = [...ownershipOmissions, ...inspection.omissions, ...runtime.omissions]; } else { - const managedMcpPolicies = resolveExactManagedMcpPolicies(sandboxName); + const managedMcpPolicies = resolveExactManagedMcpPolicies( + sandboxName, + undefined, + policyAuthority.gatewayName, + ); runtimePolicyPath = buildRuntimeManagedMcpPolicy(snapshotPath, { managedMcpPolicies, snapshotManagedPolicyKeys, @@ -4184,9 +4229,18 @@ function applyShieldsPolicySnapshot( } const runtimePolicyIsTemp = runtimePolicyPath !== snapshotPath; try { - const result = runPolicySet(buildPolicySet(runtimePolicyPath, sandboxName), { - ignoreError: true, - }); + assertShieldsPolicyMutationAuthority( + sandboxName, + "restore the Shields policy snapshot", + policyAuthority, + ); + const result = runPolicySet( + buildPolicySet(runtimePolicyPath, sandboxName, policyAuthority.gatewayName), + { + ignoreError: true, + }, + ); + rejectFinalShieldsPolicySetResult(result, "restore the Shields policy snapshot"); return managedMcpOmissions.length > 0 ? { ...result, managedMcpOmissions } : result; } finally { if (runtimePolicyIsTemp) { @@ -4601,9 +4655,21 @@ function applyRecoveredShieldsDownForwardPolicy( completion: RecoveredShieldsDownCompletion, ): void { if (!completion.authority) return; + const policyAuthority = assertShieldsPolicyMutationAuthority( + sandboxName, + "reapply the interrupted Shields down policy", + ); assertRecoveredShieldsDownAuthority(sandboxName, completion, completion.authority.phase); const policyPath = requireShieldsDownForwardPolicy(completion.authority); - const result = run(buildPolicySetCommand(policyPath, sandboxName), { ignoreError: true }); + assertShieldsPolicyMutationAuthority( + sandboxName, + "reapply the interrupted Shields down policy", + policyAuthority, + ); + const result = run(buildPolicySetCommand(policyPath, sandboxName, policyAuthority.gatewayName), { + ignoreError: true, + }); + rejectFinalShieldsPolicySetResult(result, "reapply the interrupted Shields down policy"); if (result.status !== 0) { throw new Error("Interrupted Shields down forward policy could not be reapplied"); } @@ -5002,6 +5068,8 @@ function shieldsDownWithoutHostLock( return failShieldsCommand(`Config is already unlocked for ${sandboxName}`, opts.throwOnError); } + const policyAuthority = assertShieldsPolicyMutationAuthority(sandboxName, "lower Shields"); + // Resolve the old-image compatibility contract before touching timers, // host state, policy, or sandbox files. A transport failure or an // unsupported/incomplete guard must leave an ordinary shields command with @@ -5022,6 +5090,11 @@ function shieldsDownWithoutHostLock( // Kill stale auto-restore markers only when this command will actually // transition into shields-down. A repeated shields-down must not cancel the // active timer and leave the sandbox unlocked indefinitely. + assertShieldsPolicyMutationAuthority( + sandboxName, + "revoke stale Shields timer authority", + policyAuthority, + ); const timerCancellation = killTimer(sandboxName); if (!timerCancellation.authorityRevoked) { const detail = timerCancellation.warnings.join("; "); @@ -5041,10 +5114,11 @@ function shieldsDownWithoutHostLock( console.log(" Capturing current policy snapshot..."); let rawPolicy: string; try { - rawPolicy = runCapture(buildPolicyGetCommand(sandboxName)); + rawPolicy = runCapture(buildPolicyGetCommand(sandboxName, policyAuthority.gatewayName)); } catch { rawPolicy = ""; } + assertShieldsPolicyMutationAuthority(sandboxName, "continue lowering Shields", policyAuthority); const policyYaml = parseCurrentPolicy(rawPolicy); if (!policyYaml) { @@ -5054,7 +5128,11 @@ function shieldsDownWithoutHostLock( let managedMcpPolicies: ReturnType; try { - managedMcpPolicies = resolveExactManagedMcpPolicies(sandboxName, policyYaml); + managedMcpPolicies = resolveExactManagedMcpPolicies( + sandboxName, + policyYaml, + policyAuthority.gatewayName, + ); } catch (error) { const message = error instanceof Error ? error.message : String(error); console.error(` Cannot preserve managed MCP policy state: ${message}`); @@ -5064,6 +5142,11 @@ function shieldsDownWithoutHostLock( ); } const snapshotManagedMcpPolicyKeys = managedMcpPolicies.map((policy) => policy.key); + assertShieldsPolicyMutationAuthority( + sandboxName, + "capture the Shields policy snapshot", + policyAuthority, + ); const snapshotPath = path.join( STATE_DIR, @@ -5136,6 +5219,11 @@ function shieldsDownWithoutHostLock( // down. A crash can therefore never leave an untracked mutable window. let timerStart: FreshShieldsDownTimerStart; try { + assertShieldsPolicyMutationAuthority( + sandboxName, + "start the Shields auto-restore timer", + policyAuthority, + ); timerStart = startFreshShieldsDownTimer({ sandboxName, timeoutSeconds, @@ -5160,6 +5248,11 @@ function shieldsDownWithoutHostLock( if (transition && timerAuthority) { assertFreshShieldsDownAuthority(sandboxName, timerAuthority, transition, "preparing"); } + assertShieldsPolicyMutationAuthority( + sandboxName, + "record the provisional Shields down state", + policyAuthority, + ); saveShieldsState(sandboxName, { shieldsDown: true, shieldsDownAt: now, @@ -5215,12 +5308,27 @@ function shieldsDownWithoutHostLock( console.log(` Applying ${policyName} policy...`); let policySetResult: ReturnType; try { - policySetResult = run(buildPolicySetCommand(policyPathForApply, sandboxName), { - ignoreError: true, - }); + assertShieldsPolicyMutationAuthority( + sandboxName, + "apply the Shields down policy", + policyAuthority, + ); + policySetResult = run( + buildPolicySetCommand(policyPathForApply, sandboxName, policyAuthority.gatewayName), + { + ignoreError: true, + }, + ); } finally { cleanupRuntimePolicyFile(); } + let policyAuthorityRefusal: unknown = null; + try { + rejectFinalShieldsPolicySetResult(policySetResult, "apply the Shields down policy"); + } catch (error) { + if (!isPolicyAuthorityRefusalError(error)) throw error; + policyAuthorityRefusal = error; + } if (policySetResult.status !== 0) { // The permissive policy was rejected before it applied — for example, // OpenShell refuses a live Landlock change on a sandbox whose policy is @@ -5263,6 +5371,7 @@ function shieldsDownWithoutHostLock( ` ERROR: Could not apply the ${policyName} policy, and clearing the provisional Shields down record failed: ${stateMessage}`, ); console.error(" The scheduled auto-restore remains authoritative."); + if (policyAuthorityRefusal !== null) throw policyAuthorityRefusal; return failShieldsCommand(`Could not apply ${policyName} policy`, opts.throwOnError); } const timerCancellation = killTimer(sandboxName); @@ -5273,8 +5382,10 @@ function shieldsDownWithoutHostLock( ` ERROR: Could not apply the ${policyName} policy; the sandbox remains in the Shields up state.`, ); console.error(" Shields down did not take effect. `shields status` continues to report `UP`."); + if (policyAuthorityRefusal !== null) throw policyAuthorityRefusal; return failShieldsCommand(`Could not apply ${policyName} policy`, opts.throwOnError); } + if (policyAuthorityRefusal !== null) throw policyAuthorityRefusal; // 2b. Return config to default mutable state. // OpenClaw uses sandbox:sandbox 0660/2770 here so the gateway UID, which @@ -6085,6 +6196,7 @@ function clearShieldsState(sandboxName: string): void { export { applyShieldsPolicySnapshot, + assertShieldsPolicyMutationAuthority, clearShieldsState, completeAutoRestoreTransition, DEFAULT_TIMEOUT_SECONDS, diff --git a/src/lib/shields/policy-transition.test.ts b/src/lib/shields/policy-transition.test.ts index e28c2a4a937..767afee37ac 100644 --- a/src/lib/shields/policy-transition.test.ts +++ b/src/lib/shields/policy-transition.test.ts @@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } fr import YAML from "yaml"; import { createShieldsFlowHarness, + externalPolicyAuthorityInspection, type ShieldsFlowHarnessOptions, } from "../../../test/helpers/shields-flow-harness"; @@ -31,12 +32,53 @@ function sandboxCommandFailure( } const TRANSITION_LOCK_MODULE = "./transition-lock.js"; +function mockManagedPolicyAuthority(sandboxName: string): void { + const registry = requireSource("../state/registry.js") as typeof import("../state/registry.js"); + const policyAuthority = requireSource( + "../adapters/openshell/policy-authority.js", + ) as typeof import("../adapters/openshell/policy-authority.js"); + const policy = requireSource("../policy/index.js") as typeof import("../policy/index.js"); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: sandboxName, + openshellDriver: "docker", + policyAuthority: "nemoclaw-managed", + }); + vi.spyOn(registry, "updateSandbox").mockReturnValue(true); + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: { version: 1, network_policies: {} }, + }); + const receipt = { + authority: "nemoclaw-managed" as const, + authorityRecordedNow: false, + gatewayName: "nemoclaw", + inspection: { + authority: "nemoclaw-managed" as const, + effectivePolicy: { version: 1, network_policies: {} }, + }, + }; + vi.spyOn(policy, "inspectPolicyMutationAuthority").mockReturnValue(receipt); + vi.spyOn(policy, "recheckPolicyMutationAuthority").mockReturnValue(receipt); +} + describe("shields policy transition", () => { let homeDir: string; let runSpy: MockInstance; let runCaptureSpy: MockInstance; let shields: typeof import("./index.js"); + function writePolicySnapshot(sandboxName: string, fileName: string): string { + const stateDir = path.join(homeDir, ".nemoclaw", "state"); + const snapshotPath = path.join(stateDir, fileName); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n test: {}\n"); + fs.writeFileSync( + path.join(stateDir, `shields-${sandboxName}.json`), + JSON.stringify({ shieldsDown: true, shieldsPolicySnapshotPath: snapshotPath }), + ); + return snapshotPath; + } + beforeEach(() => { homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-policy-transition-")); vi.stubEnv("HOME", homeDir); @@ -72,6 +114,7 @@ describe("shields policy transition", () => { (_sandboxName: unknown, cmd: unknown) => cmd as string[], ); vi.spyOn(dockerExec, "dockerExecFileSync").mockReturnValue(""); + mockManagedPolicyAuthority("openclaw"); vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(console, "log").mockImplementation(() => undefined); shields = requireSource(SHIELDS_MODULE); @@ -85,6 +128,40 @@ describe("shields policy transition", () => { fs.rmSync(homeDir, { recursive: true, force: true }); }); + it("rechecks policy authority immediately before direct snapshot restore (#9833)", () => { + const sandboxName = "openclaw"; + const snapshotPath = writePolicySnapshot(sandboxName, "policy-snapshot-authority-race.yaml"); + const policy = requireSource("../policy/index.js") as typeof import("../policy/index.js"); + vi.mocked(policy.recheckPolicyMutationAuthority).mockImplementation(() => { + throw new Error("OpenShell policy authority changed during snapshot restore"); + }); + + expect(() => shields.applyShieldsPolicySnapshot(sandboxName, snapshotPath)).toThrow( + /policy authority changed/, + ); + expect(runSpy).not.toHaveBeenCalled(); + }); + + it("refuses external authority before Shields snapshot recovery (#9833)", () => { + const sandboxName = "openclaw"; + const snapshotPath = writePolicySnapshot(sandboxName, "policy-snapshot-external.yaml"); + const policy = requireSource("../policy/index.js") as typeof import("../policy/index.js"); + vi.mocked(policy.inspectPolicyMutationAuthority).mockReturnValue({ + authority: "externally-managed", + authorityRecordedNow: false, + gatewayName: "nemoclaw", + inspection: { + authority: "externally-managed", + effectivePolicy: { version: 1, network_policies: {} }, + }, + }); + + expect(() => shields.applyShieldsPolicySnapshot(sandboxName, snapshotPath)).toThrow( + /externally managed/, + ); + expect(runSpy).not.toHaveBeenCalled(); + }); + it("never relaxes policy or persists mutable state when the base-policy read fails", () => { expect(() => shields.shieldsDown("openclaw", { throwOnError: true })).toThrow( "Cannot capture current policy", @@ -138,6 +215,46 @@ describe("shields down policy rejection", () => { }); } + it("stops Shields down before mutation when policy is externally managed (#9833)", () => { + const harness = createShieldsFlowHarness(requireSource, tmpDir, { + policyAuthorityInspection: externalPolicyAuthorityInspection, + sandboxEntry: { + name: "openclaw", + openshellDriver: "docker", + policyAuthority: "externally-managed", + }, + }); + + expect(() => harness.shieldsDown("openclaw", { throwOnError: true })).toThrow( + "externally managed", + ); + expect(harness.runSpy).not.toHaveBeenCalled(); + expect(harness.dockerSpawnCalls).toEqual([]); + }); + + it("pins Shields policy inspection, reads, and writes to the recorded gateway (#9833)", () => { + const gatewayName = "nemoclaw-18080"; + const harness = createShieldsFlowHarness(requireSource, tmpDir, { + confirmOpenClawInodeFlags: true, + sandboxEntry: { + name: "openclaw", + gatewayName, + gatewayPort: 18080, + openshellDriver: "docker", + policyAuthority: "nemoclaw-managed", + }, + }); + + harness.shieldsDown("openclaw", { throwOnError: true }); + + expect(harness.policyAuthoritySpy).toHaveBeenCalledWith("openclaw", "lower Shields"); + const policyCommands = [...harness.runCaptureSpy.mock.calls, ...harness.runSpy.mock.calls] + .map(([command]) => command) + .filter((command) => Array.isArray(command) && command.includes("policy")); + expect(policyCommands.length).toBeGreaterThan(0); + expect(policyCommands.every((command) => command.includes(gatewayName))).toBe(true); + }); + it("keeps `shields status` at `UP` when OpenShell rejects the permissive policy (#8198)", () => { const harness = createRejectedPolicyHarness(); @@ -589,6 +706,7 @@ describe("shields config lock without a shipped config hash", () => { vi.spyOn(stateDirLock, "preflightStateDirLock").mockReturnValue([]); applyStateDirLockModeSpy = vi.spyOn(stateDirLock, "applyStateDirLockMode").mockReturnValue([]); restoreStateDirLockPostureSpy = vi.spyOn(stateDirLock, "restoreStateDirLockPosture"); + mockManagedPolicyAuthority("dcode-safety"); errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(console, "log").mockImplementation(() => undefined); shields = requireSource(SHIELDS_MODULE); @@ -839,6 +957,9 @@ describe("managed MCP policy deadline restoration (#7952)", () => { const runner = requireSource("../runner.js") as typeof import("../runner.js"); const policy = requireSource("../policy/index.js") as typeof import("../policy/index.js"); const registry = requireSource("../state/registry.js") as typeof import("../state/registry.js"); + const policyAuthority = requireSource( + "../adapters/openshell/policy-authority.js", + ) as typeof import("../adapters/openshell/policy-authority.js"); const policySetBodies: string[] = []; vi.spyOn(runner, "runCapture").mockReturnValue( @@ -854,7 +975,24 @@ describe("managed MCP policy deadline restoration (#7952)", () => { vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "openclaw", openshellDriver: "docker", + policyAuthority: "nemoclaw-managed", + }); + vi.spyOn(registry, "updateSandbox").mockReturnValue(true); + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: { version: 1, network_policies: {} }, }); + const authorityReceipt = { + authority: "nemoclaw-managed" as const, + authorityRecordedNow: false, + gatewayName: "nemoclaw", + inspection: { + authority: "nemoclaw-managed" as const, + effectivePolicy: { version: 1, network_policies: {} }, + }, + }; + vi.spyOn(policy, "inspectPolicyMutationAuthority").mockReturnValue(authorityReceipt); + vi.spyOn(policy, "recheckPolicyMutationAuthority").mockReturnValue(authorityReceipt); const shields = requireSource(SHIELDS_MODULE) as typeof import("./index.js"); return { applyShieldsPolicySnapshot: shields.applyShieldsPolicySnapshot, policySetBodies }; diff --git a/test/helpers/shields-flow-harness.ts b/test/helpers/shields-flow-harness.ts index e17449608a6..2fd6afc51e2 100644 --- a/test/helpers/shields-flow-harness.ts +++ b/test/helpers/shields-flow-harness.ts @@ -7,11 +7,17 @@ import path from "node:path"; import { expect, type MockInstance, vi } from "vitest"; import YAML from "yaml"; import { buildMcpBridgePolicyYaml } from "../../src/lib/actions/sandbox/mcp-bridge-policy-render"; +import type { SandboxPolicyAuthorityInspection } from "../../src/lib/adapters/openshell/policy-authority"; import type { AgentConfigTarget } from "../../src/lib/sandbox/agent-config"; import type { SandboxEntry } from "../../src/lib/state/registry"; const shieldsModulePath = "./index.js"; +export const externalPolicyAuthorityInspection = { + authority: "externally-managed" as const, + effectivePolicy: { version: 1, network_policies: {} }, +}; + export type ShieldsFlowHarness = { applyShieldsPolicySnapshot: typeof import("../../src/lib/shields/index.js").applyShieldsPolicySnapshot; auditSpy: MockInstance; @@ -21,6 +27,7 @@ export type ShieldsFlowHarness = { getShieldsPosture: typeof import("../../src/lib/shields/index.js").getShieldsPosture; getOpenClawPosture: () => "locked" | "mutable"; logSpy: MockInstance; + policyAuthoritySpy: MockInstance; policySetBodies: string[]; runCaptureSpy: MockInstance; runSpy: MockInstance; @@ -54,6 +61,7 @@ export type ShieldsFlowHarnessOptions = { detail: string; }>; processStartIdentity?: string; + policyAuthorityInspection?: SandboxPolicyAuthorityInspection; timerAuthorizationOutcome?: "authorized" | "dies-before-proof"; timerDiesAfterUnlock?: boolean; fork?: (...args: unknown[]) => { @@ -160,6 +168,7 @@ export function createShieldsFlowHarness( delete require.cache[requireDist.resolve("./transition-lock.js")]; delete require.cache[requireDist.resolve("./permissive-runtime.js")]; delete require.cache[requireDist.resolve("../actions/sandbox/mcp-bridge-policy.js")]; + delete require.cache[requireDist.resolve("../adapters/openshell/policy-authority.js")]; delete require.cache[requireDist.resolve("../sandbox/privileged-exec.js")]; delete require.cache[requireDist.resolve("../cli/branding.js")]; const timerControl = requireDist( @@ -221,6 +230,9 @@ export function createShieldsFlowHarness( const policy = requireDist("../policy/index.js"); const agentConfig = requireDist("../sandbox/agent-config.js"); const registry = requireDist("../state/registry.js"); + const policyAuthority = requireDist( + "../adapters/openshell/policy-authority.js", + ) as typeof import("../../src/lib/adapters/openshell/policy-authority.js"); const privilegedExec = requireDist("../sandbox/privileged-exec.js"); const dockerExec = requireDist("../adapters/docker/exec.js"); const audit = requireDist("./audit.js"); @@ -284,11 +296,25 @@ export function createShieldsFlowHarness( }; }); } - vi.spyOn(policy, "buildPolicyGetCommand").mockReturnValue(["openshell", "policy", "get"]); - vi.spyOn(policy, "buildPolicySetCommand").mockImplementation((file: unknown) => { - recordPolicySetBody(policySetBodies, file); - return ["openshell", "policy", "set"]; - }); + vi.spyOn(policy, "buildPolicyGetCommand").mockImplementation( + (_sandboxName: unknown, gatewayName: unknown) => [ + "openshell", + "policy", + "get", + ...(typeof gatewayName === "string" ? ["-g", gatewayName] : []), + ], + ); + vi.spyOn(policy, "buildPolicySetCommand").mockImplementation( + (file: unknown, _sandbox, gateway) => { + recordPolicySetBody(policySetBodies, file); + return [ + "openshell", + "policy", + "set", + ...(typeof gateway === "string" ? ["-g", gateway] : []), + ]; + }, + ); vi.spyOn(policy, "parseCurrentPolicy").mockImplementation((raw: unknown) => String(raw)); vi.spyOn(policy, "resolvePermissivePolicyPath").mockReturnValue( path.join(tmpDir, "permissive.yaml"), @@ -305,12 +331,35 @@ export function createShieldsFlowHarness( }; vi.spyOn(agentConfig, "resolveAgentConfig").mockReturnValue(resolvedAgentConfig); vi.spyOn(registry, "getSandbox").mockReturnValue( - options.sandboxEntry ?? { - name: options.sandboxName ?? "openclaw", - agent: resolvedAgentConfig.agentName, - openshellDriver: "docker", - }, + options.sandboxEntry + ? { policyAuthority: "nemoclaw-managed", ...options.sandboxEntry } + : { + name: options.sandboxName ?? "openclaw", + agent: resolvedAgentConfig.agentName, + openshellDriver: "docker", + policyAuthority: "nemoclaw-managed", + }, ); + vi.spyOn(registry, "updateSandbox").mockReturnValue(true); + const policyAuthorityInspection = options.policyAuthorityInspection ?? { + authority: "nemoclaw-managed" as const, + effectivePolicy: YAML.parse( + options.livePolicyYaml ?? "version: 1\nnetwork_policies:\n test: {}\n", + ) as Record, + }; + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue( + policyAuthorityInspection, + ); + const policyMutationAuthority = { + authority: policyAuthorityInspection.authority, + authorityRecordedNow: false, + gatewayName: options.sandboxEntry?.gatewayName ?? "nemoclaw", + inspection: policyAuthorityInspection, + }; + const policyAuthoritySpy = vi + .spyOn(policy, "inspectPolicyMutationAuthority") + .mockReturnValue(policyMutationAuthority); + vi.spyOn(policy, "recheckPolicyMutationAuthority").mockReturnValue(policyMutationAuthority); vi.spyOn(registry, "listSandboxes").mockReturnValue({ sandboxes: [{ name: options.sandboxName ?? "openclaw", agent: resolvedAgentConfig.agentName }], }); @@ -580,6 +629,7 @@ export function createShieldsFlowHarness( getShieldsPosture: shields.getShieldsPosture, getOpenClawPosture: () => openClawPosture, logSpy, + policyAuthoritySpy, policySetBodies, runCaptureSpy, runSpy, diff --git a/test/policies.test.ts b/test/policies.test.ts index 395ae521a48..7dbb1546033 100644 --- a/test/policies.test.ts +++ b/test/policies.test.ts @@ -515,6 +515,31 @@ exit 1 expect(waitIdx < nameIdx).toBeTruthy(); }); + it("pins policy reads and writes to an explicit gateway (#9833)", () => { + expect( + policies + .buildPolicySetCommand("/tmp/policy.yaml", "my-assistant", "nemoclaw-18080") + .slice(1), + ).toEqual([ + "policy", + "set", + "-g", + "nemoclaw-18080", + "--policy", + "/tmp/policy.yaml", + "--wait", + "my-assistant", + ]); + expect(policies.buildPolicyGetCommand("my-assistant", "nemoclaw-18080").slice(1)).toEqual([ + "policy", + "get", + "-g", + "nemoclaw-18080", + "--base", + "my-assistant", + ]); + }); + it("uses the resolved openshell binary for every policy command", () => { const resolved = "/opt/nvidia/bin/openshell"; const resolveSpy = vi From eae0cc136c2b703cfb2d0b3d5589899ab814cab0 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 21:39:35 -0700 Subject: [PATCH 05/40] test(blueprint): model policy authority preflight Signed-off-by: Apurv Kumaria --- .../src/blueprint/runner-identity.test.ts | 42 +++++++++++-------- .../blueprint/runner-name-validation.test.ts | 10 ++++- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/nemoclaw/src/blueprint/runner-identity.test.ts b/nemoclaw/src/blueprint/runner-identity.test.ts index c14da4d28e5..030d581d959 100644 --- a/nemoclaw/src/blueprint/runner-identity.test.ts +++ b/nemoclaw/src/blueprint/runner-identity.test.ts @@ -19,6 +19,7 @@ import { MATCHING_INFERENCE_ROUTE_LISTING, MATCHING_RUNTIME_PROVIDER_LISTING, providersV2EnabledResult, + resultWithBlueprintPolicyAuthority, successResult, } from "./runner-test-fixtures.js"; @@ -82,10 +83,22 @@ function responseQueue( ]); mockExeca.mockImplementation(async (_command: string, args: string[]) => { const command = args.join(" "); - return responses.get(command)?.shift() ?? fallbacks.get(command) ?? success; + const fallback = responses.get(command)?.shift() ?? fallbacks.get(command) ?? success; + return fallback.exitCode === undefined + ? fallback + : resultWithBlueprintPolicyAuthority(args, { + ...fallback, + exitCode: fallback.exitCode ?? 1, + }); }); } +function nonAuthorityCommandLines(): string[] { + return mockExeca.mock.calls + .map(([command, args]) => [command, ...(args ?? [])].join(" ")) + .filter((command) => command !== "openshell status" && !command.startsWith("openshell policy ")); +} + function blueprint(overrides: Record = {}): Parameters[1] { return { components: { @@ -123,7 +136,10 @@ describe("blueprint identity wrapper", () => { realpaths.clear(); vi.clearAllMocks(); mockExeca.mockImplementation(async (_command: string, args: string[]) => - args.join(" ") === "settings get --global --json" ? providersV2Enabled : success, + resultWithBlueprintPolicyAuthority( + args, + args.join(" ") === "settings get --global --json" ? providersV2Enabled : success, + ), ); process.env.NEMOCLAW_BLUEPRINT_PATH = "/blueprint"; store.set("/blueprint", { type: "dir" }); @@ -337,9 +353,7 @@ describe("blueprint identity wrapper", () => { /Failed to inspect sandbox 'test-sandbox'.*gateway configuration not found/, ); - const commandLines = mockExeca.mock.calls.map(([command, args]) => - [command, ...(args ?? [])].join(" "), - ); + const commandLines = nonAuthorityCommandLines(); expect(commandLines).toEqual(["openshell sandbox get test-sandbox"]); }); @@ -358,9 +372,7 @@ describe("blueprint identity wrapper", () => { /Sandbox 'test-sandbox' is not reusable.*Ready phase.*Provisioning/, ); - const commandLines = mockExeca.mock.calls.map(([command, args]) => - [command, ...(args ?? [])].join(" "), - ); + const commandLines = nonAuthorityCommandLines(); expect(commandLines).toEqual(["openshell sandbox get test-sandbox"]); }); @@ -424,9 +436,7 @@ describe("blueprint identity wrapper", () => { /Failed to inspect inference provider 'test-provider'.*gateway configuration not found/, ); - const commandLines = mockExeca.mock.calls.map(([command, args]) => - [command, ...(args ?? [])].join(" "), - ); + const commandLines = nonAuthorityCommandLines(); expect(commandLines).toEqual([ "openshell sandbox get test-sandbox", "openshell provider get test-provider", @@ -454,9 +464,7 @@ describe("blueprint identity wrapper", () => { /Inference provider 'test-provider' does not match the requested non-secret binding/, ); - const commandLines = mockExeca.mock.calls.map(([command, args]) => - [command, ...(args ?? [])].join(" "), - ); + const commandLines = nonAuthorityCommandLines(); expect(commandLines).toEqual([ "openshell sandbox get test-sandbox", "openshell provider get test-provider", @@ -483,9 +491,7 @@ describe("blueprint identity wrapper", () => { /Failed to inspect the active inference route.*gateway route inspection unavailable/, ); - const commandLines = mockExeca.mock.calls.map(([command, args]) => - [command, ...(args ?? [])].join(" "), - ); + const commandLines = nonAuthorityCommandLines(); expect(commandLines).toEqual([ "openshell sandbox get test-sandbox", "openshell provider get test-provider", @@ -786,7 +792,7 @@ describe("blueprint identity wrapper", () => { { exitCode: 0, stdout: matchingProvider, stderr: "" }, ], ], - ["policy get --base test-sandbox", [failureResult("policy read rejected")]], + ["policy get -g test-gateway --base test-sandbox", [failureResult("policy read rejected")]], ]); await expect( diff --git a/nemoclaw/src/blueprint/runner-name-validation.test.ts b/nemoclaw/src/blueprint/runner-name-validation.test.ts index 82159fb78d4..c9ce84a4d42 100644 --- a/nemoclaw/src/blueprint/runner-name-validation.test.ts +++ b/nemoclaw/src/blueprint/runner-name-validation.test.ts @@ -16,7 +16,11 @@ import { inMemoryFsMethods, resolvedEndpointFor, } from "./runner-mock-fixtures.js"; -import { minimalBlueprint, successResult } from "./runner-test-fixtures.js"; +import { + minimalBlueprint, + resultWithBlueprintPolicyAuthority, + successResult, +} from "./runner-test-fixtures.js"; const { store, addFile, addDir } = createRunnerFsStore(); @@ -114,7 +118,9 @@ describe("blueprint name validation (fail-closed integration)", () => { stdout.reset(); vi.clearAllMocks(); vi.spyOn(process.stdout, "write").mockImplementation(stdout.write); - mockExeca.mockResolvedValue(successResult()); + mockExeca.mockImplementation(async (_command: string, args: string[]) => + resultWithBlueprintPolicyAuthority(args, successResult()), + ); }); afterEach(() => { From 192c23f202d194a83ce8777fec8bca0ac74a0066 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 22:07:52 -0700 Subject: [PATCH 06/40] fix(policy): retain incomplete blueprint transitions Signed-off-by: Apurv Kumaria --- .../runner-openshell-072-policy.test.ts | 124 ++++++++++- nemoclaw/src/blueprint/runner.ts | 198 ++++++++++++------ .../src/shared/openshell-policy-boundary.cts | 160 ++++++++++++++ .../shared/openshell-policy-boundary.test.ts | 83 ++++++++ .../openshell/policy-authority.test.ts | 6 +- .../adapters/openshell/policy-authority.ts | 163 +++----------- src/lib/policy/merge.ts | 11 + .../openshell-policy-boundary.test.ts | 31 +++ 8 files changed, 570 insertions(+), 206 deletions(-) diff --git a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts index 12d95ec40b5..95a17ecde60 100644 --- a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts +++ b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts @@ -8,6 +8,7 @@ import YAML from "yaml"; import { createRunnerFsStore, + createStdoutCapture, FAKE_HOME, FIXED_RUN_UUID, inMemoryFsMethods, @@ -23,6 +24,7 @@ import { const { store } = createRunnerFsStore(); const mockExeca = vi.fn(); +const stdoutCapture = createStdoutCapture(); vi.mock("node:crypto", () => ({ randomUUID: () => FIXED_RUN_UUID, @@ -38,6 +40,8 @@ vi.mock("node:fs", async (importOriginal) => { return { ...original, mkdirSync: memory.mkdirSync, + readFileSync: memory.readFileSync, + readdirSync: memory.readdirSync, writeFileSync: memory.writeFileSync, }; }); @@ -54,7 +58,7 @@ vi.mock("./ssrf.js", async (importOriginal) => { }; }); -const { actionApply } = await import("./runner.js"); +const { actionApply, actionRollback, actionStatus } = await import("./runner.js"); const BASE_POLICY = `version: 1 future_policy: @@ -164,8 +168,9 @@ function blueprint(): Parameters[1] { describe("OpenShell 0.0.72 blueprint policy round-trip", () => { beforeEach(() => { store.clear(); + stdoutCapture.reset(); mockExeca.mockReset(); - vi.spyOn(process.stdout, "write").mockImplementation(() => true); + vi.spyOn(process.stdout, "write").mockImplementation(stdoutCapture.write); const policyByCommand = new Map([ ["policy get -g test-gateway --base test-sandbox", policyOutput(BASE_POLICY)], ["policy get -g test-gateway --full test-sandbox", policyOutput(FULL_POLICY)], @@ -210,6 +215,18 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { nim_service: expect.any(Object), }); expect(merged.network_policies).not.toHaveProperty("_provider_nvidia-inference"); + const planEntry = [...store.values()].find((entry) => + entry.content?.includes('"policy_transition"'), + ); + expect(JSON.parse(planEntry?.content ?? "{}")).toMatchObject({ + policy_transition: { + status: "complete", + sandbox_name: "test-sandbox", + gateway: "test-gateway", + expected_authority: "nemoclaw-managed", + policy_addition_names: ["nim_service"], + }, + }); }); it.each([ @@ -401,6 +418,8 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { let sandboxAuthorityReads = 0; mockExeca.mockImplementation(async (_cmd: string, args: string[]) => { switch (args.join(" ")) { + case "sandbox create --from openclaw --name test-sandbox --forward 18789": + return { exitCode: 1, stdout: "", stderr: "sandbox already exists" }; case "policy get -g test-gateway --base test-sandbox": return { exitCode: 0, @@ -420,5 +439,106 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { await expect(actionApply("default", blueprint())).rejects.toThrow(/policy authority changed/); expect(policySetCalls()).toEqual([]); + expect(sandboxAuthorityReads).toBe(3); + }); + + it("records and reports an incomplete reused-sandbox policy transition (#9833)", async () => { + let sandboxAuthorityReads = 0; + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => { + switch (args.join(" ")) { + case "sandbox create --from openclaw --name test-sandbox --forward 18789": + return { exitCode: 1, stdout: "", stderr: "sandbox already exists" }; + case "policy get -g test-gateway --base test-sandbox": + return { + exitCode: 0, + stdout: "Version: 1\nHash: sha256:test\n---\nversion: 1\nnetwork_policies: {}\n", + stderr: "", + }; + case "policy get -g test-gateway --full --output json test-sandbox": + sandboxAuthorityReads += 1; + return sandboxPolicyAuthorityResult( + "test-sandbox", + sandboxAuthorityReads < 4 ? "nemoclaw-managed" : "externally-managed", + ); + default: + return defaultCommandResult(args); + } + }); + + await expect(actionApply("default", blueprint())).rejects.toThrow(/policy authority changed/); + expect(policySetCalls()).toHaveLength(1); + expect(sandboxAuthorityReads).toBe(4); + + const planEntry = [...store.entries()].find(([path]) => path.endsWith("/plan.json")); + expect(planEntry).toBeDefined(); + const plan = JSON.parse(planEntry?.[1].content ?? "{}") as { + run_id: string; + sandbox_created_by_apply: boolean; + policy_transition: Record; + }; + expect(plan).toMatchObject({ + sandbox_created_by_apply: false, + policy_transition: { + status: "incomplete", + sandbox_name: "test-sandbox", + gateway: "test-gateway", + expected_authority: "nemoclaw-managed", + policy_addition_names: ["nim_service"], + }, + }); + + stdoutCapture.reset(); + actionStatus(plan.run_id); + expect(stdoutCapture.jsonOutput()).toMatchObject({ + policy_transition: { + status: "incomplete", + sandbox_name: "test-sandbox", + reconciliation_required: true, + reconciliation_action: expect.stringContaining("reconcile the reused sandbox"), + }, + }); + + await expect(actionRollback(plan.run_id)).rejects.toThrow( + /policy transition for reused sandbox "test-sandbox".*is incomplete.*reconcile/u, + ); + expect(store.has(`${planEntry?.[0].replace(/\/plan\.json$/u, "")}/rolled_back`)).toBe(false); + }); + + it("keeps a pending receipt when a reused-sandbox policy set fails (#9833)", async () => { + const responses = new Map([ + [ + "sandbox create --from openclaw --name test-sandbox --forward 18789", + { exitCode: 1, stdout: "", stderr: "sandbox already exists" }, + ], + [ + "policy get -g test-gateway --base test-sandbox", + { + exitCode: 0, + stdout: policyOutput("version: 1\nnetwork_policies: {}\n"), + stderr: "", + }, + ], + ["policy set", { exitCode: 1, stdout: "", stderr: "policy set rejected" }], + ]); + mockExeca.mockImplementation( + async (_cmd: string, args: string[]) => + responses.get(args.join(" ")) ?? + responses.get(args.slice(0, 2).join(" ")) ?? + defaultCommandResult(args), + ); + + await expect(actionApply("default", blueprint())).rejects.toThrow(/policy set rejected/u); + const planEntry = [...store.values()].find((entry) => + entry.content?.includes('"policy_transition"'), + ); + expect(JSON.parse(planEntry?.content ?? "{}")).toMatchObject({ + sandbox_created_by_apply: false, + policy_transition: { + status: "pending", + sandbox_name: "test-sandbox", + gateway: "test-gateway", + policy_addition_names: ["nim_service"], + }, + }); }); }); diff --git a/nemoclaw/src/blueprint/runner.ts b/nemoclaw/src/blueprint/runner.ts index d645b84332e..1029f4f73a4 100644 --- a/nemoclaw/src/blueprint/runner.ts +++ b/nemoclaw/src/blueprint/runner.ts @@ -16,7 +16,6 @@ import { randomUUID } from "node:crypto"; import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join, sep } from "node:path"; -import { isDeepStrictEqual } from "node:util"; import { execa } from "execa"; import YAML from "yaml"; @@ -54,8 +53,13 @@ const sourceOrGeneratedOpenShellPolicyBoundary = importedOpenShellPolicyBoundary as typeof importedOpenShellPolicyBoundary & { default?: typeof importedOpenShellPolicyBoundary; }; -const { parseOpenShellPolicy, withoutProviderComposedPolicies } = - sourceOrGeneratedOpenShellPolicyBoundary.default ?? sourceOrGeneratedOpenShellPolicyBoundary; +const { + assertExternalPolicyRequirementContainment, + assertMatchingPolicyAuthority, + parseOpenShellPolicy, + parseSandboxPolicyAuthorityMetadata, + withoutProviderComposedPolicies, +} = sourceOrGeneratedOpenShellPolicyBoundary.default ?? sourceOrGeneratedOpenShellPolicyBoundary; // sourceOfTruth: nemoclaw/src/shared/sandbox-name.cts const sourceOrGeneratedSandboxName = importedSandboxName as typeof importedSandboxName & { @@ -73,6 +77,7 @@ type RollbackPlanSource = { inference?: unknown; identity?: unknown; policy_authority?: unknown; + policy_transition?: unknown; }; type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"; type RestProtocol = "rest"; @@ -103,10 +108,7 @@ interface PolicyAddition { type PolicyAdditions = { [name: string]: PolicyAddition }; -type BlueprintPolicyAuthorityInspection = { - authority: "nemoclaw-managed" | "externally-managed"; - effectivePolicy: UnknownRecord; -}; +type BlueprintPolicyAuthorityInspection = import("../shared/openshell-policy-boundary.cjs").SandboxPolicyAuthorityInspection; type BlueprintPolicyAuthorityReceipt = { authority: BlueprintPolicyAuthorityInspection["authority"]; @@ -115,6 +117,22 @@ type BlueprintPolicyAuthorityReceipt = { sandbox_name?: string; }; +type BlueprintPolicyTransitionReceipt = { + status: "pending" | "incomplete" | "complete"; + sandbox_name: string; + gateway: string; + expected_authority: "nemoclaw-managed"; + policy_addition_names: string[]; +}; + +type StatusPolicyTransition = BlueprintPolicyTransitionReceipt & { + reconciliation_required: boolean; + reconciliation_action?: string; +}; + +const POLICY_TRANSITION_RECONCILIATION_ACTION = + "Inspect the recorded gateway policy for the listed additions and reconcile the reused sandbox before retrying apply or rollback."; + const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]); const REST_PROTOCOLS = new Set(["rest"]); const ENDPOINT_ENFORCEMENT_MODES = new Set(["enforce", "audit"]); @@ -649,27 +667,22 @@ async function inspectBlueprintPolicyAuthority( ? ["openshell", "policy", "get", "-g", gateway, "--global", "--full", "--output", "json"] : ["openshell", "policy", "get", "-g", gateway, "--full", "--output", "json", sandboxName]; const result = await runBlueprintPolicyAuthorityCommand(command, subject); - if (result.stdout.trim().length === 0) { - throw new Error( - `OpenShell returned empty ${subject} policy authority metadata. Policy-dependent operations must stop.`, - ); - } - - let metadata: unknown; - try { - metadata = JSON.parse(result.stdout); - } catch { - throw new Error( - `OpenShell returned malformed ${subject} policy authority metadata. Policy-dependent operations must stop.`, - ); - } - if (!isPlainObject(metadata)) { - throw new Error( - `OpenShell returned invalid ${subject} policy authority metadata. Policy-dependent operations must stop.`, - ); - } if (sandboxName === undefined) { + if (result.stdout.trim().length === 0) { + throw new Error( + "OpenShell returned empty global policy authority metadata. Policy-dependent operations must stop.", + ); + } + let metadata: unknown; + try { + metadata = JSON.parse(result.stdout); + } catch { + throw new Error( + "OpenShell returned malformed global policy authority metadata. Policy-dependent operations must stop.", + ); + } if ( + !isPlainObject(metadata) || metadata.scope !== "global" || (metadata.status !== "loaded" && metadata.status !== "superseded") || (metadata.policy_source !== undefined && metadata.policy_source !== "global") || @@ -689,30 +702,24 @@ async function inspectBlueprintPolicyAuthority( } return { authority: "externally-managed", effectivePolicy: metadata.policy }; } - if ( - metadata.scope !== "sandbox" || - metadata.sandbox !== sandboxName || - metadata.status !== "effective" || - (metadata.policy_source !== "sandbox" && metadata.policy_source !== "global") || - !isPlainObject(metadata.policy) - ) { - throw new Error( - "OpenShell returned invalid sandbox policy authority metadata. Policy-dependent operations must stop.", - ); + try { + return parseSandboxPolicyAuthorityMetadata(result.stdout, sandboxName); + } catch (error) { + const detail = error instanceof Error ? error.message : "OpenShell returned invalid metadata"; + throw new Error(`${detail}. Policy-dependent operations must stop.`); } - return { - authority: metadata.policy_source === "sandbox" ? "nemoclaw-managed" : "externally-managed", - effectivePolicy: metadata.policy, - }; } function assertBlueprintPolicyAuthorityMatches( recorded: BlueprintPolicyAuthorityInspection, observed: BlueprintPolicyAuthorityInspection, ): void { - if (recorded.authority !== observed.authority) { + try { + assertMatchingPolicyAuthority(recorded.authority, observed.authority); + } catch (error) { + const detail = error instanceof Error ? error.message : "policy authority is invalid"; throw new Error( - `Refusing to apply blueprint policy additions because OpenShell policy authority changed from ${recorded.authority} to ${observed.authority}.`, + `Refusing to apply blueprint policy additions because ${detail}.`, ); } } @@ -721,30 +728,16 @@ function assertBlueprintExternalPolicyRequirements( inspection: BlueprintPolicyAuthorityInspection, additions: PolicyAdditions, ): void { - if (inspection.authority !== "externally-managed") return; - const observed = inspection.effectivePolicy.network_policies; - const observedPolicies = isPlainObject(observed) ? observed : null; - const missing: string[] = []; - const drifted: string[] = []; - for (const key of Object.keys(additions).sort()) { - if (!observedPolicies || !Object.hasOwn(observedPolicies, key)) { - missing.push(key); - } else if (!isDeepStrictEqual(observedPolicies[key], additions[key])) { - drifted.push(key); - } + try { + assertExternalPolicyRequirementContainment(inspection, { + network_policies: additions, + }); + } catch (error) { + const detail = error instanceof Error ? error.message : "the policy requirement is invalid"; + throw new Error( + `Refusing to apply the blueprint: ${detail}. Ask the external policy authority to supply the exact required entries.`, + ); } - if (missing.length === 0 && drifted.length === 0) return; - const differences = [ - ...(missing.length > 0 - ? [`missing entries ${missing.map((key) => JSON.stringify(key)).join(", ")}`] - : []), - ...(drifted.length > 0 - ? [`drifted entries ${drifted.map((key) => JSON.stringify(key)).join(", ")}`] - : []), - ].join("; "); - throw new Error( - `Refusing to apply the blueprint: the externally managed policy has ${differences}. Ask the external policy authority to supply the exact required entries.`, - ); } async function runRuntimeIdentityCommand( @@ -888,6 +881,7 @@ interface PersistedRunPlan { inference_provider_created_by_apply: boolean; policy_additions: PolicyAdditions; policy_authority: BlueprintPolicyAuthorityReceipt; + policy_transition?: BlueprintPolicyTransitionReceipt; inference: SafeInferencePlan; identity?: RuntimeIdentityReceipt; timestamp: string; @@ -906,6 +900,7 @@ type StatusRunPlan = { inference_provider_created_by_apply?: boolean; policy_additions?: PolicyAdditions; policy_authority?: BlueprintPolicyAuthorityReceipt; + policy_transition?: StatusPolicyTransition; inference?: SafeInferencePlan; identity?: RuntimeIdentityReceipt; router?: { @@ -937,6 +932,28 @@ function isBlueprintPolicyAuthorityReceipt( : isValidName(value.sandbox_name); } +function isBlueprintPolicyTransitionReceipt( + value: unknown, +): value is BlueprintPolicyTransitionReceipt { + if (!isPlainObject(value)) return false; + if ( + (value.status !== "pending" && + value.status !== "incomplete" && + value.status !== "complete") || + !isValidName(value.sandbox_name) || + !isValidName(value.gateway) || + value.expected_authority !== "nemoclaw-managed" || + !Array.isArray(value.policy_addition_names) || + value.policy_addition_names.length === 0 || + !value.policy_addition_names.every( + (name): name is string => typeof name === "string" && name.length > 0, + ) + ) { + return false; + } + return new Set(value.policy_addition_names).size === value.policy_addition_names.length; +} + function buildSafeInferencePlan(source: InferenceProfile | UnknownRecord): SafeInferencePlan { return { provider_type: optionalString(source.provider_type), @@ -990,6 +1007,7 @@ function buildPersistedRunPlan(args: { inferenceProviderCreatedByApply: boolean; policyAdditions: PolicyAdditions; policyAuthorityReceipt: BlueprintPolicyAuthorityReceipt; + policyTransition?: BlueprintPolicyTransitionReceipt; inferenceCfg: InferenceProfile; runtimeIdentityReceipt?: RuntimeIdentityReceipt; timestamp: string; @@ -1008,6 +1026,9 @@ function buildPersistedRunPlan(args: { if (args.runtimeIdentityReceipt) { plan.identity = args.runtimeIdentityReceipt; } + if (args.policyTransition) { + plan.policy_transition = args.policyTransition; + } return plan; } @@ -1063,6 +1084,22 @@ function buildStatusRunPlan(source: unknown, fallbackRunId: string): StatusRunPl if (isBlueprintPolicyAuthorityReceipt(source.policy_authority)) { safePlan.policy_authority = source.policy_authority; } + if ( + source.policy_transition !== undefined && + !isBlueprintPolicyTransitionReceipt(source.policy_transition) + ) { + return null; + } + if (isBlueprintPolicyTransitionReceipt(source.policy_transition)) { + const reconciliationRequired = source.policy_transition.status !== "complete"; + safePlan.policy_transition = { + ...source.policy_transition, + reconciliation_required: reconciliationRequired, + ...(reconciliationRequired + ? { reconciliation_action: POLICY_TRANSITION_RECONCILIATION_ACTION } + : {}), + }; + } if (isPlainObject(source.inference)) { safePlan.inference = buildSafeInferencePlan(source.inference); @@ -1188,6 +1225,7 @@ export async function actionApply( scope: "global", }; let sandboxPolicyAuthority: BlueprintPolicyAuthorityInspection | null = null; + let policyTransition: BlueprintPolicyTransitionReceipt | undefined; let sandboxCreatedByApply = false; let inferenceProviderCreatedByApply = false; const persistRunPlan = (): void => { @@ -1202,6 +1240,7 @@ export async function actionApply( inferenceProviderCreatedByApply, policyAdditions, policyAuthorityReceipt, + policyTransition, inferenceCfg, runtimeIdentityReceipt, timestamp: new Date().toISOString(), @@ -1504,6 +1543,14 @@ export async function actionApply( const beforeMutation = await inspectBlueprintPolicyAuthority(policyGateway, sandboxName); assertBlueprintPolicyAuthorityMatches(sandboxPolicyAuthority, beforeMutation); + policyTransition = { + status: "pending", + sandbox_name: sandboxName, + gateway: policyGateway, + expected_authority: "nemoclaw-managed", + policy_addition_names: Object.keys(policyAdditions).sort(), + }; + persistRunPlan(); const policySet = await runCmd( [ "openshell", @@ -1521,6 +1568,8 @@ export async function actionApply( if (policySet.exitCode !== 0) { throw new Error(`Failed to apply policy additions: ${policySet.stderr}`); } + policyTransition = { ...policyTransition, status: "incomplete" }; + persistRunPlan(); } } @@ -1531,6 +1580,9 @@ export async function actionApply( const finalPolicyAuthority = await inspectBlueprintPolicyAuthority(policyGateway, sandboxName); assertBlueprintPolicyAuthorityMatches(sandboxPolicyAuthority, finalPolicyAuthority); assertBlueprintExternalPolicyRequirements(finalPolicyAuthority, policyAdditions); + if (policyTransition) { + policyTransition = { ...policyTransition, status: "complete" }; + } persistRunPlan(); progress(100, "Apply complete"); @@ -1560,6 +1612,9 @@ export async function actionApply( }); if (remove.exitCode === 0 || MISSING_SANDBOX_PATTERN.test(remove.stderr)) { sandboxCreatedByApply = false; + if (policyTransition) { + policyTransition = { ...policyTransition, status: "complete" }; + } persistRunPlan(); } else { cleanupFailures.push( @@ -1662,6 +1717,7 @@ export async function actionRollback(rid: string): Promise { let inferenceProviderCreatedByApply = false; let inferenceProviderName: string | undefined; let runtimeIdentityReceipt: RuntimeIdentityReceipt | undefined; + let policyTransition: BlueprintPolicyTransitionReceipt | undefined; try { const planData = readFileSync(planFile, "utf-8"); const parsedPlan: unknown = JSON.parse(planData); @@ -1681,11 +1737,23 @@ export async function actionRollback(rid: string): Promise { } runtimeIdentityReceipt = rollbackPlan.identity; } + if (rollbackPlan?.policy_transition !== undefined) { + if (!isBlueprintPolicyTransitionReceipt(rollbackPlan.policy_transition)) { + throw new Error("policy transition receipt is invalid"); + } + policyTransition = rollbackPlan.policy_transition; + } } catch (error) { const detail = error instanceof Error ? error.message : String(error); throw new Error(`Cannot read rollback plan for run ${rid}: ${detail}`); } + if (!sandboxCreatedByApply && policyTransition && policyTransition.status !== "complete") { + throw new Error( + `Cannot roll back run ${rid}: the policy transition for reused sandbox ${JSON.stringify(policyTransition.sandbox_name)} through gateway ${JSON.stringify(policyTransition.gateway)} is ${policyTransition.status}. ${POLICY_TRANSITION_RECONCILIATION_ACTION}`, + ); + } + if (runtimeIdentityReceipt) { progress(20, `Removing runtime identity provider ${runtimeIdentityReceipt.provider_name}`); await removeRuntimeIdentity(runtimeIdentityReceipt, sandboxName, runtimeIdentityCommandDeps()); diff --git a/nemoclaw/src/shared/openshell-policy-boundary.cts b/nemoclaw/src/shared/openshell-policy-boundary.cts index eb2f99e9e88..bfd4e886042 100644 --- a/nemoclaw/src/shared/openshell-policy-boundary.cts +++ b/nemoclaw/src/shared/openshell-policy-boundary.cts @@ -15,6 +15,13 @@ export interface ParsedOpenShellPolicy { readonly policy: ValidatedOpenShellPolicyMapping; } +export type OpenShellPolicyAuthority = "nemoclaw-managed" | "externally-managed"; + +export interface SandboxPolicyAuthorityInspection { + readonly authority: OpenShellPolicyAuthority; + readonly effectivePolicy: OpenShellPolicyMapping; +} + const MISSING_POLICY_DOCUMENT = "Current policy from openshell policy get --base does not contain a policy YAML document"; @@ -22,6 +29,159 @@ function isMapping(value: unknown): value is OpenShellPolicyMapping { return typeof value === "object" && value !== null && !Array.isArray(value); } +function isPolicyAuthority(value: unknown): value is OpenShellPolicyAuthority { + return value === "nemoclaw-managed" || value === "externally-managed"; +} + +function parseJsonMapping(source: string, invalidMessage: string): OpenShellPolicyMapping { + let parsed: unknown; + try { + parsed = JSON.parse(source); + } catch { + throw new Error(invalidMessage); + } + if (!isMapping(parsed)) { + throw new Error(invalidMessage); + } + return parsed; +} + +/** Parse machine-readable effective policy metadata for one sandbox. */ +export function parseSandboxPolicyAuthorityMetadata( + raw: string, + sandboxName: string, +): SandboxPolicyAuthorityInspection { + if (raw.trim().length === 0) { + throw new Error("OpenShell returned empty sandbox policy authority metadata"); + } + const metadata = parseJsonMapping( + raw, + "OpenShell returned malformed sandbox policy authority metadata", + ); + if ( + metadata.scope !== "sandbox" || + metadata.sandbox !== sandboxName || + metadata.status !== "effective" || + (metadata.policy_source !== "sandbox" && metadata.policy_source !== "global") || + !isMapping(metadata.policy) + ) { + throw new Error("OpenShell returned invalid sandbox policy authority metadata"); + } + return { + authority: metadata.policy_source === "sandbox" ? "nemoclaw-managed" : "externally-managed", + effectivePolicy: metadata.policy, + }; +} + +/** Require durable and observed policy authority to describe the same owner. */ +export function assertMatchingPolicyAuthority(recorded: unknown, observed: unknown): void { + if (!isPolicyAuthority(recorded)) { + throw new Error("the recorded policy authority is unavailable or invalid"); + } + if (!isPolicyAuthority(observed)) { + throw new Error("the observed OpenShell policy authority is unavailable or invalid"); + } + if (recorded !== observed) { + throw new Error(`OpenShell policy authority changed from ${recorded} to ${observed}`); + } +} + +function policyMapping(value: unknown, invalidMessage: string): OpenShellPolicyMapping { + if (!isMapping(value)) throw new Error(invalidMessage); + return value; +} + +function policyValuesEqual(left: unknown, right: unknown): boolean { + if (Object.is(left, right)) return true; + if (Array.isArray(left) && Array.isArray(right)) { + return ( + left.length === right.length && left.every((value, index) => policyValuesEqual(value, right[index])) + ); + } + if (!isMapping(left) || !isMapping(right)) return false; + const leftKeys = Object.keys(left).sort(); + const rightKeys = Object.keys(right).sort(); + return ( + leftKeys.length === rightKeys.length && + leftKeys.every( + (key, index) => + key === rightKeys[index] && + Object.hasOwn(right, key) && + policyValuesEqual(left[key], right[key]), + ) + ); +} + +function formatPolicyKeys(keys: readonly string[]): string { + return keys.map((key) => JSON.stringify(key)).join(", "); +} + +/** + * Require an external policy to contain the requested entries and sections. + * Additional externally managed content is allowed. + */ +export function assertExternalPolicyRequirementContainment( + inspection: SandboxPolicyAuthorityInspection, + requiredPolicy: OpenShellPolicyMapping, +): void { + if (!isPolicyAuthority(inspection.authority)) { + throw new Error("the observed OpenShell policy authority is invalid"); + } + if (inspection.authority === "nemoclaw-managed") return; + const effectivePolicy = policyMapping( + inspection.effectivePolicy, + "the observed effective policy is invalid", + ); + const required = policyMapping(requiredPolicy, "the required policy input is invalid"); + const requiredNetwork = + required.network_policies === undefined + ? {} + : policyMapping(required.network_policies, "the required network policy input is invalid"); + const observedNetwork = isMapping(effectivePolicy.network_policies) + ? effectivePolicy.network_policies + : null; + const missing: string[] = []; + const drifted: string[] = []; + for (const key of Object.keys(requiredNetwork).sort()) { + if (!observedNetwork || !Object.hasOwn(observedNetwork, key)) { + missing.push(key); + } else if (!policyValuesEqual(observedNetwork[key], requiredNetwork[key])) { + drifted.push(key); + } + } + const requiredSections = Object.keys(required) + .filter((key) => key !== "network_policies" && key !== "version") + .sort(); + const missingSections: string[] = []; + const driftedSections: string[] = []; + for (const key of requiredSections) { + if (!Object.hasOwn(effectivePolicy, key)) { + missingSections.push(key); + } else if (!policyValuesEqual(effectivePolicy[key], required[key])) { + driftedSections.push(key); + } + } + if ( + missing.length === 0 && + drifted.length === 0 && + missingSections.length === 0 && + driftedSections.length === 0 + ) { + return; + } + const differences = [ + ...(missing.length > 0 ? [`missing entries ${formatPolicyKeys(missing)}`] : []), + ...(drifted.length > 0 ? [`drifted entries ${formatPolicyKeys(drifted)}`] : []), + ...(missingSections.length > 0 + ? [`missing sections ${formatPolicyKeys(missingSections)}`] + : []), + ...(driftedSections.length > 0 + ? [`drifted sections ${formatPolicyKeys(driftedSections)}`] + : []), + ].join("; "); + throw new Error(`the externally managed policy has ${differences}`); +} + function assertValidatedPolicyFields( policy: OpenShellPolicyMapping, ): asserts policy is ValidatedOpenShellPolicyMapping { diff --git a/nemoclaw/src/shared/openshell-policy-boundary.test.ts b/nemoclaw/src/shared/openshell-policy-boundary.test.ts index 448bf306664..42895ebda22 100644 --- a/nemoclaw/src/shared/openshell-policy-boundary.test.ts +++ b/nemoclaw/src/shared/openshell-policy-boundary.test.ts @@ -5,7 +5,10 @@ import { describe, expect, it } from "vitest"; import YAML from "yaml"; import { + assertExternalPolicyRequirementContainment, + assertMatchingPolicyAuthority, parseOpenShellPolicy, + parseSandboxPolicyAuthorityMetadata, stripProviderComposedPolicies, withoutProviderComposedPolicies, } from "./openshell-policy-boundary.cjs"; @@ -81,6 +84,86 @@ const POLICY_CASES = [ }, ] as const; +describe("sandbox policy authority boundary", () => { + const policy = { version: 1, network_policies: { required: { allow: true } } }; + + it.each([ + ["sandbox", "nemoclaw-managed"], + ["global", "externally-managed"], + ] as const)("classifies the %s policy source as %s", (policySource, authority) => { + expect( + parseSandboxPolicyAuthorityMetadata( + JSON.stringify({ + scope: "sandbox", + sandbox: "alpha", + status: "effective", + policy_source: policySource, + policy, + }), + "alpha", + ), + ).toEqual({ authority, effectivePolicy: policy }); + }); + + it.each([ + ["empty", " \n\t", /empty sandbox policy authority metadata/u], + ["malformed", "{", /malformed sandbox policy authority metadata/u], + [ + "mismatched", + JSON.stringify({ + scope: "sandbox", + sandbox: "beta", + status: "effective", + policy_source: "sandbox", + policy, + }), + /invalid sandbox policy authority metadata/u, + ], + ])("rejects %s sandbox authority metadata", (_caseName, raw, expected) => { + expect(() => parseSandboxPolicyAuthorityMetadata(raw, "alpha")).toThrow(expected); + }); + + it("accepts matching authority and rejects invalid or changed authority", () => { + expect(() => + assertMatchingPolicyAuthority("externally-managed", "externally-managed"), + ).not.toThrow(); + expect(() => assertMatchingPolicyAuthority(undefined, "externally-managed")).toThrow( + /recorded policy authority is unavailable/u, + ); + expect(() => assertMatchingPolicyAuthority("externally-managed", "unknown")).toThrow( + /observed OpenShell policy authority is unavailable/u, + ); + expect(() => + assertMatchingPolicyAuthority("nemoclaw-managed", "externally-managed"), + ).toThrow(/changed from nemoclaw-managed to externally-managed/u); + }); + + it("requires external entries and sections while allowing unrelated content", () => { + const inspection = { + authority: "externally-managed" as const, + effectivePolicy: { + version: 9, + filesystem_policy: { read_only: true }, + extra_section: { keep: true }, + network_policies: { required: { allow: true }, extra: { allow: true } }, + }, + }; + expect(() => + assertExternalPolicyRequirementContainment(inspection, { + version: 1, + filesystem_policy: { read_only: true }, + network_policies: { required: { allow: true } }, + }), + ).not.toThrow(); + expect(() => + assertExternalPolicyRequirementContainment(inspection, { + process: { user: 1000 }, + network_policies: { required: { allow: false }, missing: {} }, + }), + ).toThrow(/missing entries "missing"; drifted entries "required"; missing sections "process"/u); + }); +}); + describe("canonical OpenShell policy boundary", () => { it("parses marked output and versionless network policies", () => { const body = "version: 1\nnetwork_policies:\n safe: {}"; diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts index 39bf04a09a3..a64a0233e5e 100644 --- a/src/lib/adapters/openshell/policy-authority.test.ts +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -145,11 +145,11 @@ describe("OpenShell policy authority inspection", () => { expect(error.message).not.toContain(secret); }); - it("fails closed when sandbox policy output is empty (#9833)", () => { - const runCaptureEx = vi.fn(() => captureResult("")); + it.each(["", " \n\t"])("fails closed when sandbox policy output is empty (%j) (#9833)", (raw) => { + const runCaptureEx = vi.fn(() => captureResult(raw)); expect(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx })).toThrow( - /empty policy metadata/u, + /empty sandbox policy authority metadata/u, ); }); diff --git a/src/lib/adapters/openshell/policy-authority.ts b/src/lib/adapters/openshell/policy-authority.ts index d6e59e3cfc5..5a400fbbe88 100644 --- a/src/lib/adapters/openshell/policy-authority.ts +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { isDeepStrictEqual } from "node:util"; - import { diagnosticPreview, isValidName, @@ -10,17 +8,20 @@ import { NAME_MAX_LENGTH, } from "../../sandbox-name-contract"; import { buildPolicyGetFullJsonCommand } from "../../policy/commands"; +import { + assertExternalPolicyRequirementContainment, + assertMatchingPolicyAuthority, + type OpenShellPolicyAuthority, + parseSandboxPolicyAuthorityMetadata, + type SandboxPolicyAuthorityInspection as CanonicalSandboxPolicyAuthorityInspection, +} from "../../policy/merge"; const POLICY_AUTHORITY_CAPTURE_MAX_BYTES = 1024 * 1024; const POLICY_AUTHORITY_CAPTURE_TIMEOUT_MS = 30_000; type JsonObject = Record; -export type SandboxPolicyAuthority = "nemoclaw-managed" | "externally-managed"; - -export interface SandboxPolicyAuthorityInspection { - readonly authority: SandboxPolicyAuthority; - readonly effectivePolicy: JsonObject; -} +export type SandboxPolicyAuthority = OpenShellPolicyAuthority; +export type SandboxPolicyAuthorityInspection = CanonicalSandboxPolicyAuthorityInspection; const POLICY_AUTHORITY_REFUSAL_CODE = "NEMOCLAW_POLICY_AUTHORITY_REFUSAL"; @@ -81,10 +82,6 @@ function isObject(value: unknown): value is JsonObject { return typeof value === "object" && value !== null && !Array.isArray(value); } -function isPolicyAuthority(value: unknown): value is SandboxPolicyAuthority { - return value === "nemoclaw-managed" || value === "externally-managed"; -} - function failInspection(subject: "sandbox" | "global", reason: string): never { throw new PolicyAuthorityRefusalError( `OpenShell ${subject} policy authority inspection failed: ${reason}. Policy-dependent operations must stop.`, @@ -130,26 +127,6 @@ function capturePolicyQuery( return { stdout: result.stdout, stderr }; } -function parsePolicyMetadata(raw: string, subject: "sandbox" | "global"): JsonObject { - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch { - failInspection(subject, "OpenShell returned malformed machine-readable policy metadata"); - } - if (!isObject(parsed)) { - failInspection(subject, "OpenShell returned an invalid policy metadata object"); - } - return parsed; -} - -function policyObject(metadata: JsonObject, subject: "sandbox" | "global"): JsonObject { - if (!isObject(metadata.policy)) { - failInspection(subject, "OpenShell did not return an effective policy object"); - } - return metadata.policy; -} - /** Inspect the effective policy source for one live sandbox. */ export function inspectSandboxPolicyAuthority({ sandboxName, @@ -167,26 +144,14 @@ export function inspectSandboxPolicyAuthority({ "sandbox", "machine-readable policy", ); - if (raw.trim().length === 0) { - failInspection("sandbox", "OpenShell returned empty policy metadata"); - } - const metadata = parsePolicyMetadata(raw, "sandbox"); - if (metadata.scope !== "sandbox") { - failInspection("sandbox", "OpenShell returned policy metadata for another scope"); - } - if (metadata.sandbox !== validatedSandboxName) { - failInspection("sandbox", "OpenShell returned policy metadata for another sandbox"); - } - if (metadata.status !== "effective") { - failInspection("sandbox", "OpenShell did not report an effective sandbox policy"); - } - if (metadata.policy_source !== "sandbox" && metadata.policy_source !== "global") { - failInspection("sandbox", "OpenShell returned an unknown policy source"); + try { + return parseSandboxPolicyAuthorityMetadata(raw, validatedSandboxName); + } catch (error) { + failInspection( + "sandbox", + error instanceof Error ? error.message : "OpenShell returned invalid policy metadata", + ); } - return { - authority: metadata.policy_source === "sandbox" ? "nemoclaw-managed" : "externally-managed", - effectivePolicy: policyObject(metadata, "sandbox"), - }; } function operationLabel(operation: string): string { @@ -202,36 +167,12 @@ export function assertRecordedPolicyAuthority( operation: string, ): void { const label = operationLabel(operation); - if (!isPolicyAuthority(recorded)) { - throw new PolicyAuthorityRefusalError( - `Refusing to ${label}: the recorded policy authority is unavailable or invalid.`, - ); - } - if (!isPolicyAuthority(observed)) { - throw new PolicyAuthorityRefusalError( - `Refusing to ${label}: the observed OpenShell policy authority is unavailable or invalid.`, - ); - } - if (recorded !== observed) { - throw new PolicyAuthorityRefusalError( - `Refusing to ${label}: OpenShell policy authority changed from ${recorded} to ${observed}.`, - ); - } -} - -function networkPolicies(policy: JsonObject, label: string): JsonObject { - const value = policy.network_policies; - if (value === undefined) return {}; - if (!isObject(value)) { - throw new PolicyAuthorityRefusalError( - `Refusing to ${label}: the required network policy input is invalid.`, - ); + try { + assertMatchingPolicyAuthority(recorded, observed); + } catch (error) { + const detail = error instanceof Error ? error.message : "policy authority is invalid"; + throw new PolicyAuthorityRefusalError(`Refusing to ${label}: ${detail}.`); } - return value; -} - -function formatPolicyKeys(keys: readonly string[]): string { - return keys.map((key) => JSON.stringify(key)).join(", "); } /** @@ -250,65 +191,15 @@ export function assertExternalPolicyRequirements({ readonly sandboxName?: string; }): void { const label = operationLabel(operation); - if (!isPolicyAuthority(inspection.authority)) { - throw new PolicyAuthorityRefusalError( - `Refusing to ${label}: the observed OpenShell policy authority is invalid.`, - ); - } - if (inspection.authority === "nemoclaw-managed") return; - if (!isObject(requiredPolicy) || !isObject(inspection.effectivePolicy)) { + const target = sandboxName ? ` for sandbox ${JSON.stringify(sandboxName)}` : ""; + try { + assertExternalPolicyRequirementContainment(inspection, requiredPolicy); + } catch (error) { + const detail = error instanceof Error ? error.message : "the policy requirement is invalid"; throw new PolicyAuthorityRefusalError( - `Refusing to ${label}: the policy requirement input is invalid.`, + `Refusing to ${label}${target}: ${detail}. Ask the external policy authority to supply the exact required entries.`, ); } - - const required = networkPolicies(requiredPolicy, label); - const observedValue = inspection.effectivePolicy.network_policies; - const observed = isObject(observedValue) ? observedValue : null; - const missing: string[] = []; - const drifted: string[] = []; - for (const key of Object.keys(required).sort()) { - if (!observed || !Object.hasOwn(observed, key)) { - missing.push(key); - } else if (!isDeepStrictEqual(observed[key], required[key])) { - drifted.push(key); - } - } - const requiredSections = Object.keys(requiredPolicy) - .filter((key) => key !== "network_policies" && key !== "version") - .sort(); - const missingSections: string[] = []; - const driftedSections: string[] = []; - for (const key of requiredSections) { - if (!Object.hasOwn(inspection.effectivePolicy, key)) { - missingSections.push(key); - } else if (!isDeepStrictEqual(inspection.effectivePolicy[key], requiredPolicy[key])) { - driftedSections.push(key); - } - } - if ( - missing.length === 0 && - drifted.length === 0 && - missingSections.length === 0 && - driftedSections.length === 0 - ) { - return; - } - - const target = sandboxName ? ` for sandbox ${JSON.stringify(sandboxName)}` : ""; - const differences = [ - ...(missing.length > 0 ? [`missing entries ${formatPolicyKeys(missing)}`] : []), - ...(drifted.length > 0 ? [`drifted entries ${formatPolicyKeys(drifted)}`] : []), - ...(missingSections.length > 0 - ? [`missing sections ${formatPolicyKeys(missingSections)}`] - : []), - ...(driftedSections.length > 0 - ? [`drifted sections ${formatPolicyKeys(driftedSections)}`] - : []), - ].join("; "); - throw new PolicyAuthorityRefusalError( - `Refusing to ${label}${target}: the externally managed policy has ${differences}. Ask the external policy authority to supply the exact required entries.`, - ); } export const policyAuthorityInternals = { diff --git a/src/lib/policy/merge.ts b/src/lib/policy/merge.ts index 97de8eeb29c..9ad0d375f54 100644 --- a/src/lib/policy/merge.ts +++ b/src/lib/policy/merge.ts @@ -2,8 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import { + assertExternalPolicyRequirementContainment as assertCanonicalExternalPolicyRequirementContainment, + assertMatchingPolicyAuthority as assertCanonicalMatchingPolicyAuthority, parseOpenShellPolicy as parseCanonicalOpenShellPolicy, + parseSandboxPolicyAuthorityMetadata as parseCanonicalSandboxPolicyAuthorityMetadata, stripProviderComposedPolicies as stripCanonicalProviderComposedPolicies, + type OpenShellPolicyAuthority, + type SandboxPolicyAuthorityInspection, withoutProviderComposedPolicies as withoutCanonicalProviderComposedPolicies, } from "../../../nemoclaw/dist/shared/openshell-policy-boundary.cjs"; @@ -14,6 +19,12 @@ import type { JsonObject } from "../core/json-types"; // CommonJS wrapper is compiled. Keep this file implementation-free. export const parseOpenShellPolicy = parseCanonicalOpenShellPolicy; export const stripProviderComposedPolicies = stripCanonicalProviderComposedPolicies; +export const parseSandboxPolicyAuthorityMetadata = + parseCanonicalSandboxPolicyAuthorityMetadata; +export const assertMatchingPolicyAuthority = assertCanonicalMatchingPolicyAuthority; +export const assertExternalPolicyRequirementContainment = + assertCanonicalExternalPolicyRequirementContainment; +export type { OpenShellPolicyAuthority, SandboxPolicyAuthorityInspection }; export function withoutProviderComposedPolicies(policies: JsonObject): JsonObject { return withoutCanonicalProviderComposedPolicies(policies) as JsonObject; diff --git a/test/package-contract/openshell-policy-boundary.test.ts b/test/package-contract/openshell-policy-boundary.test.ts index 8106734d9be..81ba9c855cc 100644 --- a/test/package-contract/openshell-policy-boundary.test.ts +++ b/test/package-contract/openshell-policy-boundary.test.ts @@ -41,10 +41,16 @@ describe("OpenShell policy boundary package contract", () => { it("routes the CommonJS CLI and ESM plugin through one canonical CJS boundary", async () => { const cliPolicy = require("../../dist/lib/policy/merge.js") as { + assertExternalPolicyRequirementContainment: (...args: unknown[]) => void; + assertMatchingPolicyAuthority: (recorded: unknown, observed: unknown) => void; parseOpenShellPolicy: (raw: string) => { yamlBody: string; policy: Record; }; + parseSandboxPolicyAuthorityMetadata: ( + raw: string, + sandboxName: string, + ) => { authority: string; effectivePolicy: Record }; withoutProviderComposedPolicies: ( policies: Record, ) => Record; @@ -59,10 +65,13 @@ describe("OpenShell policy boundary package contract", () => { path.join(repoRoot, "nemoclaw", "dist", "shared", "openshell-policy-boundary.cjs"), ).href )) as { + assertExternalPolicyRequirementContainment: typeof cliPolicy.assertExternalPolicyRequirementContainment; + assertMatchingPolicyAuthority: typeof cliPolicy.assertMatchingPolicyAuthority; parseOpenShellPolicy: (raw: string) => { yamlBody: string; policy: Record; }; + parseSandboxPolicyAuthorityMetadata: typeof cliPolicy.parseSandboxPolicyAuthorityMetadata; withoutProviderComposedPolicies: ( policies: Record, ) => Record; @@ -70,7 +79,10 @@ describe("OpenShell policy boundary package contract", () => { }; const canonicalBoundary = require("../../nemoclaw/dist/shared/openshell-policy-boundary.cjs") as { + assertExternalPolicyRequirementContainment: typeof cliPolicy.assertExternalPolicyRequirementContainment; + assertMatchingPolicyAuthority: typeof cliPolicy.assertMatchingPolicyAuthority; parseOpenShellPolicy: typeof cliPolicy.parseOpenShellPolicy; + parseSandboxPolicyAuthorityMetadata: typeof cliPolicy.parseSandboxPolicyAuthorityMetadata; stripProviderComposedPolicies: typeof cliPolicy.stripProviderComposedPolicies; }; expect( @@ -96,6 +108,25 @@ describe("OpenShell policy boundary package contract", () => { expect(cliPolicy.stripProviderComposedPolicies).toBe( canonicalBoundary.stripProviderComposedPolicies, ); + expect(cliPolicy.parseSandboxPolicyAuthorityMetadata).toBe( + canonicalBoundary.parseSandboxPolicyAuthorityMetadata, + ); + expect(cliPolicy.assertMatchingPolicyAuthority).toBe( + canonicalBoundary.assertMatchingPolicyAuthority, + ); + expect(cliPolicy.assertExternalPolicyRequirementContainment).toBe( + canonicalBoundary.assertExternalPolicyRequirementContainment, + ); + const sandboxMetadata = JSON.stringify({ + scope: "sandbox", + sandbox: "alpha", + status: "effective", + policy_source: "global", + policy: { version: 1, network_policies: {} }, + }); + expect(pluginBoundary.parseSandboxPolicyAuthorityMetadata(sandboxMetadata, "alpha")).toEqual( + canonicalBoundary.parseSandboxPolicyAuthorityMetadata(sandboxMetadata, "alpha"), + ); const pluginRunner = await import( pathToFileURL(path.join(repoRoot, "nemoclaw", "dist", "blueprint", "runner.js")).href From b06fe62b36fcfa0a81d22a3d0a09c62d2290a74b Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 22:10:02 -0700 Subject: [PATCH 07/40] test(blueprint): keep policy mutations visible Signed-off-by: Apurv Kumaria --- nemoclaw/src/blueprint/runner-identity.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/nemoclaw/src/blueprint/runner-identity.test.ts b/nemoclaw/src/blueprint/runner-identity.test.ts index 030d581d959..0c62a4a0d6b 100644 --- a/nemoclaw/src/blueprint/runner-identity.test.ts +++ b/nemoclaw/src/blueprint/runner-identity.test.ts @@ -94,9 +94,14 @@ function responseQueue( } function nonAuthorityCommandLines(): string[] { + const authorityCommands = new Set([ + "openshell status", + "openshell policy list -g test-gateway --global --limit 1", + "openshell policy get -g test-gateway --full --output json test-sandbox", + ]); return mockExeca.mock.calls .map(([command, args]) => [command, ...(args ?? [])].join(" ")) - .filter((command) => command !== "openshell status" && !command.startsWith("openshell policy ")); + .filter((command) => !authorityCommands.has(command)); } function blueprint(overrides: Record = {}): Parameters[1] { From 915db84508a625a60467801646d0426eab8bbc16 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 22:17:14 -0700 Subject: [PATCH 08/40] test(policy): cover authority refusal states Signed-off-by: Apurv Kumaria --- .../runner-openshell-072-policy.test.ts | 26 +++++++++++++++++++ .../shared/openshell-policy-boundary.test.ts | 17 +++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts index 95a17ecde60..c102adb1c84 100644 --- a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts +++ b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts @@ -541,4 +541,30 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { }, }); }); + + it("rejects an invalid persisted policy transition (#9833)", async () => { + const runId = "invalid-transition"; + const stateDir = `${FAKE_HOME}/.nemoclaw/state/runs/${runId}`; + store.set(stateDir, { type: "dir" }); + store.set(`${stateDir}/plan.json`, { + type: "file", + content: JSON.stringify({ + run_id: runId, + sandbox_name: "test-sandbox", + sandbox_created_by_apply: false, + policy_transition: { + status: "unknown", + sandbox_name: "test-sandbox", + gateway: "test-gateway", + expected_authority: "nemoclaw-managed", + policy_addition_names: ["nim_service"], + }, + }), + }); + + stdoutCapture.reset(); + actionStatus(runId); + expect(stdoutCapture.jsonOutput()).toEqual({ run_id: runId, status: "unknown" }); + await expect(actionRollback(runId)).rejects.toThrow(/policy transition receipt is invalid/u); + }); }); diff --git a/nemoclaw/src/shared/openshell-policy-boundary.test.ts b/nemoclaw/src/shared/openshell-policy-boundary.test.ts index 42895ebda22..bc9fd8fd1ca 100644 --- a/nemoclaw/src/shared/openshell-policy-boundary.test.ts +++ b/nemoclaw/src/shared/openshell-policy-boundary.test.ts @@ -108,6 +108,7 @@ describe("sandbox policy authority boundary", () => { it.each([ ["empty", " \n\t", /empty sandbox policy authority metadata/u], ["malformed", "{", /malformed sandbox policy authority metadata/u], + ["non-object", "[]", /malformed sandbox policy authority metadata/u], [ "mismatched", JSON.stringify({ @@ -157,10 +158,24 @@ describe("sandbox policy authority boundary", () => { ).not.toThrow(); expect(() => assertExternalPolicyRequirementContainment(inspection, { + filesystem_policy: { read_only: false }, process: { user: 1000 }, network_policies: { required: { allow: false }, missing: {} }, }), - ).toThrow(/missing entries "missing"; drifted entries "required"; missing sections "process"/u); + ).toThrow( + /missing entries "missing"; drifted entries "required"; missing sections "process"; drifted sections "filesystem_policy"/u, + ); + expect(() => + assertExternalPolicyRequirementContainment( + { authority: "unknown" as never, effectivePolicy: {} }, + {}, + ), + ).toThrow(/observed OpenShell policy authority is invalid/u); + expect(() => + assertExternalPolicyRequirementContainment(inspection, { + network_policies: [] as never, + }), + ).toThrow(/required network policy input is invalid/u); }); }); From c7bd1f0fa2ab6137521569aef18b2af91a30af5b Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 22:32:07 -0700 Subject: [PATCH 09/40] fix(shields): report external policy recovery Signed-off-by: Apurv Kumaria --- .../openshell/policy-authority.test.ts | 21 ++++++ .../adapters/openshell/policy-authority.ts | 17 ++++- src/lib/policy/README.md | 6 ++ src/lib/policy/index.ts | 8 ++- src/lib/policy/policy-registry.ts | 1 + src/lib/shields/index.ts | 64 ++++++++++++++----- src/lib/shields/legacy-hermes-compat.test.ts | 8 +++ src/lib/shields/policy-transition.test.ts | 44 ++++++++++++- ...ermes-shields-provider-consumer-harness.ts | 8 +++ .../hermes-unsafe-config-shields-harness.ts | 8 +++ test/helpers/shields-flow-harness.ts | 10 +++ 11 files changed, 175 insertions(+), 20 deletions(-) diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts index a64a0233e5e..6b7bc59b9db 100644 --- a/src/lib/adapters/openshell/policy-authority.test.ts +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -8,6 +8,7 @@ import { assertExternalPolicyRequirements, assertRecordedPolicyAuthority, inspectSandboxPolicyAuthority, + isExternalPolicyAuthorityRefusalError, type PolicyAuthorityCapture, policyAuthorityInternals, type SandboxPolicyAuthorityInspection, @@ -215,6 +216,26 @@ describe("recorded policy authority", () => { assertRecordedPolicyAuthority("externally-managed", "unknown", "restore the snapshot"), ).toThrow(/observed OpenShell policy authority is unavailable or invalid/); }); + + it("classifies an observed external authority without parsing diagnostics (#9833)", () => { + const externalError = errorFrom(() => + assertRecordedPolicyAuthority( + "nemoclaw-managed", + "externally-managed", + "restore the snapshot", + ), + ); + const managedError = errorFrom(() => + assertRecordedPolicyAuthority( + "externally-managed", + "nemoclaw-managed", + "restore the snapshot", + ), + ); + + expect(isExternalPolicyAuthorityRefusalError(externalError)).toBe(true); + expect(isExternalPolicyAuthorityRefusalError(managedError)).toBe(false); + }); }); describe("externally managed policy requirements", () => { diff --git a/src/lib/adapters/openshell/policy-authority.ts b/src/lib/adapters/openshell/policy-authority.ts index 5a400fbbe88..0793d4693db 100644 --- a/src/lib/adapters/openshell/policy-authority.ts +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -28,10 +28,12 @@ const POLICY_AUTHORITY_REFUSAL_CODE = "NEMOCLAW_POLICY_AUTHORITY_REFUSAL"; /** A final refusal at the OpenShell policy authority boundary. */ export class PolicyAuthorityRefusalError extends Error { readonly code = POLICY_AUTHORITY_REFUSAL_CODE; + readonly observedAuthority?: SandboxPolicyAuthority; - constructor(message: string) { + constructor(message: string, observedAuthority?: SandboxPolicyAuthority) { super(message); this.name = "PolicyAuthorityRefusalError"; + this.observedAuthority = observedAuthority; } } @@ -43,6 +45,15 @@ export function isPolicyAuthorityRefusalError(error: unknown): boolean { ); } +/** Recognize a refusal caused by an externally managed observed policy. */ +export function isExternalPolicyAuthorityRefusalError(error: unknown): boolean { + return ( + isPolicyAuthorityRefusalError(error) && + isObject(error) && + error.observedAuthority === "externally-managed" + ); +} + interface PolicyAuthorityCaptureResult { readonly stdout: string; readonly stderr?: string; @@ -171,7 +182,9 @@ export function assertRecordedPolicyAuthority( assertMatchingPolicyAuthority(recorded, observed); } catch (error) { const detail = error instanceof Error ? error.message : "policy authority is invalid"; - throw new PolicyAuthorityRefusalError(`Refusing to ${label}: ${detail}.`); + const observedAuthority = + observed === "nemoclaw-managed" || observed === "externally-managed" ? observed : undefined; + throw new PolicyAuthorityRefusalError(`Refusing to ${label}: ${detail}.`, observedAuthority); } } diff --git a/src/lib/policy/README.md b/src/lib/policy/README.md index cf0e9bd6ec7..3340ecc814e 100644 --- a/src/lib/policy/README.md +++ b/src/lib/policy/README.md @@ -26,5 +26,11 @@ NemoClaw requires the exact preset entries before it reports success. NemoClaw does not set policy or record preset or custom-policy attribution. The external authority must supply a missing or changed entry. +If policy authority becomes external while Shields is down, NemoClaw keeps the +saved restrictive policy snapshot and refuses to restore it. Ask the external +policy authority to restore the restrictive policy. Then run +`nemoclaw shields up` to retry Shields reconciliation. `shields status` +reports this recovery requirement while the sandbox remains unlocked. + A legacy sandbox record retains the first qualified `policyAuthority` after a later operation fails. An inspection that cannot determine authority does not change the record. diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index 385bc20a781..27aadccda60 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -582,6 +582,8 @@ export interface PolicyMutationAuthority { } export const isPolicyAuthorityRefusalError = registry.isPolicyAuthorityRefusalError; +export const isExternalPolicyAuthorityRefusalError = + registry.isExternalPolicyAuthorityRefusalError; /** Inspect and, when needed, persist the authority that owns one sandbox policy. */ export function inspectPolicyMutationAuthority( @@ -637,8 +639,9 @@ export function inspectPolicyMutationAuthority( sandbox.policyAuthority === "externally-managed" || inspection.authority === "externally-managed" ) { - throw new Error( + throw new registry.PolicyAuthorityRefusalError( `${policyAuthorityError(error)} Ask the external policy authority to change the required entry.`, + inspection.authority, ); } throw error; @@ -686,9 +689,10 @@ export function assertNemoClawManagedPolicy( operation: string, ): void { if (authority.authority === "nemoclaw-managed") return; - throw new Error( + throw new registry.PolicyAuthorityRefusalError( `Refusing to ${operation}: this sandbox policy is externally managed. ` + "Ask the external policy authority to change the required entry.", + authority.authority, ); } diff --git a/src/lib/policy/policy-registry.ts b/src/lib/policy/policy-registry.ts index 16f96284dfe..ee34c18840e 100644 --- a/src/lib/policy/policy-registry.ts +++ b/src/lib/policy/policy-registry.ts @@ -31,6 +31,7 @@ export { assertExternalPolicyRequirements, assertRecordedPolicyAuthority, inspectSandboxPolicyAuthority, + isExternalPolicyAuthorityRefusalError, isPolicyAuthorityRefusalError, PolicyAuthorityRefusalError, } from "../adapters/openshell/policy-authority"; diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index 1ac4349bdb6..c95e75f3312 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -43,6 +43,7 @@ const { resolvePermissivePolicyPath, assertNemoClawManagedPolicy, inspectPolicyMutationAuthority, + isExternalPolicyAuthorityRefusalError, isPolicyAuthorityRefusalError, recheckPolicyMutationAuthority, rejectFinalPolicySetResult: rejectFinalShieldsPolicySetResult, @@ -152,6 +153,41 @@ function assertShieldsPolicyMutationAuthority( return authority; } +function externalPolicyRecoveryHandoff(sandboxName: string): string { + return ( + `NemoClaw cannot restore the externally managed policy for sandbox '${sandboxName}' ` + + "from its saved Shields policy snapshot. Ask the external policy authority to restore " + + `the restrictive policy, then run \`${CLI_NAME} ${sandboxName} shields up\` to retry Shields reconciliation.` + ); +} + +function assertShieldsPolicySnapshotRestoreAuthority( + sandboxName: string, + recorded?: PolicyMutationAuthority, +): PolicyMutationAuthority { + try { + return assertShieldsPolicyMutationAuthority( + sandboxName, + "restore the Shields policy snapshot", + recorded, + ); + } catch (error) { + if (!isExternalPolicyAuthorityRefusalError(error)) throw error; + throw new Error(externalPolicyRecoveryHandoff(sandboxName), { cause: error }); + } +} + +function inspectExternalPolicyRecoveryHandoff(sandboxName: string): string | null { + try { + assertShieldsPolicyMutationAuthority(sandboxName, "inspect Shields policy recovery"); + return null; + } catch (error) { + return isExternalPolicyAuthorityRefusalError(error) + ? externalPolicyRecoveryHandoff(sandboxName) + : null; + } +} + const STATE_DIR = resolveShieldsStateDir(); const SHIELDS_TRANSITION_POLL_MS = 50; const SHIELDS_TRANSITION_HANDOFF_GRACE_MS = 500; @@ -4095,10 +4131,7 @@ function applyShieldsPolicySnapshot( snapshotPath: string, options: ShieldsPolicySnapshotRestoreOptions = {}, ): ShieldsPolicySnapshotRestoreResult { - const policyAuthority = assertShieldsPolicyMutationAuthority( - sandboxName, - "restore the Shields policy snapshot", - ); + const policyAuthority = assertShieldsPolicySnapshotRestoreAuthority(sandboxName); const buildPolicySet = options.buildPolicySet ?? buildPolicySetCommand; const runPolicySet = options.runPolicySet ?? run; const state = loadShieldsState(sandboxName); @@ -4186,11 +4219,7 @@ function applyShieldsPolicySnapshot( fs.readFileSync(snapshotPath, "utf-8"), hasManagedMcpPolicyClaims(sandboxName), ); - assertShieldsPolicyMutationAuthority( - sandboxName, - "restore the Shields policy snapshot", - policyAuthority, - ); + assertShieldsPolicySnapshotRestoreAuthority(sandboxName, policyAuthority); const result = runPolicySet( buildPolicySet(snapshotPath, sandboxName, policyAuthority.gatewayName), { @@ -4229,11 +4258,7 @@ function applyShieldsPolicySnapshot( } const runtimePolicyIsTemp = runtimePolicyPath !== snapshotPath; try { - assertShieldsPolicyMutationAuthority( - sandboxName, - "restore the Shields policy snapshot", - policyAuthority, - ); + assertShieldsPolicySnapshotRestoreAuthority(sandboxName, policyAuthority); const result = runPolicySet( buildPolicySet(runtimePolicyPath, sandboxName, policyAuthority.gatewayName), { @@ -6107,8 +6132,13 @@ function shieldsStatusWithoutHostLock( const elapsed = downSince ? Math.floor((Date.now() - downSince.getTime()) / 1000) : 0; const remaining = state.shieldsDownTimeout != null ? Math.max(0, state.shieldsDownTimeout - elapsed) : null; + const recoveryHandoff = inspectExternalPolicyRecoveryHandoff(sandboxName); - console.log(` Shields: ${posture.statusText}`); + console.log( + recoveryHandoff + ? " Shields: DOWN (RECOVERY REQUIRED — policy is externally managed)" + : ` Shields: ${posture.statusText}`, + ); console.log(` Since: ${state.shieldsDownAt ?? "unknown"}`); if (remaining !== null) { const mins = Math.floor(remaining / 60); @@ -6117,6 +6147,10 @@ function shieldsStatusWithoutHostLock( } console.log(` Reason: ${state.shieldsDownReason ?? "not specified"}`); console.log(` Policy: ${state.shieldsDownPolicy ?? "permissive"}`); + if (recoveryHandoff) { + console.error(` Recovery: ${recoveryHandoff}`); + throw new DeferredShieldsExit("External policy restoration is required", 2); + } return; } } diff --git a/src/lib/shields/legacy-hermes-compat.test.ts b/src/lib/shields/legacy-hermes-compat.test.ts index 938cb7b86d7..6426c27ee0f 100644 --- a/src/lib/shields/legacy-hermes-compat.test.ts +++ b/src/lib/shields/legacy-hermes-compat.test.ts @@ -19,6 +19,7 @@ import { writeBoundForwardPolicy, writeTimerAuthorizationProof, } from "../../../test/helpers/hermes-shields-provider-consumer-harness"; +import { managedPolicyMutationAuthority } from "../../../test/helpers/shields-flow-harness"; import { testTimeout } from "../../../test/helpers/timeouts"; @@ -250,11 +251,18 @@ describe("legacy Hermes shields compatibility", () => { ]), vi.spyOn(policy, "parseCurrentPolicy").mockImplementation((raw: unknown) => String(raw)), vi.spyOn(policy, "resolvePermissivePolicyPath").mockReturnValue(permissivePolicyPath), + vi + .spyOn(policy, "inspectPolicyMutationAuthority") + .mockReturnValue(managedPolicyMutationAuthority), + vi + .spyOn(policy, "recheckPolicyMutationAuthority") + .mockReturnValue(managedPolicyMutationAuthority), vi.spyOn(agentConfig, "resolveAgentConfig").mockImplementation(() => hermesTarget()), vi.spyOn(registry, "getSandbox").mockImplementation((name: unknown) => ({ name: String(name), agent: "hermes", openshellDriver: "docker", + policyAuthority: "nemoclaw-managed", lifecycleGeneration: "legacy-generation", workload: { kind: "managed-image" }, })), diff --git a/src/lib/shields/policy-transition.test.ts b/src/lib/shields/policy-transition.test.ts index 767afee37ac..8c673ceadb1 100644 --- a/src/lib/shields/policy-transition.test.ts +++ b/src/lib/shields/policy-transition.test.ts @@ -157,7 +157,9 @@ describe("shields policy transition", () => { }); expect(() => shields.applyShieldsPolicySnapshot(sandboxName, snapshotPath)).toThrow( - /externally managed/, + "NemoClaw cannot restore the externally managed policy for sandbox 'openclaw' from its " + + "saved Shields policy snapshot. Ask the external policy authority to restore the " + + "restrictive policy, then run `nemoclaw openclaw shields up` to retry Shields reconciliation.", ); expect(runSpy).not.toHaveBeenCalled(); }); @@ -232,6 +234,46 @@ describe("shields down policy rejection", () => { expect(harness.dockerSpawnCalls).toEqual([]); }); + it("hands external policy restoration to its authority after Shields down (#9833)", () => { + const sandboxName = "openclaw"; + const harness = createShieldsFlowHarness(requireSource, tmpDir, { + confirmOpenClawInodeFlags: true, + initialOpenClawPosture: "locked", + }); + harness.shieldsDown(sandboxName, { throwOnError: true }); + const policySetCount = () => + harness.runSpy.mock.calls.filter( + ([command]) => + Array.isArray(command) && command.includes("policy") && command.includes("set"), + ).length; + const policySetsAfterDown = policySetCount(); + harness.policyAuthoritySpy.mockReturnValue({ + authority: "externally-managed", + authorityRecordedNow: false, + gatewayName: "nemoclaw", + inspection: externalPolicyAuthorityInspection, + }); + const recovery = + "NemoClaw cannot restore the externally managed policy for sandbox 'openclaw' from its " + + "saved Shields policy snapshot. Ask the external policy authority to restore the " + + "restrictive policy, then run `nemoclaw openclaw shields up` to retry Shields reconciliation."; + expect(() => harness.shieldsUp(sandboxName, { throwOnError: true })).toThrow(recovery); + expect(policySetCount()).toBe(policySetsAfterDown); + expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain(recovery); + harness.logSpy.mockClear(); + harness.errorSpy.mockClear(); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process exit ${String(code)}`); + }) as typeof process.exit); + expect(() => harness.shieldsStatus(sandboxName, false)).toThrow("process exit 2"); + expect(exitSpy).toHaveBeenCalledWith(2); + expect(policySetCount()).toBe(policySetsAfterDown); + expect(harness.logSpy.mock.calls.flat().join("\n")).toContain( + "Shields: DOWN (RECOVERY REQUIRED — policy is externally managed)", + ); + expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain(recovery); + }); + it("pins Shields policy inspection, reads, and writes to the recorded gateway (#9833)", () => { const gatewayName = "nemoclaw-18080"; const harness = createShieldsFlowHarness(requireSource, tmpDir, { diff --git a/test/helpers/hermes-shields-provider-consumer-harness.ts b/test/helpers/hermes-shields-provider-consumer-harness.ts index 5c146c5b139..82cbcefd1d9 100644 --- a/test/helpers/hermes-shields-provider-consumer-harness.ts +++ b/test/helpers/hermes-shields-provider-consumer-harness.ts @@ -8,6 +8,7 @@ import path from "node:path"; import { type MockInstance, vi } from "vitest"; import type { SandboxEntry } from "../../src/lib/state/registry"; +import { managedPolicyMutationAuthority } from "./shields-flow-harness"; const INDEX_MODULE = "./index.js"; export const HERMES_PROVIDER_CAPABILITY_PATH = @@ -46,6 +47,7 @@ export const hermesProviderConsumerSandbox: SandboxEntry = { name: "current-hermes", agent: "hermes", openshellDriver: "docker", + policyAuthority: "nemoclaw-managed", lifecycleGeneration: "generation-1", workload: { schemaVersion: 1, @@ -279,6 +281,12 @@ export function createHermesShieldsProviderConsumerHarness( String(file), String(name), ]), + vi + .spyOn(policy, "inspectPolicyMutationAuthority") + .mockReturnValue(managedPolicyMutationAuthority), + vi + .spyOn(policy, "recheckPolicyMutationAuthority") + .mockReturnValue(managedPolicyMutationAuthority), registrySpy, vi .spyOn(privilegedExec, "privilegedSandboxExecArgv") diff --git a/test/helpers/hermes-unsafe-config-shields-harness.ts b/test/helpers/hermes-unsafe-config-shields-harness.ts index 3e8a013ad1b..16989a94faa 100644 --- a/test/helpers/hermes-unsafe-config-shields-harness.ts +++ b/test/helpers/hermes-unsafe-config-shields-harness.ts @@ -7,6 +7,7 @@ import os from "node:os"; import path from "node:path"; import { expect, type MockInstance, vi } from "vitest"; +import { managedPolicyMutationAuthority } from "./shields-flow-harness"; type RequireSource = NodeJS.Require; @@ -280,11 +281,18 @@ export function createHermesUnsafeConfigHarness( ); vi.spyOn(policy, "parseCurrentPolicy").mockImplementation((raw: unknown) => String(raw)); vi.spyOn(policy, "resolvePermissivePolicyPath").mockReturnValue(permissivePolicyPath); + vi + .spyOn(policy, "inspectPolicyMutationAuthority") + .mockReturnValue(managedPolicyMutationAuthority); + vi + .spyOn(policy, "recheckPolicyMutationAuthority") + .mockReturnValue(managedPolicyMutationAuthority); vi.spyOn(agentConfig, "resolveAgentConfig").mockReturnValue(hermesTarget); vi.spyOn(registry, "getSandbox").mockImplementation((name: unknown) => ({ name: String(name), agent: "hermes", openshellDriver: "docker", + policyAuthority: "nemoclaw-managed", lifecycleGeneration: "legacy-generation", workload: { kind: "managed-image" }, })); diff --git a/test/helpers/shields-flow-harness.ts b/test/helpers/shields-flow-harness.ts index 2fd6afc51e2..51e195641bb 100644 --- a/test/helpers/shields-flow-harness.ts +++ b/test/helpers/shields-flow-harness.ts @@ -18,6 +18,16 @@ export const externalPolicyAuthorityInspection = { effectivePolicy: { version: 1, network_policies: {} }, }; +export const managedPolicyMutationAuthority = { + authority: "nemoclaw-managed" as const, + authorityRecordedNow: false, + gatewayName: "nemoclaw", + inspection: { + authority: "nemoclaw-managed" as const, + effectivePolicy: { version: 1, network_policies: {} }, + }, +}; + export type ShieldsFlowHarness = { applyShieldsPolicySnapshot: typeof import("../../src/lib/shields/index.js").applyShieldsPolicySnapshot; auditSpy: MockInstance; From 50782839c8b49bcb7fcf615971daa7b3fb44a741 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 23:40:10 -0700 Subject: [PATCH 10/40] fix(policy): reconcile interrupted mutations Signed-off-by: Apurv Kumaria --- .../runner-openshell-072-policy.test.ts | 111 ++++++++++++-- nemoclaw/src/blueprint/runner.ts | 139 ++++++++++++++++-- .../src/shared/openshell-policy-boundary.cts | 44 ++++-- .../shared/openshell-policy-boundary.test.ts | 24 ++- src/lib/shields/index.test.ts | 8 +- src/lib/shields/index.ts | 34 ++++- .../shields/status-state-lock-plan.test.ts | 37 +++++ test/cli/sandbox-mutations.test.ts | 5 + test/e2e-test.sh | 12 ++ test/mcp-policy-key-ownership.test.ts | 16 ++ test/policies-teams.test.ts | 4 + .../policy-openclaw-npm-compatibility.test.ts | 6 + 12 files changed, 392 insertions(+), 48 deletions(-) diff --git a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts index c102adb1c84..1cfa5bafc7c 100644 --- a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts +++ b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts @@ -58,7 +58,8 @@ vi.mock("./ssrf.js", async (importOriginal) => { }; }); -const { actionApply, actionRollback, actionStatus } = await import("./runner.js"); +const { actionApply, actionReconcile, actionRollback, actionStatus, main } = + await import("./runner.js"); const BASE_POLICY = `version: 1 future_policy: @@ -246,15 +247,22 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { }); it("fails closed when policy get --base fails", async () => { + const diagnostic = `MY_API_KEY=super-secret ${"policy details ".repeat(80)}`; mockExeca.mockImplementation(async (_cmd: string, args: string[]) => args.join(" ") === "policy get -g test-gateway --base test-sandbox" - ? { exitCode: 1, stdout: "", stderr: "gateway unavailable" } + ? { exitCode: 1, stdout: "", stderr: diagnostic } : defaultCommandResult(args), ); - await expect(actionApply("default", blueprint())).rejects.toThrow( - /Failed to read current policy.*gateway unavailable/, + const error = await actionApply("default", blueprint()).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain( + "Failed to read current policy before applying additions", ); + expect((error as Error).message).toContain("MY_API_KEY="); + expect((error as Error).message).not.toContain("super-secret"); + expect((error as Error).message).toContain("…"); + expect((error as Error).message.length).toBeLessThan(600); expect(policySetCalls()).toEqual([]); }); @@ -335,8 +343,7 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { ? { exitCode: 0, stdout: "VERSION STATUS\n1 loaded\n", stderr: "" } : args.join(" ") === "policy get -g recorded-gateway --global --full --output json" ? globalPolicyAuthorityResult(additions) - : args.join(" ") === - "policy get -g recorded-gateway --full --output json test-sandbox" + : args.join(" ") === "policy get -g recorded-gateway --full --output json test-sandbox" ? sandboxPolicyAuthorityResult("test-sandbox", "externally-managed", additions) : { exitCode: 0, stdout: "", stderr: "" }, ); @@ -494,7 +501,7 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { status: "incomplete", sandbox_name: "test-sandbox", reconciliation_required: true, - reconciliation_action: expect.stringContaining("reconcile the reused sandbox"), + reconciliation_action: expect.stringContaining("Run reconcile"), }, }); @@ -502,9 +509,29 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { /policy transition for reused sandbox "test-sandbox".*is incomplete.*reconcile/u, ); expect(store.has(`${planEntry?.[0].replace(/\/plan\.json$/u, "")}/rolled_back`)).toBe(false); + + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "policy get -g test-gateway --full --output json test-sandbox" + ? sandboxPolicyAuthorityResult( + "test-sandbox", + "nemoclaw-managed", + blueprint().components!.policy!.additions!, + ) + : defaultCommandResult(args), + ); + stdoutCapture.reset(); + await main(["reconcile", "--run-id", plan.run_id]); + expect(stdoutCapture.text()).toContain(`Policy transition for run ${plan.run_id} is complete.`); + expect(JSON.parse(store.get(planEntry?.[0] ?? "")?.content ?? "{}")).toMatchObject({ + policy_transition: { status: "complete" }, + }); + + await actionRollback(plan.run_id); + expect(store.has(`${planEntry?.[0].replace(/\/plan\.json$/u, "")}/rolled_back`)).toBe(true); }); it("keeps a pending receipt when a reused-sandbox policy set fails (#9833)", async () => { + const diagnostic = `POLICY_TOKEN=super-secret ${"policy details ".repeat(80)}`; const responses = new Map([ [ "sandbox create --from openclaw --name test-sandbox --forward 18789", @@ -518,7 +545,7 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { stderr: "", }, ], - ["policy set", { exitCode: 1, stdout: "", stderr: "policy set rejected" }], + ["policy set", { exitCode: 1, stdout: "", stderr: diagnostic }], ]); mockExeca.mockImplementation( async (_cmd: string, args: string[]) => @@ -527,11 +554,18 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { defaultCommandResult(args), ); - await expect(actionApply("default", blueprint())).rejects.toThrow(/policy set rejected/u); - const planEntry = [...store.values()].find((entry) => + const error = await actionApply("default", blueprint()).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain("Failed to apply policy additions"); + expect((error as Error).message).toContain("POLICY_TOKEN="); + expect((error as Error).message).not.toContain("super-secret"); + expect((error as Error).message).toContain("…"); + expect((error as Error).message.length).toBeLessThan(600); + const planEntry = [...store.entries()].find(([, entry]) => entry.content?.includes('"policy_transition"'), ); - expect(JSON.parse(planEntry?.content ?? "{}")).toMatchObject({ + const plan = JSON.parse(planEntry?.[1].content ?? "{}") as { run_id: string }; + expect(plan).toMatchObject({ sandbox_created_by_apply: false, policy_transition: { status: "pending", @@ -540,8 +574,62 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { policy_addition_names: ["nim_service"], }, }); + + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "policy get -g test-gateway --full --output json test-sandbox" + ? sandboxPolicyAuthorityResult( + "test-sandbox", + "nemoclaw-managed", + blueprint().components!.policy!.additions!, + ) + : defaultCommandResult(args), + ); + await actionReconcile(plan.run_id); + expect(JSON.parse(store.get(planEntry?.[0] ?? "")?.content ?? "{}")).toMatchObject({ + policy_transition: { status: "complete" }, + }); }); + it.each([ + ["authority change", "externally-managed" as const, blueprint().components!.policy!.additions!], + ["missing addition", "nemoclaw-managed" as const, {}], + ])( + "retains an incomplete receipt after a reconciliation %s (#9833)", + async (_case, authority, observed) => { + const runId = "incomplete-transition"; + const stateDir = `${FAKE_HOME}/.nemoclaw/state/runs/${runId}`; + const additions = blueprint().components!.policy!.additions!; + store.set(stateDir, { type: "dir" }); + store.set(`${stateDir}/plan.json`, { + type: "file", + content: JSON.stringify({ + run_id: runId, + sandbox_name: "test-sandbox", + sandbox_created_by_apply: false, + policy_additions: additions, + policy_transition: { + status: "incomplete", + sandbox_name: "test-sandbox", + gateway: "recorded-gateway", + expected_authority: "nemoclaw-managed", + policy_addition_names: ["nim_service"], + }, + }), + }); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "policy get -g recorded-gateway --full --output json test-sandbox" + ? sandboxPolicyAuthorityResult("test-sandbox", authority, observed) + : defaultCommandResult(args), + ); + + await expect(actionReconcile(runId)).rejects.toThrow(/Cannot reconcile/u); + expect(JSON.parse(store.get(`${stateDir}/plan.json`)?.content ?? "{}")).toMatchObject({ + policy_transition: { status: "incomplete" }, + }); + await expect(actionRollback(runId)).rejects.toThrow(/is incomplete/u); + }, + ); + it("rejects an invalid persisted policy transition (#9833)", async () => { const runId = "invalid-transition"; const stateDir = `${FAKE_HOME}/.nemoclaw/state/runs/${runId}`; @@ -565,6 +653,7 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { stdoutCapture.reset(); actionStatus(runId); expect(stdoutCapture.jsonOutput()).toEqual({ run_id: runId, status: "unknown" }); + await expect(actionReconcile(runId)).rejects.toThrow(/policy transition receipt is invalid/u); await expect(actionRollback(runId)).rejects.toThrow(/policy transition receipt is invalid/u); }); }); diff --git a/nemoclaw/src/blueprint/runner.ts b/nemoclaw/src/blueprint/runner.ts index 1029f4f73a4..13f105fa27b 100644 --- a/nemoclaw/src/blueprint/runner.ts +++ b/nemoclaw/src/blueprint/runner.ts @@ -56,6 +56,7 @@ const sourceOrGeneratedOpenShellPolicyBoundary = const { assertExternalPolicyRequirementContainment, assertMatchingPolicyAuthority, + assertPolicyRequirementContainment, parseOpenShellPolicy, parseSandboxPolicyAuthorityMetadata, withoutProviderComposedPolicies, @@ -68,7 +69,7 @@ const sourceOrGeneratedSandboxName = importedSandboxName as typeof importedSandb const { assertValidName, assertValidProviderName, isValidName } = sourceOrGeneratedSandboxName.default ?? sourceOrGeneratedSandboxName; -type Action = "plan" | "apply" | "status" | "rollback"; +type Action = "plan" | "apply" | "status" | "reconcile" | "rollback"; type RollbackPlanSource = { sandbox_name?: unknown; @@ -79,6 +80,9 @@ type RollbackPlanSource = { policy_authority?: unknown; policy_transition?: unknown; }; +type ReconciliationPlanSource = RollbackPlanSource & { + policy_additions?: unknown; +}; type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"; type RestProtocol = "rest"; type EndpointEnforcement = "enforce" | "audit"; @@ -108,7 +112,8 @@ interface PolicyAddition { type PolicyAdditions = { [name: string]: PolicyAddition }; -type BlueprintPolicyAuthorityInspection = import("../shared/openshell-policy-boundary.cjs").SandboxPolicyAuthorityInspection; +type BlueprintPolicyAuthorityInspection = + import("../shared/openshell-policy-boundary.cjs").SandboxPolicyAuthorityInspection; type BlueprintPolicyAuthorityReceipt = { authority: BlueprintPolicyAuthorityInspection["authority"]; @@ -131,7 +136,7 @@ type StatusPolicyTransition = BlueprintPolicyTransitionReceipt & { }; const POLICY_TRANSITION_RECONCILIATION_ACTION = - "Inspect the recorded gateway policy for the listed additions and reconcile the reused sandbox before retrying apply or rollback."; + "Run reconcile with this run ID before retrying apply or rollback."; const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]); const REST_PROTOCOLS = new Set(["rest"]); @@ -202,7 +207,13 @@ function isUnconfiguredInferenceRoute(output: string): boolean { } function isAction(value: string | undefined): value is Action { - return value === "plan" || value === "apply" || value === "status" || value === "rollback"; + return ( + value === "plan" || + value === "apply" || + value === "status" || + value === "reconcile" || + value === "rollback" + ); } // Redact credential-shaped output before bounding OpenShell stderr to a compact, @@ -718,9 +729,7 @@ function assertBlueprintPolicyAuthorityMatches( assertMatchingPolicyAuthority(recorded.authority, observed.authority); } catch (error) { const detail = error instanceof Error ? error.message : "policy authority is invalid"; - throw new Error( - `Refusing to apply blueprint policy additions because ${detail}.`, - ); + throw new Error(`Refusing to apply blueprint policy additions because ${detail}.`); } } @@ -740,6 +749,20 @@ function assertBlueprintExternalPolicyRequirements( } } +function assertBlueprintPolicyRequirements( + inspection: BlueprintPolicyAuthorityInspection, + additions: PolicyAdditions, +): void { + try { + assertPolicyRequirementContainment(inspection, { + network_policies: additions, + }); + } catch (error) { + const detail = error instanceof Error ? error.message : "the policy requirement is invalid"; + throw new Error(`Cannot reconcile the blueprint policy transition: ${detail}.`); + } +} + async function runRuntimeIdentityCommand( args: string[], options?: RuntimeIdentityCommandOptions, @@ -937,9 +960,7 @@ function isBlueprintPolicyTransitionReceipt( ): value is BlueprintPolicyTransitionReceipt { if (!isPlainObject(value)) return false; if ( - (value.status !== "pending" && - value.status !== "incomplete" && - value.status !== "complete") || + (value.status !== "pending" && value.status !== "incomplete" && value.status !== "complete") || !isValidName(value.sandbox_name) || !isValidName(value.gateway) || value.expected_authority !== "nemoclaw-managed" || @@ -1201,7 +1222,9 @@ export async function actionApply( const sandboxName = sandboxCfg.name ?? "openclaw"; const sandboxImage = sandboxCfg.image ?? "openclaw"; const forwardPorts = sandboxCfg.forward_ports ?? [DASHBOARD_PORT]; - const policyAdditions = blueprint.components?.policy?.additions ?? {}; + const policyAdditions = withoutProviderComposedPolicies( + blueprint.components?.policy?.additions ?? {}, + ); const runtimeIdentityConfig = blueprint.components?.identity; const providerName = inferenceCfg.provider_name ?? "default"; const providerType = inferenceCfg.provider_type ?? "openai"; @@ -1527,7 +1550,7 @@ export async function actionApply( ); if (currentPolicy.exitCode !== 0) { throw new Error( - `Failed to read current policy before applying additions: ${currentPolicy.stderr}`, + `Failed to read current policy before applying additions: ${boundedCommandError(currentPolicy.stderr)}`, ); } @@ -1566,7 +1589,9 @@ export async function actionApply( { reject: false }, ); if (policySet.exitCode !== 0) { - throw new Error(`Failed to apply policy additions: ${policySet.stderr}`); + throw new Error( + `Failed to apply policy additions: ${boundedCommandError(policySet.stderr)}`, + ); } policyTransition = { ...policyTransition, status: "incomplete" }; persistRunPlan(); @@ -1700,6 +1725,86 @@ export function actionStatus(rid?: string): void { } } +export async function actionReconcile(rid: string): Promise { + emitRunId(); + + const runsDir = join(homedir(), ".nemoclaw", "state", "runs"); + const stateDir = safeRunDir(runsDir, rid); + try { + readdirSync(stateDir); + } catch { + throw new Error(`Run ${rid} not found.`); + } + + const planFile = join(stateDir, "plan.json"); + let plan: ReconciliationPlanSource; + let transition: BlueprintPolicyTransitionReceipt; + let additions: PolicyAdditions; + try { + const parsedPlan: unknown = JSON.parse(readFileSync(planFile, "utf-8")); + if (!isPlainObject(parsedPlan)) { + throw new Error("plan.json must contain a JSON object"); + } + plan = parsedPlan; + if (plan.sandbox_created_by_apply !== false) { + throw new Error("policy reconciliation requires a reused sandbox"); + } + const sandboxName = readRollbackSandboxName(plan); + if (!isBlueprintPolicyTransitionReceipt(plan.policy_transition)) { + throw new Error("policy transition receipt is invalid"); + } + transition = plan.policy_transition; + if (transition.sandbox_name !== sandboxName) { + throw new Error("policy transition sandbox does not match the run plan"); + } + if (!isPolicyAdditions(plan.policy_additions)) { + throw new Error("policy additions are invalid"); + } + additions = withoutProviderComposedPolicies(plan.policy_additions); + const additionNames = Object.keys(additions).sort(); + if ( + additionNames.length === 0 || + additionNames.length !== transition.policy_addition_names.length || + additionNames.some((name, index) => name !== transition.policy_addition_names[index]) + ) { + throw new Error("policy transition additions do not match the run plan"); + } + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new Error(`Cannot read reconciliation plan for run ${rid}: ${detail}`); + } + + if (transition.status === "complete") { + log(`Policy transition for run ${rid} is already complete.`); + return; + } + + const observed = await inspectBlueprintPolicyAuthority( + transition.gateway, + transition.sandbox_name, + ); + try { + assertMatchingPolicyAuthority(transition.expected_authority, observed.authority); + } catch (error) { + const detail = error instanceof Error ? error.message : "policy authority is invalid"; + throw new Error(`Cannot reconcile the blueprint policy transition: ${detail}.`); + } + assertBlueprintPolicyRequirements(observed, additions); + + writeFileSync( + planFile, + JSON.stringify( + { + ...plan, + policy_transition: { ...transition, status: "complete" }, + }, + null, + 2, + ), + ); + log(`Policy transition for run ${rid} is complete.`); +} + export async function actionRollback(rid: string): Promise { emitRunId(); @@ -1832,7 +1937,7 @@ export async function main( return; } throw new Error( - `Unknown action '${rawAction ?? "(missing)"}'. Use: plan, apply, status, rollback, snapshots`, + `Unknown action '${rawAction ?? "(missing)"}'. Use: plan, apply, status, reconcile, rollback, snapshots`, ); } @@ -1874,6 +1979,12 @@ export async function main( case "status": actionStatus(runId); break; + case "reconcile": + if (!runId) { + throw new Error("--run-id is required for reconcile"); + } + await actionReconcile(runId); + break; case "rollback": if (!runId) { throw new Error("--run-id is required for rollback"); diff --git a/nemoclaw/src/shared/openshell-policy-boundary.cts b/nemoclaw/src/shared/openshell-policy-boundary.cts index bfd4e886042..3b49f2f6cd5 100644 --- a/nemoclaw/src/shared/openshell-policy-boundary.cts +++ b/nemoclaw/src/shared/openshell-policy-boundary.cts @@ -95,7 +95,8 @@ function policyValuesEqual(left: unknown, right: unknown): boolean { if (Object.is(left, right)) return true; if (Array.isArray(left) && Array.isArray(right)) { return ( - left.length === right.length && left.every((value, index) => policyValuesEqual(value, right[index])) + left.length === right.length && + left.every((value, index) => policyValuesEqual(value, right[index])) ); } if (!isMapping(left) || !isMapping(right)) return false; @@ -116,18 +117,14 @@ function formatPolicyKeys(keys: readonly string[]): string { return keys.map((key) => JSON.stringify(key)).join(", "); } -/** - * Require an external policy to contain the requested entries and sections. - * Additional externally managed content is allowed. - */ -export function assertExternalPolicyRequirementContainment( +function assertPolicyRequirementContainmentForOwner( inspection: SandboxPolicyAuthorityInspection, requiredPolicy: OpenShellPolicyMapping, + owner: string, ): void { if (!isPolicyAuthority(inspection.authority)) { throw new Error("the observed OpenShell policy authority is invalid"); } - if (inspection.authority === "nemoclaw-managed") return; const effectivePolicy = policyMapping( inspection.effectivePolicy, "the observed effective policy is invalid", @@ -179,7 +176,34 @@ export function assertExternalPolicyRequirementContainment( ? [`drifted sections ${formatPolicyKeys(driftedSections)}`] : []), ].join("; "); - throw new Error(`the externally managed policy has ${differences}`); + throw new Error(`the ${owner} has ${differences}`); +} + +/** Require a policy to contain the requested entries and sections. */ +export function assertPolicyRequirementContainment( + inspection: SandboxPolicyAuthorityInspection, + requiredPolicy: OpenShellPolicyMapping, +): void { + assertPolicyRequirementContainmentForOwner(inspection, requiredPolicy, "observed policy"); +} + +/** + * Require an external policy to contain the requested entries and sections. + * Additional externally managed content is allowed. + */ +export function assertExternalPolicyRequirementContainment( + inspection: SandboxPolicyAuthorityInspection, + requiredPolicy: OpenShellPolicyMapping, +): void { + if (!isPolicyAuthority(inspection.authority)) { + throw new Error("the observed OpenShell policy authority is invalid"); + } + if (inspection.authority === "nemoclaw-managed") return; + assertPolicyRequirementContainmentForOwner( + inspection, + requiredPolicy, + "externally managed policy", + ); } function assertValidatedPolicyFields( @@ -187,9 +211,7 @@ function assertValidatedPolicyFields( ): asserts policy is ValidatedOpenShellPolicyMapping { if ( policy.version !== undefined && - (typeof policy.version !== "number" || - !Number.isInteger(policy.version) || - policy.version < 1) + (typeof policy.version !== "number" || !Number.isInteger(policy.version) || policy.version < 1) ) { throw new Error( "Current policy from openshell policy get --base version must be a positive integer", diff --git a/nemoclaw/src/shared/openshell-policy-boundary.test.ts b/nemoclaw/src/shared/openshell-policy-boundary.test.ts index bc9fd8fd1ca..c4e69328ad8 100644 --- a/nemoclaw/src/shared/openshell-policy-boundary.test.ts +++ b/nemoclaw/src/shared/openshell-policy-boundary.test.ts @@ -7,6 +7,7 @@ import YAML from "yaml"; import { assertExternalPolicyRequirementContainment, assertMatchingPolicyAuthority, + assertPolicyRequirementContainment, parseOpenShellPolicy, parseSandboxPolicyAuthorityMetadata, stripProviderComposedPolicies, @@ -134,9 +135,9 @@ describe("sandbox policy authority boundary", () => { expect(() => assertMatchingPolicyAuthority("externally-managed", "unknown")).toThrow( /observed OpenShell policy authority is unavailable/u, ); - expect(() => - assertMatchingPolicyAuthority("nemoclaw-managed", "externally-managed"), - ).toThrow(/changed from nemoclaw-managed to externally-managed/u); + expect(() => assertMatchingPolicyAuthority("nemoclaw-managed", "externally-managed")).toThrow( + /changed from nemoclaw-managed to externally-managed/u, + ); }); it("requires external entries and sections while allowing unrelated content", () => { @@ -177,6 +178,23 @@ describe("sandbox policy authority boundary", () => { }), ).toThrow(/required network policy input is invalid/u); }); + + it("requires recorded entries in a NemoClaw-managed policy", () => { + const inspection = { + authority: "nemoclaw-managed" as const, + effectivePolicy: { network_policies: { required: { allow: true } } }, + }; + expect(() => + assertPolicyRequirementContainment(inspection, { + network_policies: { required: { allow: true } }, + }), + ).not.toThrow(); + expect(() => + assertPolicyRequirementContainment(inspection, { + network_policies: { missing: { allow: true } }, + }), + ).toThrow(/missing entries "missing"/u); + }); }); describe("canonical OpenShell policy boundary", () => { diff --git a/src/lib/shields/index.test.ts b/src/lib/shields/index.test.ts index 02363c4353c..927d9cd1d06 100644 --- a/src/lib/shields/index.test.ts +++ b/src/lib/shields/index.test.ts @@ -459,6 +459,8 @@ describe("shields — unit logic", () => { }); describe("NC-3112: status self-heals stale expired auto-restore markers", () => { + const readyPolicyRecovery = () => ({ status: "ready" as const }); + async function loadShieldsModule() { const sourceModulePath = path.join(process.cwd(), "src", "lib", "shields", "index.ts"); return import(sourceModulePath); @@ -546,7 +548,7 @@ describe("shields — unit logic", () => { const { shieldsStatus } = await loadShieldsModule(); - shieldsStatus(sandboxName); + shieldsStatus(sandboxName, true, { inspectPolicyRecovery: readyPolicyRecovery }); expect(processKillSpy).not.toHaveBeenCalled(); expect(errorSpy).toHaveBeenCalledWith( @@ -725,7 +727,7 @@ describe("shields — unit logic", () => { const { shieldsStatus } = await loadShieldsModule(); - shieldsStatus(sandboxName); + shieldsStatus(sandboxName, true, { inspectPolicyRecovery: readyPolicyRecovery }); expect(logSpy).toHaveBeenCalledWith(" Shields: DOWN (temporarily unlocked)"); expect(errorSpy).toHaveBeenCalledWith( @@ -840,7 +842,7 @@ describe("shields — unit logic", () => { ); const { shieldsStatus } = await loadShieldsModule(); - shieldsStatus(sandboxName); + shieldsStatus(sandboxName, true, { inspectPolicyRecovery: readyPolicyRecovery }); expect(errorSpy).toHaveBeenCalledWith( " Warning: auto-restore timer authority is expired, invalid, or no longer live; attempting inline restore.", diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index c95e75f3312..9e872cf0f1a 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -177,14 +177,23 @@ function assertShieldsPolicySnapshotRestoreAuthority( } } -function inspectExternalPolicyRecoveryHandoff(sandboxName: string): string | null { +type ShieldsPolicyRecoveryInspection = + | { status: "ready" } + | { status: "external"; handoff: string } + | { status: "unavailable"; detail: string }; + +function inspectShieldsPolicyRecovery(sandboxName: string): ShieldsPolicyRecoveryInspection { try { assertShieldsPolicyMutationAuthority(sandboxName, "inspect Shields policy recovery"); - return null; + return { status: "ready" }; } catch (error) { - return isExternalPolicyAuthorityRefusalError(error) - ? externalPolicyRecoveryHandoff(sandboxName) - : null; + if (isExternalPolicyAuthorityRefusalError(error)) { + return { status: "external", handoff: externalPolicyRecoveryHandoff(sandboxName) }; + } + return { + status: "unavailable", + detail: error instanceof Error ? error.message : String(error), + }; } } @@ -5924,6 +5933,7 @@ type ShieldsStatusDeps = { resolveConfig?: typeof resolveAgentConfig; verifyStateLockPlan?: (sandboxName: string, target: AgentConfigTarget) => string[]; assertCommandAvailable?: () => void; + inspectPolicyRecovery?: typeof inspectShieldsPolicyRecovery; }; function verifyHermesProviderMutableStatus( @@ -5976,6 +5986,7 @@ function shieldsStatusWithoutHostLock( const verify = deps.verifyLockState ?? verifyShieldsLockState; const resolveConfig = deps.resolveConfig ?? resolveAgentConfig; + const inspectPolicyRecovery = deps.inspectPolicyRecovery ?? inspectShieldsPolicyRecovery; const posture = getShieldsPostureWithoutHostLock(sandboxName, allowInlineRecovery); const { state } = posture; @@ -6132,7 +6143,18 @@ function shieldsStatusWithoutHostLock( const elapsed = downSince ? Math.floor((Date.now() - downSince.getTime()) / 1000) : 0; const remaining = state.shieldsDownTimeout != null ? Math.max(0, state.shieldsDownTimeout - elapsed) : null; - const recoveryHandoff = inspectExternalPolicyRecoveryHandoff(sandboxName); + const policyRecovery = inspectPolicyRecovery(sandboxName); + + if (policyRecovery.status === "unavailable") { + console.error(" Shields: DOWN (RECOVERY REQUIRED — policy authority unavailable)"); + console.error(` Policy authority: ${policyRecovery.detail}`); + console.error( + ` Recovery: restore policy authority inspection for sandbox '${sandboxName}', then retry \`${CLI_NAME} ${sandboxName} shields status\` before relying on automatic lockdown.`, + ); + throw new DeferredShieldsExit("Policy authority inspection is required", 2); + } + + const recoveryHandoff = policyRecovery.status === "external" ? policyRecovery.handoff : null; console.log( recoveryHandoff diff --git a/src/lib/shields/status-state-lock-plan.test.ts b/src/lib/shields/status-state-lock-plan.test.ts index 193e703580e..4dd060b8d1e 100644 --- a/src/lib/shields/status-state-lock-plan.test.ts +++ b/src/lib/shields/status-state-lock-plan.test.ts @@ -47,6 +47,43 @@ async function loadShieldsModule() { } describe("Shields status state lock plan drift", () => { + it("reports unavailable policy authority during temporary unlock (#9833)", async () => { + const sandboxName = "openclaw"; + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync( + path.join(stateDir, `shields-${sandboxName}.json`), + JSON.stringify({ shieldsDown: true, shieldsDownAt: new Date().toISOString() }), + { mode: 0o600 }, + ); + const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + const exitSpy = vi.spyOn(process, "exit").mockImplementation((code) => { + throw new Error(`exit ${String(code)}`); + }); + + const { shieldsStatus } = await loadShieldsModule(); + expect(() => + shieldsStatus(sandboxName, false, { + inspectPolicyRecovery: () => ({ + status: "unavailable", + detail: "OpenShell sandbox policy authority inspection failed: the query timed out.", + }), + }), + ).toThrow("exit 2"); + + const output = logSpy.mock.calls.flat().join("\n"); + const errors = errorSpy.mock.calls.flat().join("\n"); + expect(exitSpy).toHaveBeenCalledWith(2); + expect(output).not.toContain("DOWN (temporarily unlocked)"); + expect(output).not.toContain("Auto-lockdown in:"); + expect(errors).toContain("Shields: DOWN (RECOVERY REQUIRED — policy authority unavailable)"); + expect(errors).toContain("OpenShell sandbox policy authority inspection failed"); + expect(errors).toContain( + "Recovery: restore policy authority inspection for sandbox 'openclaw'", + ); + }); + it("reports a mismatched installed state lock plan as drift", async () => { const sandboxName = "openclaw"; writeSealedLockedState(sandboxName); diff --git a/test/cli/sandbox-mutations.test.ts b/test/cli/sandbox-mutations.test.ts index 4b7faaca62c..a52ad389213 100644 --- a/test/cli/sandbox-mutations.test.ts +++ b/test/cli/sandbox-mutations.test.ts @@ -29,6 +29,11 @@ function writePolicyMutationOpenshellStub(home: string): string { "#!/usr/bin/env bash", "set -euo pipefail", 'if [ "$1" = "policy" ] && [ "$2" = "get" ]; then', + ' if [[ " $* " == *" --output json "* ]]; then', + ' sandbox="${@: -1}"', + ' printf \'{"scope":"sandbox","sandbox":"%s","status":"effective","policy_source":"sandbox","policy":{}}\\n\' "$sandbox"', + " exit 0", + " fi", " cat <<'YAML'", "version: 1", "network_policies:", diff --git a/test/e2e-test.sh b/test/e2e-test.sh index 2d20f22955d..b2c11b6ed0e 100755 --- a/test/e2e-test.sh +++ b/test/e2e-test.sh @@ -157,6 +157,18 @@ trap cleanup_apply_fixture EXIT cat >"$FAKE_OPENSHELL_BIN/openshell" <<'SH' #!/usr/bin/env bash set -euo pipefail +if [ "${1:-}" = "status" ]; then + printf '%s\n' 'Gateway Status' ' Status: Connected' ' Gateway: fixture-gateway' + exit 0 +fi +if [ "${1:-} ${2:-}" = "policy list" ]; then + exit 0 +fi +if [ "${1:-} ${2:-}" = "policy get" ] && [[ " $* " == *" --output json "* ]]; then + sandbox="${@: -1}" + printf '{"scope":"sandbox","sandbox":"%s","status":"effective","policy_source":"sandbox","policy":{}}\n' "$sandbox" + exit 0 +fi case "${1:-} ${2:-} ${3:-}" in "policy get --base") printf '%s\n' 'Policy for sandbox fixture' '---' diff --git a/test/mcp-policy-key-ownership.test.ts b/test/mcp-policy-key-ownership.test.ts index 8ab9d742eda..6a6e8f01b58 100644 --- a/test/mcp-policy-key-ownership.test.ts +++ b/test/mcp-policy-key-ownership.test.ts @@ -10,6 +10,16 @@ import { describe, expect, it } from "vitest"; const MATCHING_OPENSHELL = path.resolve("test/fixtures/openshell-v0.0.106"); const MATCHING_OPENSHELL_VERSION_CLAUSE = `if [ "$1" = "--version" ]; then printf '%s\\n' 'openshell 0.0.106'; exit 0; fi`; +const MANAGED_POLICY_AUTHORITY_CLAUSE = `if [ "$1 $2" = "policy get" ]; then + case " $* " in + *" --output json "*) + sandbox="" + for sandbox in "$@"; do :; done + printf '{"scope":"sandbox","sandbox":"%s","status":"effective","policy_source":"sandbox","policy":{}}\\n' "$sandbox" + exit 0 + ;; + esac +fi`; const PRESET = `network_policies: example: @@ -29,6 +39,7 @@ function runApply( path.join(binDir, "openshell"), `#!/bin/sh ${MATCHING_OPENSHELL_VERSION_CLAUSE} +${MANAGED_POLICY_AUTHORITY_CLAUSE} printf '%s\n' "$*" >> ${JSON.stringify(callsPath)} if [ "$1 $2" = "policy get" ]; then printf 'Version: 1\nHash: test\n---\nversion: 1\n${ @@ -79,6 +90,7 @@ function runContentMatch(liveName: string) { path.join(binDir, "openshell"), `#!/bin/sh ${MATCHING_OPENSHELL_VERSION_CLAUSE} +${MANAGED_POLICY_AUTHORITY_CLAUSE} printf 'Version: 1\nHash: test\n---\nversion: 1\nnetwork_policies:\n example:\n name: ${liveName}\n endpoints: []\n' `, { mode: 0o755 }, @@ -109,6 +121,7 @@ function runFailedPolicyMutation(operation: "apply" | "remove") { path.join(binDir, "openshell"), `#!/bin/sh ${MATCHING_OPENSHELL_VERSION_CLAUSE} +${MANAGED_POLICY_AUTHORITY_CLAUSE} if [ "$1 $2" = "policy get" ]; then printf 'Version: 1\nHash: test\n---\nversion: 1\nnetwork_policies:\n example:\n name: generated-policy\n endpoints: []\n' exit 0 @@ -174,6 +187,7 @@ function runSuccessfulPolicyRemoval(skipRegistryUpdate: boolean) { path.join(binDir, "openshell"), `#!/bin/sh ${MATCHING_OPENSHELL_VERSION_CLAUSE} +${MANAGED_POLICY_AUTHORITY_CLAUSE} if [ "$1 $2" = "policy get" ]; then printf 'Version: 1\nHash: test\n---\nversion: 1\nnetwork_policies:\n example:\n name: generated-policy\n endpoints: []\n' fi @@ -295,6 +309,7 @@ describe("MCP-generated network policy ownership", () => { path.join(binDir, "openshell"), `#!/bin/sh ${MATCHING_OPENSHELL_VERSION_CLAUSE} +${MANAGED_POLICY_AUTHORITY_CLAUSE} printf '%s\n' "$*" >> ${JSON.stringify(callsPath)} if [ "$1 $2 $3" = "status --output json" ]; then printf '%s\n' 'ready' @@ -386,6 +401,7 @@ bridge.addMcpBridge("alpha", { path.join(binDir, "openshell"), `#!/bin/sh ${MATCHING_OPENSHELL_VERSION_CLAUSE} +${MANAGED_POLICY_AUTHORITY_CLAUSE} printf '%s\n' "$*" >> ${JSON.stringify(callsPath)} if [ "$1 $2 $3" = "status --output json" ]; then printf '%s\n' 'ready' diff --git a/test/policies-teams.test.ts b/test/policies-teams.test.ts index dbd13208600..19ebf572688 100644 --- a/test/policies-teams.test.ts +++ b/test/policies-teams.test.ts @@ -100,6 +100,10 @@ process.stdout.write("\n__RESULT__" + JSON.stringify({ `#!/usr/bin/env bash set -euo pipefail if [ "$1 $2" = "policy get" ]; then + if [[ " $* " == *" --output json "* ]]; then + printf '%s\n' '{"scope":"sandbox","sandbox":"hermes-sandbox","status":"effective","policy_source":"sandbox","policy":{}}' + exit 0 + fi printf 'Version: 1\nHash: test\n---\nversion: 1\n\nnetwork_policies: {}\n' exit 0 fi diff --git a/test/policy-openclaw-npm-compatibility.test.ts b/test/policy-openclaw-npm-compatibility.test.ts index 8782ed3e794..d48446f765a 100644 --- a/test/policy-openclaw-npm-compatibility.test.ts +++ b/test/policy-openclaw-npm-compatibility.test.ts @@ -139,6 +139,12 @@ function runLiveScenario({ initialPolicy, childScript, setMode = "success" }: Li fakeOpenshell, `#!/usr/bin/env bash set -euo pipefail +if [ "$1 $2" = "policy get" ] && [[ " $* " == *" --output json "* ]]; then + sandbox="" + for sandbox in "$@"; do :; done + printf '{"scope":"sandbox","sandbox":"%s","status":"effective","policy_source":"sandbox","policy":{}}\n' "$sandbox" + exit 0 +fi printf '%s\n' "$*" >> ${JSON.stringify(callsPath)} if [ "$1 $2" = "policy get" ]; then printf 'Version: 1\nHash: test\n---\n' From 548f8fd4a5df244a59127d8355dc39a03d5def02 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 23:47:36 -0700 Subject: [PATCH 11/40] test(blueprint): cover policy reconciliation refusals Signed-off-by: Apurv Kumaria --- .../runner-openshell-072-policy.test.ts | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts index 1cfa5bafc7c..f7f9c705c61 100644 --- a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts +++ b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts @@ -656,4 +656,84 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { await expect(actionReconcile(runId)).rejects.toThrow(/policy transition receipt is invalid/u); await expect(actionRollback(runId)).rejects.toThrow(/policy transition receipt is invalid/u); }); + + const reconciliationPlan = { + run_id: "invalid-reconciliation", + sandbox_name: "test-sandbox", + sandbox_created_by_apply: false, + policy_additions: blueprint().components!.policy!.additions!, + policy_transition: { + status: "incomplete", + sandbox_name: "test-sandbox", + gateway: "test-gateway", + expected_authority: "nemoclaw-managed", + policy_addition_names: ["nim_service"], + }, + }; + + it.each([ + ["a non-object body", [], /plan\.json must contain a JSON object/u], + [ + "an apply-owned sandbox", + { ...reconciliationPlan, sandbox_created_by_apply: true }, + /requires a reused sandbox/u, + ], + [ + "a mismatched sandbox", + { ...reconciliationPlan, sandbox_name: "other-sandbox" }, + /sandbox does not match/u, + ], + [ + "invalid policy additions", + { ...reconciliationPlan, policy_additions: [] }, + /policy additions are invalid/u, + ], + [ + "mismatched policy addition names", + { + ...reconciliationPlan, + policy_transition: { + ...reconciliationPlan.policy_transition, + policy_addition_names: ["other"], + }, + }, + /additions do not match/u, + ], + ])("rejects a reconciliation plan with %s (#9833)", async (_case, plan, expected) => { + const runId = "invalid-reconciliation"; + const stateDir = `${FAKE_HOME}/.nemoclaw/state/runs/${runId}`; + store.set(stateDir, { type: "dir" }); + store.set(`${stateDir}/plan.json`, { type: "file", content: JSON.stringify(plan) }); + + await expect(actionReconcile(runId)).rejects.toThrow(expected); + }); + + it("rejects reconciliation for a missing run (#9833)", async () => { + await expect(actionReconcile("missing-reconciliation")).rejects.toThrow(/not found/u); + }); + + it("treats a complete reconciliation as idempotent and requires a CLI run ID (#9833)", async () => { + const runId = "complete-reconciliation"; + const stateDir = `${FAKE_HOME}/.nemoclaw/state/runs/${runId}`; + store.set(stateDir, { type: "dir" }); + store.set(`${stateDir}/plan.json`, { + type: "file", + content: JSON.stringify({ + ...reconciliationPlan, + run_id: runId, + policy_transition: { + ...reconciliationPlan.policy_transition, + status: "complete", + }, + }), + }); + + await actionReconcile(runId); + + expect(stdoutCapture.text()).toContain( + `Policy transition for run ${runId} is already complete.`, + ); + expect(mockExeca).not.toHaveBeenCalled(); + await expect(main(["reconcile"])).rejects.toThrow(/--run-id is required/u); + }); }); From 3ecd24ba9195de2091ef99f3299d27c9f39c8158 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 23 Aug 2026 23:03:07 -0700 Subject: [PATCH 12/40] fix(onboard): respect external policy authority Signed-off-by: Apurv Kumaria --- ci/onboard-entry-composition-budget.json | 1 - ci/source-architecture-budget.json | 6 +- .../src/shared/openshell-policy-boundary.cts | 27 + .../shared/openshell-policy-boundary.test.ts | 37 ++ .../checks/openshell-policy-mutation-read.mts | 7 +- .../sandbox/vm-dns-monkeypatch.test.ts | 32 + src/lib/actions/sandbox/vm-dns-monkeypatch.ts | 15 + .../openshell/policy-authority.test.ts | 83 +++ .../adapters/openshell/policy-authority.ts | 51 +- src/lib/adapters/openshell/runtime.ts | 11 +- .../llama-cpp/managed-installer.test.ts | 177 ++++- .../inference/llama-cpp/managed-installer.ts | 24 + src/lib/onboard.ts | 161 +++-- .../onboard/agent-dashboard-forward.test.ts | 47 ++ src/lib/onboard/agent-dashboard-forward.ts | 165 +++-- src/lib/onboard/agent-fixed-forward.test.ts | 31 + src/lib/onboard/agent-fixed-forward.ts | 17 +- src/lib/onboard/bedrock-runtime.test.ts | 4 + src/lib/onboard/bedrock-runtime.ts | 5 + .../onboard/created-sandbox-finalization.ts | 68 +- src/lib/onboard/credential-navigation.test.ts | 83 +++ src/lib/onboard/credential-navigation.ts | 52 +- .../credential-provider-registration.test.ts | 315 ++++++--- .../credential-provider-registration.ts | 67 +- .../onboard/dashboard-forward-control.test.ts | 19 + src/lib/onboard/dashboard-forward-control.ts | 7 + src/lib/onboard/dashboard.ts | 144 +++- .../docker-gpu-local-inference.test.ts | 25 + src/lib/onboard/docker-gpu-local-inference.ts | 2 + .../hermes-portable-onboarding.test.ts | 2 + .../hermes-portable-onboarding.ts | 27 +- src/lib/onboard/forward-cleanup.ts | 7 +- .../gateway-teardown-authority.test.ts | 135 +++- src/lib/onboard/gateway-teardown-authority.ts | 51 +- src/lib/onboard/hermes-dashboard.test.ts | 84 +++ src/lib/onboard/hermes-dashboard.ts | 67 +- .../inference-providers/routed-selection.ts | 148 +++++ .../setup-nim-policy-authority.test.ts | 88 +++ src/lib/onboard/inference-providers/types.ts | 1 + .../inference-selection-validation.test.ts | 5 +- .../onboard/inference-selection-validation.ts | 27 +- src/lib/onboard/lifecycle-contracts.md | 10 +- .../local-model-profile/onboarder.test.ts | 70 +- .../onboard/local-model-profile/onboarder.ts | 27 +- .../onboard/machine/core-flow-phases.test.ts | 6 + src/lib/onboard/machine/final-flow-phases.ts | 6 +- .../machine/handlers/finalization.test.ts | 35 + .../onboard/machine/handlers/finalization.ts | 18 +- .../onboard/machine/handlers/policies.test.ts | 25 + src/lib/onboard/machine/handlers/policies.ts | 28 +- ...r-inference-authoritative-recovery.test.ts | 1 + ...der-inference-managed-llama-resume.test.ts | 120 +++- ...rovider-inference-policy-authority.test.ts | 114 ++++ ...provider-inference-recovery-gating.test.ts | 11 + ...ovider-inference-route-containment.test.ts | 1 + .../provider-inference.test-support.ts | 2 + .../handlers/provider-inference.test.ts | 77 ++- .../machine/handlers/provider-inference.ts | 109 ++- .../sandbox-create-intent-boundary.test.ts | 177 +++-- ...andbox-policy-authority-completion.test.ts | 103 +++ .../sandbox-provider-effect-replay.test.ts | 2 + .../machine/handlers/sandbox-test-fixtures.ts | 2 + src/lib/onboard/machine/handlers/sandbox.ts | 88 ++- .../machine/initial-flow-phases.test.ts | 66 +- .../onboard/machine/initial-flow-phases.ts | 10 +- .../machine/resume-provider-shim.test.ts | 5 +- .../onboard/machine/resume-provider-shim.ts | 10 +- .../managed-workload/onboard-orchestration.ts | 6 + src/lib/onboard/messaging-host-forward.ts | 5 + .../policy-authority/preflight.test.ts | 141 ++++ src/lib/onboard/policy-authority/preflight.ts | 283 ++++++++ src/lib/onboard/policy-presets.ts | 3 + src/lib/onboard/provider-key-bridge.ts | 14 +- src/lib/onboard/providers.test.ts | 60 ++ src/lib/onboard/providers.ts | 58 +- src/lib/onboard/resume-provider-recovery.ts | 3 + src/lib/onboard/resume/locked-runtime.test.ts | 17 +- .../onboard/sandbox-create-intent-types.ts | 8 +- src/lib/onboard/sandbox-create-launch.test.ts | 18 + src/lib/onboard/sandbox-create-launch.ts | 3 + .../sandbox-create-plan-materialization.ts | 57 +- src/lib/onboard/sandbox-create-plan.test.ts | 48 ++ src/lib/onboard/sandbox-create-plan.ts | 1 + .../sandbox-create/orchestration.test.ts | 628 +++++++++++++++++- .../onboard/sandbox-create/orchestration.ts | 513 +++++++++++--- src/lib/onboard/sandbox-gpu-create-flow.ts | 20 +- src/lib/onboard/sandbox-recreate-probe.ts | 27 + src/lib/onboard/sandbox-registration.test.ts | 8 + src/lib/onboard/sandbox-registration.ts | 3 + .../onboard/sandbox-registry-metadata.test.ts | 46 ++ src/lib/onboard/sandbox-registry-metadata.ts | 4 + src/lib/onboard/sandbox-reuse.test.ts | 186 +++--- src/lib/onboard/sandbox-reuse.ts | 51 +- src/lib/onboard/session-bootstrap.test.ts | 30 + src/lib/onboard/session-updates.ts | 3 + .../setup-inference-gateway-scope.test.ts | 31 +- .../setup-inference-policy-authority.test.ts | 88 +++ src/lib/onboard/setup-inference.ts | 95 ++- .../setup-nim-flow-vllm-resume.test.ts | 66 +- src/lib/onboard/setup-nim-flow.test.ts | 1 + src/lib/onboard/setup-nim-flow.ts | 106 ++- src/lib/onboard/setup-nim-ollama.test.ts | 56 ++ src/lib/onboard/setup-nim-ollama.ts | 7 + src/lib/onboard/setup-nim-selection.ts | 51 +- .../validation-recovery-prompt.test.ts | 21 + src/lib/onboard/validation-recovery-prompt.ts | 7 + src/lib/onboard/vm-dns-monkeypatch.test.ts | 26 +- src/lib/onboard/vm-dns-monkeypatch.ts | 18 +- src/lib/policy/commands.ts | 25 + src/lib/policy/merge.ts | 3 + .../onboard-session-normalization.test.ts | 39 +- src/lib/state/onboard-session.ts | 40 +- test/install-hermes-portable-active.test.ts | 1 + .../openshell-policy-boundary.test.ts | 17 + 114 files changed, 5474 insertions(+), 916 deletions(-) create mode 100644 src/lib/onboard/inference-providers/routed-selection.ts create mode 100644 src/lib/onboard/inference-providers/setup-nim-policy-authority.test.ts create mode 100644 src/lib/onboard/machine/handlers/provider-inference-policy-authority.test.ts create mode 100644 src/lib/onboard/machine/handlers/sandbox-policy-authority-completion.test.ts create mode 100644 src/lib/onboard/policy-authority/preflight.test.ts create mode 100644 src/lib/onboard/policy-authority/preflight.ts create mode 100644 src/lib/onboard/setup-inference-policy-authority.test.ts diff --git a/ci/onboard-entry-composition-budget.json b/ci/onboard-entry-composition-budget.json index 3acda42d863..8c495e298d3 100644 --- a/ci/onboard-entry-composition-budget.json +++ b/ci/onboard-entry-composition-budget.json @@ -21,7 +21,6 @@ "handleRemoteProviderSelection": 84, "handleRemoteProviderSelection.providerExistsInGateway": 1, "handleRemoteProviderSelection.readGatewayProviderMetadata": 1, - "handleRoutedSelection": 16, "handleVllmSelection.queryVllmModels": 1, "preflightAuthoritativeRebuildTarget": 1, "runOnboard": 8, diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index c9b0c1938cb..3c2d5cba005 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -8,7 +8,7 @@ "src/lib/adapters/docker/index.ts": 43, "src/lib/adapters/openshell/client.ts": 23, "src/lib/adapters/openshell/resolve.ts": 27, - "src/lib/adapters/openshell/runtime.ts": 54, + "src/lib/adapters/openshell/runtime.ts": 55, "src/lib/adapters/openshell/timeouts.ts": 38, "src/lib/agent/defs.ts": 33, "src/lib/cli/branding.ts": 87, @@ -26,7 +26,7 @@ "src/lib/onboard/gateway-binding.ts": 52, "src/lib/runner.ts": 86, "src/lib/security/redact.ts": 54, - "src/lib/state/onboard-session.ts": 37, + "src/lib/state/onboard-session.ts": 36, "src/lib/state/registry.ts": 101, "src/lib/state/state-root.ts": 21, "src/lib/subprocess-env.ts": 24, @@ -49,7 +49,7 @@ "src/lib/inference/local.ts": 22, "src/lib/inference/onboard-probes.ts": 21, "src/lib/inference/vllm.ts": 21, - "src/lib/onboard.ts": 201, + "src/lib/onboard.ts": 202, "src/lib/onboard/machine/handlers/sandbox.ts": 21, "src/lib/policy/index.ts": 22, "src/lib/sandbox/config.ts": 22, diff --git a/nemoclaw/src/shared/openshell-policy-boundary.cts b/nemoclaw/src/shared/openshell-policy-boundary.cts index 3b49f2f6cd5..67e403225c4 100644 --- a/nemoclaw/src/shared/openshell-policy-boundary.cts +++ b/nemoclaw/src/shared/openshell-policy-boundary.cts @@ -73,6 +73,33 @@ export function parseSandboxPolicyAuthorityMetadata( }; } +/** Parse machine-readable global policy metadata after history proves a revision exists. */ +export function parseGlobalPolicyAuthorityMetadata( + raw: string, +): SandboxPolicyAuthorityInspection { + if (raw.trim().length === 0) { + throw new Error("OpenShell returned empty global policy authority metadata"); + } + const metadata = parseJsonMapping( + raw, + "OpenShell returned malformed global policy authority metadata", + ); + if ( + metadata.scope !== "global" || + Object.hasOwn(metadata, "sandbox") || + (metadata.policy_source !== undefined && metadata.policy_source !== "global") + ) { + throw new Error("OpenShell returned invalid global policy authority metadata"); + } + if (metadata.status === "superseded") { + return { authority: "nemoclaw-managed", effectivePolicy: {} }; + } + if (metadata.status !== "loaded" || !isMapping(metadata.policy)) { + throw new Error("OpenShell returned invalid global policy authority metadata"); + } + return { authority: "externally-managed", effectivePolicy: metadata.policy }; +} + /** Require durable and observed policy authority to describe the same owner. */ export function assertMatchingPolicyAuthority(recorded: unknown, observed: unknown): void { if (!isPolicyAuthority(recorded)) { diff --git a/nemoclaw/src/shared/openshell-policy-boundary.test.ts b/nemoclaw/src/shared/openshell-policy-boundary.test.ts index c4e69328ad8..f9c0cf62665 100644 --- a/nemoclaw/src/shared/openshell-policy-boundary.test.ts +++ b/nemoclaw/src/shared/openshell-policy-boundary.test.ts @@ -8,6 +8,7 @@ import { assertExternalPolicyRequirementContainment, assertMatchingPolicyAuthority, assertPolicyRequirementContainment, + parseGlobalPolicyAuthorityMetadata, parseOpenShellPolicy, parseSandboxPolicyAuthorityMetadata, stripProviderComposedPolicies, @@ -197,6 +198,42 @@ describe("sandbox policy authority boundary", () => { }); }); +describe("global policy authority boundary", () => { + const policy = { version: 1, network_policies: { required: { allow: true } } }; + + it("classifies a loaded global policy as externally managed", () => { + expect( + parseGlobalPolicyAuthorityMetadata( + JSON.stringify({ + scope: "global", + status: "loaded", + policy_source: "global", + policy, + }), + ), + ).toEqual({ authority: "externally-managed", effectivePolicy: policy }); + }); + + it("classifies a superseded global revision as NemoClaw-managed", () => { + expect( + parseGlobalPolicyAuthorityMetadata( + JSON.stringify({ scope: "global", status: "superseded", policy_source: "global" }), + ), + ).toEqual({ authority: "nemoclaw-managed", effectivePolicy: {} }); + }); + + it.each([ + ["empty", ""], + ["malformed", "{"], + ["wrong scope", JSON.stringify({ scope: "sandbox", status: "loaded", policy })], + ["sandbox identity", JSON.stringify({ scope: "global", sandbox: "alpha", status: "loaded", policy })], + ["unknown source", JSON.stringify({ scope: "global", status: "loaded", policy_source: "sandbox", policy })], + ["unknown status", JSON.stringify({ scope: "global", status: "pending", policy })], + ])("rejects %s global authority metadata", (_caseName, raw) => { + expect(() => parseGlobalPolicyAuthorityMetadata(raw)).toThrow(/global policy authority metadata/u); + }); +}); + describe("canonical OpenShell policy boundary", () => { it("parses marked output and versionless network policies", () => { const body = "version: 1\nnetwork_policies:\n safe: {}"; diff --git a/scripts/checks/openshell-policy-mutation-read.mts b/scripts/checks/openshell-policy-mutation-read.mts index bfa1ffb494a..99152123196 100644 --- a/scripts/checks/openshell-policy-mutation-read.mts +++ b/scripts/checks/openshell-policy-mutation-read.mts @@ -98,7 +98,10 @@ export const MUTATION_READS: readonly AuditedPolicyReadFile[] = [ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ { relativePath: "src/lib/adapters/openshell/policy-authority.ts", - expectedReads: [unclassifiedFull("inspectSandboxPolicyAuthority")], + expectedReads: [ + unclassifiedFull("inspectSandboxPolicyAuthority"), + unclassifiedFull("inspectGlobalPolicyAuthority"), + ], }, { relativePath: "src/lib/actions/sandbox/gateway-state.ts", @@ -125,6 +128,7 @@ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ failureHandling: "unclassified", }, unclassifiedFull("buildPolicyGetFullJsonCommand"), + unclassifiedFull("buildGlobalPolicyGetFullJsonCommand"), ], }, ] as const; @@ -139,6 +143,7 @@ const POLICY_GET_BUILDERS = new Map([ ["buildPolicyGetCommand", "base"], ["buildPolicyGetFullCommand", "full"], ["buildPolicyGetFullJsonCommand", "full"], + ["buildGlobalPolicyGetFullJsonCommand", "full"], ]); interface PolicyBuilderBindings { diff --git a/src/lib/actions/sandbox/vm-dns-monkeypatch.test.ts b/src/lib/actions/sandbox/vm-dns-monkeypatch.test.ts index 679b5bd8db2..716115c29b5 100644 --- a/src/lib/actions/sandbox/vm-dns-monkeypatch.test.ts +++ b/src/lib/actions/sandbox/vm-dns-monkeypatch.test.ts @@ -183,6 +183,38 @@ describe("OpenShell VM DNS monkeypatch", () => { ).toContain('echo "nameserver ${GVPROXY_GATEWAY_IP}" > /etc/resolv.conf'); }); + it("stops VM DNS mutation when authority changes between file writes (#9833)", () => { + const stateDir = makeTempDir(); + const rootfs = sandboxRootfs(stateDir); + const resolverPath = path.join(rootfs, "etc", "resolv.conf"); + const initPath = path.join(rootfs, "srv", "openshell-vm-sandbox-init.sh"); + writeRootfsFiles(rootfs, "nameserver 8.8.8.8\n"); + const originalInit = fs.readFileSync(initPath, "utf-8"); + const revalidatePolicyAuthority = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("policy authority changed"); + }); + + expect(() => + applyOpenShellVmDnsMonkeypatch( + "demo", + { openshellDriver: "vm" }, + { + capture: () => ({ status: 0, output: "Id: abc\n" }), + platform: "darwin", + revalidatePolicyAuthority, + stateDir, + }, + ), + ).toThrow("policy authority changed"); + + expect(fs.readFileSync(resolverPath, "utf-8")).toBe("nameserver 192.168.127.1\n"); + expect(fs.readFileSync(initPath, "utf-8")).toBe(originalInit); + expect(revalidatePolicyAuthority).toHaveBeenCalledTimes(2); + }); + it("is idempotent when resolver and init script are already patched", () => { const stateDir = makeTempDir(); const rootfs = sandboxRootfs(stateDir); diff --git a/src/lib/actions/sandbox/vm-dns-monkeypatch.ts b/src/lib/actions/sandbox/vm-dns-monkeypatch.ts index b5e07858ae8..27362ba7bda 100644 --- a/src/lib/actions/sandbox/vm-dns-monkeypatch.ts +++ b/src/lib/actions/sandbox/vm-dns-monkeypatch.ts @@ -277,6 +277,7 @@ export function applyOpenShellVmDnsMonkeypatch( env?: NodeJS.ProcessEnv; homeDir?: string; platform?: NodeJS.Platform; + revalidatePolicyAuthority?: (operation: string) => void; stateDir?: string; } = {}, ): VmDnsMonkeypatchResult { @@ -306,6 +307,15 @@ export function applyOpenShellVmDnsMonkeypatch( let changed = false; let rootfsContext: string | undefined; + let policyAuthorityError: unknown; + const revalidatePolicyAuthority = (operation: string): void => { + try { + deps.revalidatePolicyAuthority?.(operation); + } catch (error) { + policyAuthorityError = error; + throw error; + } + }; try { const sandboxDir = path.join(stateDirReal, "vm-driver", "sandboxes", sandboxId); const sandboxDirReal = realpathIfPresent(sandboxDir); @@ -353,11 +363,13 @@ export function applyOpenShellVmDnsMonkeypatch( const currentResolver = readTextFileIfPresent(resolvConf.path) ?? ""; const desiredResolver = normalizeResolver(currentResolver); if (currentResolver !== desiredResolver) { + revalidatePolicyAuthority(`write VM resolver for sandbox '${sandboxName}'`); fs.writeFileSync(resolvConf.path, desiredResolver); changed = true; } if (initPatch.changed && initPatch.content !== undefined) { + revalidatePolicyAuthority(`write VM init script for sandbox '${sandboxName}'`); fs.writeFileSync(initScript.path, initPatch.content); changed = true; } @@ -371,6 +383,8 @@ export function applyOpenShellVmDnsMonkeypatch( ); } + revalidatePolicyAuthority(`report successful VM DNS repair for sandbox '${sandboxName}'`); + return { attempted: true, changed, @@ -379,6 +393,7 @@ export function applyOpenShellVmDnsMonkeypatch( status: changed ? "applied" : "already-present", }; } catch (error) { + if (error === policyAuthorityError) throw error; return { attempted: true, changed, diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts index 6b7bc59b9db..86cfff2efed 100644 --- a/src/lib/adapters/openshell/policy-authority.test.ts +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -7,6 +7,7 @@ import * as openshellResolveModule from "./resolve"; import { assertExternalPolicyRequirements, assertRecordedPolicyAuthority, + inspectGlobalPolicyAuthority, inspectSandboxPolicyAuthority, isExternalPolicyAuthorityRefusalError, type PolicyAuthorityCapture, @@ -41,6 +42,16 @@ function sandboxMetadata(overrides: Record = {}): Record = {}): Record { + return { + scope: "global", + status: "loaded", + policy_source: "global", + policy: { version: 1, network_policies: { baseline: { endpoints: ["base.test"] } } }, + ...overrides, + }; +} + function errorFrom(action: () => unknown): Error { try { action(); @@ -108,6 +119,78 @@ describe("OpenShell policy authority inspection", () => { ]); }); + it("uses empty bounded global history as managed authority (#9833)", () => { + const runCaptureEx = vi.fn(() => captureResult("")); + + expect(inspectGlobalPolicyAuthority({ gatewayName: "nemoclaw-18080", runCaptureEx })).toEqual({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); + expect(runCaptureEx).toHaveBeenCalledTimes(1); + expect(runCaptureEx.mock.calls[0]?.[0]).toEqual([ + "openshell", + "policy", + "list", + "-g", + "nemoclaw-18080", + "--global", + "--limit", + "1", + ]); + }); + + it("uses loaded global metadata as external authority (#9833)", () => { + const policy = { version: 1, network_policies: { required: { endpoints: ["api.test"] } } }; + const runCaptureEx = vi + .fn() + .mockReturnValueOnce(captureResult("revision-1")) + .mockReturnValueOnce(captureResult(JSON.stringify(globalMetadata({ policy })))); + + expect(inspectGlobalPolicyAuthority({ gatewayName: "nemoclaw-18080", runCaptureEx })).toEqual({ + authority: "externally-managed", + effectivePolicy: policy, + }); + expect(runCaptureEx.mock.calls[1]?.[0]).toEqual([ + "openshell", + "policy", + "get", + "-g", + "nemoclaw-18080", + "--global", + "--full", + "--output", + "json", + ]); + }); + + it("treats a superseded global revision as managed authority (#9833)", () => { + const runCaptureEx = vi + .fn() + .mockReturnValueOnce(captureResult("revision-1")) + .mockReturnValueOnce(captureResult(JSON.stringify(globalMetadata({ status: "superseded" })))); + + expect(inspectGlobalPolicyAuthority({ runCaptureEx })).toEqual({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }); + }); + + it.each([ + ["malformed metadata", "{"], + ["wrong scope", JSON.stringify(globalMetadata({ scope: "sandbox" }))], + ["unknown status", JSON.stringify(globalMetadata({ status: "pending" }))], + ])("fails closed on %s after global history is present (#9833)", (_caseName, raw) => { + const secret = "captured-global-policy-secret"; + const runCaptureEx = vi + .fn() + .mockReturnValueOnce(captureResult("revision-1")) + .mockReturnValueOnce(captureResult(`${raw}${secret}`)); + + const error = errorFrom(() => inspectGlobalPolicyAuthority({ runCaptureEx })); + expect(error.message).toContain("inspection failed"); + expect(error.message).not.toContain(secret); + }); + it("rejects invalid sandbox and gateway identities before querying policy (#9833)", () => { const runCaptureEx = vi.fn(() => captureResult(JSON.stringify(sandboxMetadata())), diff --git a/src/lib/adapters/openshell/policy-authority.ts b/src/lib/adapters/openshell/policy-authority.ts index 0793d4693db..9ab9dee313a 100644 --- a/src/lib/adapters/openshell/policy-authority.ts +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -7,14 +7,20 @@ import { NAME_ALLOWED_FORMAT, NAME_MAX_LENGTH, } from "../../sandbox-name-contract"; -import { buildPolicyGetFullJsonCommand } from "../../policy/commands"; +import { + buildGlobalPolicyGetFullJsonCommand, + buildGlobalPolicyListCommand, + buildPolicyGetFullJsonCommand, +} from "../../policy/commands"; import { assertExternalPolicyRequirementContainment, assertMatchingPolicyAuthority, type OpenShellPolicyAuthority, + parseGlobalPolicyAuthorityMetadata, parseSandboxPolicyAuthorityMetadata, type SandboxPolicyAuthorityInspection as CanonicalSandboxPolicyAuthorityInspection, } from "../../policy/merge"; +import { captureResolvedOpenshellCommand } from "./runtime"; const POLICY_AUTHORITY_CAPTURE_MAX_BYTES = 1024 * 1024; const POLICY_AUTHORITY_CAPTURE_TIMEOUT_MS = 30_000; @@ -69,7 +75,12 @@ export type PolicyAuthorityCapture = ( interface SandboxPolicyAuthorityInspectionOptions { readonly sandboxName: string; readonly gatewayName?: string; - readonly runCaptureEx: PolicyAuthorityCapture; + readonly runCaptureEx?: PolicyAuthorityCapture; +} + +interface GlobalPolicyAuthorityInspectionOptions { + readonly gatewayName?: string; + readonly runCaptureEx?: PolicyAuthorityCapture; } function validatePolicyAuthorityName(name: string, label: string): string { @@ -142,7 +153,7 @@ function capturePolicyQuery( export function inspectSandboxPolicyAuthority({ sandboxName, gatewayName, - runCaptureEx, + runCaptureEx = captureResolvedOpenshellCommand, }: SandboxPolicyAuthorityInspectionOptions): SandboxPolicyAuthorityInspection { const validatedSandboxName = validatePolicyAuthorityName(sandboxName, "sandbox name"); const validatedGatewayName = @@ -165,6 +176,40 @@ export function inspectSandboxPolicyAuthority({ } } +/** Inspect whether an active global policy will manage a sandbox created next. */ +export function inspectGlobalPolicyAuthority({ + gatewayName, + runCaptureEx = captureResolvedOpenshellCommand, +}: GlobalPolicyAuthorityInspectionOptions = {}): SandboxPolicyAuthorityInspection { + const validatedGatewayName = + gatewayName === undefined + ? undefined + : validatePolicyAuthorityName(gatewayName, "gateway name"); + const { stdout: history } = capturePolicyQuery( + buildGlobalPolicyListCommand(validatedGatewayName), + runCaptureEx, + "global", + "policy history", + ); + if (history.trim().length === 0) { + return { authority: "nemoclaw-managed", effectivePolicy: {} }; + } + const { stdout: raw } = capturePolicyQuery( + buildGlobalPolicyGetFullJsonCommand(validatedGatewayName), + runCaptureEx, + "global", + "machine-readable policy", + ); + try { + return parseGlobalPolicyAuthorityMetadata(raw); + } catch (error) { + failInspection( + "global", + error instanceof Error ? error.message : "OpenShell returned invalid policy metadata", + ); + } +} + function operationLabel(operation: string): string { return typeof operation === "string" && operation.trim().length > 0 ? operation.trim() diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index f4fd2537907..d4415326998 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -4,7 +4,7 @@ import type { StdioOptions } from "node:child_process"; import path from "node:path"; -import { ROOT } from "../../runner"; +import { type CaptureResult, ROOT, runCaptureEx } from "../../runner"; import { captureOpenshellCommand, captureOpenshellCommandAsync, @@ -18,6 +18,15 @@ import { OPENSHELL_PROBE_TIMEOUT_MS } from "./timeouts"; type CommandArgs = string[]; export { buildOpenShellSubprocessEnv }; +export type ResolvedOpenshellCaptureResult = CaptureResult; + +/** Capture one fully resolved OpenShell command with structured finality metadata. */ +export function captureResolvedOpenshellCommand( + command: readonly string[], + options?: { readonly maxBuffer?: number; readonly timeout?: number }, +): CaptureResult { + return runCaptureEx(command, options); +} type RunnerOptions = { /** Exact canonical executable selected by the caller. */ diff --git a/src/lib/inference/llama-cpp/managed-installer.test.ts b/src/lib/inference/llama-cpp/managed-installer.test.ts index f7aed675d77..c9a2071b27a 100644 --- a/src/lib/inference/llama-cpp/managed-installer.test.ts +++ b/src/lib/inference/llama-cpp/managed-installer.test.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createInMemoryRuntimeProviderBundle } from "../../../../test/helpers/runtime-provider-bundle"; +import { PolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; import type { ContainerEngine } from "../../adapters/container-engine"; import type { PodmanContainerEngine } from "../../adapters/podman"; import type { RuntimeProviderWorkloadProfile } from "../../onboard/runtime-provider/contract"; @@ -28,6 +29,7 @@ import { type HostLocalLlamaCppLifecycle, serializeHostLocalInferenceReceipt, } from "../../onboard/runtime-provider/host-local-inference"; +import { persistedEngineAuthorityPath } from "../../onboard/runtime-provider/persisted-engine-authority"; import { createPodmanRuntimeProviderBundle } from "../../onboard/runtime-provider/podman"; import { isLlamaCppServingRecipe } from "../serving/adapter-registry"; import { loadManagedInferenceCatalog } from "../serving/catalog-loader"; @@ -46,6 +48,7 @@ import { } from "./managed-installer.test-support"; import { createManagedLlamaCppReceiptWriter, + loadManagedLlamaCppApiKey, loadOrCreateManagedLlamaCppApiKey, managedLlamaCppStatePaths, reserveManagedLlamaCppOwner, @@ -160,6 +163,34 @@ function selection(): ResolvedLlamaCppInferenceSelection { }; } +function verifiedArtifact(selected: ResolvedLlamaCppInferenceSelection, homeDir: string) { + const hostPath = path.join(homeDir, "model.gguf"); + fs.writeFileSync(hostPath, "fixture", { mode: 0o600 }); + const identity = fs.lstatSync(hostPath, { bigint: true }); + return { + digest: selected.recipe.spec.model.files[0]!.digest, + filesystemIdentity: { + ctimeNs: identity.ctimeNs, + dev: identity.dev, + ino: identity.ino, + mtimeNs: identity.mtimeNs, + size: identity.size, + }, + hostPath, + sizeBytes: selected.recipe.spec.model.files[0]!.sizeBytes, + }; +} + +function dormantManagedLifecycle(): DockerLlamaCppManagedLifecycle { + const receipt = { schemaVersion: 1 } as HostLocalInferenceReceipt; + return { + recoverUnfinished: vi.fn(() => ({ recovered: [], failures: [] })), + resume: vi.fn(() => receipt), + runtime: {} as DockerLlamaCppManagedLifecycle["runtime"], + start: vi.fn(() => receipt), + }; +} + describe("managed llama.cpp Docker authority", () => { it("rejects a direct plaintext TCP daemon before spawning and never exposes HF_TOKEN", () => { const capture = successfulDockerCapture({}); @@ -416,44 +447,140 @@ describe("managed llama.cpp Docker authority", () => { }); describe("managed llama.cpp installer", () => { - it.each([ - "podman", - "unsupported-runtime", - ])("rejects the %s provider before any Docker or installer mutation", async (providerId) => { + it("stops after acquisition when policy authority refuses activation (#9833)", async () => { const selected = selection(); const homeDir = temporaryHome(); - const pullImage = vi.fn(); - const acquireGguf = vi.fn(); - const verifyGguf = vi.fn(); - const checkPort = vi.fn(); - const runtimeProvider = createInMemoryRuntimeProviderBundle({ - providerId, - workloadProfile: TEST_WORKLOAD_PROFILE, - }); + const paths = managedLlamaCppStatePaths(homeDir); + const harness = engineHarness(); + harness.images.add(selected.recipe.spec.runtime.image); + harness.images.add(selected.recipe.spec.readiness.probeImage); + const lifecycle = dormantManagedLifecycle(); + const revalidatePolicyRequirements = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new PolicyAuthorityRefusalError( + "External policy authority must supply the managed llama.cpp entry.", + ); + }); await expect( installManagedLlamaCpp(selected, { sandboxName: "spark-agent", homeDir, - runtimeProvider, - pullImage: pullImage as never, - acquireGguf: acquireGguf as never, - verifyGguf: verifyGguf as never, - checkPort: checkPort as never, + runtimeProvider: managedRuntimeProvider(harness.engine, () => lifecycle), + verifyGguf: vi.fn(async () => verifiedArtifact(selected, homeDir)), + checkPort: vi.fn(async () => ({ ok: true })), log: vi.fn(), + revalidatePolicyRequirements, }), - ).resolves.toEqual({ - ok: false, - reason: `Runtime provider '${providerId}' does not provide the host-local-inference capability required for llama-cpp: Unsupported by this in-memory contract fixture.`, + ).rejects.toBeInstanceOf(PolicyAuthorityRefusalError); + + expect(revalidatePolicyRequirements).toHaveBeenNthCalledWith( + 1, + "reserve the managed llama.cpp runtime", + ); + expect(revalidatePolicyRequirements).toHaveBeenNthCalledWith( + 2, + "activate the managed llama.cpp runtime", + ); + expect(fs.existsSync(paths.ownerPath)).toBe(false); + expect( + fs.existsSync(persistedEngineAuthorityPath(paths.stateDir, "host-local-inference")), + ).toBe(false); + expect(loadManagedLlamaCppApiKey(paths)).toBeNull(); + expect(lifecycle.recoverUnfinished).not.toHaveBeenCalled(); + expect(lifecycle.start).not.toHaveBeenCalled(); + expect(lifecycle.resume).not.toHaveBeenCalled(); + }); + + it("rechecks a resumed runtime before lifecycle recovery or credentials (#9833)", async () => { + const selected = selection(); + const homeDir = temporaryHome(); + const paths = managedLlamaCppStatePaths(homeDir); + reserveManagedLlamaCppOwner(paths, { + schemaVersion: 1, + sandboxName: "spark-agent", + catalogDigest: selected.catalogDigest, + presetDigest: selected.presetDigest, + recipeDigest: selected.recipeDigest, + recipeId: selected.recipe.metadata.id, }); + const harness = engineHarness(); + harness.images.add(selected.recipe.spec.runtime.image); + harness.images.add(selected.recipe.spec.readiness.probeImage); + const lifecycle = dormantManagedLifecycle(); + const revalidatePolicyRequirements = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new PolicyAuthorityRefusalError( + "External policy authority must supply the managed llama.cpp entry.", + ); + }); - expect(pullImage).not.toHaveBeenCalled(); - expect(acquireGguf).not.toHaveBeenCalled(); - expect(verifyGguf).not.toHaveBeenCalled(); - expect(checkPort).not.toHaveBeenCalled(); - expect(fs.existsSync(managedLlamaCppStatePaths(homeDir).stateDir)).toBe(false); + await expect( + resumeManagedLlamaCppRuntime("spark-agent", { + homeDir, + runtimeProvider: managedRuntimeProvider(harness.engine, () => lifecycle), + verifyGguf: vi.fn(async () => verifiedArtifact(selected, homeDir)), + checkPort: vi.fn(async () => ({ ok: true })), + revalidatePolicyRequirements, + }), + ).rejects.toBeInstanceOf(PolicyAuthorityRefusalError); + + expect(revalidatePolicyRequirements).toHaveBeenNthCalledWith( + 1, + "inspect the managed llama.cpp runtime", + ); + expect(revalidatePolicyRequirements).toHaveBeenNthCalledWith( + 2, + "recover the managed llama.cpp runtime", + ); + expect(loadManagedLlamaCppApiKey(paths)).toBeNull(); + expect(lifecycle.recoverUnfinished).not.toHaveBeenCalled(); + expect(lifecycle.start).not.toHaveBeenCalled(); + expect(lifecycle.resume).not.toHaveBeenCalled(); }); + it.each(["podman", "unsupported-runtime"])( + "rejects the %s provider before any Docker or installer mutation", + async (providerId) => { + const selected = selection(); + const homeDir = temporaryHome(); + const pullImage = vi.fn(); + const acquireGguf = vi.fn(); + const verifyGguf = vi.fn(); + const checkPort = vi.fn(); + const runtimeProvider = createInMemoryRuntimeProviderBundle({ + providerId, + workloadProfile: TEST_WORKLOAD_PROFILE, + }); + + await expect( + installManagedLlamaCpp(selected, { + sandboxName: "spark-agent", + homeDir, + runtimeProvider, + pullImage: pullImage as never, + acquireGguf: acquireGguf as never, + verifyGguf: verifyGguf as never, + checkPort: checkPort as never, + log: vi.fn(), + }), + ).resolves.toEqual({ + ok: false, + reason: `Runtime provider '${providerId}' does not provide the host-local-inference capability required for llama-cpp: Unsupported by this in-memory contract fixture.`, + }); + + expect(pullImage).not.toHaveBeenCalled(); + expect(acquireGguf).not.toHaveBeenCalled(); + expect(verifyGguf).not.toHaveBeenCalled(); + expect(checkPort).not.toHaveBeenCalled(); + expect(fs.existsSync(managedLlamaCppStatePaths(homeDir).stateDir)).toBe(false); + }, + ); + it("rejects the real Podman provider before engine, acquisition, or state mutation", async () => { const selected = selection(); const homeDir = temporaryHome(); diff --git a/src/lib/inference/llama-cpp/managed-installer.ts b/src/lib/inference/llama-cpp/managed-installer.ts index 692e0d52ed8..1c47abaf9a5 100644 --- a/src/lib/inference/llama-cpp/managed-installer.ts +++ b/src/lib/inference/llama-cpp/managed-installer.ts @@ -7,6 +7,10 @@ import os from "node:os"; import path from "node:path"; import type { ContainerEngine } from "../../adapters/container-engine"; +import { + isPolicyAuthorityRefusalError, + PolicyAuthorityRefusalError, +} from "../../adapters/openshell/policy-authority"; import { checkPortAvailable } from "../../onboard/preflight"; import type { RuntimeProviderBundle } from "../../onboard/runtime-provider/contract"; import { createHostLocalCreateJournalStore } from "../../onboard/runtime-provider/host-local-create-journal"; @@ -60,6 +64,7 @@ export interface ManagedLlamaCppInstallOptions { readonly acquireGguf?: typeof acquireVerifiedLlamaCppGguf; readonly verifyGguf?: typeof verifyLlamaCppGgufCacheEntry; readonly checkPort?: typeof checkPortAvailable; + readonly revalidatePolicyRequirements?: (operation: string) => void; readonly log?: (message: string) => void; } @@ -79,6 +84,7 @@ export interface ManagedLlamaCppResumeOptions { readonly env?: NodeJS.ProcessEnv; readonly verifyGguf?: typeof verifyLlamaCppGgufCacheEntry; readonly checkPort?: typeof checkPortAvailable; + readonly revalidatePolicyRequirements?: (operation: string) => void; } export interface ManagedLlamaCppExactInspectionOptions { @@ -584,6 +590,7 @@ export async function installManagedLlamaCpp( { env }, ); engine = operation.engine; + options.revalidatePolicyRequirements?.("reserve the managed llama.cpp runtime"); const reservation = claimManagedLlamaCppOwner(paths, { schemaVersion: 1, sandboxName: options.sandboxName, @@ -670,6 +677,7 @@ export async function installManagedLlamaCpp( if (artifact === null) { throw new Error("Managed llama.cpp could not verify its exact GGUF artifact."); } + options.revalidatePolicyRequirements?.("activate the managed llama.cpp runtime"); loadOrCreateManagedLlamaCppApiKey(paths); const lifecycle = lifecycleFor({ selection, @@ -690,6 +698,7 @@ export async function installManagedLlamaCpp( let receipt = loadManagedLlamaCppReceipt(paths); if (receipt !== null) { + options.revalidatePolicyRequirements?.("resume the managed llama.cpp runtime"); receipt = lifecycle.resume(receipt); } else { const port = await checkPort(hostPort); @@ -698,9 +707,13 @@ export async function installManagedLlamaCpp( `Managed llama.cpp port ${String(hostPort)} is unavailable: ${port.reason}`, ); } + options.revalidatePolicyRequirements?.("start the managed llama.cpp runtime"); const transactionId = randomBytes(32).toString("hex"); receipt = lifecycle.start(createManagedLlamaCppReceiptWriter(paths, transactionId)); } + options.revalidatePolicyRequirements?.( + "report successful managed llama.cpp runtime activation", + ); const apiKey = loadOrCreateManagedLlamaCppApiKey(paths); env[LLAMA_CPP_CREDENTIAL_ENV] = apiKey; return { ok: true, apiKey, model: recipe.spec.model.servedName, receipt }; @@ -712,6 +725,12 @@ export async function installManagedLlamaCpp( ownerCreated, paths, }); + if (isPolicyAuthorityRefusalError(error)) { + if (rollbackError === null) throw error; + throw new PolicyAuthorityRefusalError( + `${reason} Fresh ownership rollback also failed: ${rollbackError}`, + ); + } return { ok: false, reason: @@ -745,6 +764,7 @@ export async function resumeManagedLlamaCppRuntime( "llama-cpp", { env }, ); + options.revalidatePolicyRequirements?.("inspect the managed llama.cpp runtime"); const engine = operation.engine; const verify = options.verifyGguf ?? verifyLlamaCppGgufCacheEntry; const checkPort = options.checkPort ?? checkPortAvailable; @@ -781,6 +801,7 @@ export async function resumeManagedLlamaCppRuntime( artifact, operation, }); + options.revalidatePolicyRequirements?.("recover the managed llama.cpp runtime"); if (pending.length === 1) { const recovery = lifecycle.recoverUnfinished( createManagedLlamaCppReceiptWriter(paths, pending[0]!.transactionId), @@ -795,12 +816,15 @@ export async function resumeManagedLlamaCppRuntime( if (!port.ok) { throw new Error(`Managed llama.cpp port ${String(hostPort)} is unavailable: ${port.reason}`); } + options.revalidatePolicyRequirements?.("start the managed llama.cpp runtime"); loadOrCreateManagedLlamaCppApiKey(paths); const transactionId = randomBytes(32).toString("hex"); lifecycle.start(createManagedLlamaCppReceiptWriter(paths, transactionId)); } else { + options.revalidatePolicyRequirements?.("resume the managed llama.cpp runtime"); lifecycle.resume(receipt); } + options.revalidatePolicyRequirements?.("report successful managed llama.cpp runtime recovery"); const apiKey = loadManagedLlamaCppApiKey(paths); if (apiKey === null) throw new Error("Managed llama.cpp API-key authority is missing."); env[LLAMA_CPP_CREDENTIAL_ENV] = apiKey; diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index d04c6c29ac3..c98430a8c82 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -26,10 +26,14 @@ const { clearNimContainerBeforeRetry, createNvidiaFeaturedModelSession, createRemoteModelValidator, + assertSelectionMutationAuthority, + credentialMutationGuardFor, + withCredentialMutationGuard, resolveCompatibleEndpointSelection, selectFeaturedModelAfterCredentialPrompt, }: typeof import("./onboard/setup-nim-selection") = require("./onboard/setup-nim-selection"); const setupNimFlow: typeof import("./onboard/setup-nim-flow") = require("./onboard/setup-nim-flow"); +const setupNimRoutedSelection: typeof import("./onboard/inference-providers/routed-selection") = require("./onboard/inference-providers/routed-selection"); const openrouterSelection: typeof import("./onboard/openrouter-selection") = require("./onboard/openrouter-selection"); const setupNimOllama: typeof import("./onboard/setup-nim-ollama") = require("./onboard/setup-nim-ollama"); const inferenceInputCapability = require("./onboard/inference-input-capability"); @@ -742,7 +746,8 @@ const { getGatewayReuseSnapshot, selectNamedGatewayForReuseIfNeeded } = const { refreshDockerDriverGatewayReuseState } = gatewayReuse.createDockerDriverGatewayReuseApplication({ gatewayName: () => GATEWAY_NAME, - getGatewayCompatContainerName: () => gatewayBinding.resolveGatewayCompatContainerName(GATEWAY_PORT), + getGatewayCompatContainerName: () => + gatewayBinding.resolveGatewayCompatContainerName(GATEWAY_PORT), isDockerDriverGatewayEnabled: isLinuxDockerDriverGatewayEnabled, resolveOpenShellGatewayBinary, getDockerDriverGatewayEnv, @@ -1668,7 +1673,6 @@ const createSandboxWithBaseImageResolution = sandboxCreateOrchestrationRuntime, ); - const { createSandbox, createSandboxWithTemporaryManagedRuntime } = agentOnboard.createHermesApiPortScopedSandboxEntryPoints({ createBaseImageResolutionContext: () => @@ -1823,64 +1827,6 @@ type RemoteProviderSelectionArgs = { recoverySessionId: string | null | undefined; }; -async function handleRoutedSelection( - state: SetupNimSelectionState, -): Promise { - const bp = loadBlueprintProfile("routed"); - if (!bp || bp.router?.enabled !== true) { - console.error(" Router is not enabled in nemoclaw-blueprint/blueprint.yaml."); - if (isNonInteractive()) process.exit(1); - return "retry-selection"; - } - - state.provider = bp.provider_name || "nvidia-router"; - state.model = bp.model; - const { HOST_GATEWAY_URL } = require("./inference/local"); - const routerEndpointUrl = bp.endpoint || ""; - state.endpointUrl = routerEndpointUrl; - if (routerEndpointUrl.match(/localhost|127\.0\.0\.1/)) { - const u = new URL(routerEndpointUrl); - state.endpointUrl = `${HOST_GATEWAY_URL}:${u.port}${u.pathname}`; - } - state.preferredInferenceApi = "openai-completions"; - state.assertRouteCompatible?.(); - - const routerCredentialEnv = - bp.router?.credential_env || bp.credential_env || DEFAULT_MODEL_ROUTER_CREDENTIAL_ENV; - state.credentialEnv = routerCredentialEnv; - const routedCredential = - hydrateCredentialEnv(routerCredentialEnv) || - normalizeCredentialValue(bp.credential_default || ""); - if (routedCredential) { - saveCredential(routerCredentialEnv, routedCredential); - } - providerKeyBridge.stageRouterProviderKeyBridge(routerCredentialEnv); - if (isNonInteractive()) { - if (!resolveProviderCredential(routerCredentialEnv)) { - console.error( - ` ${routerCredentialEnv} (or NEMOCLAW_PROVIDER_KEY) is required for Model Router in non-interactive mode.`, - ); - process.exit(1); - } - } else if (!resolveProviderCredential(routerCredentialEnv)) { - console.log(""); - console.log(" Model Router accepts NVIDIA API keys (nvapi-...)."); - console.log(" Get one at https://build.nvidia.com"); - console.log(""); - const routerCredentialResult = await credentialPrompt.ensureNamedCredential( - routerCredentialEnv, - "Model Router API key", - null, - ); - if (credentialPrompt.returningToProviderSelection(routerCredentialResult)) { - return "retry-selection"; - } - } - - console.log(` ✓ Using Model Router: ${state.provider} / ${state.model}`); - return "selected"; -} - async function handleNimLocalSelection( gpu: ReturnType, args: Pick< @@ -1954,12 +1900,18 @@ async function handleNimLocalSelection( console.error(" NGC API Key is required for Local NIM."); process.exit(1); } + assertSelectionMutationAuthority(state, "register the NIM container credential"); if (!nim.dockerLoginNgc(ngcKey)) { console.error(" Failed to login to NGC registry. Check your API key and try again."); console.log(""); ngcKey = await credentialPrompt.readValue(" NGC API Key: "); if (credentialPrompt.returningToProviderSelection(ngcKey)) return "retry-selection"; - if (!ngcKey || !nim.dockerLoginNgc(ngcKey)) { + if (!ngcKey) { + console.error(" NGC login failed. Cannot pull NIM images."); + process.exit(1); + } + assertSelectionMutationAuthority(state, "register the NIM container credential"); + if (!nim.dockerLoginNgc(ngcKey)) { console.error(" NGC login failed. Cannot pull NIM images."); process.exit(1); } @@ -1979,10 +1931,12 @@ async function handleNimLocalSelection( } console.log(` Pulling NIM image for ${catalogModel}...`); + assertSelectionMutationAuthority(state, "install the local NIM runtime"); nim.pullNimImage(catalogModel); console.log(" Starting NIM container..."); const nimContainerNameLocal = nim.containerName(GATEWAY_NAME); + assertSelectionMutationAuthority(state, "start the local NIM runtime"); state.nimContainer = nim.startNimContainerByName(nimContainerNameLocal, catalogModel, undefined, { ngcApiKey: ngcApiKey ?? undefined, }); @@ -2089,6 +2043,7 @@ async function handleRemoteProviderSelection( ); if (state.hermesAuthMethod === HERMES_AUTH_METHOD_API_KEY) { state.credentialEnv = HERMES_NOUS_API_KEY_CREDENTIAL_ENV; + assertSelectionMutationAuthority(state, "stage the Hermes provider credential"); stageNousApiKeyProviderEnv(); if (isNonInteractive()) { if (!resolveHermesNousApiKey()) { @@ -2096,6 +2051,7 @@ async function handleRemoteProviderSelection( process.exit(1); } } else { + assertSelectionMutationAuthority(state, "register the Hermes provider credential"); const hermesKeyResult = await ensureHermesNousApiKeyEnv(); if (credentialPrompt.returningToProviderSelection(hermesKeyResult)) { return "retry-selection"; @@ -2107,6 +2063,7 @@ async function handleRemoteProviderSelection( const recordedHermesToolGateways = sandboxName ? normalizeHermesToolGatewaySelections(registry.getSandbox(sandboxName)?.hermesToolGateways) : null; + assertSelectionMutationAuthority(state, "configure Hermes provider credentials"); state.hermesToolGateways = await setupHermesToolGateways( state.provider, state.hermesAuthMethod, @@ -2153,6 +2110,7 @@ async function handleRemoteProviderSelection( } hydrateCredentialEnv(state.credentialEnv); if (selected.key === "build") { + assertSelectionMutationAuthority(state, "stage the NVIDIA provider credential"); providerKeyBridge.stageBuildProviderKeyBridge(); let apiKeyNavigation: unknown = null; if (isNonInteractive()) { @@ -2166,6 +2124,7 @@ async function handleRemoteProviderSelection( state.skipHostInferenceSmoke = reuseGatewayCredential; state.reuseGatewayCredentialWithoutLocalKey = reuseGatewayCredential; } else { + assertSelectionMutationAuthority(state, "register the NVIDIA provider credential"); apiKeyNavigation = await ensureApiKey(); } state.model = await selectFeaturedModelAfterCredentialPrompt( @@ -2183,6 +2142,10 @@ async function handleRemoteProviderSelection( return "retry-selection"; } } else { + assertSelectionMutationAuthority( + state, + `stage inference provider ${JSON.stringify(state.provider)} credential`, + ); providerKeyBridge.stageRemoteProviderKeyBridge(state.credentialEnv); const _envModelRemote = (process.env.NEMOCLAW_MODEL || "").trim(); @@ -2209,6 +2172,10 @@ async function handleRemoteProviderSelection( compatibleNoAuth && (!isNonInteractive() || (process.env.NEMOCLAW_COMPATIBLE_AUTH_MODE || "").trim().toLowerCase() === "none"); + assertSelectionMutationAuthority( + state, + `register inference provider ${JSON.stringify(state.provider)} credential`, + ); const bedrockSelection = await bedrockRuntimeOnboard.selectBedrockRuntimeCustomAnthropic({ selectedKey: selected.key, endpointUrl: state.endpointUrl, @@ -2220,6 +2187,7 @@ async function handleRemoteProviderSelection( isNonInteractive, promptInputModel, replaceNamedCredential, + credentialMutationGuard: credentialMutationGuardFor(state), exitProcess: (code) => process.exit(code), error: (message) => console.error(message), log: (message) => console.log(message), @@ -2266,6 +2234,10 @@ async function handleRemoteProviderSelection( }, ); } else { + assertSelectionMutationAuthority( + state, + `register inference provider ${JSON.stringify(state.provider)} credential`, + ); const credentialResult = await credentialPrompt.ensureNamedCredential( selectedCredentialEnv, compatibleNoAuth @@ -2274,6 +2246,7 @@ async function handleRemoteProviderSelection( remoteConfig.helpUrl, openrouterSelection.credentialValidatorForProvider(selected.key), compatibleNoAuth, + credentialMutationGuardFor(state), ); if (credentialPrompt.returningToProviderSelection(credentialResult)) { return "retry-selection"; @@ -2379,11 +2352,11 @@ async function handleRemoteProviderSelection( state.credentialEnv, "Please choose a provider/model again.", remoteConfig.helpUrl, - { + withCredentialMutationGuard(state, { requireResponsesToolCalling: shouldRequireResponsesToolCalling(state.provider), skipResponsesProbe: shouldSkipResponsesProbe(state.provider), authMode: getProbeAuthMode(state.provider), - }, + }), ), }); if (buildValidation.retrySelection) return "retry-selection"; @@ -2439,7 +2412,18 @@ function getSetupNimDeps(): SetupNimDeps { installVllm: setupNimFlow.withServingPortGuard(vllmInference.installVllm, checkPortAvailable), handleVllmSelection, selectVllmModelFromEnv: vllmInference.selectVllmModelFromEnv, - handleRoutedSelection, + handleRoutedSelection: (state) => + setupNimRoutedSelection.handleRoutedSelection(state, { + modelRouter, + localInference, + urlUtils, + credentials, + hydrateCredentialEnv, + providerKeyBridge, + isNonInteractive, + exitProcess: (code): never => process.exit(code), + credentialPrompt, + }), coerceAgentInferenceApi: inferenceConfig.coerceAgentInferenceApi, resolveAgentInferenceApi: inferenceConfig.resolveAgentInferenceApi, ...reasoningMode.compatibleEndpointReasoningClearDeps, @@ -2623,6 +2607,7 @@ const { buildOrphanedSandboxRollbackMessage, ensureDashboardForward, ensureAgentDashboardForward, + ensureFinalizationAgentDashboardForward, ensureFinalizationDashboardForward, ensureAgentFixedForward, fetchGatewayAuthTokenFromSandbox, @@ -2810,7 +2795,9 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { collector: null, span: null, }; - let completed = false, preserveDeferredExitSession = false, preserveIncompleteSession = false; + let completed = false, + preserveDeferredExitSession = false, + preserveIncompleteSession = false; try { await portableRetirementEntry.run(async () => { const lockedRuntime = await resumeRuntime.prepare( @@ -2919,7 +2906,10 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { process.exit(1); } - registerIncompleteOnboardExitHandlerForSession(onboardSession, () => completed || preserveIncompleteSession); + registerIncompleteOnboardExitHandlerForSession( + onboardSession, + () => completed || preserveIncompleteSession, + ); const agent = await selectOnboardAgent({ agentFlag: opts.agent, session, @@ -3011,6 +3001,11 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { resumeHasResolvedGpuIntent: false, requestedGpuPassthrough: opts.gpu === true, }; + const policyAuthorityBindings = + sandboxCreateOrchestration.createOnboardPolicyAuthorityBindings( + sandboxCreateOrchestrationRuntime, + opts.policyTier, + ); const [preflightPhase, gatewayPhase]: readonly [ import("./onboard/machine/sequence-runner").OnboardSequencePhase, @@ -3050,10 +3045,10 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { }, getInitialGatewayReuseState: () => selectNamedGatewayForReuseIfNeeded(getGatewayReuseSnapshot()).gatewayReuseState, - assertGatewayReadiness: async () => { - await onboardPreflightGatewayAuthority.collectGatewayReadiness(); - }, + assertGatewayReadiness: () => + onboardPreflightGatewayAuthority.collectGatewayReadiness().then(() => undefined), gatewayName: GATEWAY_NAME, + bindPolicyAuthority: policyAuthorityBindings.bindPolicyAuthority, recreateSandbox: isRecreateSandbox, requiresBindMounts: effectiveHostMounts.length > 0, gatewayDeps: { @@ -3130,11 +3125,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { isRoutedInferenceProvider, providerExistsInGateway, replaceNamedCredential, - resumeManagedLlamaCppRuntime: (sandboxName) => - setupNimFlow.resumeManagedLlamaCppRuntime(sandboxName, { - gatewayPort: GATEWAY_PORT, - runtimeProvider: setupNimFlow.resolveCurrentRuntimeProviderBundle(), - }), + resumeManagedLlamaCppRuntime: setupNimFlow.bindManagedLlamaCppResume(GATEWAY_PORT), }, providerInference: { gatewayName: GATEWAY_NAME, @@ -3150,6 +3141,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { deps: { checkGatewayRouteCompatibility, preflightGatewayRouteDiscovery, + preflightPolicyRequirements: policyAuthorityBindings.preflightPolicyRequirements, getSandboxRecoveryAuthority: providerRecovery.getSandboxRecoveryAuthority, withGatewayRouteMutationLock: gatewayRouteMutationLock.withGatewayRouteMutationLock, normalizeHermesAuthMethod, @@ -3162,6 +3154,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { assertRouteCompatible, canProbeRoute, recoverySessionId, + revalidatePolicyRequirements, ) => setupNim( g, @@ -3173,9 +3166,16 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { assertRouteCompatible, canProbeRoute, recoverySessionId, + revalidatePolicyRequirements, ), setupInference, - resolveHostLocalInferenceStartupSelection: setupNimFlow.createHermesPortableOllamaInferenceResolver({ runtimeContext: lockedRuntime.portableRuntimeContext, credentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, getReservationSessionId: () => session?.sessionId, runGatewayOpenshell: runCoreGatewayOpenshell }), + resolveHostLocalInferenceStartupSelection: + setupNimFlow.createHermesPortableOllamaInferenceResolver({ + runtimeContext: lockedRuntime.portableRuntimeContext, + credentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, + getReservationSessionId: () => session?.sessionId, + runGatewayOpenshell: runCoreGatewayOpenshell, + }), startRecordedStep, recordStepComplete, recordStepRejected, @@ -3287,6 +3287,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { getRegistrySandboxMessagingAuthority: messagingChannelSetup.getRegistrySandboxMessagingAuthority, providerMatchesGatewayCredential, + preflightPolicyRequirements: policyAuthorityBindings.preflightPolicyRequirements, stageSandboxCredentialProviders, promptValidatedSandboxName, selectResourceProfileForSandbox: () => @@ -3308,7 +3309,6 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { hermesApiPortReservationScope, ...createArgs, ), - ), ), updateSandboxRegistry: (name, updates) => registry.updateSandbox(name, updates), @@ -3343,6 +3343,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { branchState: agent ? "agent_setup" : "openclaw", authoritativePolicyTier: opts.authoritativeResumeConfig === true ? (opts.policyTier ?? null) : undefined, + revalidatePolicyRequirements: policyAuthorityBindings.revalidatePolicyRequirements, agentSetupDeps: { handleAgentSetup: agentOnboard.handleAgentSetup, agentSetupContext: () => ({ @@ -3408,10 +3409,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { webSearchProvider: (config) => webSearchProviderForConfig(config), }, finalizationDeps: { - ensureAgentDashboardForward: (name, selectedAgent) => - selectedAgent - ? ensureAgentDashboardForward(name, selectedAgent) - : ensureFinalizationDashboardForward(name), + ensureAgentDashboardForward: ensureFinalizationAgentDashboardForward, setDefaultSandbox: registry.setDefault, verifyWebSearchInsideSandbox, toSessionUpdates: (updates) => @@ -3487,7 +3485,8 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { process.exitCode = completed ? 0 : 1; }); } catch (error) { - preserveDeferredExitSession = onboardSessionBootstrap.shouldPreserveIncompleteOnboardSession(error); + preserveDeferredExitSession = + onboardSessionBootstrap.shouldPreserveIncompleteOnboardSession(error); throw error; } finally { try { diff --git a/src/lib/onboard/agent-dashboard-forward.test.ts b/src/lib/onboard/agent-dashboard-forward.test.ts index 8c78fdbe1fc..9f2dd0cf37a 100644 --- a/src/lib/onboard/agent-dashboard-forward.test.ts +++ b/src/lib/onboard/agent-dashboard-forward.test.ts @@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import { PolicyAuthorityRefusalError } from "../adapters/openshell/policy-authority"; import { ensureAgentDashboardForward } from "./agent-dashboard-forward"; describe("ensureAgentDashboardForward", () => { @@ -158,6 +159,52 @@ describe("ensureAgentDashboardForward", () => { expect(process.env.CHAT_UI_URL).toBe("https://hermes.example.test:9120/ui"); }); + it("compensates primary and optional forwards when final authority is refused (#9833)", async () => { + const refusal = new PolicyAuthorityRefusalError("policy authority changed at finality"); + const revalidatePolicyAuthority = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw refusal; + }); + const compensateDashboardForward = vi.fn(); + const ensureDashboardForward = vi.fn( + ( + _sandboxName, + chatUiUrl = "", + options?: { + revalidatePolicyAuthority?: (operation: string) => void; + onForwardStarted?: (port: number) => void; + }, + ) => { + const port = Number(new URL(chatUiUrl).port); + options?.revalidatePolicyAuthority?.(`start dashboard forward ${String(port)}`); + options?.onForwardStarted?.(port); + return port; + }, + ); + + await expect( + ensureAgentDashboardForward({ + sandboxName: "hm", + agent: { + dashboard: { kind: "ui" }, + forwardPort: 18789, + forward_ports: [18789, 8642], + }, + ensureDashboardForward, + revalidatePolicyAuthority, + compensateDashboardForward, + }), + ).rejects.toBe(refusal); + + expect(ensureDashboardForward).toHaveBeenCalledTimes(2); + expect(compensateDashboardForward.mock.calls).toEqual([[8642], [18789]]); + expect(process.env.CHAT_UI_URL).toBeUndefined(); + }); + it("forwards an API-kind agent on the sandbox-owned primary port", async () => { const ensureDashboardForward = vi.fn((_sandboxName, chatUiUrl = "") => { return Number(new URL(chatUiUrl).port); diff --git a/src/lib/onboard/agent-dashboard-forward.ts b/src/lib/onboard/agent-dashboard-forward.ts index a22ea1774bc..7e7b4012ca0 100644 --- a/src/lib/onboard/agent-dashboard-forward.ts +++ b/src/lib/onboard/agent-dashboard-forward.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 { DASHBOARD_PORT, HERMES_OPENAI_API_PORT } from "../core/ports"; import { type DashboardRuntimeAgent, @@ -22,6 +23,8 @@ export type EnsureDashboardForward = ( options?: { preserveSandboxPorts?: Array; allowPortReallocation?: boolean; + revalidatePolicyAuthority?: (operation: string) => void; + onForwardStarted?: (port: number) => void; }, ) => number; @@ -40,6 +43,8 @@ export async function ensureAgentDashboardForward(options: { hermesApiPort?: number | null; preserveForwardPorts?: readonly (number | null | undefined)[]; beforeForwardPort?: (port: number) => Promise | void; + revalidatePolicyAuthority?: (operation: string) => void; + compensateDashboardForward?: (port: number) => void; warn?: (message: string) => void; }): Promise { const { @@ -51,75 +56,115 @@ export async function ensureAgentDashboardForward(options: { hermesApiPort, preserveForwardPorts = [], beforeForwardPort, + revalidatePolicyAuthority, + compensateDashboardForward, warn = (message: string) => console.warn(message), } = options; if (!shouldManageDashboardForAgent(agent)) { return 0; } + const previousChatUiUrl = process.env.CHAT_UI_URL; + const startedForwardPorts: number[] = []; + const recordStartedForward = (port: number): void => { + if (!startedForwardPorts.includes(port)) startedForwardPorts.push(port); + }; + const startedForwardCallback = + revalidatePolicyAuthority && compensateDashboardForward ? recordStartedForward : undefined; + const restoreChatUiUrl = (): void => { + if (previousChatUiUrl === undefined) delete process.env.CHAT_UI_URL; + else process.env.CHAT_UI_URL = previousChatUiUrl; + }; - // The manifest names the agent's default API port. This sandbox owns its own, - // so forward the allocated port instead of the sibling sandbox's default. - const resolveDeclaredPort = (port: number): number => - port === HERMES_OPENAI_API_PORT - ? (hermesApiPort ?? resolveOnboardHermesApiPort(sandboxName, { warn })) - : port; - const declaredPrimaryPort = getAgentPrimaryForwardPort(agent, DASHBOARD_PORT); - const usesFixedApiPort = agent.dashboard?.kind === "api"; - const agentDashboardPort = usesFixedApiPort - ? resolveDeclaredPort(declaredPrimaryPort) - : isValidForwardPort(controlUiPort) - ? controlUiPort - : declaredPrimaryPort; - const optionalDashboardPort = - usesFixedApiPort && agent.dashboardUi && isValidForwardPort(controlUiPort) - ? controlUiPort - : null; - const declaredPorts = getAgentDeclaredForwardPorts(agent) - .filter((port) => port !== declaredPrimaryPort || port === agentDashboardPort) - .map(resolveDeclaredPort); - const preservePorts = [ - ...new Set([ - agentDashboardPort, - ...declaredPorts, - optionalDashboardPort, - ...preserveForwardPorts, - ]), - ].filter(isValidForwardPort); - const requestedDashboardUrl = - !usesFixedApiPort && chatUiUrl - ? replaceUrlPort(chatUiUrl, agentDashboardPort) - : `http://127.0.0.1:${agentDashboardPort}`; - await beforeForwardPort?.(agentDashboardPort); - const actualAgentDashboardPort = ensureDashboardForward(sandboxName, requestedDashboardUrl, { - preserveSandboxPorts: preservePorts, - }); - if (!usesFixedApiPort) { - process.env.CHAT_UI_URL = replaceUrlPort(requestedDashboardUrl, actualAgentDashboardPort); - } + try { + // The manifest names the agent's default API port. This sandbox owns its own, + // so forward the allocated port instead of the sibling sandbox's default. + const resolveDeclaredPort = (port: number): number => + port === HERMES_OPENAI_API_PORT + ? (hermesApiPort ?? resolveOnboardHermesApiPort(sandboxName, { warn })) + : port; + const declaredPrimaryPort = getAgentPrimaryForwardPort(agent, DASHBOARD_PORT); + const usesFixedApiPort = agent.dashboard?.kind === "api"; + const agentDashboardPort = usesFixedApiPort + ? resolveDeclaredPort(declaredPrimaryPort) + : isValidForwardPort(controlUiPort) + ? controlUiPort + : declaredPrimaryPort; + const optionalDashboardPort = + usesFixedApiPort && agent.dashboardUi && isValidForwardPort(controlUiPort) + ? controlUiPort + : null; + const declaredPorts = getAgentDeclaredForwardPorts(agent) + .filter((port) => port !== declaredPrimaryPort || port === agentDashboardPort) + .map(resolveDeclaredPort); + const preservePorts = [ + ...new Set([ + agentDashboardPort, + ...declaredPorts, + optionalDashboardPort, + ...preserveForwardPorts, + ]), + ].filter(isValidForwardPort); + const requestedDashboardUrl = + !usesFixedApiPort && chatUiUrl + ? replaceUrlPort(chatUiUrl, agentDashboardPort) + : `http://127.0.0.1:${agentDashboardPort}`; + await beforeForwardPort?.(agentDashboardPort); + const actualAgentDashboardPort = ensureDashboardForward(sandboxName, requestedDashboardUrl, { + preserveSandboxPorts: preservePorts, + ...(startedForwardCallback ? { onForwardStarted: startedForwardCallback } : {}), + ...(revalidatePolicyAuthority ? { revalidatePolicyAuthority } : {}), + }); + if (!usesFixedApiPort) { + revalidatePolicyAuthority?.(`publish the dashboard URL for sandbox '${sandboxName}'`); + process.env.CHAT_UI_URL = replaceUrlPort(requestedDashboardUrl, actualAgentDashboardPort); + } - const portsToPreserve = [...new Set([...preservePorts, actualAgentDashboardPort])]; - for (const port of preservePorts) { - if (port === agentDashboardPort) continue; - try { - await beforeForwardPort?.(port); - const forwardUrl = - port === optionalDashboardPort && chatUiUrl - ? replaceUrlPort(chatUiUrl, port) - : `http://127.0.0.1:${port}`; - ensureDashboardForward(sandboxName, forwardUrl, { - preserveSandboxPorts: portsToPreserve, - allowPortReallocation: false, - }); - } catch (err) { - warn( - ` ! Could not start optional agent port forward ${port}: ${ - err instanceof Error ? err.message : String(err) - }`, - ); + const portsToPreserve = [...new Set([...preservePorts, actualAgentDashboardPort])]; + for (const port of preservePorts) { + if (port === agentDashboardPort) continue; + try { + await beforeForwardPort?.(port); + const forwardUrl = + port === optionalDashboardPort && chatUiUrl + ? replaceUrlPort(chatUiUrl, port) + : `http://127.0.0.1:${port}`; + ensureDashboardForward(sandboxName, forwardUrl, { + preserveSandboxPorts: portsToPreserve, + allowPortReallocation: false, + ...(startedForwardCallback ? { onForwardStarted: startedForwardCallback } : {}), + ...(revalidatePolicyAuthority ? { revalidatePolicyAuthority } : {}), + }); + } catch (err) { + if (isPolicyAuthorityRefusalError(err)) throw err; + warn( + ` ! Could not start optional agent port forward ${port}: ${ + err instanceof Error ? err.message : String(err) + }`, + ); + } } - } - return actualAgentDashboardPort; + revalidatePolicyAuthority?.( + `report successful dashboard forwarding for sandbox '${sandboxName}'`, + ); + return actualAgentDashboardPort; + } catch (error) { + if (isPolicyAuthorityRefusalError(error)) { + restoreChatUiUrl(); + for (const port of [...startedForwardPorts].reverse()) { + try { + compensateDashboardForward?.(port); + } catch (cleanupError) { + warn( + ` ! Could not stop dashboard forward ${String(port)} after policy authority refusal: ${ + cleanupError instanceof Error ? cleanupError.message : String(cleanupError) + }`, + ); + } + } + } + throw error; + } } export function replaceUrlPort(value: string, port: number): string { diff --git a/src/lib/onboard/agent-fixed-forward.test.ts b/src/lib/onboard/agent-fixed-forward.test.ts index 981561f1eaf..f7ab6acb477 100644 --- a/src/lib/onboard/agent-fixed-forward.test.ts +++ b/src/lib/onboard/agent-fixed-forward.test.ts @@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { ensureAgentFixedForward } from "./agent-fixed-forward"; +import { runDetachedForwardStartWithRetries } from "./forward-start"; vi.mock("./forward-start", () => ({ buildDetachedForwardStartSpawn: vi.fn(() => vi.fn()), @@ -54,4 +55,34 @@ describe("ensureAgentFixedForward", () => { suppressOutput: true, }); }); + + it("rechecks policy authority before each fixed-forward start (#9833)", () => { + const deps = makeDeps(() => ""); + const revalidatePolicyAuthority = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("policy authority changed"); + }); + vi.mocked(runDetachedForwardStartWithRetries).mockImplementationOnce((runSpawn) => { + runSpawn({ stdout: 1, stderr: 2 }); + return { ok: true, diagnostic: "", reason: "ok" }; + }); + + expect(() => + ensureAgentFixedForward( + deps, + "my-sandbox", + 18789, + "messaging webhook", + revalidatePolicyAuthority, + ), + ).toThrow("policy authority changed"); + + expect(deps.runOpenshell).toHaveBeenCalledWith( + ["forward", "stop", "18789", "my-sandbox"], + expect.anything(), + ); + expect(revalidatePolicyAuthority).toHaveBeenCalledTimes(2); + }); }); diff --git a/src/lib/onboard/agent-fixed-forward.ts b/src/lib/onboard/agent-fixed-forward.ts index b65d501e9f4..4fb70451ab6 100644 --- a/src/lib/onboard/agent-fixed-forward.ts +++ b/src/lib/onboard/agent-fixed-forward.ts @@ -24,6 +24,7 @@ export function ensureAgentFixedForward( sandboxName: string, port: number, label: string, + revalidatePolicyAuthority?: (operation: string) => void, ): boolean { const forwardTarget = String(port); const stopForwardForSandbox = (portToStop: string | number) => @@ -32,13 +33,23 @@ export function ensureAgentFixedForward( (args, opts) => deps.runCaptureOpenshell(args, opts), portToStop, sandboxName, + () => + revalidatePolicyAuthority?.( + `stop ${label} forward ${String(portToStop)} for sandbox '${sandboxName}'`, + ), ); stopForwardForSandbox(port); + const startForward = buildDetachedForwardStartSpawn( + deps.openshellArgv(["forward", "start", "--background", forwardTarget, sandboxName]), + ); const { ok, diagnostic } = runDetachedForwardStartWithRetries( - buildDetachedForwardStartSpawn( - deps.openshellArgv(["forward", "start", "--background", forwardTarget, sandboxName]), - ), + (stdio) => { + revalidatePolicyAuthority?.( + `start ${label} forward ${String(port)} for sandbox '${sandboxName}'`, + ); + return startForward(stdio); + }, () => deps.runCaptureOpenshell(["forward", "list"], { timeout: OPENSHELL_PROBE_TIMEOUT_MS }), { port, sandboxName }, () => { diff --git a/src/lib/onboard/bedrock-runtime.test.ts b/src/lib/onboard/bedrock-runtime.test.ts index 7e8fe7f327b..cad6c202701 100644 --- a/src/lib/onboard/bedrock-runtime.test.ts +++ b/src/lib/onboard/bedrock-runtime.test.ts @@ -145,6 +145,8 @@ describe("Bedrock Runtime onboarding helper", () => { "COMPATIBLE_ANTHROPIC_API_KEY", "Other Anthropic-compatible endpoint API key", null, + null, + undefined, ); expect(result).toEqual({ action: "selected", @@ -178,6 +180,8 @@ describe("Bedrock Runtime onboarding helper", () => { "COMPATIBLE_ANTHROPIC_API_KEY", "Other Anthropic-compatible endpoint API key", null, + null, + undefined, ); expect(promptInputModel).not.toHaveBeenCalled(); expect(result).toEqual({ action: "retry-selection" }); diff --git a/src/lib/onboard/bedrock-runtime.ts b/src/lib/onboard/bedrock-runtime.ts index 6b8c36a09c1..ee08c521e8a 100644 --- a/src/lib/onboard/bedrock-runtime.ts +++ b/src/lib/onboard/bedrock-runtime.ts @@ -80,7 +80,10 @@ export async function selectBedrockRuntimeCustomAnthropic( envName: string, label: string, helpUrl: string | null, + validator?: ((value: string) => string | null) | null, + revalidatePolicyRequirements?: (operation: string) => void, ) => Promise; + credentialMutationGuard?: (operation: string) => void; } & BedrockRuntimeDependencies, ): Promise< | { action: "not-bedrock" } @@ -104,6 +107,8 @@ export async function selectBedrockRuntimeCustomAnthropic( credentialEnv, `${options.label} API key`, options.helpUrl, + null, + options.credentialMutationGuard, ); if (credentialResult === options.backToSelection) { return { action: "retry-selection" }; diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index 593239e406d..6fd4059ce71 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -57,6 +57,7 @@ export type CreatedSandboxFinalizationOptions = { }; export type CreatedSandboxFinalizationDeps = { + revalidatePolicyAuthority?(operation: string): void; discoverFreshOpenClawImagePluginInstalls( sandboxName: string, ): OpenClawManagedExtensionDiscoveryResult; @@ -118,7 +119,10 @@ export interface CreatedSandboxCompletionOptions { readonly ensureForward: ( sandboxName: string, chatUiUrl: string, - options: { rollbackSandboxOnFailure: true }, + options: { + rollbackSandboxOnFailure: true; + revalidatePolicyAuthority?: (operation: string) => void; + }, ) => number; readonly getForwardPort: (chatUiUrl: string) => string; readonly resolveHermesState: (port: number) => HermesDashboardOnboardState; @@ -126,6 +130,7 @@ export interface CreatedSandboxCompletionOptions { state: HermesDashboardOnboardState, sandboxName: string, rollback: true, + revalidatePolicyAuthority?: (operation: string) => void, ) => void; }; readonly workload: Omit< @@ -232,9 +237,13 @@ export function completeOrdinaryOnboardSandboxCreation( readonly armCancelRollback: (sandboxName: string) => void; readonly dockerInfoFormat: Parameters[0]["dockerInfoFormat"]; readonly runCapture: Parameters[0]["runCapture"]; + readonly revalidatePolicyAuthority: (operation: string) => void; + readonly applyVmDnsMonkeypatch?: typeof applyOnboardVmDnsMonkeypatch; }, ): string { + deps.revalidatePolicyAuthority(`completing sandbox '${input.sandboxName}'`); restoreDefaultAfterRecreate(deps.setDefault, input.sandboxName, input.sandboxWasLiveDefault); + deps.revalidatePolicyAuthority(`starting DNS setup for sandbox '${input.sandboxName}'`); if (input.runtimeFields.openshellDriver === "kubernetes") { console.log(" Setting up sandbox DNS proxy..."); deps.runFile( @@ -242,11 +251,17 @@ export function completeOrdinaryOnboardSandboxCreation( [path.join(deps.scriptsDir, "setup-dns-proxy.sh"), deps.gatewayName, input.sandboxName], { ignoreError: true }, ); + deps.revalidatePolicyAuthority(`applying DNS settings for sandbox '${input.sandboxName}'`); } - applyOnboardVmDnsMonkeypatch(input.sandboxName, input.runtimeFields); + (deps.applyVmDnsMonkeypatch ?? applyOnboardVmDnsMonkeypatch)( + input.sandboxName, + input.runtimeFields, + { revalidatePolicyAuthority: deps.revalidatePolicyAuthority }, + ); for (const provider of input.messagingProviders) { if (!deps.providerExistsInGateway(provider)) printMessagingProviderMissing(provider); } + deps.revalidatePolicyAuthority(`reporting sandbox '${input.sandboxName}' creation success`); console.log(` ✓ Sandbox '${input.sandboxName}' created`); warnIfLandlockUnsupported(deps); if (!input.liveExists) deps.armCancelRollback(input.sandboxName); @@ -304,6 +319,10 @@ export function createCreatedSandboxCompletionActions( log: console.log, }, created.runtimePatch, + () => + deps.revalidatePolicyAuthority?.( + `committing GPU capability for sandbox '${options.finalization.sandboxName}'`, + ), ); } function recordHermesGpuProof(): void { @@ -313,18 +332,32 @@ export function createCreatedSandboxCompletionActions( } async function finalizeDashboard(): Promise { await options.dashboard.releasePort(); + deps.revalidatePolicyAuthority?.( + `configuring dashboard capability for sandbox '${options.finalization.sandboxName}'`, + ); dashboardPort = options.dashboard.ensureForward(options.finalization.sandboxName, chatUiUrl, { rollbackSandboxOnFailure: true, + revalidatePolicyAuthority: deps.revalidatePolicyAuthority, }); + deps.revalidatePolicyAuthority?.( + `configuring dashboard capability for sandbox '${options.finalization.sandboxName}'`, + ); if (dashboardPort !== Number(options.dashboard.getForwardPort(chatUiUrl))) { chatUiUrl = `http://127.0.0.1:${dashboardPort}`; } process.env.CHAT_UI_URL = chatUiUrl; hermesDashboardState = options.dashboard.resolveHermesState(dashboardPort); + deps.revalidatePolicyAuthority?.( + `configuring Hermes dashboard capability for sandbox '${options.finalization.sandboxName}'`, + ); options.dashboard.ensureHermesForward( hermesDashboardState, options.finalization.sandboxName, true, + deps.revalidatePolicyAuthority, + ); + deps.revalidatePolicyAuthority?.( + `recording Hermes dashboard capability for sandbox '${options.finalization.sandboxName}'`, ); } return { @@ -338,11 +371,22 @@ export function createCreatedSandboxCompletionActions( inferenceRouteReservation, ) => { if (providerGpuDisposition === "created") { + deps.revalidatePolicyAuthority?.( + `committing GPU capability for sandbox '${options.finalization.sandboxName}'`, + ); await verifyCreatedProviderGpu(created!); } else if (providerGpuDisposition === "hermes") { + deps.revalidatePolicyAuthority?.( + `recording GPU capability for sandbox '${options.finalization.sandboxName}'`, + ); recordHermesGpuProof(); } - if (manageDashboard) await finalizeDashboard(); + if (manageDashboard) { + deps.revalidatePolicyAuthority?.( + `configuring dashboard capability for sandbox '${options.finalization.sandboxName}'`, + ); + await finalizeDashboard(); + } const resolved = managedWorkloadOnboard.resolveOnboardSandboxWorkloadReceipt({ ...options.workload, registryImageRef: created?.registryImageRef ?? configuredReceipt?.container.imageId ?? null, @@ -425,8 +469,10 @@ type OnboardGatewayBinding = { }; type OnboardPreparedPolicy = Pick< managedWorkloadOnboard.PreparedOnboardSandboxWorkloadLaunch, - "initialSandboxPolicy" | "policyTier" | "dashboardRemoteBindPrepared" ->; + "initialSandboxPolicy" | "policyTier" | "policyAuthority" | "dashboardRemoteBindPrepared" +> & { + readonly revalidatePolicyAuthority: (operation: string) => void; +}; /** Assemble the exact post-Ready owners without adding an onboarding decision. */ export function createOnboardCreatedSandboxCompletion( @@ -493,7 +539,11 @@ export function createOnboardCreatedSandboxCompletion( agent, agentVersionKnown: !fromDockerfile, portableLifecycle, - appliedPolicies: preparedPolicy.initialSandboxPolicy.appliedPresets, + appliedPolicies: + preparedPolicy.policyAuthority === "externally-managed" + ? [] + : preparedPolicy.initialSandboxPolicy.appliedPresets, + policyAuthority: preparedPolicy.policyAuthority, toolDisclosure: policyRegistration.toolDisclosure, observabilityEnabled: createIntent?.observabilityEnabled === true, ...(agentFlags.isManagedDcodeAgent @@ -552,6 +602,7 @@ export function createOnboardCreatedSandboxCompletion( note, error: console.error, exitProcess: (code) => process.exit(code), + revalidatePolicyAuthority: preparedPolicy.revalidatePolicyAuthority, }, ); } @@ -584,6 +635,7 @@ export function finalizeCreatedSandbox( ? " Restoring workspace state from pre-upgrade backup..." : " Restoring workspace state from pre-recreate backup...", ); + deps.revalidatePolicyAuthority?.(`restoring files for sandbox '${options.sandboxName}'`); const restore = deps.restoreRecreatedSandboxState( options.sandboxName, options.restoreBackupPath, @@ -595,6 +647,9 @@ export function finalizeCreatedSandbox( : {}), }, ); + deps.revalidatePolicyAuthority?.( + `reporting restored state for sandbox '${options.sandboxName}'`, + ); if (restore.success) { deps.note( ` ✓ State restored (${restore.restoredDirs.length} directories, ${restore.restoredFiles.length} files)`, @@ -658,5 +713,6 @@ export function finalizeCreatedSandbox( } } + deps.revalidatePolicyAuthority?.(`registering sandbox '${options.sandboxName}'`); return deps.register(freshOpenClawImagePluginInstalls); } diff --git a/src/lib/onboard/credential-navigation.test.ts b/src/lib/onboard/credential-navigation.test.ts index 4921f4456e4..b1147fadb60 100644 --- a/src/lib/onboard/credential-navigation.test.ts +++ b/src/lib/onboard/credential-navigation.test.ts @@ -10,6 +10,8 @@ import { returningToProviderSelection, shouldReturnToProviderSelection, } from "./credential-navigation"; +import { handleRoutedSelection } from "./inference-providers/routed-selection"; +import type { SetupNimSelectionState } from "./setup-nim-selection"; describe("credential prompt navigation helpers", () => { it("treats both the shared back sentinel and credential back intents as provider-selection navigation", () => { @@ -74,4 +76,85 @@ describe("credential prompt navigation helpers", () => { vi.restoreAllMocks(); } }); + + it("rechecks policy authority after the credential prompt before persistence (#9833)", async () => { + const prompt = vi + .spyOn(credentials, "readCredentialPrompt") + .mockResolvedValue({ kind: "credential", value: "new-secret" }); + const saveCredential = vi.spyOn(credentials, "saveCredential"); + delete process.env.NEMOCLAW_TEST_POLICY_CREDENTIAL; + + await expect( + replaceNamedCredential({ + envName: "NEMOCLAW_TEST_POLICY_CREDENTIAL", + label: "Policy credential", + exitOnboardFromPrompt: () => process.exit(1), + revalidatePolicyRequirements: () => { + throw new Error("external policy authority must supply the selected route"); + }, + }), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(prompt).toHaveBeenCalledOnce(); + expect(saveCredential).not.toHaveBeenCalled(); + expect(process.env.NEMOCLAW_TEST_POLICY_CREDENTIAL).toBeUndefined(); + vi.restoreAllMocks(); + }); + + it.each(["configured", "bridged"] as const)( + "stops Model Router %s credential persistence when policy authority changes (#9833)", + async (source) => { + const saveCredential = vi.fn(); + const stageRouterProviderKeyBridge = vi.fn(); + const state = { + model: null, + provider: "", + endpointUrl: null, + credentialEnv: null, + hermesAuthMethod: null, + hermesToolGateways: [], + preferredInferenceApi: null, + nimContainer: null, + allowToolsIncompatible: false, + revalidatePolicyRequirements: () => { + throw new Error("external policy authority must supply the selected route"); + }, + } satisfies SetupNimSelectionState; + + await expect( + handleRoutedSelection(state, { + modelRouter: { + DEFAULT_MODEL_ROUTER_CREDENTIAL_ENV: "ROUTER_KEY", + loadBlueprintProfile: () => ({ + model: "router/model", + router: { enabled: true, credential_env: "ROUTER_KEY" }, + }), + }, + localInference: { HOST_GATEWAY_URL: "http://host.openshell.internal" }, + urlUtils: { isLoopbackHostname: () => false }, + credentials: { + normalizeCredentialValue: (value) => String(value ?? ""), + resolveProviderCredential: () => null, + saveCredential, + }, + hydrateCredentialEnv: () => (source === "configured" ? "configured-secret" : null), + providerKeyBridge: { + resolveRouterProviderKeyBridge: () => (source === "bridged" ? "bridged-secret" : null), + stageRouterProviderKeyBridge, + }, + isNonInteractive: () => true, + exitProcess: (code): never => { + throw new Error(`unexpected exit ${String(code)}`); + }, + credentialPrompt: { + ensureNamedCredential: vi.fn(), + returningToProviderSelection: () => false, + }, + }), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(saveCredential).not.toHaveBeenCalled(); + expect(stageRouterProviderKeyBridge).not.toHaveBeenCalled(); + }, + ); }); diff --git a/src/lib/onboard/credential-navigation.ts b/src/lib/onboard/credential-navigation.ts index b546df29034..df706d38f17 100644 --- a/src/lib/onboard/credential-navigation.ts +++ b/src/lib/onboard/credential-navigation.ts @@ -69,6 +69,7 @@ export async function replaceNamedCredential({ validator = null, allowEmpty = false, exitOnboardFromPrompt, + revalidatePolicyRequirements, }: { envName: string; label: string; @@ -76,6 +77,7 @@ export async function replaceNamedCredential({ validator?: ((value: string) => string | null) | null; allowEmpty?: boolean; exitOnboardFromPrompt: () => never; + revalidatePolicyRequirements?: (operation: string) => void; }): Promise { if (helpUrl) { console.log(""); @@ -96,6 +98,7 @@ export async function replaceNamedCredential({ console.error(validationError); continue; } + revalidatePolicyRequirements?.(`save ${label}`); credentials.saveCredential(envName, key); process.env[envName] = key; console.log(""); @@ -112,6 +115,7 @@ export async function ensureNamedCredential({ validator = null, allowEmpty = false, exitOnboardFromPrompt, + revalidatePolicyRequirements, }: { envName: string | null; label: string; @@ -119,6 +123,7 @@ export async function ensureNamedCredential({ validator?: ((value: string) => string | null) | null; allowEmpty?: boolean; exitOnboardFromPrompt: () => never; + revalidatePolicyRequirements?: (operation: string) => void; }): Promise { if (!envName) { console.error(` Missing credential target for ${label}.`); @@ -133,7 +138,15 @@ export async function ensureNamedCredential({ } console.error(validationError); } - return replaceNamedCredential({ envName, label, helpUrl, validator, allowEmpty, exitOnboardFromPrompt }); + return replaceNamedCredential({ + envName, + label, + helpUrl, + validator, + allowEmpty, + exitOnboardFromPrompt, + revalidatePolicyRequirements, + }); } export function createCredentialPromptHelpers(exitOnboardFromPrompt: () => never): { @@ -143,6 +156,7 @@ export function createCredentialPromptHelpers(exitOnboardFromPrompt: () => never label: string, helpUrl?: string | null, validator?: ((value: string) => string | null) | null, + revalidatePolicyRequirements?: (operation: string) => void, ) => Promise; ensureNamedCredential: ( envName: string | null, @@ -150,15 +164,45 @@ export function createCredentialPromptHelpers(exitOnboardFromPrompt: () => never helpUrl?: string | null, validator?: ((value: string) => string | null) | null, allowEmpty?: boolean, + revalidatePolicyRequirements?: (operation: string) => void, ) => Promise; shouldReturnToProviderSelection: (result: unknown) => boolean; returningToProviderSelection: (result: unknown) => result is BackNavigationResult; } { return { readValue: (question) => readCredentialValue(question, exitOnboardFromPrompt), - replaceNamedCredential: (envName, label, helpUrl = null, validator = null) => - replaceNamedCredential({ envName, label, helpUrl, validator, exitOnboardFromPrompt }), - ensureNamedCredential: (envName, label, helpUrl = null, validator = null, allowEmpty = false) => ensureNamedCredential({ envName, label, helpUrl, validator, allowEmpty, exitOnboardFromPrompt }), + replaceNamedCredential: ( + envName, + label, + helpUrl = null, + validator = null, + revalidatePolicyRequirements, + ) => + replaceNamedCredential({ + envName, + label, + helpUrl, + validator, + exitOnboardFromPrompt, + revalidatePolicyRequirements, + }), + ensureNamedCredential: ( + envName, + label, + helpUrl = null, + validator = null, + allowEmpty = false, + revalidatePolicyRequirements, + ) => + ensureNamedCredential({ + envName, + label, + helpUrl, + validator, + allowEmpty, + exitOnboardFromPrompt, + revalidatePolicyRequirements, + }), shouldReturnToProviderSelection: (result) => shouldReturnToProviderSelection(result, exitOnboardFromPrompt), returningToProviderSelection: (result) => diff --git a/src/lib/onboard/credential-provider-registration.test.ts b/src/lib/onboard/credential-provider-registration.test.ts index c3236ce907b..369e4a2ed44 100644 --- a/src/lib/onboard/credential-provider-registration.test.ts +++ b/src/lib/onboard/credential-provider-registration.test.ts @@ -14,6 +14,9 @@ import type { MessagingTokenDef } from "./messaging-prep"; const BRAVE_SECRET = "brv-resume-secret"; const DISCORD_SECRET = "discord-resume-secret"; +const refuseAuthorityChange = (): never => { + throw new Error("authority changed"); +}; const DISCORD_STATIC_PROFILE = { id: "discord-hermes-static-v1", @@ -103,9 +106,9 @@ describe("credential provider registration", () => { const runOpenshell = vi.fn((args: string[]) => args.includes("profile") && args.includes("export") ? { - status: 0, - stdout: JSON.stringify({ ...DISCORD_STATIC_PROFILE, endpoints }), - stderr: "", + status: 0, + stdout: JSON.stringify({ ...DISCORD_STATIC_PROFILE, endpoints }), + stderr: "", } : providerMetadata( "alpha-discord-bridge", @@ -154,11 +157,7 @@ describe("credential provider registration", () => { ], [ "provider get -g test-gateway alpha-discord-bridge", - providerMetadata( - "alpha-discord-bridge", - "discord-hermes-static-v1", - "DISCORD_BOT_TOKEN", - ), + providerMetadata("alpha-discord-bridge", "discord-hermes-static-v1", "DISCORD_BOT_TOKEN"), ], ]); const ambientProfileMismatch = { @@ -194,18 +193,14 @@ describe("credential provider registration", () => { const runOpenshell = vi.fn((args: string[]) => args.includes("profile") && args.includes("export") ? { - status: 0, - stdout: JSON.stringify({ - ...DISCORD_STATIC_PROFILE, - binaries: ["/usr/bin/curl"], - }), - stderr: "", + status: 0, + stdout: JSON.stringify({ + ...DISCORD_STATIC_PROFILE, + binaries: ["/usr/bin/curl"], + }), + stderr: "", } - : providerMetadata( - "alpha-discord-bridge", - "discord-hermes-static-v1", - "DISCORD_BOT_TOKEN", - ), + : providerMetadata("alpha-discord-bridge", "discord-hermes-static-v1", "DISCORD_BOT_TOKEN"), ); const deps = registrationDeps(runOpenshell, session); deps.root = process.cwd(); @@ -251,36 +246,35 @@ describe("credential provider registration", () => { ambientValue: "legacy-key", expectedMigrated: false, }, - ])("records migration according to the value sent when $condition", ({ - env, - ambientValue, - expectedMigrated, - }) => { - const session = { stagedCredentialProviders: [] } as unknown as Session; - const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); - const deps = registrationDeps(runOpenshell, session); - deps.getCredential = vi.fn(() => ambientValue); - deps.stagedLegacyValues = new Map([["COMPATIBLE_API_KEY", "legacy-key"]]); - deps.migratedLegacyKeys.add("COMPATIBLE_API_KEY"); - const registration = createCredentialProviderRegistration(deps); + ])( + "records migration according to the value sent when $condition", + ({ env, ambientValue, expectedMigrated }) => { + const session = { stagedCredentialProviders: [] } as unknown as Session; + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + const deps = registrationDeps(runOpenshell, session); + deps.getCredential = vi.fn(() => ambientValue); + deps.stagedLegacyValues = new Map([["COMPATIBLE_API_KEY", "legacy-key"]]); + deps.migratedLegacyKeys.add("COMPATIBLE_API_KEY"); + const registration = createCredentialProviderRegistration(deps); - const result = registration.upsertProvider( - "compatible-endpoint", - "openai", - "COMPATIBLE_API_KEY", - "https://inference.example.com/v1", - env, - "alternate-gateway", - ); + const result = registration.upsertProvider( + "compatible-endpoint", + "openai", + "COMPATIBLE_API_KEY", + "https://inference.example.com/v1", + env, + "alternate-gateway", + ); - expect(result).toEqual({ ok: true }); - expect(deps.migratedLegacyKeys.has("COMPATIBLE_API_KEY")).toBe(expectedMigrated); - expect(deps.persistMigratedLegacyKeys).toHaveBeenCalledOnce(); - expect(runOpenshell).toHaveBeenCalledWith( - expect.arrayContaining(["-g", "alternate-gateway"]), - expect.any(Object), - ); - }); + expect(result).toEqual({ ok: true }); + expect(deps.migratedLegacyKeys.has("COMPATIBLE_API_KEY")).toBe(expectedMigrated); + expect(deps.persistMigratedLegacyKeys).toHaveBeenCalledOnce(); + expect(runOpenshell).toHaveBeenCalledWith( + expect.arrayContaining(["-g", "alternate-gateway"]), + expect.any(Object), + ); + }, + ); it("does not record migration when provider registration fails", () => { const session = { stagedCredentialProviders: [] } as unknown as Session; @@ -651,53 +645,55 @@ describe("credential provider registration", () => { appProvider: providerMetadata("alpha-slack-app", "generic", "OTHER_SLACK_APP_TOKEN"), error: "An existing credential provider does not match the required binding.", }, - ])("rejects partial Slack credentials before mutation when $condition (#7718)", async ({ - appProvider, - error, - }) => { - const session = { - stagedCredentialProviders: ["alpha-slack-bridge", "alpha-slack-app"], - } as unknown as Session; - const missing = { status: 1, stdout: "", stderr: "not found" }; - const success = { status: 0, stdout: "", stderr: "" }; - const responses = new Map([ - ["provider get -g test-gateway alpha-slack-bridge", missing], - ["provider get -g test-gateway alpha-slack-app", appProvider], - ]); - const runOpenshell = vi.fn((args: string[]) => responses.get(args.join(" ")) ?? success); - const deps = registrationDeps(runOpenshell, session); - const registration = createCredentialProviderRegistration(deps); - const tokenDefs: MessagingTokenDef[] = [ - { - name: "alpha-slack-bridge", - envKey: "SLACK_BOT_TOKEN", - token: "xoxb-current-token", - }, - { - name: "alpha-slack-app", - envKey: "SLACK_APP_TOKEN", - token: null, - }, - ]; - - await expect( - registration.stageSandboxCredentialProviders( + ])( + "rejects partial Slack credentials before mutation when $condition (#7718)", + async ({ appProvider, error }) => { + const session = { + stagedCredentialProviders: ["alpha-slack-bridge", "alpha-slack-app"], + } as unknown as Session; + const missing = { status: 1, stdout: "", stderr: "not found" }; + const success = { status: 0, stdout: "", stderr: "" }; + const responses = new Map([ + ["provider get -g test-gateway alpha-slack-bridge", missing], + ["provider get -g test-gateway alpha-slack-app", appProvider], + ]); + const runOpenshell = vi.fn((args: string[]) => responses.get(args.join(" ")) ?? success); + const deps = registrationDeps(runOpenshell, session); + const registration = createCredentialProviderRegistration(deps); + const tokenDefs: MessagingTokenDef[] = [ { - ...sandboxInput(requiredBindings(tokenDefs)), - enabledChannels: ["slack"], + name: "alpha-slack-bridge", + envKey: "SLACK_BOT_TOKEN", + token: "xoxb-current-token", }, - async () => ({ messagingTokenDefs: tokenDefs }), - ), - ).rejects.toThrow(error); + { + name: "alpha-slack-app", + envKey: "SLACK_APP_TOKEN", + token: null, + }, + ]; - expect(session.stagedCredentialProviders).toEqual(["alpha-slack-bridge", "alpha-slack-app"]); - expect(deps.updateSession).not.toHaveBeenCalled(); - expect( - runOpenshell.mock.calls - .map(([args]) => args) - .filter((args) => args[0] === "provider" && (args[1] === "create" || args[1] === "update")), - ).toEqual([]); - }); + await expect( + registration.stageSandboxCredentialProviders( + { + ...sandboxInput(requiredBindings(tokenDefs)), + enabledChannels: ["slack"], + }, + async () => ({ messagingTokenDefs: tokenDefs }), + ), + ).rejects.toThrow(error); + + expect(session.stagedCredentialProviders).toEqual(["alpha-slack-bridge", "alpha-slack-app"]); + expect(deps.updateSession).not.toHaveBeenCalled(); + expect( + runOpenshell.mock.calls + .map(([args]) => args) + .filter( + (args) => args[0] === "provider" && (args[1] === "create" || args[1] === "update"), + ), + ).toEqual([]); + }, + ); it.each([ { @@ -724,33 +720,56 @@ describe("credential provider registration", () => { credentialEnv: "OTHER_DISCORD_TOKEN", }, }, - ])("rejects a credential plan with a different $mismatch before gateway mutation (#7701)", async ({ - required, - }) => { + ])( + "rejects a credential plan with a different $mismatch before gateway mutation (#7701)", + async ({ required }) => { + const session = { stagedCredentialProviders: [] } as unknown as Session; + const runOpenshell = vi.fn(); + const deps = registrationDeps(runOpenshell, session); + const registration = createCredentialProviderRegistration(deps); + const tokenDefs: MessagingTokenDef[] = [ + { + name: "alpha-discord-bridge", + envKey: "DISCORD_BOT_TOKEN", + token: DISCORD_SECRET, + }, + ]; + + await expect( + registration.stageSandboxCredentialProviders(sandboxInput([required]), async () => ({ + messagingTokenDefs: tokenDefs, + })), + ).rejects.toThrow("Credential provider plan does not match the required bindings."); + + expect(runOpenshell).not.toHaveBeenCalled(); + expect(deps.updateSession).not.toHaveBeenCalled(); + expect(session.stagedCredentialProviders).toEqual([]); + }, + ); + + it("rejects duplicate planned provider names before gateway mutation (#7701)", async () => { const session = { stagedCredentialProviders: [] } as unknown as Session; const runOpenshell = vi.fn(); const deps = registrationDeps(runOpenshell, session); const registration = createCredentialProviderRegistration(deps); - const tokenDefs: MessagingTokenDef[] = [ - { - name: "alpha-discord-bridge", - envKey: "DISCORD_BOT_TOKEN", - token: DISCORD_SECRET, - }, - ]; + const tokenDef: MessagingTokenDef = { + name: "alpha-discord-bridge", + envKey: "DISCORD_BOT_TOKEN", + token: DISCORD_SECRET, + }; await expect( - registration.stageSandboxCredentialProviders(sandboxInput([required]), async () => ({ - messagingTokenDefs: tokenDefs, - })), + registration.stageSandboxCredentialProviders( + sandboxInput(requiredBindings([tokenDef])), + async () => ({ messagingTokenDefs: [tokenDef, tokenDef] }), + ), ).rejects.toThrow("Credential provider plan does not match the required bindings."); expect(runOpenshell).not.toHaveBeenCalled(); expect(deps.updateSession).not.toHaveBeenCalled(); - expect(session.stagedCredentialProviders).toEqual([]); }); - it("rejects duplicate planned provider names before gateway mutation (#7701)", async () => { + it("refuses authority drift after credential-provider planning without side effects (#9833)", async () => { const session = { stagedCredentialProviders: [] } as unknown as Session; const runOpenshell = vi.fn(); const deps = registrationDeps(runOpenshell, session); @@ -760,15 +779,93 @@ describe("credential provider registration", () => { envKey: "DISCORD_BOT_TOKEN", token: DISCORD_SECRET, }; + const prepare = vi.fn(async () => ({ messagingTokenDefs: [tokenDef] })); await expect( registration.stageSandboxCredentialProviders( - sandboxInput(requiredBindings([tokenDef])), - async () => ({ messagingTokenDefs: [tokenDef, tokenDef] }), + { + ...sandboxInput(requiredBindings([tokenDef])), + revalidatePolicyRequirements: () => { + throw new Error("authority changed"); + }, + }, + prepare, ), - ).rejects.toThrow("Credential provider plan does not match the required bindings."); + ).rejects.toThrow("authority changed"); + expect(prepare).toHaveBeenCalledOnce(); expect(runOpenshell).not.toHaveBeenCalled(); expect(deps.updateSession).not.toHaveBeenCalled(); + expect(session.stagedCredentialProviders).toEqual([]); + }); + + it("stops provider registration when authority changes after the first provider (#9833)", async () => { + const session = { stagedCredentialProviders: [] } as unknown as Session; + const runOpenshell = vi.fn((args: string[]) => + args[1] === "get" + ? { status: 1, stdout: "", stderr: "not found" } + : { status: 0, stdout: "", stderr: "" }, + ); + const deps = registrationDeps(runOpenshell, session); + const registration = createCredentialProviderRegistration(deps); + const tokenDefs: MessagingTokenDef[] = [ + { name: "alpha-first", envKey: "FIRST_TOKEN", token: "first-secret" }, + { name: "alpha-second", envKey: "SECOND_TOKEN", token: "second-secret" }, + ]; + const revalidatePolicyRequirements = vi.fn((operation: string) => + operation === 'inspect or change provider "alpha-second"' + ? refuseAuthorityChange() + : undefined, + ); + + await expect( + registration.stageSandboxCredentialProviders( + { + ...sandboxInput(requiredBindings(tokenDefs)), + revalidatePolicyRequirements, + }, + async () => ({ messagingTokenDefs: tokenDefs }), + ), + ).rejects.toThrow("authority changed"); + + expect( + runOpenshell.mock.calls + .map(([args]) => args) + .filter((args) => args[0] === "provider" && args[1] === "create"), + ).toHaveLength(1); + expect(session.stagedCredentialProviders).toEqual([]); + }); + + it("rechecks before persisting migrated messaging credentials (#9833)", () => { + const session = { stagedCredentialProviders: [] } as unknown as Session; + const runOpenshell = vi.fn((args: string[]) => + args[1] === "get" + ? { status: 1, stdout: "", stderr: "not found" } + : { status: 0, stdout: "", stderr: "" }, + ); + const deps = registrationDeps(runOpenshell, session); + deps.stagedLegacyValues = new Map([["DISCORD_BOT_TOKEN", DISCORD_SECRET]]); + const registration = createCredentialProviderRegistration(deps); + const revalidatePolicyRequirements = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(refuseAuthorityChange); + + expect(() => + registration.upsertMessagingProviders( + [ + { + name: "alpha-discord-bridge", + envKey: "DISCORD_BOT_TOKEN", + token: DISCORD_SECRET, + }, + ], + { revalidatePolicyRequirements }, + ), + ).toThrow("authority changed"); + + expect(deps.migratedLegacyKeys).toEqual(new Set()); + expect(deps.persistMigratedLegacyKeys).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/onboard/credential-provider-registration.ts b/src/lib/onboard/credential-provider-registration.ts index 1feaef2dd4d..d054a4e4d52 100644 --- a/src/lib/onboard/credential-provider-registration.ts +++ b/src/lib/onboard/credential-provider-registration.ts @@ -19,6 +19,25 @@ export interface StageSandboxCredentialProvidersInput { webSearchConfig: WebSearchConfig | null; agent: Agent; requiredBindings: readonly CheckpointProviderBinding[]; + revalidatePolicyRequirements?(operation: string): void; +} + +export interface MessagingProviderRegistrationOptions { + replaceExisting?: boolean; + allowedSandboxes?: readonly string[]; + 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 = { @@ -46,21 +65,23 @@ function recordMigratedLegacyMessagingCredentials( tokenDefs: readonly MessagingTokenDef[], registeredProviderNames: readonly string[], deps: CredentialProviderRegistrationDeps, + revalidatePolicyRequirements?: (operation: string) => void, ): void { const registeredProviders = new Set(registeredProviderNames); - let mutated = false; + const migrations: Array<{ envKey: string; migrated: boolean }> = []; for (const def of tokenDefs) { if (!registeredProviders.has(def.name) || !def.token || !def.envKey) continue; const stagedValue = deps.stagedLegacyValues.get(def.envKey); if (stagedValue === undefined) continue; - if (def.token === stagedValue) { - deps.migratedLegacyKeys.add(def.envKey); - } else { - deps.migratedLegacyKeys.delete(def.envKey); - } - mutated = true; + migrations.push({ envKey: def.envKey, migrated: def.token === stagedValue }); } - if (mutated) deps.persistMigratedLegacyKeys(); + if (migrations.length === 0) return; + revalidatePolicyRequirements?.("record migrated messaging provider credentials"); + for (const migration of migrations) { + if (migration.migrated) deps.migratedLegacyKeys.add(migration.envKey); + else deps.migratedLegacyKeys.delete(migration.envKey); + } + deps.persistMigratedLegacyKeys(); } function setStagedCredentialProviderReceipts( @@ -148,6 +169,7 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg baseUrl: string | null, env: NodeJS.ProcessEnv = {}, gatewayName = deps.getGatewayName(), + options: MessagingProviderRegistrationOptions = {}, ) { const result = providers.upsertProvider( name, @@ -156,10 +178,14 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg baseUrl, env, gatewayRunner(gatewayName), + options, ); if (result.ok && credentialEnv) { const stagedValue = deps.stagedLegacyValues.get(credentialEnv); if (stagedValue !== undefined) { + options.revalidatePolicyRequirements?.( + `record migrated credential for provider ${JSON.stringify(name)}`, + ); const upsertedValue = env[credentialEnv] ?? deps.getCredential(credentialEnv); if (upsertedValue === stagedValue) { deps.migratedLegacyKeys.add(credentialEnv); @@ -174,16 +200,26 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg function upsertMessagingProviders( tokenDefs: MessagingTokenDef[], - options: { replaceExisting?: boolean; allowedSandboxes?: readonly string[] } = {}, + options: MessagingProviderRegistrationOptions = {}, runOpenshell: OpenshellCliHelpers["runOpenshell"] = deps.runOpenshell, ): string[] { - ensureWebSearchProviderProfiles(tokenDefs, runOpenshell); + const runWebSearchOpenshell = policyAuthorityCheckedRunner( + runOpenshell, + options.revalidatePolicyRequirements, + "import a web-search provider profile", + ); + ensureWebSearchProviderProfiles(tokenDefs, runWebSearchOpenshell); const upserted = providers.upsertMessagingProviders( tokenDefs, runOpenshell, options, ) as string[]; - recordMigratedLegacyMessagingCredentials(tokenDefs, upserted, deps); + recordMigratedLegacyMessagingCredentials( + tokenDefs, + upserted, + deps, + options.revalidatePolicyRequirements, + ); return upserted; } @@ -240,6 +276,7 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg prepareCredentialProviders: PrepareCredentialProviders, ): Promise { const messaging = await prepareCredentialProviders(input); + input.revalidatePolicyRequirements?.("stage sandbox credential providers after planning"); const plannedBindings = validatePlannedCredentialProviderBindings( messaging.messagingTokenDefs, input.requiredBindings, @@ -257,12 +294,18 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg plannedTokenDefs, runOpenshell, ); + input.revalidatePolicyRequirements?.("clear staged credential provider receipts"); setStagedCredentialProviderReceipts( tokenDefs.map((tokenDef) => tokenDef.name), false, deps, ); - const registered = upsertMessagingProviders(tokenDefs, {}, runOpenshell); + const registered = upsertMessagingProviders( + tokenDefs, + { revalidatePolicyRequirements: input.revalidatePolicyRequirements }, + runOpenshell, + ); + input.revalidatePolicyRequirements?.("record staged credential provider receipts"); setStagedCredentialProviderReceipts(registered, true, deps); return registered.map((name) => { const binding = plannedBindings.get(name); diff --git a/src/lib/onboard/dashboard-forward-control.test.ts b/src/lib/onboard/dashboard-forward-control.test.ts index 1c6081636b3..83b839c4d85 100644 --- a/src/lib/onboard/dashboard-forward-control.test.ts +++ b/src/lib/onboard/dashboard-forward-control.test.ts @@ -22,4 +22,23 @@ describe("createSandboxForwardStopper", () => { ); expect(runOpenshell).not.toHaveBeenCalled(); }); + + it("rechecks policy authority after the forward read and before stop (#9833)", () => { + const runOpenshell = vi.fn(); + const runCaptureOpenshell = vi.fn().mockReturnValue(""); + const revalidatePolicyAuthority = vi.fn(() => { + throw new Error("policy authority changed"); + }); + const stopForward = createSandboxForwardStopper({ + runOpenshell, + runCaptureOpenshell, + sandboxName: "my-sandbox", + revalidatePolicyAuthority, + }); + + expect(() => stopForward(18789)).toThrow("policy authority changed"); + expect(runCaptureOpenshell).toHaveBeenCalledOnce(); + expect(revalidatePolicyAuthority).toHaveBeenCalledOnce(); + expect(runOpenshell).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/onboard/dashboard-forward-control.ts b/src/lib/onboard/dashboard-forward-control.ts index 73a09ae1353..42fcc74bece 100644 --- a/src/lib/onboard/dashboard-forward-control.ts +++ b/src/lib/onboard/dashboard-forward-control.ts @@ -7,6 +7,8 @@ export interface DashboardForwardOptions { rollbackSandboxOnFailure?: boolean; preserveSandboxPorts?: Array; allowPortReallocation?: boolean; + revalidatePolicyAuthority?: (operation: string) => void; + onForwardStarted?: (port: number) => void; } export function normalizeDashboardForwardOptions(options: DashboardForwardOptions = {}): { @@ -25,6 +27,7 @@ export function createSandboxForwardStopper(deps: { runOpenshell: Parameters[0]; runCaptureOpenshell: (args: string[], opts?: Record) => string | null; sandboxName: string; + revalidatePolicyAuthority?: (operation: string) => void; }): (port: string | number) => ReturnType | null { const stoppedPorts = new Set(); return (port: string | number) => { @@ -35,6 +38,10 @@ export function createSandboxForwardStopper(deps: { (args, opts) => deps.runCaptureOpenshell(args, opts), port, deps.sandboxName, + () => + deps.revalidatePolicyAuthority?.( + `stop dashboard forward ${String(port)} for sandbox '${deps.sandboxName}'`, + ), ); if (result === "stopped" || result === "no-entry") { stoppedPorts.add(portKey); diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 7ed1fbaa35b..d8882aca6c6 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -5,6 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../adapters/openshell/timeouts"; +import { isPolicyAuthorityRefusalError } from "../adapters/openshell/policy-authority"; import type { AgentDefinition } from "../agent/defs"; import { getInteractiveAgentCommand } from "../agent/gateway-restart-scripts"; import { DASHBOARD_PORT } from "../core/ports"; @@ -33,7 +34,11 @@ import { isLiveForwardStatus, type ListSandboxesFn, } from "./dashboard-port"; -import { bestEffortForwardStop, waitForStoppedForwardPortRelease } from "./forward-cleanup"; +import { + bestEffortForwardStop, + bestEffortForwardStopForSandbox, + waitForStoppedForwardPortRelease, +} from "./forward-cleanup"; import { buildDetachedForwardStartSpawn, buildForwardStartProgressLogger, @@ -117,10 +122,26 @@ export interface OnboardDashboardHelpers { ensureAgentDashboardForward( sandboxName: string, agent: { forwardPort?: number | null; forward_ports?: number[] | null }, - options?: { beforeForwardPort?: (port: number) => Promise | void }, + options?: { + beforeForwardPort?: (port: number) => Promise | void; + revalidatePolicyAuthority?: (operation: string) => void; + }, ): Promise; - ensureFinalizationDashboardForward(sandboxName: string): number; - ensureAgentFixedForward(sandboxName: string, port: number, label: string): boolean; + ensureFinalizationDashboardForward( + sandboxName: string, + revalidatePolicyAuthority?: (operation: string) => void, + ): number; + ensureFinalizationAgentDashboardForward( + sandboxName: string, + agent: { forwardPort?: number | null; forward_ports?: number[] | null } | null, + revalidatePolicyAuthority?: (operation: string) => void, + ): Promise | number; + ensureAgentFixedForward( + sandboxName: string, + port: number, + label: string, + revalidatePolicyAuthority?: (operation: string) => void, + ): boolean; fetchGatewayAuthTokenFromSandbox(sandboxName: string): string | null; fetchAgentWebAuthTokenFromSandbox(sandboxName: string, agent: AgentDefinition): string | null; getDashboardForwardPort( @@ -294,7 +315,12 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa return lines; } - function rollbackSandboxAndExit(sandboxName: string, err: unknown): never { + function rollbackSandboxAndExit( + sandboxName: string, + err: unknown, + revalidatePolicyAuthority?: (operation: string) => void, + ): never { + revalidatePolicyAuthority?.(`remove sandbox '${sandboxName}' after dashboard failure`); const delResult = deps.runOpenshell(["sandbox", "delete", sandboxName], { ignoreError: true }); for (const line of buildOrphanedSandboxRollbackMessage( sandboxName, @@ -314,6 +340,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa chatUiUrl ||= `http://127.0.0.1:${CONTROL_UI_PORT}`; const { rollbackSandboxOnFailure, preservedPorts, allowPortReallocation } = normalizeDashboardForwardOptions(options); + const { revalidatePolicyAuthority } = options; const messagingForward = resolveMessagingHostForwardForSandbox(sandboxName); if (messagingForward) preservedPorts.add(String(messagingForward.port)); const preferredPort = Number(getDashboardForwardPort(chatUiUrl)); @@ -322,6 +349,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa runOpenshell: deps.runOpenshell, runCaptureOpenshell: deps.runCaptureOpenshell, sandboxName, + revalidatePolicyAuthority, }); const stopForwardForSandbox = makeStopForwardForSandbox(); let existingForwards = deps.runCaptureOpenshell(["forward", "list"], { ignoreError: true }); @@ -358,7 +386,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa ); } catch (err) { if (!rollbackSandboxOnFailure) throw err; - rollbackSandboxAndExit(sandboxName, err); + rollbackSandboxAndExit(sandboxName, err, revalidatePolicyAuthority); } if (actualPort !== preferredPort) { @@ -374,7 +402,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa `CHAT_UI_URL=${preferredPort}. Free the port and re-run \`${deps.cliName()} onboard\`, ` + `or pass \`--control-ui-port \` to pick a different dashboard port.`, ); - rollbackSandboxAndExit(sandboxName, err); + rollbackSandboxAndExit(sandboxName, err, revalidatePolicyAuthority); } console.warn(` ! Port ${preferredPort} is taken. Using port ${actualPort} instead.`); } @@ -390,10 +418,16 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa parsedUrl.port = String(actualPort); const actualTarget = getDashboardForwardTarget(parsedUrl.toString()); stopForwardForSandbox(actualPort); + const startDashboardForward = buildDetachedForwardStartSpawn( + deps.openshellArgv(["forward", "start", "--background", actualTarget, sandboxName]), + ); const { ok: fwdOk, diagnostic: fwdDiagnostic } = runDetachedForwardStartWithRetries( - buildDetachedForwardStartSpawn( - deps.openshellArgv(["forward", "start", "--background", actualTarget, sandboxName]), - ), + (stdio) => { + revalidatePolicyAuthority?.( + `start dashboard forward ${String(actualPort)} for sandbox '${sandboxName}'`, + ); + return startDashboardForward(stdio); + }, () => deps.runCaptureOpenshell(["forward", "list"], { timeout: OPENSHELL_PROBE_TIMEOUT_MS }), { port: actualPort, sandboxName }, () => { @@ -415,7 +449,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa `or pass \`--control-ui-port \` to pick a different dashboard port.` : `Failed to start dashboard forward on port ${actualPort}: ${fwdDiagnostic.slice(0, 240)}`, ); - rollbackSandboxAndExit(sandboxName, err); + rollbackSandboxAndExit(sandboxName, err, revalidatePolicyAuthority); } if (looksLikePortConflict) { console.warn( @@ -432,16 +466,19 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa ); } } + if (fwdOk) options.onForwardStarted?.(actualPort); if (fwdOk && rollbackSandboxOnFailure) { ensureMessagingHostForwardForSandbox({ sandboxName, - ensureForward: ensureAgentFixedForward, + ensureForward: (name, port, label) => + ensureFixedAgentForward(deps, name, port, label, revalidatePolicyAuthority), note: deps.note, rollbackOnFailure: { runOpenshell: deps.runOpenshell, buildRollbackMessage: buildOrphanedSandboxRollbackMessage, cliName: deps.cliName, forwardPortsToStop: [actualPort], + beforeMutation: revalidatePolicyAuthority, }, }); } @@ -461,27 +498,55 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa * `CHAT_UI_URL`, so after the forward starts this writes the bound port to * `CHAT_UI_URL`. (#8970) */ - function ensureFinalizationDashboardForward(sandboxName: string): number { + function ensureFinalizationDashboardForward( + sandboxName: string, + revalidatePolicyAuthority?: (operation: string) => void, + ): number { const envUrl = process.env.CHAT_UI_URL; - const persistedPort = envUrl ? null : getPersistedDashboardPort(sandboxName, deps.listSandboxes); + const persistedPort = envUrl + ? null + : getPersistedDashboardPort(sandboxName, deps.listSandboxes); const requestedUrl = envUrl || (persistedPort === null ? undefined : `http://127.0.0.1:${String(persistedPort)}`); - const actualPort = ensureDashboardForward( - sandboxName, - requestedUrl, - persistedPort === null ? {} : { allowPortReallocation: false }, - ); - process.env.CHAT_UI_URL = replaceUrlPort( - requestedUrl || `http://127.0.0.1:${String(actualPort)}`, - actualPort, - ); - return actualPort; + let startedPort: number | null = null; + try { + const actualPort = ensureDashboardForward(sandboxName, requestedUrl, { + ...(persistedPort === null ? {} : { allowPortReallocation: false }), + ...(revalidatePolicyAuthority ? { revalidatePolicyAuthority } : {}), + onForwardStarted: (port) => { + startedPort = port; + }, + }); + revalidatePolicyAuthority?.(`publish the dashboard URL for sandbox '${sandboxName}'`); + process.env.CHAT_UI_URL = replaceUrlPort( + requestedUrl || `http://127.0.0.1:${String(actualPort)}`, + actualPort, + ); + return actualPort; + } catch (error) { + if (isPolicyAuthorityRefusalError(error) && startedPort !== null) { + try { + bestEffortForwardStopForSandbox( + deps.runOpenshell, + (args, options) => deps.runCaptureOpenshell(args, options), + startedPort, + sandboxName, + ); + } catch { + // Compensation is best effort and must not replace the typed refusal. + } + } + throw error; + } } function ensureAgentDashboardForward( sandboxName: string, agent: { forwardPort?: number | null; forward_ports?: number[] | null }, - options: { beforeForwardPort?: (port: number) => Promise | void } = {}, + options: { + beforeForwardPort?: (port: number) => Promise | void; + revalidatePolicyAuthority?: (operation: string) => void; + } = {}, ): Promise { const chatUiUrl = process.env.CHAT_UI_URL; return ensureAgentDashboardForwardForAgent({ @@ -491,11 +556,35 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa chatUiUrl, controlUiPort: chatUiUrl ? Number(getDashboardForwardPort(chatUiUrl)) : undefined, beforeForwardPort: options.beforeForwardPort, + revalidatePolicyAuthority: options.revalidatePolicyAuthority, + compensateDashboardForward: (port) => { + bestEffortForwardStopForSandbox( + deps.runOpenshell, + (args, captureOptions) => deps.runCaptureOpenshell(args, captureOptions), + port, + sandboxName, + ); + }, }); } - function ensureAgentFixedForward(sandboxName: string, port: number, label: string): boolean { - return ensureFixedAgentForward(deps, sandboxName, port, label); + function ensureFinalizationAgentDashboardForward( + sandboxName: string, + agent: { forwardPort?: number | null; forward_ports?: number[] | null } | null, + revalidatePolicyAuthority?: (operation: string) => void, + ): Promise | number { + return agent + ? ensureAgentDashboardForward(sandboxName, agent, { revalidatePolicyAuthority }) + : ensureFinalizationDashboardForward(sandboxName, revalidatePolicyAuthority); + } + + function ensureAgentFixedForward( + sandboxName: string, + port: number, + label: string, + revalidatePolicyAuthority?: (operation: string) => void, + ): boolean { + return ensureFixedAgentForward(deps, sandboxName, port, label, revalidatePolicyAuthority); } /** @@ -677,6 +766,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa buildOrphanedSandboxRollbackMessage, ensureDashboardForward, ensureAgentDashboardForward, + ensureFinalizationAgentDashboardForward, ensureFinalizationDashboardForward, ensureAgentFixedForward, fetchGatewayAuthTokenFromSandbox, diff --git a/src/lib/onboard/docker-gpu-local-inference.test.ts b/src/lib/onboard/docker-gpu-local-inference.test.ts index 6ed6f3a5a7c..8e8f8dc10f4 100644 --- a/src/lib/onboard/docker-gpu-local-inference.test.ts +++ b/src/lib/onboard/docker-gpu-local-inference.test.ts @@ -449,6 +449,31 @@ describe("verifyGpuSandboxLocalInferenceAndCommitAfterReady", () => { ).rejects.toThrow("durable commit acknowledgement failed"); expect(runtimePatch.rollbackManagedStartupAfterCreateFailure).not.toHaveBeenCalled(); }); + + it("rechecks policy authority after verification and before GPU commit (#9833)", async () => { + const runtimePatch = { + commitAfterReady: vi.fn(), + rollbackManagedStartupAfterCreateFailure: vi.fn(), + }; + + await expect( + verifyGpuSandboxLocalInferenceAndCommitAfterReady( + GPU_CONFIG, + "ollama-local", + { + ...options(), + deps: { execInSandbox: execEmitting("HTTP_200"), sleep: vi.fn() }, + }, + runtimePatch, + () => { + throw new Error("policy authority changed"); + }, + ), + ).rejects.toThrow("policy authority changed"); + + expect(runtimePatch.commitAfterReady).not.toHaveBeenCalled(); + expect(runtimePatch.rollbackManagedStartupAfterCreateFailure).toHaveBeenCalledOnce(); + }); }); describe("printDockerGpuSandboxInferenceVerificationFailure", () => { diff --git a/src/lib/onboard/docker-gpu-local-inference.ts b/src/lib/onboard/docker-gpu-local-inference.ts index a51ad8aa213..051c5013a48 100644 --- a/src/lib/onboard/docker-gpu-local-inference.ts +++ b/src/lib/onboard/docker-gpu-local-inference.ts @@ -512,9 +512,11 @@ export async function verifyGpuSandboxLocalInferenceAndCommitAfterReady( ManagedBootstrapRuntimePatch, "commitAfterReady" | "rollbackManagedStartupAfterCreateFailure" >, + revalidateBeforeCommit?: () => void, ): Promise { try { verifyGpuSandboxLocalInferenceAfterReady(config, provider, options); + revalidateBeforeCommit?.(); } catch (error) { const failure = error instanceof Error ? error : new Error(String(error)); try { diff --git a/src/lib/onboard/experimental/hermes-portable-onboarding.test.ts b/src/lib/onboard/experimental/hermes-portable-onboarding.test.ts index ed904d8e6d5..25531921c27 100644 --- a/src/lib/onboard/experimental/hermes-portable-onboarding.test.ts +++ b/src/lib/onboard/experimental/hermes-portable-onboarding.test.ts @@ -803,9 +803,11 @@ describe("Hermes portable onboarding transaction", () => { const run = createHermesPortableReadyRunner("alpha", "nemoclaw", capture); expect(run(["sandbox", "get", "alpha"]).status).toBe(0); + expect(run(["sandbox", "delete", "alpha"]).status).toBe(0); expect(run(["sandbox", "exec", "--name", "alpha", "--", "true"]).status).toBe(0); expect(capture.mock.calls).toEqual([ [["sandbox", "get", "-g", "nemoclaw", "alpha"]], + [["sandbox", "delete", "-g", "nemoclaw", "alpha"]], [["sandbox", "exec", "-g", "nemoclaw", "--name", "alpha", "--", "true"]], ]); expect(() => run(["sandbox", "get", "beta"])).toThrow("unsupported OpenShell command"); diff --git a/src/lib/onboard/experimental/hermes-portable-onboarding.ts b/src/lib/onboard/experimental/hermes-portable-onboarding.ts index f73b80b52c6..452d96e72bd 100644 --- a/src/lib/onboard/experimental/hermes-portable-onboarding.ts +++ b/src/lib/onboard/experimental/hermes-portable-onboarding.ts @@ -230,7 +230,7 @@ export function createHermesPortableReadyCapture( }; } -/** Route every generic create-readiness command through exact schema-5 authority. */ +/** Route create readiness and failed-create cleanup through exact schema-5 authority. */ export function createHermesPortableReadyRunner( sandboxName: string, gatewayName: string, @@ -242,16 +242,21 @@ export function createHermesPortableReadyRunner( ? ["sandbox", "list", "-g", gatewayName] : args[0] === "sandbox" && args[1] === "get" && args.length === 3 && args[2] === sandboxName ? ["sandbox", "get", "-g", gatewayName, args[2]!] - : args.length === 6 && - args[0] === "sandbox" && - args[1] === "exec" && - args[2] === "--name" && - args[3] === sandboxName && - args[4] === "--" && - args[5] === "true" - ? ["sandbox", "exec", "-g", gatewayName, "--name", args[3]!, "--", "true"] - : null; - if (!scoped) fail("create readiness attempted an unsupported OpenShell command"); + : args[0] === "sandbox" && + args[1] === "delete" && + args.length === 3 && + args[2] === sandboxName + ? ["sandbox", "delete", "-g", gatewayName, args[2]!] + : args.length === 6 && + args[0] === "sandbox" && + args[1] === "exec" && + args[2] === "--name" && + args[3] === sandboxName && + args[4] === "--" && + args[5] === "true" + ? ["sandbox", "exec", "-g", gatewayName, "--name", args[3]!, "--", "true"] + : null; + if (!scoped) fail("create lifecycle attempted an unsupported OpenShell command"); return capture(scoped); }; } diff --git a/src/lib/onboard/forward-cleanup.ts b/src/lib/onboard/forward-cleanup.ts index 423ce4ef92c..b7ecec54bbc 100644 --- a/src/lib/onboard/forward-cleanup.ts +++ b/src/lib/onboard/forward-cleanup.ts @@ -48,10 +48,7 @@ export function waitForStoppedForwardPortRelease( } /** Poll a forward ownership/readiness condition within its configured recovery budget. */ -export function waitForForwardRecoveryState( - condition: () => boolean, - budgetMs: number, -): boolean { +export function waitForForwardRecoveryState(condition: () => boolean, budgetMs: number): boolean { return waitUntil(condition, { deadlineMs: Date.now() + budgetMs, initialIntervalMs: FORWARD_RECOVERY_INITIAL_POLL_MS, @@ -108,6 +105,7 @@ export function bestEffortForwardStopForSandbox( runCaptureOpenshell: ForwardListRunner, port: string | number, sandboxName: string, + beforeStop?: () => void, ): "stopped" | "owned-other" | "no-entry" | "list-failed" { // A runner reports failure either by throwing or by returning null; both // mean "list-failed" here. Do not pass either result to getOccupiedPorts, @@ -131,6 +129,7 @@ export function bestEffortForwardStopForSandbox( if (owner && owner !== sandboxName) { return "owned-other"; } + beforeStop?.(); runOpenshell(["forward", "stop", String(port), sandboxName], { ignoreError: true, suppressOutput: true, diff --git a/src/lib/onboard/gateway-teardown-authority.test.ts b/src/lib/onboard/gateway-teardown-authority.test.ts index 564c56ec606..9a2364c6976 100644 --- a/src/lib/onboard/gateway-teardown-authority.test.ts +++ b/src/lib/onboard/gateway-teardown-authority.test.ts @@ -1,13 +1,19 @@ // 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 { describe, expect, it } from "vitest"; import { createSession } from "../state/onboard-session"; +import { nemoclawStateRoot } from "../state/state-root"; import { bindGatewayAuthorityToCheckpoint } from "./gateway-authority-checkpoint"; import type { GatewayManagementDeclaration } from "./gateway-management"; import { type GatewayOwner, resolveGatewayOwner } from "./gateway-ownership"; import { + GatewayAuthorityError, resolveGatewayCredentialMutationAuthority, resolveGatewayRebuildAuthority, resolveGatewayTeardownAuthority, @@ -15,6 +21,18 @@ import { const target = { gatewayName: "nemoclaw", gatewayPort: 8080 }; +function targetSessionFile(homeDir: string): string { + const stateDir = nemoclawStateRoot(homeDir, target.gatewayPort); + return path.join(stateDir, "onboard-session.json"); +} + +function writeTargetSession(homeDir: string, content: string): void { + const sessionFile = targetSessionFile(homeDir); + const stateDir = path.dirname(sessionFile); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync(sessionFile, content, { mode: 0o600 }); +} + function declaration( kind: "systemd-system" | "systemd-user" = "systemd-system", ): GatewayManagementDeclaration { @@ -55,25 +73,25 @@ function checkpointSession(recordedOwner: GatewayOwner) { } describe("resolveGatewayTeardownAuthority", () => { - it.each([ - "systemd-system", - "systemd-user", - ] as const)("returns the exact recorded %s authority when the declaration still matches (#6576)", (kind) => { - const currentDeclaration = declaration(kind); - const recordedOwner = owner(currentDeclaration); - - expect( - resolveGatewayTeardownAuthority(target, { - hasPackagedService: () => false, - loadDeclaration: () => ({ - ok: true, - declaration: currentDeclaration, - source: "profile", + it.each(["systemd-system", "systemd-user"] as const)( + "returns the exact recorded %s authority when the declaration still matches (#6576)", + (kind) => { + const currentDeclaration = declaration(kind); + const recordedOwner = owner(currentDeclaration); + + expect( + resolveGatewayTeardownAuthority(target, { + hasPackagedService: () => false, + loadDeclaration: () => ({ + ok: true, + declaration: currentDeclaration, + source: "profile", + }), + loadSession: () => checkpointSession(recordedOwner), }), - loadSession: () => checkpointSession(recordedOwner), - }), - ).toEqual(recordedOwner); - }); + ).toEqual(recordedOwner); + }, + ); it("uses the current external declaration when no checkpoint exists (#6576)", () => { const currentDeclaration = declaration(); @@ -93,6 +111,87 @@ describe("resolveGatewayTeardownAuthority", () => { ).toBe("externally-supervised"); }); + it("uses persisted gateway authority even when the unrelated policy authority is malformed (#9833)", () => { + const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-teardown-authority-")); + const currentDeclaration = declaration(); + const recordedOwner = owner(currentDeclaration); + const session = { + ...checkpointSession(recordedOwner), + policyAuthority: "global", + }; + writeTargetSession(homeDir, JSON.stringify(session)); + + try { + expect( + resolveGatewayTeardownAuthority(target, { + env: { HOME: homeDir }, + hasPackagedService: () => false, + loadDeclaration: () => ({ + ok: true, + declaration: currentDeclaration, + source: "profile", + }), + }), + ).toEqual(recordedOwner); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } + }); + + it("does not adopt a different current owner when policy authority is malformed (#9833)", () => { + const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-teardown-authority-")); + const recordedOwner = owner(declaration("systemd-system")); + const session = { + ...checkpointSession(recordedOwner), + policyAuthority: "global", + }; + writeTargetSession(homeDir, JSON.stringify(session)); + + try { + expect(() => + resolveGatewayTeardownAuthority(target, { + env: { HOME: homeDir }, + hasPackagedService: () => false, + loadDeclaration: () => ({ + ok: true, + declaration: declaration("systemd-user"), + source: "profile", + }), + }), + ).toThrow(/authority changed since onboarding.*teardown will not perform gateway effects/); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } + }); + + it("fails closed without disclosing the state path when persisted authority is malformed (#9833)", () => { + const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-teardown-authority-")); + writeTargetSession(homeDir, "{"); + + try { + let refusal: unknown; + try { + resolveGatewayTeardownAuthority(target, { + env: { HOME: homeDir }, + hasPackagedService: () => false, + loadDeclaration: () => ({ + ok: true, + declaration: declaration("systemd-user"), + source: "profile", + }), + }); + } catch (error) { + refusal = error; + } + expect(refusal).toBeInstanceOf(GatewayAuthorityError); + expect((refusal as Error).message).toMatch(/unreadable or is not valid JSON/); + expect((refusal as Error).message).toContain("fresh onboarding run"); + expect((refusal as Error).message).not.toContain(homeDir); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } + }); + it("does not inspect the default packaged service for a custom gateway port (#6903)", () => { const customTarget = { gatewayName: "nemoclaw-9123", gatewayPort: 9123 }; diff --git a/src/lib/onboard/gateway-teardown-authority.ts b/src/lib/onboard/gateway-teardown-authority.ts index 2f1e07e1eb2..3bc9ed1d940 100644 --- a/src/lib/onboard/gateway-teardown-authority.ts +++ b/src/lib/onboard/gateway-teardown-authority.ts @@ -13,8 +13,10 @@ import fs from "node:fs"; import path from "node:path"; +import { isErrnoException } from "../core/errno"; import { DEFAULT_GATEWAY_PORT } from "../core/ports"; -import { normalizeSession, type Session } from "../state/onboard-session"; +import { inspectCheckpoint } from "../state/onboard-checkpoint"; +import type { Session } from "../state/onboard-session"; import { nemoclawStateRoot, resolveHome } from "../state/state-root"; import { hasOpenShellGatewayUserService } from "./docker-driver-gateway-service"; import { gatewayOwnerFromCheckpoint } from "./gateway-authority-checkpoint"; @@ -41,7 +43,10 @@ export interface GatewayTeardownAuthorityDeps { env?: NodeJS.ProcessEnv; hasPackagedService?: () => boolean; loadDeclaration?: (env: NodeJS.ProcessEnv) => GatewayManagementLoadResult; - loadSession?: (target: GatewayTeardownTarget, env: NodeJS.ProcessEnv) => Session | null; + loadSession?: ( + target: GatewayTeardownTarget, + env: NodeJS.ProcessEnv, + ) => Pick | null; } export type GatewayTeardownAuthorityResolver = ( @@ -51,6 +56,9 @@ export type GatewayTeardownAuthorityResolver = ( type GatewayAuthorityEffect = "credential mutation" | "rebuild" | "teardown"; +const FRESH_ONBOARDING_CHECKPOINT_RECOVERY = + " Start a fresh onboarding run to replace the invalid checkpoint before retrying."; + export function isManagedPackagedServiceMigration( recorded: GatewayOwner, resolved: GatewayOwner, @@ -64,19 +72,44 @@ export function isManagedPackagedServiceMigration( ); } -function loadTargetSession(target: GatewayTeardownTarget, env: NodeJS.ProcessEnv): Session | null { +function loadTargetSession( + target: GatewayTeardownTarget, + env: NodeJS.ProcessEnv, +): Pick | null { const sessionFile = path.join( nemoclawStateRoot(resolveHome(env), target.gatewayPort), "onboard-session.json", ); + let raw: unknown; try { - if (!fs.existsSync(sessionFile)) return null; - return normalizeSession(JSON.parse(fs.readFileSync(sessionFile, "utf-8"))); - } catch { - // Preserve loadSession() compatibility for legacy or interrupted state. - // A valid selected authority still remains binding when it can be read. - return null; + raw = JSON.parse(fs.readFileSync(sessionFile, "utf-8")); + } catch (error) { + if (isErrnoException(error) && error.code === "ENOENT") return null; + throw new GatewayAuthorityError( + "The persisted onboarding session is unreadable or is not valid JSON; gateway lifecycle authority cannot be revalidated." + + FRESH_ONBOARDING_CHECKPOINT_RECOVERY, + ); + } + + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + throw new GatewayAuthorityError( + "The persisted onboarding session is corrupt; gateway lifecycle authority cannot be revalidated." + + FRESH_ONBOARDING_CHECKPOINT_RECOVERY, + ); } + + const inspected = inspectCheckpoint((raw as { checkpoint?: unknown }).checkpoint); + if (inspected.status === "loaded") return { checkpoint: inspected.checkpoint }; + if (inspected.status === "none" || inspected.status === "legacy") return null; + if (inspected.status === "unsupported_future") { + throw new GatewayAuthorityError( + `The persisted onboarding checkpoint uses unsupported schema version ${String(inspected.foundVersion)}; gateway lifecycle authority cannot be revalidated.${FRESH_ONBOARDING_CHECKPOINT_RECOVERY}`, + ); + } + throw new GatewayAuthorityError( + "The persisted onboarding checkpoint is corrupt; gateway lifecycle authority cannot be revalidated." + + FRESH_ONBOARDING_CHECKPOINT_RECOVERY, + ); } /** diff --git a/src/lib/onboard/hermes-dashboard.test.ts b/src/lib/onboard/hermes-dashboard.test.ts index 9ee1cb83ed7..224cb8e1991 100644 --- a/src/lib/onboard/hermes-dashboard.test.ts +++ b/src/lib/onboard/hermes-dashboard.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { createHermesDashboardForwardEnsurer, + createHermesDashboardOnboardForwarding, getHermesDashboardRegistryFields, hasHermesDashboardDrift, resolveHermesDashboardOnboardState, @@ -206,4 +207,87 @@ describe("onboard Hermes dashboard helpers", () => { ); expect(fail.mock.calls[0]?.[0]).not.toContain("NEMOCLAW_HERMES_DASHBOARD_PORT"); }); + + it("stops Hermes dashboard forwarding when authority changes between retries (#9833)", () => { + const starts: string[] = []; + const revalidatePolicyAuthority = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("policy authority changed"); + }); + const ensureForward = vi.fn( + ( + _sandboxName: string, + _port: number, + _label: string, + revalidate?: (operation: string) => void, + ) => { + revalidate?.("start Hermes dashboard forward attempt 1"); + starts.push("attempt 1"); + revalidate?.("start Hermes dashboard forward attempt 2"); + starts.push("attempt 2"); + return true; + }, + ); + const ensure = createHermesDashboardForwardEnsurer({ + state: resolveHermesDashboardOnboardState({ + agentName: "hermes", + effectivePort: 18789, + env: { NEMOCLAW_HERMES_DASHBOARD: "1" }, + }), + ensureForward, + note: vi.fn(), + rollbackSandbox: vi.fn(), + fail: (message): never => { + throw new Error(message); + }, + }); + + expect(() => ensure("my-hermes", false, revalidatePolicyAuthority)).toThrow( + "policy authority changed", + ); + + expect(starts).toEqual(["attempt 1"]); + expect(revalidatePolicyAuthority).toHaveBeenCalledTimes(2); + }); + + it("stops Hermes dashboard rollback when authority changes between commands (#9833)", () => { + const runOpenshell = vi.fn(); + const revalidatePolicyAuthority = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("policy authority changed"); + }); + 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, revalidatePolicyAuthority), + ).toThrow("policy authority changed"); + + expect(runOpenshell).toHaveBeenCalledTimes(1); + expect(runOpenshell).toHaveBeenCalledWith(["forward", "stop", "8642", "my-hermes"], { + ignoreError: true, + }); + expect(runOpenshell).not.toHaveBeenCalledWith( + ["forward", "stop", "18789", "my-hermes"], + expect.anything(), + ); + expect(runOpenshell).not.toHaveBeenCalledWith( + ["sandbox", "delete", "my-hermes"], + expect.anything(), + ); + }); }); diff --git a/src/lib/onboard/hermes-dashboard.ts b/src/lib/onboard/hermes-dashboard.ts index c410be4f9e0..56fa8d22f49 100644 --- a/src/lib/onboard/hermes-dashboard.ts +++ b/src/lib/onboard/hermes-dashboard.ts @@ -19,6 +19,13 @@ export interface HermesDashboardOnboardState { } type RunOpenshell = (args: string[], options: { ignoreError: true }) => unknown; +type RevalidatePolicyAuthority = (operation: string) => void; +type EnsureForward = ( + sandboxName: string, + port: number, + label: string, + revalidatePolicyAuthority?: RevalidatePolicyAuthority, +) => boolean; export function resolveHermesDashboardOnboardState({ agentName, @@ -138,14 +145,21 @@ export function ensureHermesDashboardForwardIfEnabled({ sandboxName, ensureForward, note, + revalidatePolicyAuthority, }: { state: HermesDashboardOnboardState; sandboxName: string; - ensureForward: (sandboxName: string, port: number, label: string) => boolean; + ensureForward: EnsureForward; note: (message: string) => void; + revalidatePolicyAuthority?: RevalidatePolicyAuthority; }): boolean { if (!state.enabled || !state.config) return true; - if (!ensureForward(sandboxName, state.config.port, "Hermes dashboard")) return false; + if ( + !ensureForward(sandboxName, state.config.port, "Hermes dashboard", revalidatePolicyAuthority) + ) { + return false; + } + revalidatePolicyAuthority?.(`report Hermes dashboard forward for sandbox '${sandboxName}'`); note(` ✓ Hermes dashboard forwarded at http://127.0.0.1:${state.config.port}/`); return true; } @@ -163,15 +177,38 @@ export function createHermesDashboardForwardEnsurer({ fail, }: { state: HermesDashboardOnboardState; - ensureForward: (sandboxName: string, port: number, label: string) => boolean; + ensureForward: EnsureForward; note: (message: string) => void; - rollbackSandbox: (sandboxName: string) => void; + rollbackSandbox: ( + sandboxName: string, + revalidatePolicyAuthority?: RevalidatePolicyAuthority, + ) => void; fail: (message: string) => never; -}): (sandboxName: string, rollback?: boolean) => void { - return (sandboxName: string, rollback = false): void => { - const ok = ensureHermesDashboardForwardIfEnabled({ state, sandboxName, ensureForward, note }); +}): ( + sandboxName: string, + rollback?: boolean, + revalidatePolicyAuthority?: RevalidatePolicyAuthority, +) => void { + return ( + sandboxName: string, + rollback = false, + revalidatePolicyAuthority?: RevalidatePolicyAuthority, + ): void => { + const ok = ensureHermesDashboardForwardIfEnabled({ + state, + sandboxName, + ensureForward, + note, + revalidatePolicyAuthority, + }); if (ok) return; - if (rollback) rollbackSandbox(sandboxName); + if (rollback) { + if (revalidatePolicyAuthority) { + rollbackSandbox(sandboxName, revalidatePolicyAuthority); + } else { + rollbackSandbox(sandboxName); + } + } fail(formatHermesDashboardForwardFailure(state)); }; } @@ -187,7 +224,7 @@ export function createHermesDashboardOnboardForwarding({ }: { agentName: string | null | undefined; env: NodeJS.ProcessEnv; - ensureForward: (sandboxName: string, port: number, label: string) => boolean; + ensureForward: EnsureForward; note: (message: string) => void; runOpenshell: RunOpenshell; getApiForwardPort: () => string; @@ -206,24 +243,32 @@ export function createHermesDashboardOnboardForwarding({ state: HermesDashboardOnboardState, sandboxName: string, rollback = false, + revalidatePolicyAuthority?: RevalidatePolicyAuthority, ) => createHermesDashboardForwardEnsurer({ state, ensureForward, note, - rollbackSandbox: (targetSandbox) => { + rollbackSandbox: (targetSandbox, revalidateRollback) => { + revalidateRollback?.( + `stop Hermes API forward for sandbox '${targetSandbox}' during rollback`, + ); runOpenshell(["forward", "stop", getApiForwardPort(), targetSandbox], { ignoreError: true, }); if (state.config) { + revalidateRollback?.( + `stop Hermes dashboard forward for sandbox '${targetSandbox}' during rollback`, + ); runOpenshell(["forward", "stop", String(state.config.port), targetSandbox], { ignoreError: true, }); } + revalidateRollback?.(`delete sandbox '${targetSandbox}' during dashboard rollback`); runOpenshell(["sandbox", "delete", targetSandbox], { ignoreError: true }); }, fail: failWithMessage, - })(sandboxName, rollback); + })(sandboxName, rollback, revalidatePolicyAuthority); return { resolveStateForPort, ensureForState }; } diff --git a/src/lib/onboard/inference-providers/routed-selection.ts b/src/lib/onboard/inference-providers/routed-selection.ts new file mode 100644 index 00000000000..272fa5d2d30 --- /dev/null +++ b/src/lib/onboard/inference-providers/routed-selection.ts @@ -0,0 +1,148 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { SetupNimSelectionState } from "../setup-nim-selection"; + +type RoutedSelectionDeps = { + modelRouter: { + readonly DEFAULT_MODEL_ROUTER_CREDENTIAL_ENV: string; + loadBlueprintProfile(name: "routed"): { + provider_name?: string; + endpoint?: string; + model: string; + credential_env?: string; + credential_default?: string; + router: { enabled?: boolean; credential_env?: string }; + } | null; + }; + localInference: { readonly HOST_GATEWAY_URL: string }; + urlUtils: { isLoopbackHostname(hostname: string): boolean }; + credentials: { + normalizeCredentialValue(value: unknown): string; + resolveProviderCredential(name: string): string | null; + saveCredential(name: string, value: string): void; + }; + hydrateCredentialEnv(name: string): string | null; + providerKeyBridge: { + resolveRouterProviderKeyBridge(): string | null; + stageRouterProviderKeyBridge(name: string, value: string): void; + }; + isNonInteractive(): boolean; + exitProcess(code: number): never; + credentialPrompt: { + ensureNamedCredential( + name: string | null, + label: string, + helpUrl?: string | null, + validator?: ((value: string) => string | null) | null, + allowEmpty?: boolean, + revalidatePolicyRequirements?: (operation: string) => void, + ): Promise; + returningToProviderSelection(value: unknown): boolean; + }; +}; + +function isExactLoopbackHost(hostname: string, deps: RoutedSelectionDeps): boolean { + const normalized = hostname.toLowerCase(); + return ( + deps.urlUtils.isLoopbackHostname(normalized) && + (normalized === "localhost" || + normalized === "127.0.0.1" || + normalized === "::1" || + normalized === "[::1]") + ); +} + +function rewriteLoopbackEndpoint(endpointUrl: string, deps: RoutedSelectionDeps): string { + let parsed: URL; + try { + parsed = new URL(endpointUrl); + } catch { + return endpointUrl; + } + if (!isExactLoopbackHost(parsed.hostname, deps)) return endpointUrl; + + const schemeEnd = endpointUrl.indexOf("://") + 3; + const authorityEndOffset = endpointUrl.slice(schemeEnd).search(/[/?#]/u); + const authorityEnd = authorityEndOffset < 0 ? endpointUrl.length : schemeEnd + authorityEndOffset; + const authority = endpointUrl.slice(schemeEnd, authorityEnd); + const credentialEnd = authority.lastIndexOf("@") + 1; + const hostAndPort = authority.slice(credentialEnd); + const portSeparator = hostAndPort.indexOf(":"); + const hostEnd = hostAndPort.startsWith("[") + ? hostAndPort.indexOf("]") + 1 + : portSeparator < 0 + ? hostAndPort.length + : portSeparator; + if (!isExactLoopbackHost(hostAndPort.slice(0, hostEnd), deps)) return endpointUrl; + + const gatewayHost = new URL(deps.localInference.HOST_GATEWAY_URL).hostname; + return `${endpointUrl.slice(0, schemeEnd + credentialEnd)}${gatewayHost}${hostAndPort.slice(hostEnd)}${endpointUrl.slice(authorityEnd)}`; +} + +/** Select the built-in Model Router while guarding each credential mutation. */ +export async function handleRoutedSelection( + state: SetupNimSelectionState, + deps: RoutedSelectionDeps, +): Promise<"selected" | "retry-selection"> { + const profile = deps.modelRouter.loadBlueprintProfile("routed"); + if (!profile || profile.router.enabled !== true) { + console.error(" Router is not enabled in nemoclaw-blueprint/blueprint.yaml."); + if (deps.isNonInteractive()) deps.exitProcess(1); + return "retry-selection"; + } + + state.provider = profile.provider_name || "nvidia-router"; + state.model = profile.model; + state.endpointUrl = profile.endpoint ? rewriteLoopbackEndpoint(profile.endpoint, deps) : ""; + state.preferredInferenceApi = "openai-completions"; + state.assertRouteCompatible?.(); + + const credentialEnv = + profile.router.credential_env || + profile.credential_env || + deps.modelRouter.DEFAULT_MODEL_ROUTER_CREDENTIAL_ENV; + state.credentialEnv = credentialEnv; + const configuredCredential = + deps.hydrateCredentialEnv(credentialEnv) || + deps.credentials.normalizeCredentialValue(profile.credential_default || ""); + const resolvedCredential = + configuredCredential || deps.credentials.resolveProviderCredential(credentialEnv); + const bridgedCredential = resolvedCredential + ? null + : deps.providerKeyBridge.resolveRouterProviderKeyBridge(); + if (!resolvedCredential && !bridgedCredential) { + if (deps.isNonInteractive()) { + console.error( + ` ${credentialEnv} (or NEMOCLAW_PROVIDER_KEY) is required for Model Router in non-interactive mode.`, + ); + deps.exitProcess(1); + } + console.log(""); + console.log(" Model Router accepts NVIDIA API keys (nvapi-...)."); + console.log(" Get one at https://build.nvidia.com"); + console.log(""); + const result = await deps.credentialPrompt.ensureNamedCredential( + credentialEnv, + "Model Router API key", + null, + null, + false, + state.revalidatePolicyRequirements, + ); + if (deps.credentialPrompt.returningToProviderSelection(result)) return "retry-selection"; + if (typeof result !== "string" || !deps.credentials.normalizeCredentialValue(result)) { + console.error(` ${credentialEnv} is required for Model Router.`); + return "retry-selection"; + } + } else if (configuredCredential) { + state.revalidatePolicyRequirements?.("save Model Router credential"); + deps.credentials.saveCredential(credentialEnv, configuredCredential); + } else if (bridgedCredential) { + state.revalidatePolicyRequirements?.("stage Model Router provider credential"); + deps.providerKeyBridge.stageRouterProviderKeyBridge(credentialEnv, bridgedCredential); + } + + console.log(` ✓ Using Model Router: ${state.provider} / ${state.model}`); + return "selected"; +} diff --git a/src/lib/onboard/inference-providers/setup-nim-policy-authority.test.ts b/src/lib/onboard/inference-providers/setup-nim-policy-authority.test.ts new file mode 100644 index 00000000000..3bc02dd7538 --- /dev/null +++ b/src/lib/onboard/inference-providers/setup-nim-policy-authority.test.ts @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { PolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; +import { makeDeps } from "../__test-helpers__/setup-nim-flow"; +import { createSetupNim, type SetupNimFlowDeps } from "../setup-nim-flow"; + +function refusePolicyChange(): never { + throw new Error("external policy authority must supply the selected provider entry"); +} + +describe("provider selection policy authority", () => { + it("stops before a remote provider can register credentials (#9833)", async () => { + const handleRemoteProviderSelection = + vi.fn(); + const setupNim = createSetupNim( + makeDeps({ + isNonInteractive: () => true, + getNonInteractiveProvider: () => "build", + handleRemoteProviderSelection, + }), + ); + + await expect( + setupNim( + null, + null, + null, + true, + null, + "nemoclaw", + undefined, + undefined, + null, + refusePolicyChange, + ), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(handleRemoteProviderSelection).not.toHaveBeenCalled(); + }); + + it("does not retry selection after a typed llama.cpp activation refusal (#9833)", async () => { + const selection = { + recipe: { + metadata: { id: "test.llama.recipe" }, + spec: { model: { servedName: "nvidia-nemotron-3-nano-30b-a3b" } }, + }, + } as never; + const installManagedLlamaCpp = vi.fn(async (_selection, options) => { + options.revalidatePolicyRequirements?.("activate the managed llama.cpp runtime"); + throw new PolicyAuthorityRefusalError( + "External policy authority must supply the managed llama.cpp entry.", + ); + }); + const setupNim = createSetupNim( + makeDeps({ + isNonInteractive: () => true, + getNonInteractiveProvider: () => "install-llama-cpp", + resolveManagedLlamaCppSelection: () => ({ kind: "selected", selection }), + installManagedLlamaCpp: installManagedLlamaCpp as never, + }), + ); + const revalidatePolicyRequirements = vi.fn(); + + await expect( + setupNim( + { platform: "spark" } as never, + "spark-agent", + null, + true, + null, + "nemoclaw", + undefined, + undefined, + null, + revalidatePolicyRequirements, + ), + ).rejects.toBeInstanceOf(PolicyAuthorityRefusalError); + + expect(installManagedLlamaCpp).toHaveBeenCalledOnce(); + expect(revalidatePolicyRequirements).toHaveBeenCalledWith( + expect.objectContaining({ provider: "llama-cpp-local" }), + "activate the managed llama.cpp runtime", + ); + }); +}); diff --git a/src/lib/onboard/inference-providers/types.ts b/src/lib/onboard/inference-providers/types.ts index 45f4e5a3b23..030b47861f0 100644 --- a/src/lib/onboard/inference-providers/types.ts +++ b/src/lib/onboard/inference-providers/types.ts @@ -77,6 +77,7 @@ export type PromptValidationRecovery = ( classification: any, credentialEnv: any, helpUrl: any, + revalidatePolicyRequirements?: (operation: string) => void, ) => Promise<"credential" | "selection" | "retry" | "model">; export type ClassifyApplyFailure = (message: string) => any; diff --git a/src/lib/onboard/inference-selection-validation.test.ts b/src/lib/onboard/inference-selection-validation.test.ts index 602b9c37515..fadcb3fdb89 100644 --- a/src/lib/onboard/inference-selection-validation.test.ts +++ b/src/lib/onboard/inference-selection-validation.test.ts @@ -209,9 +209,7 @@ describe("inference selection validation", () => { expect(errorOutput).toContain( "This 404 came from Google's OpenAI-compatible Chat Completions runtime route, not the native /v1beta/models catalog.", ); - expect(errorOutput).toContain( - "the sandbox uses that Chat Completions route at runtime", - ); + expect(errorOutput).toContain("the sandbox uses that Chat Completions route at runtime"); expect(errorOutput).not.toContain(apiKey); } finally { log.mockRestore(); @@ -528,6 +526,7 @@ describe("inference selection validation", () => { expect.objectContaining({ kind: "transport", retry: "retry" }), "COMPATIBLE_API_KEY", null, + undefined, ); } finally { error.mockRestore(); diff --git a/src/lib/onboard/inference-selection-validation.ts b/src/lib/onboard/inference-selection-validation.ts index 071f41448e8..be538dfc6b8 100644 --- a/src/lib/onboard/inference-selection-validation.ts +++ b/src/lib/onboard/inference-selection-validation.ts @@ -70,6 +70,7 @@ export interface OpenAiSelectionValidationOptions { retryChatCompletionsToolReadiness?: boolean; /** Provider identity used only for safe, provider-specific diagnostics. */ provider?: string; + revalidatePolicyRequirements?: (operation: string) => void; skipResponsesProbe?: boolean; probeStreaming?: boolean; @@ -98,6 +99,7 @@ export interface InferenceSelectionValidationDeps { recovery: ReturnType, credentialEnv?: string | null, helpUrl?: string | null, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise<"credential" | "selection" | "retry" | "model">; } @@ -118,6 +120,7 @@ export interface InferenceSelectionValidationHelpers { credentialEnv: string, retryMessage?: string, helpUrl?: string | null, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise; validateCustomOpenAiLikeSelection( label: string, @@ -126,6 +129,7 @@ export interface InferenceSelectionValidationHelpers { credentialEnv: string, helpUrl?: string | null, capabilityCache?: OnboardInferenceCapabilityCache, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise; validateCustomAnthropicSelection( label: string, @@ -135,6 +139,7 @@ export interface InferenceSelectionValidationHelpers { helpUrl?: string | null, options?: { intendedApi?: "anthropic-messages" | "openai-completions"; + revalidatePolicyRequirements?: (operation: string) => void; }, ): Promise; } @@ -199,9 +204,7 @@ export function createInferenceSelectionValidationHelpers( if (!failure || typeof failure !== "object") return false; const { name, httpStatus } = failure as Record; return ( - typeof name === "string" && - name.startsWith("Chat Completions API") && - httpStatus === 404 + typeof name === "string" && name.startsWith("Chat Completions API") && httpStatus === 404 ); }); if (!chatNotFound) return; @@ -225,6 +228,7 @@ export function createInferenceSelectionValidationHelpers( endpointUrl: string, credentialEnv: string | null, helpUrl: string | null, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise< | { blocked: EndpointValidationResult } | { @@ -289,6 +293,7 @@ export function createInferenceSelectionValidationHelpers( getProbeRecovery(syntheticProbe), credentialEnv, helpUrl, + revalidatePolicyRequirements, ); if (retry === "selection") { console.log(" Please choose a provider/model again."); @@ -329,6 +334,7 @@ export function createInferenceSelectionValidationHelpers( getProbeRecovery(probe), credentialEnv, helpUrl, + options.revalidatePolicyRequirements, ); if (retry === "selection") { console.log(` ${retryMessage}`); @@ -363,6 +369,7 @@ export function createInferenceSelectionValidationHelpers( credentialEnv: string, retryMessage = "Please choose a provider/model again.", helpUrl: string | null = null, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise { const apiKey = resolveCredential(credentialEnv); const probe = runAnthropicProbe(endpointUrl, model, apiKey); @@ -376,6 +383,7 @@ export function createInferenceSelectionValidationHelpers( getProbeRecovery(probe), credentialEnv, helpUrl, + revalidatePolicyRequirements, ); if (retry === "selection") { console.log(` ${retryMessage}`); @@ -394,12 +402,14 @@ export function createInferenceSelectionValidationHelpers( credentialEnv: string, helpUrl: string | null = null, capabilityCache?: OnboardInferenceCapabilityCache, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise { const preflight = await preflightCustomEndpointOrFail( label, endpointUrl, credentialEnv, helpUrl, + revalidatePolicyRequirements, ); if ("blocked" in preflight) return preflight.blocked; const { pinnedAddresses, trustedPrivateCapability } = preflight; @@ -448,6 +458,7 @@ export function createInferenceSelectionValidationHelpers( getProbeRecovery(probe, { allowModelRetry: true }), credentialEnv, helpUrl, + revalidatePolicyRequirements, ); if (retry === "selection") { console.log(" Please choose a provider/model again."); @@ -464,6 +475,7 @@ export function createInferenceSelectionValidationHelpers( helpUrl: string | null = null, options: { intendedApi?: "anthropic-messages" | "openai-completions"; + revalidatePolicyRequirements?: (operation: string) => void; } = {}, ): Promise { const preflight = await preflightCustomEndpointOrFail( @@ -471,6 +483,7 @@ export function createInferenceSelectionValidationHelpers( endpointUrl, credentialEnv, helpUrl, + options.revalidatePolicyRequirements, ); if ("blocked" in preflight) return preflight.blocked; const { pinnedAddresses, trustedPrivateCapability } = preflight; @@ -526,7 +539,13 @@ export function createInferenceSelectionValidationHelpers( if (deps.isNonInteractive()) { exitNonInteractiveValidationFailure(); } - const retry = await deps.promptValidationRecovery(label, recovery, credentialEnv, helpUrl); + const retry = await deps.promptValidationRecovery( + label, + recovery, + credentialEnv, + helpUrl, + options.revalidatePolicyRequirements, + ); if (retry === "selection") { console.log(" Please choose a provider/model again."); console.log(""); diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 071d64f2e13..ed5a1d957b6 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -64,6 +64,14 @@ The versioned checkpoint also records durable sandbox identity and completed web Resume skips an effect only after its live postcondition is revalidated. The machine still cannot resume inside gateway startup, an individual credential upsert, sandbox creation, policy application, or another handler-owned effect group. +## Onboarding policy authority + +Onboarding binds policy authority after gateway setup and before provider, credential, service, registry, or sandbox changes. Empty global policy history means NemoClaw manages the sandbox policy. An active global policy means an external owner manages it. Missing, malformed, unavailable, or contradictory OpenShell metadata stops onboarding. + +The session records the decision before later effects. A live sandbox must agree with both the saved session and registry entry. Onboarding rechecks that agreement before each policy-dependent change and after the created sandbox reaches Ready. + +NemoClaw-managed onboarding keeps the existing policy creation and attribution behavior. Externally managed onboarding verifies that the effective policy contains every requirement for the selected agent, provider, messaging channels, observability, GPU mode, and web search setup. It does not pass a policy file, export `OPENSHELL_SANDBOX_POLICY`, change policy, or record NemoClaw policy attribution. A post-create authority failure can remove only the exact sandbox identity created by that attempt. + ## Effect-order flows `*` marks a durable checkpoint and `!` marks the sandbox-delete boundary. In-place destructive effects that occur earlier are called out in the matrix. @@ -235,7 +243,7 @@ The schema and sanitation authority is `Session` plus `normalizeSession`/`filter | Progress and recovery | `lastStepStarted`, `lastCompletedStep`, `failure`, `steps`, `machine`, `sandboxPromptProgress`, `stagedCredentialProviders`, `checkpoint` | Step helpers record step-progress bookkeeping and context updates accepted by `filterSafeUpdates`. `OnboardRuntime` owns machine transitions, terminal state, and machine events. Explicit session recovery and the process-exit failure backstop are separate recovery boundaries. The OpenClaw sandbox handler owns prompt-group completion markers. `stagedCredentialProviders` contains only names registered before sandbox setup so OpenClaw resume can require both durable ownership and an exact live binding. A recreate journal handed to this run by the driver that owns the replacement — matching sandbox name and target-intent fingerprint, and past the delete boundary at `deleted` — is the equivalent ownership proof for a replacement that reset the session and can no longer read a host credential, and it stays paired with the same exact live binding check. A journal merely resident in the session is not that proof, because nothing binds it to this run: one survives a failed attempt, and one is opened straight at `deleted` when the sandbox is already missing. Provider-effect replay requires the receipt provider set to match the providers selected by the current web search configuration or messaging plan. Each persisted and live provider name, provider type, and credential key must match before the handler skips registration. After a successful replay, the handler replaces obsolete bindings owned by that effect group before sandbox creation and preserves bindings owned by the other provider effect group. A marker is trusted only when its matching persisted value is present and valid, including an explicit `null` where supported. `checkpoint` is the dedicated versioned resume contract: a secret-free tri-state decision record plus durable sandbox identity, effect-group receipts, and logical web-search and messaging provider bindings, serialized alongside the session under its own `schemaVersion` with fail-closed handling of an unknown future version. The primary inference provider binding remains owned and revalidated by the provider and inference phases instead of entering this checkpoint ledger. | | Target identity | `agent`, `sandboxName`, `metadata.gatewayName`, `metadata.fromDockerfile` | Onboard selection, sandbox handler/registration, and rebuild session preparation. A completed sandbox step or valid `sandboxPromptProgress.sandboxName` marker is the trust gate for a recorded name. | | Inference intent | `provider`, `model`, `endpointUrl`, `credentialEnv`, `preferredInferenceApi`, `compatibleEndpointReasoning`, `nimContainer`, `webSearchConfig` | Provider/inference handlers and `runInferenceSet`. Known credential state is an environment-variable name or presence metadata, never the value. `redactUrl` masks userinfo and fragments, redacts values under sensitive parameter names, and redacts canonical token-shaped values even under benign parameter names. | -| Agent and policy intent | `hermesAuthMethod`, `toolDisclosure`, `hermesToolGateways`, `policyPresets` | Agent setup and policy handling. Channel commands update matching-session `policyPresets` only best-effort. Nullable fields conflate unset, declined, and cleared where the CLI makes those distinctions. | +| Agent and policy intent | `hermesAuthMethod`, `toolDisclosure`, `hermesToolGateways`, `policyPresets`, `policyAuthority` | Agent setup and policy handling. `policyAuthority` records the strict OpenShell metadata decision before policy-dependent onboarding effects. External authority clears local preset attribution. Channel commands update matching-session `policyPresets` only best-effort. Nullable fields conflate unset, declined, and cleared where the CLI makes those distinctions. | | Messaging intent | `messagingPlan`, `telegramConfig`, `wechatConfig` | `../messaging/plan-authority.ts` selects the registry messaging plan for an existing sandbox. Consumers with a known sandbox target resolve registry authority before they read a staged environment plan. Disabled-channel resolution also skips session loading when registry state is authoritative. A valid staged plan can still resolve a different target during implicit configuration lookup. For a new or pending target, a staged plan takes precedence over a matching session plan. `telegramConfig` and `wechatConfig` provide legacy configuration fallback. Raw credential values remain outside the session. | | Resource choice | `resourceProfile` | The sandbox handler records concrete CPU/RAM values or `null` for an explicit OpenShell-default choice after the prompt completes. Environment overrides still take precedence on the recovery run. | | Runtime metadata | `routerPid`, `routerCredentialHash`, `gpuPassthrough` | Router and sandbox setup/recovery. PID is a live-process hint; credential hash is a digest; GPU is a concrete boolean. | diff --git a/src/lib/onboard/local-model-profile/onboarder.test.ts b/src/lib/onboard/local-model-profile/onboarder.test.ts index 03cf5641096..5de1b778e67 100644 --- a/src/lib/onboard/local-model-profile/onboarder.test.ts +++ b/src/lib/onboard/local-model-profile/onboarder.test.ts @@ -47,6 +47,7 @@ describe("dedicated local model profile onboarder", () => { const checkpointVllmInstallModel = vi.fn(); const handleVllmSelection = vi.fn(async () => "selected" as const); const installVllm = vi.fn(async (_profile: VllmProfile, options) => { + options.checkpointInstallIntent?.("nvidia/Qwen3.6-35B-A3B-NVFP4"); options.beforeInstall?.("nvidia/Qwen3.6-35B-A3B-NVFP4"); return { ok: true }; }); @@ -77,9 +78,10 @@ describe("dedicated local model profile onboarder", () => { }), expect.objectContaining({ nonInteractive: true, - checkpointInstallIntent: checkpointVllmInstallModel, + checkpointInstallIntent: expect.any(Function), }), ); + expect(checkpointVllmInstallModel).toHaveBeenCalledWith("nvidia/Qwen3.6-35B-A3B-NVFP4"); expect(handleVllmSelection).toHaveBeenCalledWith(selection, { managedInstall: true, sparkHost: true, @@ -119,7 +121,7 @@ describe("dedicated local model profile onboarder", () => { ).resolves.toBe("selected"); expect(installVllm).toHaveBeenCalledWith( expect.anything(), - expect.objectContaining({ checkpointInstallIntent: checkpointVllmInstallModel }), + expect.objectContaining({ checkpointInstallIntent: expect.any(Function) }), ); expect(installVllm.mock.calls[0]?.[1]).not.toHaveProperty("modelIntent"); }); @@ -157,6 +159,70 @@ describe("dedicated local model profile onboarder", () => { expect(error).toHaveBeenCalledWith(expect.stringContaining("resumed vLLM model conflicts")); }); + it("refuses vLLM install intent persistence when policy authority changes (#9833)", async () => { + const selection = state(); + const checkpointVllmInstallModel = vi.fn(); + const installEffect = vi.fn(); + const handleVllmSelection = vi.fn(async () => "selected" as const); + const observedRoutes: Array> = []; + selection.revalidatePolicyRequirements = (operation) => { + observedRoutes.push({ + operation, + provider: selection.provider, + model: selection.model, + endpointUrl: selection.endpointUrl, + credentialEnv: selection.credentialEnv, + preferredInferenceApi: selection.preferredInferenceApi, + }); + throw new Error("external policy authority must supply local inference"); + }; + const installVllm = vi.fn(async (_profile: VllmProfile, options) => { + options.checkpointInstallIntent?.("nvidia/Qwen3.6-35B-A3B-NVFP4"); + installEffect(); + options.beforeInstall?.("nvidia/Qwen3.6-35B-A3B-NVFP4"); + return { ok: true }; + }); + const onboard = createLocalModelProfileOnboarder({ + env: {}, + installVllm, + handleVllmSelection, + prompt: vi.fn(async () => ""), + error: vi.fn(), + checkpointVllmInstallModel, + }); + + await expect( + onboard( + plan(), + { + hasVllmImage: false, + sparkHost: true, + vllmProfile: { + name: "DGX Spark", + platform: "spark", + architecture: "arm64", + } as VllmProfile, + vllmRunning: false, + }, + selection, + ), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(checkpointVllmInstallModel).not.toHaveBeenCalled(); + expect(installEffect).not.toHaveBeenCalled(); + expect(handleVllmSelection).not.toHaveBeenCalled(); + expect(observedRoutes).toEqual([ + { + operation: "record managed vLLM install intent", + provider: "vllm-local", + model: "nvidia/Qwen3.6-35B-A3B-NVFP4", + endpointUrl: null, + credentialEnv: null, + preferredInferenceApi: "openai-completions", + }, + ]); + }); + it("accepts a vLLM host port override for the fixed serving recipe", async () => { const installVllm = vi.fn(async () => ({ ok: true })); const error = vi.fn(); diff --git a/src/lib/onboard/local-model-profile/onboarder.ts b/src/lib/onboard/local-model-profile/onboarder.ts index fc28530bf21..d544d4ca87a 100644 --- a/src/lib/onboard/local-model-profile/onboarder.ts +++ b/src/lib/onboard/local-model-profile/onboarder.ts @@ -99,20 +99,31 @@ export function createLocalModelProfileOnboarder(deps: LocalModelProfileOnboarde ); return "retry-selection"; } + const seedVllmInstallRoute = (modelId: string): void => { + state.provider = "vllm-local"; + state.model = modelId; + state.endpointUrl = null; + state.credentialEnv = null; + state.preferredInferenceApi = "openai-completions"; + state.assertRouteCompatible?.(); + }; + const checkpointInstallIntent = recovery.checkpointInstallIntent; const result = await deps.installVllm(materialized.profile, { hasImage: host.hasVllmImage, nonInteractive: true, promptFn: deps.prompt, - ...(recovery.checkpointInstallIntent - ? { checkpointInstallIntent: recovery.checkpointInstallIntent } + ...(checkpointInstallIntent + ? { + checkpointInstallIntent: (modelId: string) => { + seedVllmInstallRoute(modelId); + state.revalidatePolicyRequirements?.("record managed vLLM install intent"); + checkpointInstallIntent(modelId); + }, + } : {}), beforeInstall: (modelId) => { - state.provider = "vllm-local"; - state.model = modelId; - state.endpointUrl = null; - state.credentialEnv = null; - state.preferredInferenceApi = "openai-completions"; - state.assertRouteCompatible?.(); + seedVllmInstallRoute(modelId); + state.revalidatePolicyRequirements?.("install managed vLLM runtime"); }, }); if (!result.ok) return "retry-selection"; diff --git a/src/lib/onboard/machine/core-flow-phases.test.ts b/src/lib/onboard/machine/core-flow-phases.test.ts index 443871dfcf2..e39bfa208f2 100644 --- a/src/lib/onboard/machine/core-flow-phases.test.ts +++ b/src/lib/onboard/machine/core-flow-phases.test.ts @@ -216,6 +216,8 @@ function createPhases( }) as (code: number) => never, deleteEnv: vi.fn(), ...overrides.providerDeps, + preflightPolicyRequirements: + overrides.providerDeps?.preflightPolicyRequirements ?? (() => undefined), }, }); const sandbox = createSandboxOnboardFlowPhase({ @@ -311,6 +313,8 @@ function createPhases( throw new Error(`exit ${code}`); }) as (code: number) => never, ...overrides.sandboxDeps, + preflightPolicyRequirements: + overrides.sandboxDeps?.preflightPolicyRequirements ?? (() => undefined), checkGatewayRouteCompatibility: overrides.sandboxDeps?.checkGatewayRouteCompatibility ?? (() => ({ ok: true })), withGatewayRouteMutationLock: @@ -566,6 +570,7 @@ describe("core onboard flow phases", () => { expect.any(Function), expect.any(Function), expect.any(String), + expect.any(Function), ); }); @@ -630,6 +635,7 @@ describe("core onboard flow phases", () => { allowToolsIncompatible: false, endpointSource: null, reservationSessionId: session.sessionId, + revalidatePolicyRequirements: expect.any(Function), }, ); expect(result.context.hermesToolGateways).toEqual(["nous-web"]); diff --git a/src/lib/onboard/machine/final-flow-phases.ts b/src/lib/onboard/machine/final-flow-phases.ts index 9de5af8825a..76fdc6f7f4c 100644 --- a/src/lib/onboard/machine/final-flow-phases.ts +++ b/src/lib/onboard/machine/final-flow-phases.ts @@ -32,6 +32,7 @@ export interface FinalOnboardFlowPhaseOptions< > { branchState: "agent_setup" | "openclaw"; authoritativePolicyTier?: string | null; + revalidatePolicyRequirements?(context: Context, operation: string): void; agentSetupDeps: AgentSetupStateOptions["deps"]; policiesDeps: PoliciesStateOptions["deps"]; finalization: { @@ -116,6 +117,9 @@ export function createFinalOnboardFlowPhases< const finalizationPhase = createFinalizationPhase(async (context) => { assertSandboxCreatedContext(context, "finalization"); const webSearchEnabled = options.finalization.webSearchEnabled(context.webSearchConfig); + const revalidatePolicyRequirements = + options.revalidatePolicyRequirements?.bind(null, context) ?? + finalizationDeps.revalidatePolicyRequirements; const finalizationResult = await handleFinalizationState({ sandboxName: context.sandboxName, model: context.model, @@ -133,7 +137,7 @@ export function createFinalOnboardFlowPhases< : null, portableProfileSelected: context.session?.checkpoint?.profile.value === "portable", recreateJournalHandoff: context.recreateJournalHandoff, - deps: finalizationDeps, + deps: { ...finalizationDeps, revalidatePolicyRequirements }, }); return { result: finalizationResult.stateResult }; }); diff --git a/src/lib/onboard/machine/handlers/finalization.test.ts b/src/lib/onboard/machine/handlers/finalization.test.ts index 07ae616c09f..794adf88d86 100644 --- a/src/lib/onboard/machine/handlers/finalization.test.ts +++ b/src/lib/onboard/machine/handlers/finalization.test.ts @@ -347,6 +347,41 @@ describe("finalization handlers", () => { expect(persistDashboardPort).toHaveBeenCalledWith("my-assistant", 18792); }); + it("withholds dashboard-port persistence when authority drifts after forwarding (#9833)", async () => { + const persistDashboardPort = vi.fn(); + const revalidatePolicyRequirements = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("policy authority changed"); + }); + const ensureAgentDashboardForward = vi.fn( + (_sandboxName, _agent, revalidate?: (operation: string) => void) => { + revalidate?.("start dashboard forward"); + return 18792; + }, + ); + const { deps } = createDeps({ + ensureAgentDashboardForward, + persistDashboardPort, + revalidatePolicyRequirements, + }); + + await expect( + handleFinalizationPhase({ + ...baseOptions(deps), + agent: { name: "hermes" }, + }), + ).rejects.toThrow("policy authority changed"); + + expect(ensureAgentDashboardForward).toHaveBeenCalledWith( + "my-assistant", + { name: "hermes" }, + revalidatePolicyRequirements, + ); + expect(persistDashboardPort).not.toHaveBeenCalled(); + }); + it("does not persist a zero dashboard port after final recovery (#8214)", async () => { const persistDashboardPort = vi.fn(); const { deps } = createDeps({ diff --git a/src/lib/onboard/machine/handlers/finalization.ts b/src/lib/onboard/machine/handlers/finalization.ts index b6b05105ad9..cc421b7a033 100644 --- a/src/lib/onboard/machine/handlers/finalization.ts +++ b/src/lib/onboard/machine/handlers/finalization.ts @@ -30,7 +30,12 @@ export interface FinalizationStateOptions | number; + ensureAgentDashboardForward( + sandboxName: string, + agent: Agent, + revalidatePolicyRequirements?: (operation: string) => void, + ): Promise | number; + revalidatePolicyRequirements?(operation: string): void; persistDashboardPort(sandboxName: string, dashboardPort: number): void; /** * Mark this sandbox as the default. Called here (not at sandbox creation) so @@ -229,8 +234,17 @@ export async function handleFinalizationState 0) { + deps.revalidatePolicyRequirements?.( + `persist the dashboard port for sandbox '${sandboxName}'`, + ); deps.persistDashboardPort(sandboxName, dashboardPort); } } diff --git a/src/lib/onboard/machine/handlers/policies.test.ts b/src/lib/onboard/machine/handlers/policies.test.ts index e966c69c484..eef99efeaff 100644 --- a/src/lib/onboard/machine/handlers/policies.test.ts +++ b/src/lib/onboard/machine/handlers/policies.test.ts @@ -436,6 +436,31 @@ describe("handlePoliciesState", () => { expect(result.appliedPolicyPresets).toEqual(["dns", "github"]); }); + it("verifies external selections without recording NemoClaw preset ownership (#9833)", async () => { + const setupPolicies = vi.fn(async (_name: string, options: SetupOptions) => { + options.onSelection(["dns", "github"]); + return ["dns", "github"]; + }); + const { deps, calls } = createDeps({ + getActiveSandbox: vi.fn(() => ({ + messaging: null, + policyAuthority: "externally-managed" as const, + })), + setupPoliciesWithSelection: setupPolicies, + }); + + const result = await handlePoliciesState({ ...baseOptions(deps), resume: true }); + + expect(setupPolicies).toHaveBeenCalledOnce(); + expect(calls.persistPolicies).not.toHaveBeenCalled(); + expect(calls.updateSession).not.toHaveBeenCalled(); + expect(calls.complete).toHaveBeenCalledWith( + "policies", + expect.objectContaining({ policyPresets: null }), + ); + expect(result.appliedPolicyPresets).toEqual([]); + }); + it("re-onboard carries the persisted set forward without re-adding removed defaults (#4621)", async () => { // A prior onboard recorded the custom "Balanced minus npm plus github" set. // On re-onboard the recorded set is re-applied verbatim and persisted back — diff --git a/src/lib/onboard/machine/handlers/policies.ts b/src/lib/onboard/machine/handlers/policies.ts index 5316dbb51fb..3c5927fc9d8 100644 --- a/src/lib/onboard/machine/handlers/policies.ts +++ b/src/lib/onboard/machine/handlers/policies.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { SandboxMessagingPlan } from "../../../messaging/manifest"; +import type { SandboxPolicyAuthority } from "../../../adapters/openshell/policy-authority"; import type { Session, SessionUpdates } from "../../../state/onboard-session"; import { getActiveChannelsFromPlan, @@ -26,6 +27,7 @@ export interface PolicyPresetEntry { export interface ActiveSandboxPolicyState { messaging?: { plan: SandboxMessagingPlan } | null; + policyAuthority?: SandboxPolicyAuthority; policyTier?: string | null; /** Preset names already applied to the sandbox, as recorded in the registry. */ policies?: string[] | null; @@ -171,6 +173,7 @@ export async function handlePoliciesState({ : rawRecordedPolicyPresets; const recordedMessagingChannels = getActiveChannelsFromPlan(latestSession?.messagingPlan); const activeSandbox = deps.getActiveSandbox(sandboxName); + const externallyManagedPolicy = activeSandbox?.policyAuthority === "externally-managed"; const effectivePolicyTier = authoritativePolicyTier ?? activeSandbox?.policyTier ?? null; const activePlan = activeSandbox?.messaging?.plan; const activeMessagingChannels = getActiveChannelsFromPlan(activePlan); @@ -185,9 +188,7 @@ export async function handlePoliciesState({ // the plans: a sandbox can carry a channel's egress in `policies` after every // plan that named the channel is gone, and only a candidate here can retire // it. - const appliedPresetMessagingChannels = messagingChannelsForPolicyPresets( - activeSandbox?.policies, - ); + const appliedPresetMessagingChannels = messagingChannelsForPolicyPresets(activeSandbox?.policies); const unconfiguredMessagingChannels = deps.detectUnconfiguredMessagingChannels( [...recordedMessagingChannels, ...activeMessagingChannels, ...appliedPresetMessagingChannels], selectedMessagingChannels, @@ -237,6 +238,7 @@ export async function handlePoliciesState({ (rawRecordedPolicyPresets?.includes("local-inference") === true || deps.arePolicyPresetsApplied(sandboxName, ["local-inference"])); const resumePolicies = + !externallyManagedPolicy && resume && !staleLocalInferencePolicy && !policyResumeSelection.recordedPolicyPresetsNeedReconcile && @@ -306,13 +308,16 @@ export async function handlePoliciesState({ // gateway (resume reapply, non-interactive custom/suggested, the // interactive tier selector, or exclusion cleanup during skip). An // ordinary skip without exclusions returns before calling it. - reflectsLiveAppliedSet = true; - deps.updateSession((current) => { - current.policyPresets = policyPresets; - return current; - }); + if (!externallyManagedPolicy) { + reflectsLiveAppliedSet = true; + deps.updateSession((current) => { + current.policyPresets = policyPresets; + return current; + }); + } }, }); + if (externallyManagedPolicy) appliedPolicyPresets = []; // Reconcile the registry with the *effective* preset selection so a later // recreate/re-onboard carries the operator's exact set forward instead of // reapplying stale tier defaults. Done *before* recordStepComplete so an @@ -328,7 +333,12 @@ export async function handlePoliciesState({ if (hostLocalInferenceRouteOnly) verifySandboxInferenceRoute(); session = await deps.recordStepComplete( "policies", - deps.toSessionUpdates({ sandboxName, provider, model, policyPresets: appliedPolicyPresets }), + deps.toSessionUpdates({ + sandboxName, + provider, + model, + policyPresets: externallyManagedPolicy ? null : appliedPolicyPresets, + }), ); } diff --git a/src/lib/onboard/machine/handlers/provider-inference-authoritative-recovery.test.ts b/src/lib/onboard/machine/handlers/provider-inference-authoritative-recovery.test.ts index 6d3350f3831..bfedfaebb6e 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-authoritative-recovery.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-authoritative-recovery.test.ts @@ -64,6 +64,7 @@ describe("authoritative provider inference recovery", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); expect(calls.setupInference).toHaveBeenCalledWith( "my-assistant", diff --git a/src/lib/onboard/machine/handlers/provider-inference-managed-llama-resume.test.ts b/src/lib/onboard/machine/handlers/provider-inference-managed-llama-resume.test.ts index fa6712ca29b..d96426a201d 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-managed-llama-resume.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-managed-llama-resume.test.ts @@ -11,9 +11,60 @@ describe("handleProviderInferenceState managed llama.cpp resume", () => { it.each([ { label: "normal resume", authoritativeResumeConfig: false }, { label: "authoritative rebuild", authoritativeResumeConfig: true }, - ])("recovers the exact runtime before $label skips provider selection (#8144)", async ({ - authoritativeResumeConfig, - }) => { + ])( + "recovers the exact runtime before $label skips provider selection (#8144)", + async ({ authoritativeResumeConfig }) => { + const session = createSession({ + sandboxName: "spark-agent", + provider: "llama-cpp-local", + model: "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-GGUF", + endpointUrl: "http://host.openshell.internal:8081/v1", + credentialEnv: "LLAMA_CPP_API_KEY", + preferredInferenceApi: "openai-completions", + sandboxPromptProgress: { + sandboxName: true, + webSearch: false, + messaging: false, + resourceProfile: false, + }, + }); + session.steps.provider_selection.status = authoritativeResumeConfig ? "pending" : "complete"; + const recoverManagedLlamaCpp = vi.fn(async () => true); + const { deps, calls } = createDeps({ + ensureManagedLlamaCppResumeReady: recoverManagedLlamaCpp, + isInferenceRouteReady: vi.fn(() => true), + }); + + const result = await handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + authoritativeResumeConfig, + sandboxName: "spark-agent", + }); + + expect(recoverManagedLlamaCpp).toHaveBeenCalledOnce(); + expect(recoverManagedLlamaCpp).toHaveBeenCalledWith( + "llama-cpp-local", + "spark-agent", + expect.any(Function), + ); + expect(recoverManagedLlamaCpp.mock.invocationCallOrder[0]).toBeLessThan( + calls.recoverProvider.mock.invocationCallOrder[0]!, + ); + expect(recoverManagedLlamaCpp.mock.invocationCallOrder[0]).toBeLessThan( + calls.skipped.mock.invocationCallOrder[0]!, + ); + expect(calls.setupNim).not.toHaveBeenCalled(); + expect(calls.setupInference).not.toHaveBeenCalled(); + expect(result).toMatchObject({ + sandboxName: "spark-agent", + provider: "llama-cpp-local", + model: "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-GGUF", + }); + }, + ); + + it("stops after managed runtime verification before resume recovery effects (#9833)", async () => { const session = createSession({ sandboxName: "spark-agent", provider: "llama-cpp-local", @@ -21,41 +72,46 @@ describe("handleProviderInferenceState managed llama.cpp resume", () => { endpointUrl: "http://host.openshell.internal:8081/v1", credentialEnv: "LLAMA_CPP_API_KEY", preferredInferenceApi: "openai-completions", - sandboxPromptProgress: { - sandboxName: true, - webSearch: false, - messaging: false, - resourceProfile: false, - }, }); - session.steps.provider_selection.status = authoritativeResumeConfig ? "pending" : "complete"; - const recoverManagedLlamaCpp = vi.fn(async () => true); + session.steps.provider_selection.status = "complete"; + const ensureManagedLlamaCppResumeReady = vi.fn( + async ( + _provider: string | null | undefined, + _sandboxName: string | null | undefined, + revalidatePolicyRequirements?: (operation: string) => void, + ) => { + await Promise.resolve(); + revalidatePolicyRequirements?.("activate the verified managed llama.cpp runtime"); + return true; + }, + ); + const refusal = () => { + throw new Error("external policy authority must supply the managed llama.cpp entry"); + }; + const actions = new Map void>([ + ["activate the verified managed llama.cpp runtime", refusal], + ]); + const preflightPolicyRequirements = vi.fn((input: { operation: string }) => + actions.get(input.operation)?.(), + ); const { deps, calls } = createDeps({ - ensureManagedLlamaCppResumeReady: recoverManagedLlamaCpp, + ensureManagedLlamaCppResumeReady, + preflightPolicyRequirements, isInferenceRouteReady: vi.fn(() => true), }); - const result = await handleProviderInferenceState({ - ...baseOptions(deps, session), - resume: true, - authoritativeResumeConfig, - sandboxName: "spark-agent", - }); + await expect( + handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + sandboxName: "spark-agent", + }), + ).rejects.toThrow(/external policy authority must supply/u); - expect(recoverManagedLlamaCpp).toHaveBeenCalledOnce(); - expect(recoverManagedLlamaCpp).toHaveBeenCalledWith("llama-cpp-local", "spark-agent"); - expect(recoverManagedLlamaCpp.mock.invocationCallOrder[0]).toBeLessThan( - calls.recoverProvider.mock.invocationCallOrder[0]!, - ); - expect(recoverManagedLlamaCpp.mock.invocationCallOrder[0]).toBeLessThan( - calls.skipped.mock.invocationCallOrder[0]!, - ); - expect(calls.setupNim).not.toHaveBeenCalled(); + expect(ensureManagedLlamaCppResumeReady).toHaveBeenCalledOnce(); + expect(calls.recoverProvider).not.toHaveBeenCalled(); + expect(calls.skipped).not.toHaveBeenCalled(); + expect(calls.recordSkip).not.toHaveBeenCalled(); expect(calls.setupInference).not.toHaveBeenCalled(); - expect(result).toMatchObject({ - sandboxName: "spark-agent", - provider: "llama-cpp-local", - model: "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-GGUF", - }); }); }); diff --git a/src/lib/onboard/machine/handlers/provider-inference-policy-authority.test.ts b/src/lib/onboard/machine/handlers/provider-inference-policy-authority.test.ts new file mode 100644 index 00000000000..adafc940b3a --- /dev/null +++ b/src/lib/onboard/machine/handlers/provider-inference-policy-authority.test.ts @@ -0,0 +1,114 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { createSession } from "../../../state/onboard-session"; +import { handleProviderInferenceState } from "./provider-inference"; +import { baseOptions, baseSelection, createDeps } from "./provider-inference.test-support"; + +function refuseExternalPolicy(): never { + throw new Error("external policy authority must supply the selected route"); +} + +describe("provider inference policy authority", () => { + it("stops before provider setup when policy requirements are not met (#9833)", async () => { + const preflightPolicyRequirements = vi.fn(refuseExternalPolicy); + const { deps, calls } = createDeps({ preflightPolicyRequirements }); + + await expect(handleProviderInferenceState(baseOptions(deps))).rejects.toThrow( + /external policy authority must supply/u, + ); + + expect(preflightPolicyRequirements).toHaveBeenCalledOnce(); + expect(calls.startStep).not.toHaveBeenCalled(); + expect(calls.setupNim).not.toHaveBeenCalled(); + expect(calls.setupInference).not.toHaveBeenCalled(); + }); + + it("rechecks after routed provider upsert before reserving the route (#9833)", async () => { + const session = createSession({ + sandboxName: "router-sandbox", + provider: "nvidia-router", + model: "router/model", + }); + session.steps.provider_selection.status = "complete"; + const preflightPolicyRequirements = vi.fn((requirements: { operation: string }) => + requirements.operation.startsWith("reserve routed inference route") + ? refuseExternalPolicy() + : undefined, + ); + const { deps, calls } = createDeps({ + isInferenceRouteReady: vi.fn(() => true), + preflightPolicyRequirements, + }); + + await expect( + handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + sandboxName: "router-sandbox", + }), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(calls.reupsertRoutedProvider).toHaveBeenCalledOnce(); + expect(calls.reserveRoute).not.toHaveBeenCalled(); + expect(calls.updateSandbox).not.toHaveBeenCalled(); + }); + + it("rechecks before local inference provider preparation (#9833)", async () => { + const setupNim = vi.fn(async () => ({ + ...baseSelection, + provider: "ollama-local", + model: "llama3.1", + endpointUrl: "http://127.0.0.1:11434/v1", + credentialEnv: null, + })); + const preflightPolicyRequirements = vi.fn((requirements: { operation: string }) => + requirements.operation.startsWith("prepare local inference provider") + ? refuseExternalPolicy() + : undefined, + ); + const { deps, calls } = createDeps({ setupNim, preflightPolicyRequirements }); + + await expect(handleProviderInferenceState(baseOptions(deps))).rejects.toThrow( + /external policy authority must supply/u, + ); + + expect(calls.prepareLocalProviderForInference).not.toHaveBeenCalled(); + expect(calls.setupInference).not.toHaveBeenCalled(); + expect(calls.updateSandbox).not.toHaveBeenCalled(); + }); + + it("withholds inference success after a deferred selection loses authority (#9833)", async () => { + const session = createSession({ + sandboxName: "alpha", + provider: "nvidia-prod", + model: "nvidia/model", + sandboxPromptProgress: { + sandboxName: true, + webSearch: false, + messaging: false, + resourceProfile: false, + }, + }); + session.steps.provider_selection.status = "failed"; + const preflightPolicyRequirements = vi.fn((requirements: { operation: string }) => + requirements.operation.startsWith("record successful deferred provider selection") + ? refuseExternalPolicy() + : undefined, + ); + const { deps, calls } = createDeps({ preflightPolicyRequirements }); + + await expect( + handleProviderInferenceState({ + ...baseOptions(deps, session), + sandboxName: "alpha", + }), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(calls.setupInference).toHaveBeenCalledOnce(); + expect(calls.complete).toHaveBeenCalledWith("provider_selection", expect.any(Object)); + expect(calls.complete).not.toHaveBeenCalledWith("inference", expect.any(Object)); + }); +}); diff --git a/src/lib/onboard/machine/handlers/provider-inference-recovery-gating.test.ts b/src/lib/onboard/machine/handlers/provider-inference-recovery-gating.test.ts index 5d5b6a3070f..d35676aec0d 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-recovery-gating.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-recovery-gating.test.ts @@ -49,6 +49,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), expect.any(String), + expect.any(Function), ); }); @@ -71,6 +72,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); }); @@ -108,6 +110,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); }); @@ -139,6 +142,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); }); @@ -172,6 +176,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); }); @@ -195,6 +200,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), expect.any(String), + expect.any(Function), ); expect(getAuthority).toHaveBeenCalledWith("dc-after", expect.any(String)); }); @@ -233,6 +239,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); expect(getAuthority).toHaveBeenCalledWith("dc-after", session.sessionId); }, @@ -267,6 +274,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); expect(getAuthority).toHaveBeenCalledWith("dc-after", session.sessionId); }); @@ -327,6 +335,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); expect(getAuthority).toHaveBeenNthCalledWith(1, "dc-after", session.sessionId); expect(getAuthority).toHaveBeenLastCalledWith("dc-after", session.sessionId); @@ -406,6 +415,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), sessionId, + expect.any(Function), ); } finally { vi.unstubAllEnvs(); @@ -435,6 +445,7 @@ describe("provider inference recovery gating", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); }); diff --git a/src/lib/onboard/machine/handlers/provider-inference-route-containment.test.ts b/src/lib/onboard/machine/handlers/provider-inference-route-containment.test.ts index 89a1680bb69..5182943e871 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-route-containment.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-route-containment.test.ts @@ -86,6 +86,7 @@ function createDeps() { const deps: Options["deps"] = { checkGatewayRouteCompatibility: calls.checkGatewayRouteCompatibility, preflightGatewayRouteDiscovery: calls.preflightGatewayRouteDiscovery, + preflightPolicyRequirements: vi.fn(), getSandboxRecoveryAuthority: (): "missing" => "missing", withGatewayRouteMutationLock: async (_gatewayName, operation) => await operation(), withModelRouterPortLifecycleLock: async (_port, operation) => await operation(), diff --git a/src/lib/onboard/machine/handlers/provider-inference.test-support.ts b/src/lib/onboard/machine/handlers/provider-inference.test-support.ts index f0fe5a7f1b6..d580ca20bc4 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.test-support.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.test-support.ts @@ -97,6 +97,7 @@ export function createDeps( requiredEndpointUrl: null, requiredInferenceApi: null, })), + preflightPolicyRequirements: vi.fn(), setupNim: vi.fn(async () => ({ ...baseSelection })), setupInference: vi.fn< ProviderInferenceStateOptions["deps"]["setupInference"] @@ -155,6 +156,7 @@ export function createDeps( deps: { checkGatewayRouteCompatibility: calls.checkGatewayRouteCompatibility, preflightGatewayRouteDiscovery: calls.preflightGatewayRouteDiscovery, + preflightPolicyRequirements: calls.preflightPolicyRequirements, getSandboxRecoveryAuthority: (): "missing" => "missing", withGatewayRouteMutationLock: async ( _gatewayName: string, diff --git a/src/lib/onboard/machine/handlers/provider-inference.test.ts b/src/lib/onboard/machine/handlers/provider-inference.test.ts index 05237753bc9..9c3e9045450 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.test.ts @@ -30,6 +30,7 @@ function setupOptions( allowToolsIncompatible: false, endpointSource: null, reservationSessionId: session.sessionId, + revalidatePolicyRequirements: expect.any(Function), ...overrides, }; } @@ -56,6 +57,7 @@ describe("handleProviderInferenceState", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); const selectionUpdates = ( calls.complete.mock.calls as unknown as Array<[string, Record]> @@ -275,6 +277,7 @@ describe("handleProviderInferenceState", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); expect(calls.setupInference).toHaveBeenCalled(); }); @@ -303,6 +306,7 @@ describe("handleProviderInferenceState", () => { "nemoclaw", "compatible-endpoint", "COMPATIBLE_API_KEY", + expect.any(Function), ); expect(calls.complete).toHaveBeenCalledWith( "provider_selection", @@ -445,7 +449,12 @@ describe("handleProviderInferenceState", () => { expect(calls.setupNim).not.toHaveBeenCalled(); expect(calls.setupInference).not.toHaveBeenCalled(); - expect(calls.recoverProvider).toHaveBeenCalledWith("nemoclaw", "ollama-local", null); + expect(calls.recoverProvider).toHaveBeenCalledWith( + "nemoclaw", + "ollama-local", + null, + expect.any(Function), + ); expect(calls.skipped).toHaveBeenCalledWith("provider_selection", "ollama-local / llama3.1"); expect(calls.recordSkip).toHaveBeenCalledWith("provider_selection", { reason: "resume", @@ -635,36 +644,39 @@ describe("handleProviderInferenceState", () => { it.each([ ["is unset", decisionUnset()], ["names another sandbox", decisionSelected({ name: "other-sandbox", agent: "openclaw" })], - ])("prompts before route reservation when the checkpoint identity %s", async (_label, identity) => { - const session = createSession({ - sandboxName: "stale-sandbox", - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", - preferredInferenceApi: "openai-responses", - }); - session.steps.provider_selection.status = "complete"; - session.checkpoint = { - ...deriveCheckpointFromSession(session), - sandboxIdentity: identity, - }; - const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); - calls.promptName.mockResolvedValueOnce("prompted-sandbox"); - - const result = await handleProviderInferenceState({ - ...baseOptions(deps, session), - resume: true, - sandboxName: "stale-sandbox", - }); - - expect(calls.promptName).toHaveBeenCalledWith(null); - expect(calls.reserveRoute).toHaveBeenCalledWith( - "prompted-sandbox", - expect.objectContaining({ reservationSessionId: session.sessionId }), - ); - expect(result.sandboxName).toBe("prompted-sandbox"); - }); + ])( + "prompts before route reservation when the checkpoint identity %s", + async (_label, identity) => { + const session = createSession({ + sandboxName: "stale-sandbox", + provider: "nvidia-prod", + model: "nvidia/nemotron-test", + endpointUrl: "https://integrate.api.nvidia.com/v1", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + preferredInferenceApi: "openai-responses", + }); + session.steps.provider_selection.status = "complete"; + session.checkpoint = { + ...deriveCheckpointFromSession(session), + sandboxIdentity: identity, + }; + const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); + calls.promptName.mockResolvedValueOnce("prompted-sandbox"); + + const result = await handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + sandboxName: "stale-sandbox", + }); + + expect(calls.promptName).toHaveBeenCalledWith(null); + expect(calls.reserveRoute).toHaveBeenCalledWith( + "prompted-sandbox", + expect.objectContaining({ reservationSessionId: session.sessionId }), + ); + expect(result.sandboxName).toBe("prompted-sandbox"); + }, + ); it("does not reserve a route when resume skips inference after sandbox completion (#6562)", async () => { const session = createSession({ @@ -1071,6 +1083,7 @@ describe("handleProviderInferenceState", () => { expect.any(Function), expect.any(Function), session.sessionId, + expect.any(Function), ); expect(setupInference).toHaveBeenCalledWith( "my-assistant", @@ -1388,6 +1401,7 @@ describe("handleProviderInferenceState", () => { expect.any(Function), expect.any(Function), expect.any(String), + expect.any(Function), ); expect(setupNim).toHaveBeenNthCalledWith( 2, @@ -1399,6 +1413,7 @@ describe("handleProviderInferenceState", () => { expect.any(Function), expect.any(Function), expect.any(String), + expect.any(Function), ); expect(setupInference).toHaveBeenCalledTimes(2); expect(result.model).toBe("good"); diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index bc5a8362804..9cf48fa871a 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -84,6 +84,8 @@ export interface ProviderInferenceSetupOptions { reservationSessionId?: string; /** Recheck recorded-route ownership after acquiring route mutation locks. */ isRecordedProviderRecoveryAuthorized?: () => boolean; + /** Recheck the receipt-bound policy requirements at each inference mutation edge. */ + revalidatePolicyRequirements?: (operation: string) => void; /** Operation-scoped provider request selected for this onboarding attempt. */ hostLocalInference?: HostLocalInferenceStartupSelection; /** Proxy token prepared after configuration review; avoids repeating host mutations in setup. */ @@ -159,6 +161,18 @@ export interface ProviderInferenceStateOptions { deps: { checkGatewayRouteCompatibility: CurrentGatewayRouteCompatibilityCheck; preflightGatewayRouteDiscovery: CurrentGatewayRouteDiscoveryPreflight; + preflightPolicyRequirements(input: { + gatewayName: string; + sandboxName: string | null; + agent: Agent; + selectedMessagingChannels: readonly string[]; + hermesToolGateways: readonly string[]; + gpuPassthrough: boolean; + provider: string | null; + webSearchConfig: WebSearchConfig | null; + observabilityEnabled: boolean; + operation: string; + }): void; getSandboxRecoveryAuthority( sandboxName: string, sessionId: string | null | undefined, @@ -181,6 +195,10 @@ export interface ProviderInferenceStateOptions { ) => GatewayRouteDiscoveryConstraints, canProbeRoute?: (provider: string) => boolean, recoverySessionId?: string | null, + revalidatePolicyRequirements?: ( + route: ProviderInferenceProbeRoute, + operation: string, + ) => void, ): Promise; setupInference( sandboxName: string | null, @@ -206,10 +224,12 @@ export interface ProviderInferenceStateOptions { gatewayName: string, provider: string | null | undefined, credentialEnv: string | null | undefined, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise<{ forceInferenceSetup: boolean; credentialEnv: string | null }>; ensureManagedLlamaCppResumeReady( provider: string | null | undefined, sandboxName: string | null | undefined, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise; isResumeProviderSurfaceReady( gatewayName: string, @@ -671,10 +691,12 @@ async function ensureLegacyManagedLlamaCppResumeReady( ensure: ( provider: string | null | undefined, sandboxName: string | null | undefined, + revalidatePolicyRequirements?: (operation: string) => void, ) => Promise, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise { if (selection?.setupOptions.hostLocalInference?.request.service === "llama-cpp") return; - await ensure(provider, sandboxName); + await ensure(provider, sandboxName, revalidatePolicyRequirements); } function endpointSourceForCurrentUrl( @@ -1023,6 +1045,7 @@ export async function handleProviderInferenceState({ let compatibleEndpointReasoningEffort = initial.compatibleEndpointReasoningEffort; let nimContainer = initial.nimContainer; const webSearchConfig = initial.webSearchConfig; + const observabilityEnabled = session?.observabilityEnabled === true; let forceProviderSelection = initialForceProviderSelection; let allowToolsIncompatible = false; let skipHostInferenceSmoke = false; @@ -1050,6 +1073,25 @@ export async function handleProviderInferenceState({ const stateResults: OnboardStateTransitionResult[] = []; const retryStateResults: OnboardStateTransitionResult[] = []; + const revalidatePolicyRequirements = ( + operation: string, + requiredProvider: string | null = provider, + ): void => + deps.preflightPolicyRequirements({ + gatewayName, + sandboxName, + agent, + selectedMessagingChannels, + hermesToolGateways, + gpuPassthrough, + provider: requiredProvider, + webSearchConfig, + observabilityEnabled, + operation, + }); + + revalidatePolicyRequirements("select an inference provider"); + while (true) { // Drop a context window auto-detected by a prior compatible-endpoint pass // before every provider-selection path — fresh, resume, and repair — so a @@ -1112,13 +1154,23 @@ export async function handleProviderInferenceState({ // gateway-owned llama.cpp lifecycle before the selection shortcut can // skip setup. The dependency is a no-op for operator-attached llama.cpp // routes because those routes have no matching managed owner state. + revalidatePolicyRequirements( + `recover managed runtime for inference provider ${JSON.stringify(provider)}`, + ); await ensureLegacyManagedLlamaCppResumeReady( earlyManagedLlamaLifecycleSelection, provider, sandboxName, deps.ensureManagedLlamaCppResumeReady, + (operation) => revalidatePolicyRequirements(operation, provider), + ); + revalidatePolicyRequirements(`recover inference provider ${JSON.stringify(provider)}`); + const recovery = await deps.ensureResumeProviderReady( + gatewayName, + provider, + credentialEnv, + (operation) => revalidatePolicyRequirements(operation, provider), ); - const recovery = await deps.ensureResumeProviderReady(gatewayName, provider, credentialEnv); forceInferenceSetup ||= recovery.forceInferenceSetup; credentialEnv = recovery.credentialEnv; // Rebuild may be resuming a legacy session whose step marker was never @@ -1182,6 +1234,7 @@ export async function handleProviderInferenceState({ if ((!selectedAgentName || selectedAgentName === "openclaw") && reusableResumeSandboxName) { deps.log(` [resume] Reusing sandbox name: ${reusableResumeSandboxName}.`); } + revalidatePolicyRequirements("record resumed provider selection"); await deps.recordStateSkipped("provider_selection", { reason: "resume", provider, @@ -1197,6 +1250,10 @@ export async function handleProviderInferenceState({ ); compatibleEndpointReasoning = configuredReasoning.reasoning; compatibleEndpointReasoningEffort = configuredReasoning.effort; + revalidatePolicyRequirements( + `repair local inference provider ${JSON.stringify(resumedSelection.provider)}`, + resumedSelection.provider, + ); await repairResumedLocalInference(resumedSelection.provider, resumedSelection.model, agent, { ...deps, repairLocalInferenceSystemdOverrideOrExit: (options) => @@ -1210,6 +1267,7 @@ export async function handleProviderInferenceState({ // Station resume wrapper restores the exact provider/model as non-interactive env input, // so this re-runs the failed managed install without presenting selection prompts and // obtains a fresh checkpoint identity before the provider step is committed. + revalidatePolicyRequirements("record provider selection start"); await deps.startRecordedStep("provider_selection"); const recoverRecordedProvider = providerRecovery.shouldRecover(); const selection = await withProviderSelectionTrace( @@ -1238,6 +1296,7 @@ export async function handleProviderInferenceState({ return preflight.ok || isAdvisoryGatewayRouteConflict(preflight.result); }, providerRecovery.sessionId, + (route, operation) => revalidatePolicyRequirements(operation, route.provider), ), ); model = selection.model; @@ -1307,6 +1366,7 @@ export async function handleProviderInferenceState({ preferredInferenceApi, }); } + revalidatePolicyRequirements(`configure inference provider ${JSON.stringify(provider)}`); if ( shouldRecordProviderSelection && (authoritativeResumeConfig || effectiveResume) && @@ -1398,6 +1458,7 @@ export async function handleProviderInferenceState({ const inferenceOptions = { gatewayName, allowToolsIncompatible, + revalidatePolicyRequirements, ...(skipHostInferenceSmoke ? { skipHostInferenceSmoke } : {}), ...(reuseGatewayCredentialWithoutLocalKey ? { reuseGatewayCredentialWithoutLocalKey } @@ -1417,8 +1478,11 @@ export async function handleProviderInferenceState({ selectedProvider, selectedModel, credentialEnv, - () => - deps.setupInference( + () => { + revalidatePolicyRequirements( + `configure inference provider ${JSON.stringify(provider)}`, + ); + return deps.setupInference( confirmedSandboxName, selectedModel, selectedProvider, @@ -1427,7 +1491,8 @@ export async function handleProviderInferenceState({ hermesAuthMethod, hermesToolGateways, inferenceOptions, - ), + ); + }, ); } finally { clearStagedCredentialEnv(deps, credentialEnv); @@ -1441,6 +1506,7 @@ export async function handleProviderInferenceState({ forceProviderSelection = true; continue; } + revalidatePolicyRequirements("record successful resumed inference configuration"); session = await deps.recordStepComplete( "inference", deps.toSessionUpdates({ @@ -1453,6 +1519,7 @@ export async function handleProviderInferenceState({ hermesToolGateways, }), ); + revalidatePolicyRequirements("finish successful resumed inference configuration"); break; } const sandboxStepComplete = session?.steps?.sandbox?.status === "complete"; @@ -1478,6 +1545,9 @@ export async function handleProviderInferenceState({ credentialEnv, preferredInferenceApi, }); + revalidatePolicyRequirements( + `reconcile model router for inference provider ${JSON.stringify(provider)}`, + ); try { await deps.reconcileModelRouter(); } catch (err) { @@ -1486,12 +1556,20 @@ export async function handleProviderInferenceState({ ); deps.exitProcess(1); } + revalidatePolicyRequirements( + `update routed inference provider ${JSON.stringify(provider)}`, + ); const reupserted = deps.reupsertRoutedProvider( gatewayName, selectedProvider, endpointUrl, credentialEnv, ); + if (reupserted.ok && resumeReservationName) { + revalidatePolicyRequirements( + `reserve routed inference route for sandbox ${JSON.stringify(resumeReservationName)}`, + ); + } const reservationEndpointSource = endpointSourceForCurrentUrl( endpointSource, reupserted.endpointUrl, @@ -1537,6 +1615,9 @@ export async function handleProviderInferenceState({ credentialEnv, preferredInferenceApi, }); + revalidatePolicyRequirements( + `reserve inference route for sandbox ${JSON.stringify(resumeReservationName)}`, + ); return deps.reserveSandboxInferenceRoute(resumeReservationName, { provider: selectedProvider, model: selectedModel, @@ -1553,12 +1634,14 @@ export async function handleProviderInferenceState({ deps.exitProcess(1); } } + revalidatePolicyRequirements("record reused inference setup"); deps.skippedStepMessage("inference", `${provider} / ${model}`); await deps.recordStateSkipped("inference", { reason: "resume", provider, model, }); + revalidatePolicyRequirements("record successful reused inference configuration"); if (nimContainer && sandboxName) deps.registryUpdateSandbox(sandboxName, { nimContainer }); session = await deps.recordStepComplete( "inference", @@ -1572,6 +1655,7 @@ export async function handleProviderInferenceState({ hermesToolGateways, }), ); + revalidatePolicyRequirements("finish successful reused inference configuration"); break; } @@ -1621,6 +1705,7 @@ export async function handleProviderInferenceState({ !effectiveResume && !deferProviderSelectionUntilInference ) { + revalidatePolicyRequirements("record reviewed provider selection"); session = await deps.recordStepComplete( "provider_selection", deps.toSessionUpdates({ @@ -1642,6 +1727,7 @@ export async function handleProviderInferenceState({ // secret-free route. Do not start or persist the legacy host Ollama // proxy alongside it; that would leave cross-engine residue before the // provider-owned transaction can prove and commit its authority. + revalidatePolicyRequirements(`prepare local inference provider ${JSON.stringify(provider)}`); const preparedOllamaProxyToken = await prepareSelectedLocalProvider( activeHostLocalInferenceSetupOptions.hostLocalInference, provider, @@ -1650,6 +1736,7 @@ export async function handleProviderInferenceState({ const inferenceOptions = { gatewayName, allowToolsIncompatible, + revalidatePolicyRequirements, ...(preparedOllamaProxyToken ? { preparedOllamaProxyToken } : {}), ...(skipHostInferenceSmoke ? { skipHostInferenceSmoke } : {}), ...(reuseGatewayCredentialWithoutLocalKey ? { reuseGatewayCredentialWithoutLocalKey } : {}), @@ -1667,14 +1754,16 @@ export async function handleProviderInferenceState({ ), ...activeHostLocalInferenceSetupOptions, }; + revalidatePolicyRequirements("record inference setup start"); await deps.startRecordedStep("inference", { provider, model }); inferenceResult = await withInferenceTrace( confirmedSandboxName, selectedProvider, selectedModel, credentialEnv, - () => - deps.setupInference( + () => { + revalidatePolicyRequirements(`configure inference provider ${JSON.stringify(provider)}`); + return deps.setupInference( confirmedSandboxName, selectedModel, selectedProvider, @@ -1683,7 +1772,8 @@ export async function handleProviderInferenceState({ hermesAuthMethod, hermesToolGateways, inferenceOptions, - ), + ); + }, ); } finally { clearStagedCredentialEnv(deps, credentialEnv); @@ -1706,6 +1796,7 @@ export async function handleProviderInferenceState({ endpointUrl = hostLocalRoute.endpointUrl; endpointSource = hostLocalRoute.endpointSource; onboardEndpointUrl = hostLocalRoute.onboardEndpointUrl; + revalidatePolicyRequirements("record successful inference configuration"); if (nimContainer && sandboxName) deps.registryUpdateSandbox(sandboxName, { nimContainer }); if (deferProviderSelectionUntilInference) { // Provider selection remains in progress until its inference route has @@ -1729,6 +1820,7 @@ export async function handleProviderInferenceState({ stationExpressModelIdentity: vllmModelIdentity, }), ); + revalidatePolicyRequirements("record successful deferred provider selection"); } session = await deps.recordStepComplete( "inference", @@ -1746,6 +1838,7 @@ export async function handleProviderInferenceState({ ...(healAdjustedInferenceApi ? { preferredInferenceApi } : {}), }), ); + revalidatePolicyRequirements("finish successful inference configuration"); break; } diff --git a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts index 9ec4f8cad8f..f828537e3f8 100644 --- a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts @@ -25,6 +25,30 @@ const resourceProfiles: [string, { cpu: string; memory: string } | null][] = [ ]; describe("sandbox create intent machine boundary", () => { + it("checks final policy requirements before credential provider registration (#9833)", async () => { + const preflightPolicyRequirements = vi.fn(() => { + throw new Error("external policy authority must supply the selected route"); + }); + const { deps, calls } = createDeps({ preflightPolicyRequirements }); + calls.setupMessaging.mockResolvedValue(["telegram"]); + + await expect(handleSandboxState(baseOptions(deps))).rejects.toThrow( + /external policy authority must supply/u, + ); + + expect(preflightPolicyRequirements).toHaveBeenCalledWith( + expect.objectContaining({ + provider: "provider", + selectedMessagingChannels: ["telegram"], + observabilityEnabled: false, + }), + ); + expect(calls.stageCredentialProviders).not.toHaveBeenCalled(); + expect(calls.resolveCreateIntent).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + expect(calls.updateSandbox).not.toHaveBeenCalled(); + }); + it("rejects deterministic create conflicts before resume recreation mutates state (#6226)", async () => { const session = createSession({ sandboxName: "saved" }); session.steps.sandbox.status = "complete"; @@ -166,6 +190,36 @@ describe("sandbox create intent machine boundary", () => { }); }); + it.each([ + { label: "resume", authoritativeResumeConfig: false }, + { label: "repair", authoritativeResumeConfig: true }, + ])( + "suppresses stale rebuild presets at the externally managed $label create boundary (#9833)", + async ({ authoritativeResumeConfig }) => { + const session = createSession({ + sandboxName: "saved", + policyAuthority: "externally-managed", + }); + session.policyPresets = ["github"]; + const { deps, calls } = createDeps({}, session); + + await handleSandboxState({ + ...baseOptions(deps, session), + authoritativeResumeConfig, + rebuildPolicyPresets: ["github"], + resume: true, + sandboxName: "saved", + }); + + const createIntent = calls.createSandbox.mock.calls[0]?.at(-1); + expect(createIntent).not.toHaveProperty("rebuildPolicyPresets"); + expect(createIntent).toMatchObject({ + resolved: { policy: { options: { additionalPresets: [] } } }, + }); + expect(session.policyPresets).toBeNull(); + }, + ); + it("carries an explicit recreate request through a fresh sandbox decision (#8847)", async () => { const session = createSession({ sandboxName: "same-sandbox" }); const { deps, calls } = createDeps({ getSandboxReuseState: () => "ready" }); @@ -394,6 +448,7 @@ describe("sandbox create intent machine boundary", () => { requiredBindings: [ { name: "tm-brave-search", type: "brave", credentialEnv: "BRAVE_API_KEY" }, ], + revalidatePolicyRequirements: expect.any(Function), }); expect(stageSandboxCredentialProviders.mock.invocationCallOrder[0]).toBeGreaterThan( setupMessagingChannels.mock.invocationCallOrder[0] ?? Number.NEGATIVE_INFINITY, @@ -413,6 +468,7 @@ describe("sandbox create intent machine boundary", () => { credentialEnv: "TELEGRAM_BOT_TOKEN", }, ], + revalidatePolicyRequirements: expect.any(Function), }); expect(stageSandboxCredentialProviders.mock.invocationCallOrder[1]).toBeGreaterThan( setupMessagingChannels.mock.invocationCallOrder[0] ?? Number.NEGATIVE_INFINITY, @@ -551,65 +607,66 @@ describe("sandbox create intent machine boundary", () => { expect(result.selectedMessagingChannels).toEqual([]); }); - it.each( - resourceProfiles, - )("reuses %s after intent resolution is interrupted and recomputes the intent (#6743)", async (_label, selectedResourceProfile) => { - const messagingPlan = makeMinimalPlan("tm"); - const durableSession = createSession({ - sandboxName: "tm", - webSearchConfig: braveConfig, - messagingPlan, - resourceProfile: null, - sandboxPromptProgress: { - sandboxName: true, - webSearch: true, - messaging: true, - resourceProfile: false, - }, - }); - const updateSession = vi.fn((mutator: (value: typeof durableSession) => void) => { - mutator(durableSession); - return durableSession; - }); - const recordStepComplete = vi.fn(async (_stepName: string, updates: object) => { - Object.assign(durableSession, updates); - return durableSession; - }); - const { deps, calls } = createDeps({ updateSession, recordStepComplete }); - calls.selectResourceProfile.mockResolvedValue(selectedResourceProfile); - calls.resolveCreateIntent.mockRejectedValueOnce(new Error("intent resolution interrupted")); - - const options = () => ({ - ...baseOptions(deps, durableSession), - resume: true, - sandboxName: durableSession.sandboxName, - webSearchConfig: durableSession.webSearchConfig, - }); - await expect(handleSandboxState(options())).rejects.toThrow("intent resolution interrupted"); - - expect(durableSession.sandboxPromptProgress.resourceProfile).toBe(true); - expect(durableSession.resourceProfile).toEqual(selectedResourceProfile); - expect(calls.startStep).not.toHaveBeenCalled(); - expect(calls.createSandbox).not.toHaveBeenCalled(); - - await handleSandboxState(options()); - - expect(calls.configureWebSearch).not.toHaveBeenCalled(); - expect(calls.setupMessaging).not.toHaveBeenCalled(); - expect(calls.promptName).not.toHaveBeenCalled(); - expect(calls.selectResourceProfile).toHaveBeenCalledTimes(1); - expect(calls.resolveCreateIntent).toHaveBeenCalledTimes(2); - expect(calls.resolveCreateIntent.mock.calls[1]?.[0]).toEqual( - calls.resolveCreateIntent.mock.calls[0]?.[0], - ); - expect(calls.resolveCreateIntent).toHaveBeenLastCalledWith( - expect.objectContaining({ resourceProfile: selectedResourceProfile }), - ); - expect(calls.createSandbox).toHaveBeenCalledTimes(1); - expect((calls.createSandbox.mock.calls[0] as unknown[])[11]).toEqual(selectedResourceProfile); + it.each(resourceProfiles)( + "reuses %s after intent resolution is interrupted and recomputes the intent (#6743)", + async (_label, selectedResourceProfile) => { + const messagingPlan = makeMinimalPlan("tm"); + const durableSession = createSession({ + sandboxName: "tm", + webSearchConfig: braveConfig, + messagingPlan, + resourceProfile: null, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: false, + }, + }); + const updateSession = vi.fn((mutator: (value: typeof durableSession) => void) => { + mutator(durableSession); + return durableSession; + }); + const recordStepComplete = vi.fn(async (_stepName: string, updates: object) => { + Object.assign(durableSession, updates); + return durableSession; + }); + const { deps, calls } = createDeps({ updateSession, recordStepComplete }); + calls.selectResourceProfile.mockResolvedValue(selectedResourceProfile); + calls.resolveCreateIntent.mockRejectedValueOnce(new Error("intent resolution interrupted")); - const serializedSession = JSON.stringify(durableSession); - expect(serializedSession).not.toContain('"resolved"'); - expect(serializedSession).not.toContain('"resourceCreateArgs"'); - }); + const options = () => ({ + ...baseOptions(deps, durableSession), + resume: true, + sandboxName: durableSession.sandboxName, + webSearchConfig: durableSession.webSearchConfig, + }); + await expect(handleSandboxState(options())).rejects.toThrow("intent resolution interrupted"); + + expect(durableSession.sandboxPromptProgress.resourceProfile).toBe(true); + expect(durableSession.resourceProfile).toEqual(selectedResourceProfile); + expect(calls.startStep).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + + await handleSandboxState(options()); + + expect(calls.configureWebSearch).not.toHaveBeenCalled(); + expect(calls.setupMessaging).not.toHaveBeenCalled(); + expect(calls.promptName).not.toHaveBeenCalled(); + expect(calls.selectResourceProfile).toHaveBeenCalledTimes(1); + expect(calls.resolveCreateIntent).toHaveBeenCalledTimes(2); + expect(calls.resolveCreateIntent.mock.calls[1]?.[0]).toEqual( + calls.resolveCreateIntent.mock.calls[0]?.[0], + ); + expect(calls.resolveCreateIntent).toHaveBeenLastCalledWith( + expect.objectContaining({ resourceProfile: selectedResourceProfile }), + ); + expect(calls.createSandbox).toHaveBeenCalledTimes(1); + expect((calls.createSandbox.mock.calls[0] as unknown[])[11]).toEqual(selectedResourceProfile); + + const serializedSession = JSON.stringify(durableSession); + expect(serializedSession).not.toContain('"resolved"'); + expect(serializedSession).not.toContain('"resourceCreateArgs"'); + }, + ); }); 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 new file mode 100644 index 00000000000..ea37b33227d --- /dev/null +++ b/src/lib/onboard/machine/handlers/sandbox-policy-authority-completion.test.ts @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { createSession } from "../../../state/onboard-session"; +import { handleSandboxState } from "./sandbox"; +import { baseOptions, bindJournaledRecreate, createDeps } from "./sandbox-test-fixtures"; + +vi.mock("../../messaging-channel-setup", () => ({ + detectMessagingChannelsFromEnv: vi.fn(() => []), +})); + +function refuseAt(targetOperation: string) { + const actions = new Map void>([ + [ + targetOperation, + () => { + throw new Error("external policy authority must supply the final sandbox entries"); + }, + ], + ]); + return vi.fn((input: { operation: string }) => actions.get(input.operation)?.()); +} + +describe("sandbox completion policy authority", () => { + 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 }); + + await expect(handleSandboxState(baseOptions(deps))).rejects.toThrow( + /external policy authority must supply/u, + ); + + expect(calls.createSandbox).toHaveBeenCalledOnce(); + expect(calls.updateSandbox).not.toHaveBeenCalled(); + expect(calls.complete).not.toHaveBeenCalled(); + }); + + it("rechecks after repair persistence before registry completion (#9833)", async () => { + const session = createSession({ sandboxName: "saved" }); + const journal = bindJournaledRecreate(session); + const preflightPolicyRequirements = refuseAt("complete sandbox repair"); + const { deps, calls } = createDeps( + { + getSandboxReuseState: () => "not_ready", + getSandboxRecreateObservation: journal.observe, + createSandbox: journal.completeCreate, + preflightPolicyRequirements, + }, + session, + ); + + await expect( + handleSandboxState({ + ...baseOptions(deps, session), + resume: true, + sandboxName: "saved", + }), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(calls.repairEvent).toHaveBeenCalledWith("state.repair.completed", { + state: "sandbox", + metadata: { repair: "recorded-sandbox-cleanup", sandboxName: "saved" }, + }); + expect(calls.updateSandbox).not.toHaveBeenCalled(); + expect(calls.complete).not.toHaveBeenCalled(); + }); + + it.each([ + { + operation: "register the created sandbox", + registryCalls: 0, + completionCalls: 0, + }, + { + operation: "complete the sandbox onboarding session", + registryCalls: 1, + completionCalls: 0, + }, + { + operation: "record the final sandbox creation receipt", + registryCalls: 1, + completionCalls: 1, + }, + ])( + "rechecks before $operation mutation (#9833)", + async ({ operation, registryCalls, completionCalls }) => { + const session = createSession(); + const preflightPolicyRequirements = refuseAt(operation); + const { deps, calls, getSession } = createDeps({ preflightPolicyRequirements }, session); + + await expect(handleSandboxState(baseOptions(deps, session))).rejects.toThrow( + /external policy authority must supply/u, + ); + + expect(calls.updateSandbox).toHaveBeenCalledTimes(registryCalls); + expect(calls.complete).toHaveBeenCalledTimes(completionCalls); + expect(getSession().checkpoint?.effectGroups.sandbox_create).toBeUndefined(); + expect(getSession().checkpoint?.effectGroups.sandbox_register).toBeUndefined(); + }, + ); +}); diff --git a/src/lib/onboard/machine/handlers/sandbox-provider-effect-replay.test.ts b/src/lib/onboard/machine/handlers/sandbox-provider-effect-replay.test.ts index bec9781bc79..bd72bbafe24 100644 --- a/src/lib/onboard/machine/handlers/sandbox-provider-effect-replay.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-provider-effect-replay.test.ts @@ -151,6 +151,7 @@ describe("handleSandboxState provider effect replay", () => { webSearchConfig: null, agent: null, requiredBindings: slackProviderBindings, + revalidatePolicyRequirements: expect.any(Function), }); expect(calls.createSandbox).toHaveBeenCalledTimes(1); expect(result.session?.checkpoint?.bindings).toEqual({ @@ -238,6 +239,7 @@ describe("handleSandboxState provider effect replay", () => { webSearchConfig: { fetchEnabled: true, provider: "tavily" }, agent: null, requiredBindings: [tavilyBinding], + revalidatePolicyRequirements: expect.any(Function), }); expect(calls.createSandbox).toHaveBeenCalledTimes(1); expect(result.session?.checkpoint?.bindings).toEqual({ diff --git a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts index b22295b246d..6aebcdd37b2 100644 --- a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts +++ b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts @@ -183,6 +183,7 @@ export function createDeps( getRecordedChannels: vi.fn(() => null), showMessagingStage: vi.fn(), setupMessaging: vi.fn(async () => [] as string[]), + preflightPolicyRequirements: vi.fn(), stageCredentialProviders: vi.fn(async () => [] as CheckpointProviderBinding[]), promptName: vi.fn(async () => "my-assistant"), selectResourceProfile: vi.fn(async () => null as ResourceProfile | null), @@ -308,6 +309,7 @@ export function createDeps( clearPlanEnv: calls.clearPlanEnv, getRegistrySandboxMessagingAuthority: () => ({ authoritative: false, plan: null }), providerMatchesGatewayCredential: () => true, + preflightPolicyRequirements: calls.preflightPolicyRequirements, stageSandboxCredentialProviders: calls.stageCredentialProviders, promptValidatedSandboxName: calls.promptName, selectResourceProfileForSandbox: calls.selectResourceProfile, diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 7039dd650b4..e0d0e9aafe6 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -305,12 +305,25 @@ export interface SandboxStateOptions< sandboxName: string, ): import("../../../messaging/plan-authority").RegistryMessagingAuthority; providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; + preflightPolicyRequirements(input: { + gatewayName: string; + sandboxName: string | null; + agent: Agent; + selectedMessagingChannels: readonly string[]; + hermesToolGateways: readonly string[]; + gpuPassthrough: boolean; + provider: string | null; + webSearchConfig: WebSearchConfig | null; + observabilityEnabled: boolean; + operation: string; + }): void; stageSandboxCredentialProviders(input: { sandboxName: string; enabledChannels: readonly string[]; webSearchConfig: WebSearchConfig | null; agent: Agent; requiredBindings: readonly CheckpointProviderBinding[]; + revalidatePolicyRequirements?(operation: string): void; }): Promise; promptValidatedSandboxName(agent: Agent): Promise; selectResourceProfileForSandbox(): Promise; @@ -487,6 +500,7 @@ function rebuildPolicyPresetsForCreateIntent( session: Session | null, sandboxName: string, ): Pick { + if (session?.policyAuthority === "externally-managed") return {}; // A later `onboard --resume` no longer has the outer rebuild's in-memory // options. The matching recreate journal makes its filtered session value // the durable replacement target instead of the preserved source row. @@ -499,6 +513,18 @@ function rebuildPolicyPresetsForCreateIntent( return Array.isArray(selectedValue) ? { rebuildPolicyPresets: [...selectedValue] } : {}; } +function clearExternallyManagedPolicyPresets( + session: Session | null, + updateSession: (mutator: (current: Session) => Session | void) => Session, +): void { + if (session?.policyAuthority !== "externally-managed" || session.policyPresets === null) return; + updateSession((current) => { + if (current.policyAuthority === "externally-managed") current.policyPresets = null; + return current; + }); + session.policyPresets = null; +} + /** Replace a resumed create-plan snapshot with the outer rebuild's normalized built-ins. */ function applyAuthoritativeRebuildPolicyPresets( intent: ResolvedSandboxCreateIntent, @@ -1436,13 +1462,40 @@ class SandboxStateFlow< return { ...state, session }; } + private revalidatePolicyRequirements( + sandboxName: string, + selectedMessagingChannels: readonly string[], + webSearchConfig: WebSearchConfig | null, + session: Session | null, + operation: string, + ): void { + this.deps.preflightPolicyRequirements({ + gatewayName: this.options.gatewayName, + sandboxName, + agent: this.options.agent, + selectedMessagingChannels, + hermesToolGateways: effectiveHermesToolGatewaysForWebSearch( + this.options.agent as { name?: string } | null, + webSearchConfig as unknown as SharedWebSearchConfig | null, + this.options.hermesToolGateways, + ), + gpuPassthrough: session?.gpuPassthrough === true, + provider: this.options.provider, + webSearchConfig, + observabilityEnabled: session?.observabilityEnabled === true, + operation, + }); + } + private async registerCompletedCredentialProviders( sandboxName: string, enabledChannels: readonly string[], + selectedMessagingChannels: readonly string[], webSearchConfig: WebSearchConfig | null, requiredBindings: readonly CheckpointProviderBinding[], group: ProviderEffectGroupName, checkpoint: OnboardCheckpoint | null, + session: Session | null, force = false, ): Promise { if ( @@ -1481,12 +1534,24 @@ class SandboxStateFlow< const registeredProviders = await this.deps.withGatewayRouteMutationLock( this.options.gatewayName, async () => { + const revalidatePolicyRequirements = (operation: string) => + this.revalidatePolicyRequirements( + sandboxName, + selectedMessagingChannels, + webSearchConfig, + session, + operation, + ); + revalidatePolicyRequirements( + `register credential providers for sandbox ${JSON.stringify(sandboxName)}`, + ); const staged = await this.deps.stageSandboxCredentialProviders({ sandboxName, enabledChannels, webSearchConfig, agent: this.options.agent, requiredBindings, + revalidatePolicyRequirements, }); const stagedProviderNames = new Set(); for (const binding of staged) { @@ -1535,10 +1600,12 @@ class SandboxStateFlow< await this.registerCompletedCredentialProviders( sandboxName, state.selectedMessagingChannels, + state.selectedMessagingChannels, null, requiredBindings, "messaging_providers", state.session?.checkpoint ?? null, + state.session, force, ); }; @@ -1594,6 +1661,7 @@ class SandboxStateFlow< resourceProfile: ResourceProfile | null, hermesToolGateways: readonly string[], ): Promise { + clearExternallyManagedPolicyPresets(state.session, this.deps.updateSession); const reuseRegisteredCredentials = this.resumesSandboxPrompts && this.options.resume; const rebuildPolicyPresetSelection = rebuildPolicyPresetsForCreateIntent( this.options.rebuildPolicyPresets, @@ -1888,6 +1956,14 @@ class SandboxStateFlow< state.webSearchConfig as unknown as SharedWebSearchConfig | null, this.options.hermesToolGateways, ); + const revalidatePolicyRequirements = (operation: string) => + this.revalidatePolicyRequirements( + requestedSandboxName, + state.selectedMessagingChannels, + state.webSearchConfig, + state.session, + operation, + ); const extraProviderPlan = this.deps.planRegisteredExtraProviders(this.options.gatewayName); const createAndRecord = async (): Promise> => { this.assertRegistryMessagingPlanUnchanged( @@ -1969,15 +2045,18 @@ class SandboxStateFlow< await this.recordSandboxRecreateRepairFailure(transaction, repairMetadata, error); throw error; } + revalidatePolicyRequirements("complete the created sandbox"); + let recordedTransaction: CheckpointSandboxRecreateTransaction | null; try { - const recordedTransaction = this.reloadSandboxRecreateTransaction(transaction); + recordedTransaction = this.reloadSandboxRecreateTransaction(transaction); this.retireSandboxRecreateSourceWorkload(recordedTransaction, sourceEntry, sandboxName); await this.recordSandboxRecreateRepairSuccess(recordedTransaction, repairMetadata); - this.recordSandboxRecreateRegistryCommit(recordedTransaction); } catch (error) { await this.recordSandboxRecreateRepairFailure(transaction, repairMetadata, error); throw error; } + revalidatePolicyRequirements("complete sandbox repair"); + this.recordSandboxRecreateRegistryCommit(recordedTransaction); // createSandbox() owns the build fingerprint. In particular, reusing an // image must not stamp it with the current version and hide build drift. const { @@ -1986,6 +2065,7 @@ class SandboxStateFlow< ...agentRegistryFields } = this.deps.getSandboxAgentRegistryFields(this.options.agent, !this.options.fromDockerfile); // Preserve the validated route and credential env-var name, never a credential value. + revalidatePolicyRequirements("register the created sandbox"); this.deps.updateSandboxRegistry(sandboxName, { model: this.options.model, provider: this.options.provider, @@ -1998,6 +2078,7 @@ class SandboxStateFlow< }); // Finalization marks the default so a cancelled onboarding cannot leave a // partially configured sandbox selected as the default. + revalidatePolicyRequirements("complete the sandbox onboarding session"); await this.deps.recordStepComplete( "sandbox", this.deps.toSessionUpdates({ @@ -2010,6 +2091,7 @@ class SandboxStateFlow< hermesToolGateways: effectiveHermesToolGateways, }), ); + revalidatePolicyRequirements("record the final sandbox creation receipt"); const recordedSession = this.recordSandboxCreateEffects( transaction, sandboxName, @@ -2161,10 +2243,12 @@ class SandboxStateFlow< await this.registerCompletedCredentialProviders( requestedSandboxName, [], + nextState.selectedMessagingChannels, nextState.webSearchConfig, webSearchProviderBindings, "web_search_provider", nextState.session?.checkpoint ?? null, + nextState.session, ); nextState = this.checkpointProviderEffectGroup( nextState, diff --git a/src/lib/onboard/machine/initial-flow-phases.test.ts b/src/lib/onboard/machine/initial-flow-phases.test.ts index 2f8e55e3984..b739b333f92 100644 --- a/src/lib/onboard/machine/initial-flow-phases.test.ts +++ b/src/lib/onboard/machine/initial-flow-phases.test.ts @@ -163,6 +163,7 @@ describe("initial onboard flow phases", () => { getInitialGatewayReuseState: () => "healthy", assertGatewayReadiness: vi.fn(async () => undefined), gatewayName: "nemoclaw", + bindPolicyAuthority: async (_gatewayName, session) => session, recreateSandbox: () => false, gatewayDeps: { resolveGatewayOwner: () => @@ -434,6 +435,7 @@ describe("initial onboard flow phases", () => { calls.push("assert-gateway-readiness"); }), gatewayName: "nemoclaw", + bindPolicyAuthority: async (_gatewayName, gatewaySession) => gatewaySession, recreateSandbox: () => false, gatewayDeps: { resolveGatewayOwner: () => @@ -615,38 +617,38 @@ describe("initial onboard flow phases", () => { ]); }); - it.each([ - "complete", - "failed", - ] as const)("rejects terminal %s sessions before initial repair effects", async (state) => { - const phase: OnboardSequencePhase = { - state: "preflight", - run: vi.fn((ctx) => ({ - context: ctx, - result: advanceTo("gateway", { metadata: { state: "preflight" } }), - })), - }; - - await expect( - runInitialOnboardFlowSlice({ - context: context({ resume: true }), - runtime: runtime( - createSession({ - machine: { - version: 1, - state, - stateEnteredAt: "2026-06-09T00:00:00.000Z", - revision: 7, - }, - }), - ), - phases: [phase], - resume: true, - recordRepairEvent: repairRecorder(), - }), - ).rejects.toThrow("Unexpected onboarding flow state before slice entry"); - expect(phase.run).not.toHaveBeenCalled(); - }); + it.each(["complete", "failed"] as const)( + "rejects terminal %s sessions before initial repair effects", + async (state) => { + const phase: OnboardSequencePhase = { + state: "preflight", + run: vi.fn((ctx) => ({ + context: ctx, + result: advanceTo("gateway", { metadata: { state: "preflight" } }), + })), + }; + + await expect( + runInitialOnboardFlowSlice({ + context: context({ resume: true }), + runtime: runtime( + createSession({ + machine: { + version: 1, + state, + stateEnteredAt: "2026-06-09T00:00:00.000Z", + revision: 7, + }, + }), + ), + phases: [phase], + resume: true, + recordRepairEvent: repairRecorder(), + }), + ).rejects.toThrow("Unexpected onboarding flow state before slice entry"); + expect(phase.run).not.toHaveBeenCalled(); + }, + ); it.each([ { runKind: "fresh", resume: false }, diff --git a/src/lib/onboard/machine/initial-flow-phases.ts b/src/lib/onboard/machine/initial-flow-phases.ts index 3fef64a6338..aa048cde0b5 100644 --- a/src/lib/onboard/machine/initial-flow-phases.ts +++ b/src/lib/onboard/machine/initial-flow-phases.ts @@ -67,6 +67,10 @@ export interface InitialOnboardFlowPhaseOptions< getInitialGatewayReuseState(): GatewayReuseState; assertGatewayReadiness(): Promise; gatewayName: string; + bindPolicyAuthority( + gatewayName: string, + session: import("../../state/onboard-session").Session | null, + ): Promise; recreateSandbox(): boolean; requiresBindMounts?: boolean; gatewayDeps: GatewayStateOptions["deps"]; @@ -209,8 +213,12 @@ export function createInitialOnboardFlowPhases< requiresBindMounts: options.requiresBindMounts === true, deps: options.gatewayDeps, }); + const policySession = await options.bindPolicyAuthority( + options.gatewayName, + gatewayResult.session, + ); return { - context: { ...context, session: gatewayResult.session }, + context: { ...context, session: policySession }, result: gatewayResult.stateResult, }; }, diff --git a/src/lib/onboard/machine/resume-provider-shim.test.ts b/src/lib/onboard/machine/resume-provider-shim.test.ts index b5277674ac2..3c33eb3f0c5 100644 --- a/src/lib/onboard/machine/resume-provider-shim.test.ts +++ b/src/lib/onboard/machine/resume-provider-shim.test.ts @@ -39,6 +39,7 @@ describe("createResumeProviderShim", () => { expect.any(String), null, expect.any(Function), + undefined, ); }); @@ -68,8 +69,8 @@ describe("createResumeProviderShim", () => { ); expect(resumeManagedLlamaCppRuntime).toHaveBeenCalledTimes(2); - expect(resumeManagedLlamaCppRuntime).toHaveBeenNthCalledWith(1, "spark-agent"); - expect(resumeManagedLlamaCppRuntime).toHaveBeenNthCalledWith(2, "operator-attached"); + expect(resumeManagedLlamaCppRuntime).toHaveBeenNthCalledWith(1, "spark-agent", undefined); + expect(resumeManagedLlamaCppRuntime).toHaveBeenNthCalledWith(2, "operator-attached", undefined); }); it("propagates a conflicting managed llama.cpp owner instead of reusing its provider", async () => { diff --git a/src/lib/onboard/machine/resume-provider-shim.ts b/src/lib/onboard/machine/resume-provider-shim.ts index b26fd2ed667..2eb54cbb861 100644 --- a/src/lib/onboard/machine/resume-provider-shim.ts +++ b/src/lib/onboard/machine/resume-provider-shim.ts @@ -27,7 +27,10 @@ export type ResumeProviderShimDeps = { isRoutedInferenceProvider: ResumeProviderRecoveryDeps["isRoutedInferenceProvider"]; replaceNamedCredential: ResumeProviderRecoveryDeps["replaceNamedCredential"]; /** Recover an exact gateway-scoped managed runtime; false means no managed owner state exists. */ - resumeManagedLlamaCppRuntime?: (sandboxName: string) => Promise; + resumeManagedLlamaCppRuntime?: ( + sandboxName: string, + revalidatePolicyRequirements?: (operation: string) => void, + ) => Promise; }; export function createResumeProviderShim(deps: ResumeProviderShimDeps) { @@ -35,16 +38,18 @@ export function createResumeProviderShim(deps: ResumeProviderShimDeps) { async ensureManagedLlamaCppResumeReady( provider: string | null | undefined, sandboxName: string | null | undefined, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise { if (provider !== "llama-cpp-local" || !sandboxName || !deps.resumeManagedLlamaCppRuntime) { return false; } - return deps.resumeManagedLlamaCppRuntime(sandboxName); + return deps.resumeManagedLlamaCppRuntime(sandboxName, revalidatePolicyRequirements); }, async ensureResumeProviderReady( gatewayName: string, provider: string | null | undefined, credentialEnv: string | null | undefined, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise { return ensureResumeProviderReadyImpl(provider, credentialEnv, { remoteProviderConfig: onboardProviders.REMOTE_PROVIDER_CONFIG, @@ -56,6 +61,7 @@ export function createResumeProviderShim(deps: ResumeProviderShimDeps) { isNonInteractive: deps.isNonInteractive, note: (message) => console.log(`${D}${message}${R}`), replaceNamedCredential: deps.replaceNamedCredential, + revalidatePolicyRequirements, validateNvidiaApiKeyValue, log: (message) => console.log(message), warn: (message) => console.error(message), diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index bdf12aff70b..24ab4390df4 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -340,6 +340,7 @@ export interface PrepareOnboardSandboxWorkloadLaunchInput { }; readonly plan: { readonly intent: SandboxCreateIntent; + readonly policyAuthority: MaterializeSandboxCreatePlanInput["policyAuthority"]; readonly rebindMessagingTokenDefs: () => Promise; readonly runProviderPreDeleteCleanup: () => void; readonly upsertMessagingProviders: MaterializeSandboxCreatePlanInput["upsertMessagingProviders"]; @@ -369,6 +370,7 @@ export interface PrepareOnboardSandboxWorkloadLaunchInput { export interface PreparedOnboardSandboxWorkloadLaunch { readonly initialSandboxPolicy: InitialSandboxPolicy; readonly policyTier: string | null; + readonly policyAuthority: MaterializeSandboxCreatePlanInput["policyAuthority"]; readonly messagingProviders: string[]; readonly gpuRoutePlan: SandboxCreateIntent["gpuRoutePlan"]; readonly compatibilityPolicyPath: string | null; @@ -412,6 +414,7 @@ export async function prepareOnboardSandboxWorkloadLaunch( const createPlan = input.dependencies.materializeSandboxCreatePlan({ intent: input.plan.intent, fromRef, + policyAuthority: input.plan.policyAuthority, messagingTokenDefs: [...messagingTokenDefs], runProviderPreDeleteCleanup: input.plan.runProviderPreDeleteCleanup, upsertMessagingProviders: input.plan.upsertMessagingProviders, @@ -493,6 +496,7 @@ export async function prepareOnboardSandboxWorkloadLaunch( return { initialSandboxPolicy: createPlan.initialSandboxPolicy, policyTier: createPlan.policyTier, + policyAuthority: createPlan.policyAuthority, messagingProviders: createPlan.messagingProviders, gpuRoutePlan: createPlan.gpuRoutePlan, compatibilityPolicyPath: createPlan.compatibilityPolicyPath, @@ -509,12 +513,14 @@ export async function prepareOnboardSandboxWorkloadLaunch( export function prepareHermesPortableOnboardSandboxLaunch(input: { readonly intent: SandboxCreateIntent; readonly fromRef: string; + readonly policyAuthority: MaterializeSandboxCreatePlanInput["policyAuthority"]; readonly launchInput: Omit; readonly gpuConfig: SandboxGpuConfig; }): PreparedOnboardSandboxWorkloadLaunch { const createPlan = materializeHermesPortableCreatePlan({ intent: input.intent, fromRef: input.fromRef, + policyAuthority: input.policyAuthority, }); const launch = prepareSandboxCreateLaunch({ ...input.launchInput, diff --git a/src/lib/onboard/messaging-host-forward.ts b/src/lib/onboard/messaging-host-forward.ts index f750b35c37a..5cc53465c21 100644 --- a/src/lib/onboard/messaging-host-forward.ts +++ b/src/lib/onboard/messaging-host-forward.ts @@ -25,6 +25,7 @@ export interface MessagingHostForwardRollbackOptions { ) => readonly string[]; readonly cliName: () => string; readonly forwardPortsToStop?: readonly (number | string | null | undefined)[]; + readonly beforeMutation?: (operation: string) => void; readonly error?: (message?: string) => void; readonly exit?: (code: number) => never; } @@ -113,8 +114,12 @@ function abortMessagingHostForwardFailure({ portsToStop.add(String(forward.port)); for (const port of portsToStop) { + rollback.beforeMutation?.( + `stop messaging forward ${port} for sandbox '${sandboxName}' after dashboard failure`, + ); rollback.runOpenshell(["forward", "stop", port, sandboxName], { ignoreError: true }); } + rollback.beforeMutation?.(`remove sandbox '${sandboxName}' after dashboard failure`); const deleteResult = rollback.runOpenshell(["sandbox", "delete", sandboxName], { ignoreError: true, }); diff --git a/src/lib/onboard/policy-authority/preflight.test.ts b/src/lib/onboard/policy-authority/preflight.test.ts new file mode 100644 index 00000000000..bf7811fff8a --- /dev/null +++ b/src/lib/onboard/policy-authority/preflight.test.ts @@ -0,0 +1,141 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { qualifySandboxPolicyAuthority, requiredOnboardPolicyPresets } from "./preflight"; + +const requiredPolicy = { + policyPath: "/tmp/unused.yaml", + sourceBytes: Buffer.from( + "version: 1\nnetwork_policies:\n required_route:\n endpoints: [example.com]\n", + ), + appliedPresets: [], +}; + +describe("sandbox policy authority preflight", () => { + it("includes every final selected policy requirement (#9833)", () => { + expect( + requiredOnboardPolicyPresets({ + additionalPresets: ["github", "github"], + provider: "ollama-local", + webSearchConfig: { provider: "tavily", fetchEnabled: true }, + agentName: "langchain-deepagents-code", + observabilityEnabled: true, + }), + ).toEqual(["github", "local-inference", "tavily", "observability-otlp-local"]); + }); + + it("uses live sandbox metadata and accepts externally supplied requirements (#9833)", () => { + const inspectSandbox = vi.fn(() => ({ + authority: "externally-managed" as const, + effectivePolicy: { + network_policies: { required_route: { endpoints: ["example.com"] } }, + }, + })); + const inspectGlobal = vi.fn(() => ({ + authority: "externally-managed" as const, + effectivePolicy: { + network_policies: { required_route: { endpoints: ["example.com"] } }, + }, + })); + + const result = qualifySandboxPolicyAuthority( + { + sandboxName: "demo", + gatewayName: "nemoclaw", + liveExists: true, + recordedAuthorities: ["externally-managed"], + prepareRequiredPolicy: () => requiredPolicy, + operation: "prepare sandbox 'demo'", + }, + { + inspectGlobalPolicyAuthority: inspectGlobal, + inspectSandboxPolicyAuthority: inspectSandbox, + }, + ); + + expect(result.authority).toBe("externally-managed"); + expect(inspectSandbox).toHaveBeenCalledWith({ + sandboxName: "demo", + gatewayName: "nemoclaw", + }); + expect(inspectGlobal).toHaveBeenCalledWith({ gatewayName: "nemoclaw" }); + }); + + it("stops before cleanup-owning callers when external requirements are missing (#9833)", () => { + const cleanup = vi.fn(() => true); + + expect(() => + qualifySandboxPolicyAuthority( + { + sandboxName: "demo", + gatewayName: "nemoclaw", + liveExists: false, + recordedAuthorities: [], + prepareRequiredPolicy: () => ({ ...requiredPolicy, cleanup }), + operation: "create sandbox 'demo'", + }, + { + inspectGlobalPolicyAuthority: () => ({ + authority: "externally-managed", + effectivePolicy: { network_policies: {} }, + }), + }, + ), + ).toThrow(/external policy authority to supply/u); + expect(cleanup).toHaveBeenCalledOnce(); + }); + + it("rejects live and create-time authority drift before materializing requirements (#9833)", () => { + const prepareRequiredPolicy = vi.fn(() => requiredPolicy); + + expect(() => + qualifySandboxPolicyAuthority( + { + sandboxName: "demo", + gatewayName: "nemoclaw", + liveExists: true, + recordedAuthorities: ["nemoclaw-managed"], + prepareRequiredPolicy, + operation: "recreate sandbox 'demo'", + }, + { + inspectSandboxPolicyAuthority: () => ({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }), + inspectGlobalPolicyAuthority: () => ({ + authority: "externally-managed", + effectivePolicy: { network_policies: {} }, + }), + }, + ), + ).toThrow(/authority changed/u); + expect(prepareRequiredPolicy).not.toHaveBeenCalled(); + }); + + it("does not materialize requirements for NemoClaw-managed policy (#9833)", () => { + const prepareRequiredPolicy = vi.fn(() => requiredPolicy); + + expect( + qualifySandboxPolicyAuthority( + { + sandboxName: "demo", + gatewayName: "nemoclaw", + liveExists: false, + recordedAuthorities: [], + prepareRequiredPolicy, + operation: "create sandbox 'demo'", + }, + { + inspectGlobalPolicyAuthority: () => ({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }), + }, + ).authority, + ).toBe("nemoclaw-managed"); + expect(prepareRequiredPolicy).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/policy-authority/preflight.ts b/src/lib/onboard/policy-authority/preflight.ts new file mode 100644 index 00000000000..44eaea7dd19 --- /dev/null +++ b/src/lib/onboard/policy-authority/preflight.ts @@ -0,0 +1,283 @@ +// 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 YAML from "yaml"; + +import type { AgentDefinition } from "../../agent/defs"; +import { + assertExternalPolicyRequirements, + assertRecordedPolicyAuthority, + inspectGlobalPolicyAuthority, + inspectSandboxPolicyAuthority, + type SandboxPolicyAuthority, + type SandboxPolicyAuthorityInspection, +} from "../../adapters/openshell/policy-authority"; +import type { SandboxEntry } from "../../state/registry"; +import { type InitialSandboxPolicy, prepareInitialSandboxCreatePolicy } from "../initial-policy"; +import { requiredObservabilityPolicyPresets } from "../observability-policy-presets"; +import { type WebSearchConfig, webSearchProviderForConfig } from "../policy-presets"; +import { getDefaultSandboxNameForAgent } from "../sandbox-agent"; + +const { LOCAL_INFERENCE_POLICY_PROVIDERS } = require("../providers") as { + LOCAL_INFERENCE_POLICY_PROVIDERS: string[]; +}; + +type PolicyAuthorityInspectionDeps = { + readonly inspectGlobalPolicyAuthority?: typeof inspectGlobalPolicyAuthority; + readonly inspectSandboxPolicyAuthority?: typeof inspectSandboxPolicyAuthority; +}; + +/** Bind the global policy authority before provider selection can mutate gateway state. */ +export function qualifyGlobalPolicyAuthority( + input: { + readonly gatewayName: string; + readonly recordedAuthority?: SandboxPolicyAuthority | null; + readonly operation: string; + }, + deps: Pick = {}, +): SandboxPolicyAuthorityInspection { + const inspection = (deps.inspectGlobalPolicyAuthority ?? inspectGlobalPolicyAuthority)({ + gatewayName: input.gatewayName, + }); + if (input.recordedAuthority) { + assertRecordedPolicyAuthority(input.recordedAuthority, inspection.authority, input.operation); + } + return inspection; +} + +function parseRequiredPolicy(content: string, operation: string): Record { + let parsed: unknown; + try { + parsed = YAML.parse(content); + } catch { + throw new Error(`Refusing to ${operation}: the required sandbox policy is invalid.`); + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error(`Refusing to ${operation}: the required sandbox policy is invalid.`); + } + return parsed as Record; +} + +function readInitialPolicy(policy: InitialSandboxPolicy, operation: string): string { + if (policy.sourceBytes) return policy.sourceBytes.toString("utf8"); + try { + return fs.readFileSync(policy.policyPath, "utf8"); + } catch { + throw new Error(`Refusing to ${operation}: the required sandbox policy is unreadable.`); + } +} + +function cleanupRequirement(policy: InitialSandboxPolicy, operation: string): void { + if (policy.cleanup && policy.cleanup() !== true) { + throw new Error(`Refusing to ${operation}: the temporary sandbox policy could not be removed.`); + } +} + +/** Resolve and verify policy authority before sandbox lifecycle effects. */ +export function qualifySandboxPolicyAuthority( + input: { + readonly sandboxName: string; + readonly gatewayName: string; + readonly liveExists: boolean; + readonly recordedAuthorities: readonly (SandboxPolicyAuthority | null | undefined)[]; + readonly prepareRequiredPolicy: () => InitialSandboxPolicy; + readonly operation: string; + }, + deps: PolicyAuthorityInspectionDeps = {}, +): SandboxPolicyAuthorityInspection { + const sandboxInspection = input.liveExists + ? (deps.inspectSandboxPolicyAuthority ?? inspectSandboxPolicyAuthority)({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + }) + : null; + const globalInspection = (deps.inspectGlobalPolicyAuthority ?? inspectGlobalPolicyAuthority)({ + gatewayName: input.gatewayName, + }); + if (sandboxInspection) { + assertRecordedPolicyAuthority( + sandboxInspection.authority, + globalInspection.authority, + input.operation, + ); + } + const inspection = sandboxInspection ?? globalInspection; + + for (const recorded of input.recordedAuthorities) { + if (recorded) { + assertRecordedPolicyAuthority(recorded, inspection.authority, input.operation); + } + } + if (inspection.authority !== "externally-managed") return inspection; + + const requiredPolicy = input.prepareRequiredPolicy(); + try { + const parsedPolicy = parseRequiredPolicy( + readInitialPolicy(requiredPolicy, input.operation), + input.operation, + ); + for (const observed of sandboxInspection + ? [sandboxInspection, globalInspection] + : [globalInspection]) { + assertExternalPolicyRequirements({ + inspection: observed, + requiredPolicy: parsedPolicy, + operation: input.operation, + sandboxName: input.sandboxName, + }); + } + } finally { + cleanupRequirement(requiredPolicy, input.operation); + } + return inspection; +} + +type ProviderPolicyRequirements = { + readonly gatewayName: string; + readonly sandboxName: string | null; + readonly agent: AgentDefinition; + readonly selectedMessagingChannels: readonly string[]; + readonly hermesToolGateways: readonly string[]; + readonly gpuPassthrough: boolean; + readonly provider: string | null; + readonly webSearchConfig: WebSearchConfig | null; + readonly observabilityEnabled: boolean; + readonly operation: string; +}; + +type RevalidatedPolicyContext = Omit< + ProviderPolicyRequirements, + "agent" | "gatewayName" | "observabilityEnabled" | "operation" +> & { + readonly agent: AgentDefinition | null; + readonly session: { readonly observabilityEnabled?: boolean | null } | null; +}; + +/** Include every selected feature that adds a network policy requirement. */ +export function requiredOnboardPolicyPresets(input: { + readonly additionalPresets: readonly string[]; + readonly provider: string | null; + readonly webSearchConfig: WebSearchConfig | null; + readonly agentName: string | null | undefined; + readonly observabilityEnabled: boolean; + readonly hostLocalInferenceRouteOnly?: boolean; +}): string[] { + const required = new Set(input.additionalPresets); + if ( + input.provider && + !input.hostLocalInferenceRouteOnly && + LOCAL_INFERENCE_POLICY_PROVIDERS.includes(input.provider) + ) { + required.add("local-inference"); + } + if (input.webSearchConfig) { + required.add(webSearchProviderForConfig(input.webSearchConfig)); + } + for (const preset of requiredObservabilityPolicyPresets( + input.agentName, + input.observabilityEnabled, + )) { + required.add(preset); + } + return [...required]; +} + +/** Keep gateway and provider authority checks out of the onboarding entry point. */ +type PolicyAuthoritySession = { + policyAuthority?: SandboxPolicyAuthority | null; + policyPresets?: string[] | null; +}; + +export function createOnboardPolicyAuthorityBindings( + runtime: { + readonly GATEWAY_NAME: string; + readonly ROOT: string; + readonly agentDefs: { + readonly loadAgent: (name: string) => AgentDefinition; + }; + readonly agentOnboard: { + readonly getAgentPolicyPath: (agent: AgentDefinition) => string | null; + }; + readonly inspectSandboxForCreate: (sandboxName: string) => { + readonly existingEntry: SandboxEntry | null; + readonly liveExists: boolean; + }; + readonly onboardSession: { + loadSession(): Session | null; + updateSession(mutator: (session: Session) => void): Session | Promise; + }; + }, + policyTier: string | null | undefined, +): { + readonly bindPolicyAuthority: (gatewayName: string, session: Session | null) => Promise; + readonly preflightPolicyRequirements: (requirements: ProviderPolicyRequirements) => void; + readonly revalidatePolicyRequirements: ( + context: RevalidatedPolicyContext, + operation: string, + ) => void; +} { + const preflightPolicyRequirements = (requirements: ProviderPolicyRequirements): void => { + const sandboxName = + requirements.sandboxName ?? getDefaultSandboxNameForAgent(requirements.agent); + const observed = runtime.inspectSandboxForCreate(sandboxName); + qualifySandboxPolicyAuthority({ + sandboxName, + gatewayName: requirements.gatewayName, + liveExists: observed.liveExists, + recordedAuthorities: [ + observed.existingEntry?.policyAuthority, + runtime.onboardSession.loadSession()?.policyAuthority, + ], + operation: requirements.operation, + prepareRequiredPolicy: () => + prepareInitialSandboxCreatePolicy( + runtime.agentOnboard.getAgentPolicyPath(requirements.agent) ?? + path.join(runtime.ROOT, "nemoclaw-blueprint", "policies", "openclaw-sandbox.yaml"), + [...requirements.selectedMessagingChannels], + { + directGpu: requirements.gpuPassthrough, + additionalPresets: requiredOnboardPolicyPresets({ + additionalPresets: requirements.hermesToolGateways, + provider: requirements.provider, + webSearchConfig: requirements.webSearchConfig, + agentName: requirements.agent.name, + observabilityEnabled: requirements.observabilityEnabled, + }), + agentName: requirements.agent.name, + policyTier: observed.existingEntry?.policyTier ?? policyTier, + baselineExclusions: observed.existingEntry?.baselineExclusions ?? [], + }, + ), + }); + }; + return { + async bindPolicyAuthority(gatewayName, session) { + const inspection = qualifyGlobalPolicyAuthority({ + gatewayName, + recordedAuthority: session?.policyAuthority, + operation: "continue onboarding after gateway setup", + }); + return runtime.onboardSession.updateSession((current) => { + current.policyAuthority = inspection.authority; + if (inspection.authority === "externally-managed") current.policyPresets = null; + }); + }, + preflightPolicyRequirements, + revalidatePolicyRequirements(context, operation) { + preflightPolicyRequirements({ + gatewayName: runtime.GATEWAY_NAME, + sandboxName: context.sandboxName, + agent: context.agent ?? runtime.agentDefs.loadAgent("openclaw"), + selectedMessagingChannels: context.selectedMessagingChannels, + hermesToolGateways: context.hermesToolGateways, + gpuPassthrough: context.gpuPassthrough, + provider: context.provider, + webSearchConfig: context.webSearchConfig, + observabilityEnabled: context.session?.observabilityEnabled === true, + operation, + }); + }, + }; +} diff --git a/src/lib/onboard/policy-presets.ts b/src/lib/onboard/policy-presets.ts index 1ad05144425..78f4a503ed9 100644 --- a/src/lib/onboard/policy-presets.ts +++ b/src/lib/onboard/policy-presets.ts @@ -15,6 +15,9 @@ const { LOCAL_INFERENCE_POLICY_PROVIDERS } = require("./providers") as { import { isOpenclawAgent, requiredOpenclawOtelPolicyPresets } from "./openclaw-otel-policy-presets"; +export { webSearchProviderForConfig }; +export type { WebSearchConfig }; + export interface SuggestedPolicyPresetOptions { enabledChannels?: string[] | null; webSearchConfig?: WebSearchConfig | null; diff --git a/src/lib/onboard/provider-key-bridge.ts b/src/lib/onboard/provider-key-bridge.ts index 5f158cadfdd..6b8cf8d6d80 100644 --- a/src/lib/onboard/provider-key-bridge.ts +++ b/src/lib/onboard/provider-key-bridge.ts @@ -20,11 +20,19 @@ function getProviderKeyBridgeHint(): string { return (process.env.NEMOCLAW_PROVIDER_KEY || "").trim(); } -export function stageRouterProviderKeyBridge(routerCredentialEnv: string): void { +/** Resolve the compatibility bridge without staging a provider credential. */ +export function resolveRouterProviderKeyBridge(): string | null { const providerKeyHint = getProviderKeyBridgeHint(); - if (!isProviderKeyCredentialCandidate(providerKeyHint)) return; + return isProviderKeyCredentialCandidate(providerKeyHint) ? providerKeyHint : null; +} + +export function stageRouterProviderKeyBridge( + routerCredentialEnv: string, + resolvedProviderKeyHint: string | null = resolveRouterProviderKeyBridge(), +): void { + if (!isProviderKeyCredentialCandidate(resolvedProviderKeyHint)) return; if (resolveProviderCredential(routerCredentialEnv)) return; - saveCredential(routerCredentialEnv, providerKeyHint); + saveCredential(routerCredentialEnv, resolvedProviderKeyHint); } export function stageBuildProviderKeyBridge(): void { diff --git a/src/lib/onboard/providers.test.ts b/src/lib/onboard/providers.test.ts index 058d3943e3a..42196de41f5 100644 --- a/src/lib/onboard/providers.test.ts +++ b/src/lib/onboard/providers.test.ts @@ -103,6 +103,7 @@ const { replaceExisting?: boolean; allowedSandboxes?: readonly string[]; requireExactBinding?: boolean; + revalidatePolicyRequirements?(operation: string): void; }, ) => { ok: boolean; status?: number; message?: string; reason?: string }; upsertMessagingProviders: ( @@ -117,6 +118,7 @@ const { allowedSandboxes?: readonly string[]; bestEffort?: boolean; replaceExisting?: boolean; + revalidatePolicyRequirements?(operation: string): void; requireExactBindings?: boolean; }, ) => string[]; @@ -898,6 +900,63 @@ describe("onboard provider helpers", () => { ]); }); + it("revalidates policy requirements before each messaging provider mutation (#9833)", () => { + const commands: string[] = []; + const revalidationSteps = [ + () => undefined, + () => undefined, + () => { + throw new Error("policy authority changed between providers"); + }, + ]; + + expect(() => + upsertMessagingProviders( + [ + { name: "alpha-first", envKey: "FIRST_TOKEN", token: "first" }, + { name: "alpha-second", envKey: "SECOND_TOKEN", token: "second" }, + ], + (command) => { + commands.push(command.join(" ")); + return command.includes("get") + ? { status: 1, stdout: "", stderr: "" } + : { status: 0, stdout: "", stderr: "" }; + }, + { revalidatePolicyRequirements: () => revalidationSteps.shift()?.() }, + ), + ).toThrow(/authority changed between providers/); + expect(commands).toEqual([ + "provider get alpha-first", + "provider create --name alpha-first --type generic --credential FIRST_TOKEN", + ]); + }); + + it("rechecks policy authority after a provider probe and before its mutation (#9833)", () => { + const commands: string[] = []; + const revalidationSteps = [ + () => undefined, + () => { + throw new Error("policy authority changed after provider probe"); + }, + ]; + + expect(() => + upsertProvider( + "alpha-discord-bridge", + "generic", + "DISCORD_BOT_TOKEN", + null, + { DISCORD_BOT_TOKEN: "secret" }, + (command) => { + commands.push(command.join(" ")); + return { status: 1, stdout: "", stderr: "not found" }; + }, + { revalidatePolicyRequirements: () => revalidationSteps.shift()?.() }, + ), + ).toThrow(/authority changed after provider probe/u); + expect(commands).toEqual(["provider get alpha-discord-bridge"]); + }); + it("rejects an existing generic provider when an exact credential binding is required", () => { const commands: string[] = []; const result = upsertProvider( @@ -967,6 +1026,7 @@ 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) => { diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index 324a45a62db..94570d9c2bb 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -456,6 +456,23 @@ function providerExistsInGateway(name, _runOpenshell) { return result.status === 0; } +/** + * Recheck the caller's policy receipt immediately before each OpenShell + * provider command. Commands in one provider operation can be separated by + * probes and recovery work, so one outer check is not sufficient. + * @param {Function} runOpenshell + * @param {((operation: string) => void)|undefined} revalidatePolicyRequirements + * @param {string} operation + * @returns {Function} + */ +function policyAuthorityCheckedRunner(runOpenshell, revalidatePolicyRequirements, operation) { + if (!revalidatePolicyRequirements) return runOpenshell; + return (...args) => { + revalidatePolicyRequirements(operation); + return runOpenshell(...args); + }; +} + /** * Create or update an OpenShell provider in the gateway. * @@ -473,16 +490,21 @@ function providerExistsInGateway(name, _runOpenshell) { * @param {string|null} baseUrl - Optional base URL for the provider endpoint. * @param {Record} env - Environment variables for the openshell command. * @param {Function} _runOpenshell - Injected runOpenshell from onboard.ts. - * @param {{replaceExisting?: boolean, knownExists?: boolean, allowedSandboxes?: readonly string[], requireExactBinding?: boolean}} options - Optional replacement controls. + * @param {{replaceExisting?: boolean, knownExists?: boolean, allowedSandboxes?: readonly string[], requireExactBinding?: boolean, revalidatePolicyRequirements?: (operation: string) => void}} options - Optional replacement controls. * @returns {{ ok: boolean, status?: number, message?: string, reason?: string }} */ function upsertProvider(name, type, credentialEnv, baseUrl, env, _runOpenshell, options = {}) { - const exists = options.knownExists ?? providerExistsInGateway(name, _runOpenshell); + const runOpenshell = policyAuthorityCheckedRunner( + _runOpenshell, + options.revalidatePolicyRequirements, + `inspect or change provider ${JSON.stringify(name)}`, + ); + const exists = options.knownExists ?? providerExistsInGateway(name, runOpenshell); if ( exists && options.requireExactBinding && !options.replaceExisting && - !matchesGatewayCredentialOnlyProviderBinding(readGatewayProviderMetadata(name, _runOpenshell), { + !matchesGatewayCredentialOnlyProviderBinding(readGatewayProviderMetadata(name, runOpenshell), { name, type, credentialKey: credentialEnv, @@ -498,7 +520,7 @@ function upsertProvider(name, type, credentialEnv, baseUrl, env, _runOpenshell, if (exists && options.replaceExisting) { const { deleteProviderWithRecovery } = require("./sandbox-provider-cleanup"); const r = deleteProviderWithRecovery(name, { - runOpenshell: _runOpenshell, + runOpenshell, allowedSandboxes: options.allowedSandboxes, }); if (!r.ok) { @@ -524,7 +546,7 @@ function upsertProvider(name, type, credentialEnv, baseUrl, env, _runOpenshell, const includeCredential = action === "create" || credentialValueAvailable; const args = buildProviderArgs(action, name, type, credentialEnv, baseUrl, { includeCredential }); const runOpts = { ignoreError: true, env, stdio: ["ignore", "pipe", "pipe"] }; - const result = _runOpenshell(args, runOpts); + const result = runOpenshell(args, runOpts); if (result.status !== 0) { const output = compactText(redact(`${result.stderr || ""}`)) || @@ -565,10 +587,15 @@ function preflightMessagingProviderBindings(tokenDefs, _runOpenshell) { * of terminating the CLI. * @param {Array<{name: string, envKey: string, token: string|null, providerType?: string}>} tokenDefs * @param {Function} _runOpenshell - Injected runOpenshell from onboard.ts. - * @param {{replaceExisting?: boolean, bestEffort?: boolean, allowedSandboxes?: readonly string[], requireExactBindings?: boolean}} options - Forwarded to every upsertProvider call. + * @param {{replaceExisting?: boolean, bestEffort?: boolean, allowedSandboxes?: readonly string[], requireExactBindings?: boolean, revalidatePolicyRequirements?: (operation: string) => void}} options - Forwarded to every upsertProvider call. * @returns {string[]} Provider names that were upserted. */ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { + const runMessagingBridgeOpenshell = policyAuthorityCheckedRunner( + _runOpenshell, + options.revalidatePolicyRequirements, + "inspect or change a messaging bridge provider", + ); // Provider creation order. Bridges (e.g. Google Chat) need two steps bracketing // the uniform create loop, ordered around `provider create`: // @@ -589,7 +616,7 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { // channels//provider-profile/.yaml (not a flag inside it); both // bracket steps self-gate when no bridge token def is present. if (options.requireExactBindings && !options.replaceExisting) { - const bindingFailures = preflightMessagingProviderBindings(tokenDefs, _runOpenshell); + const bindingFailures = preflightMessagingProviderBindings(tokenDefs, runMessagingBridgeOpenshell); if (bindingFailures.length > 0) { const message = bindingFailures .map(({ name, message: failure }) => `${name}: ${failure}`) @@ -603,15 +630,11 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { } const messagingBridgeProvider = require("./messaging-bridge-provider"); - if ( - tokenDefs.some( - ({ providerType }) => providerType === MESSAGING_CREDENTIAL_PROVIDER_TYPE, - ) - ) { + if (tokenDefs.some(({ providerType }) => providerType === MESSAGING_CREDENTIAL_PROVIDER_TYPE)) { try { ensureMessagingCredentialProviderProfile({ root: ROOT, - runOpenshell: _runOpenshell, + runOpenshell: runMessagingBridgeOpenshell, }); } catch (error) { const message = error instanceof Error ? error.message : String(error); @@ -622,7 +645,7 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { } messagingBridgeProvider.ensureMessagingBridgeProfiles(tokenDefs, { root: ROOT, - runOpenshell: _runOpenshell, + runOpenshell: runMessagingBridgeOpenshell, redact, }); const upserted = []; @@ -634,7 +657,7 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { if (providerType === MESSAGING_CREDENTIAL_PROVIDER_TYPE) { const inspection = inspectGatewayCredentialOnlyProviderBinding( { name, type: providerType, credentialKey: envKey }, - _runOpenshell, + runMessagingBridgeOpenshell, ); if (inspection.kind === "indeterminate") { result = { @@ -663,13 +686,14 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { replaceExisting: Boolean(options.replaceExisting), knownExists, allowedSandboxes: options.allowedSandboxes, + revalidatePolicyRequirements: options.revalidatePolicyRequirements, requireExactBinding: Boolean(options.requireExactBindings && providerType), }, ); if (result.ok && providerType === MESSAGING_CREDENTIAL_PROVIDER_TYPE) { const verified = inspectGatewayCredentialOnlyProviderBinding( { name, type: providerType, credentialKey: envKey }, - _runOpenshell, + runMessagingBridgeOpenshell, ); if (verified.kind !== "exact") { result = { @@ -700,7 +724,7 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { // self-gates without a bridge token def). Secret material stays gateway-side — // never written into the sandbox. const refreshResult = messagingBridgeProvider.configureMessagingBridgeRefreshes(tokenDefs, { - runOpenshell: _runOpenshell, + runOpenshell: runMessagingBridgeOpenshell, redact, getCredential, env: process.env, diff --git a/src/lib/onboard/resume-provider-recovery.ts b/src/lib/onboard/resume-provider-recovery.ts index cdf4ba63bd5..7821ab6bfe0 100644 --- a/src/lib/onboard/resume-provider-recovery.ts +++ b/src/lib/onboard/resume-provider-recovery.ts @@ -38,7 +38,9 @@ export type ResumeProviderRecoveryDeps = { label: string, helpUrl: string | null, validator: (value: string) => string | null, + revalidatePolicyRequirements?: (operation: string) => void, ) => Promise; + revalidatePolicyRequirements?: (operation: string) => void; validateNvidiaApiKeyValue: (key: string, credentialEnv: string) => string | null; }; @@ -140,6 +142,7 @@ export async function ensureResumeProviderReady( `${providerLabel} API key`, helpUrl, (value) => deps.validateNvidiaApiKeyValue(value, resolvedCredentialEnv), + deps.revalidatePolicyRequirements, ); } else { deps.note(` [resume] Provider '${provider}' is missing from the gateway; recreating it.`); diff --git a/src/lib/onboard/resume/locked-runtime.test.ts b/src/lib/onboard/resume/locked-runtime.test.ts index e24df6b32af..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(); @@ -88,9 +101,7 @@ describe("locked onboarding runtime preparation", () => { () => ({ checkpoint, metadata: { - hostMounts: [ - { source: "/srv/project", target: "/sandbox/project", readOnly: true }, - ], + hostMounts: [{ source: "/srv/project", target: "/sandbox/project", readOnly: true }], }, }), ), diff --git a/src/lib/onboard/sandbox-create-intent-types.ts b/src/lib/onboard/sandbox-create-intent-types.ts index 743e4b6f690..09aed1cadac 100644 --- a/src/lib/onboard/sandbox-create-intent-types.ts +++ b/src/lib/onboard/sandbox-create-intent-types.ts @@ -3,6 +3,7 @@ import type { BaselineExclusionEntry } from "../state/registry"; import type { SandboxHostMount } from "../state/registry/types"; +import type { SandboxPolicyAuthority } from "../adapters/openshell/policy-authority"; import type { DockerGpuRoutePlan } from "./docker-gpu-route"; import type { InitialSandboxPolicy } from "./initial-policy"; import type { ManagedHermesStateVolumeMount } from "./managed-workload/hermes-state-volume"; @@ -95,12 +96,17 @@ export type ResolveSandboxCreateIntentInput = { export type MaterializeSandboxCreatePlanInput = { intent: SandboxCreateIntent; fromRef: string; + policyAuthority: SandboxPolicyAuthority; managedStateMount?: ManagedHermesStateVolumeMount | null; messagingTokenDefs: MessagingTokenDef[]; runProviderPreDeleteCleanup(): void; upsertMessagingProviders( tokenDefs: MessagingTokenDef[], - options: { replaceExisting: true; allowedSandboxes: readonly [string] }, + options: { + replaceExisting: true; + allowedSandboxes: readonly [string]; + revalidatePolicyRequirements?(operation: string): void; + }, ): string[]; getHermesToolGatewayProviderName(sandboxName: string): string; discloseInitialSandboxPolicy?(policy: InitialSandboxPolicy): void; diff --git a/src/lib/onboard/sandbox-create-launch.test.ts b/src/lib/onboard/sandbox-create-launch.test.ts index 7bddef4eee7..65fca2e4986 100644 --- a/src/lib/onboard/sandbox-create-launch.test.ts +++ b/src/lib/onboard/sandbox-create-launch.test.ts @@ -230,6 +230,24 @@ describe("buildSandboxRuntimeEnvArgs", () => { }); describe("prepareSandboxCreateLaunch", () => { + it("removes an inherited sandbox policy when create omits caller policy (#9833)", () => { + const result = prepareSandboxCreateLaunch({ + agent: null, + chatUiUrl: "", + createArgs: ["--from", "example.invalid/image", "--name", "demo"], + extraPlaceholderKeys: [], + getDashboardForwardPort: () => "", + hermesDashboardState: disabledHermesDashboardState, + openshellShellCommand: (args) => `openshell ${args.join(" ")}`, + buildEnv: () => ({ + HOME: "/home/user", + OPENSHELL_SANDBOX_POLICY: "/tmp/inherited-policy.yaml", + }), + }); + + expect(result.sandboxEnv).toEqual({ HOME: "/home/user" }); + }); + it.each(["openclaw", "hermes", "langchain-deepagents-code"] as const)( "renders one identity-bound held launch for %s without exposing the startup profile", (agentName) => { diff --git a/src/lib/onboard/sandbox-create-launch.ts b/src/lib/onboard/sandbox-create-launch.ts index b0ca4f33a50..7bb82ec3541 100644 --- a/src/lib/onboard/sandbox-create-launch.ts +++ b/src/lib/onboard/sandbox-create-launch.ts @@ -138,6 +138,9 @@ export function prepareSandboxCreateLaunch(input: SandboxCreateLaunchInput): San // permits for host-side processes but that must not enter the sandbox. delete sandboxEnv.KUBECONFIG; delete sandboxEnv.SSH_AUTH_SOCK; + if (!input.createArgs.includes("--policy")) { + delete sandboxEnv.OPENSHELL_SANDBOX_POLICY; + } // Run without piping through awk; the pipe masked non-zero exit codes // from openshell because bash returns the status of the last pipeline diff --git a/src/lib/onboard/sandbox-create-plan-materialization.ts b/src/lib/onboard/sandbox-create-plan-materialization.ts index d59133d8416..b7d06179b96 100644 --- a/src/lib/onboard/sandbox-create-plan-materialization.ts +++ b/src/lib/onboard/sandbox-create-plan-materialization.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { InitialSandboxPolicy } from "./initial-policy"; +import type { SandboxPolicyAuthority } from "../adapters/openshell/policy-authority"; import type { MessagingTokenDef } from "./messaging-prep"; import type { MaterializeSandboxCreatePlanInput, @@ -74,6 +75,7 @@ export type SandboxCreatePlan = { initialSandboxPolicy: InitialSandboxPolicy; /** Tier resolved before create, persisted with the registry entry for safe resume. */ policyTier: string | null; + policyAuthority: SandboxPolicyAuthority; createArgs: string[]; messagingProviders: string[]; gpuRoutePlan: SandboxCreateIntent["gpuRoutePlan"]; @@ -133,6 +135,33 @@ function getHermesPortableInitialSandboxPolicy( return planHermesPortableInitialSandboxPolicy(...args); } +export function prepareSandboxCreatePolicy( + intent: SandboxCreateIntent, + prepareInitialSandboxCreatePolicy: PrepareInitialSandboxCreatePolicy = getInitialSandboxCreatePolicy, +): { + readonly initialSandboxPolicy: InitialSandboxPolicy; + readonly compatibilityPolicyPath: string | null; +} { + return prepareSandboxGpuRoutePolicies( + intent.policy.basePolicyPath, + [...intent.policy.activeMessagingChannels], + { + directGpu: intent.policy.options.directGpu, + hostGpuAvailable: intent.policy.options.hostGpuAvailable, + additionalPresets: intent.policy.options.hostLocalInferenceRouteOnly + ? intent.policy.options.additionalPresets.filter((name) => name !== "local-inference") + : [...intent.policy.options.additionalPresets], + agentName: intent.policy.options.agentName, + policyTier: intent.policy.options.policyTier, + baselineExclusions: intent.policy.options.baselineExclusions.map((exclusion) => ({ + ...exclusion, + })), + }, + intent.gpuRoutePlan, + prepareInitialSandboxCreatePolicy, + ); +} + function messagingProviderRequestKey( request: Pick, ): string { @@ -217,6 +246,7 @@ function filterDisabledMessagingProviders( export function materializeSandboxCreatePlan({ intent, fromRef, + policyAuthority, managedStateMount, messagingTokenDefs, runProviderPreDeleteCleanup, @@ -246,19 +276,22 @@ export function materializeSandboxCreatePlan({ intent.gpuRoutePlan, prepareInitialSandboxCreatePolicy, ); - try { - discloseInitialSandboxPolicy?.(initialSandboxPolicy); - } catch (error) { - initialSandboxPolicy.cleanup?.(); - throw error; + if (policyAuthority === "nemoclaw-managed") { + try { + discloseInitialSandboxPolicy?.(initialSandboxPolicy); + } catch (error) { + initialSandboxPolicy.cleanup?.(); + throw error; + } } const createArgs = [ "--from", fromRef, "--name", intent.sandboxName, - "--policy", - initialSandboxPolicy.policyPath, + ...(policyAuthority === "nemoclaw-managed" + ? ["--policy", initialSandboxPolicy.policyPath] + : []), ...(driverConfig ? ["--driver-config-json", driverConfig] : []), ...intent.gpuCreateArgs, ...intent.resourceCreateArgs, @@ -294,6 +327,7 @@ export function materializeSandboxCreatePlan({ activeMessagingChannels: [...intent.activeMessagingChannels], initialSandboxPolicy, policyTier: intent.policy.options.policyTier, + policyAuthority, createArgs, messagingProviders, gpuRoutePlan: intent.gpuRoutePlan, @@ -306,8 +340,14 @@ export function materializeSandboxCreatePlan({ export function materializeHermesPortableCreatePlan(input: { readonly intent: SandboxCreateIntent; readonly fromRef: string; + readonly policyAuthority: SandboxPolicyAuthority; }): SandboxCreatePlan { - const { intent, fromRef } = input; + const { intent, fromRef, policyAuthority } = input; + if (policyAuthority !== "nemoclaw-managed") { + throw new Error( + "Hermes portable sandbox creation requires NemoClaw-managed policy authority.", + ); + } if ( intent.policy.options.agentName !== "hermes" || !["none", "native-only"].includes(intent.gpuRoutePlan) || @@ -354,6 +394,7 @@ export function materializeHermesPortableCreatePlan(input: { activeMessagingChannels: [], initialSandboxPolicy, policyTier: intent.policy.options.policyTier, + policyAuthority, createArgs, messagingProviders: [], gpuRoutePlan: intent.gpuRoutePlan, diff --git a/src/lib/onboard/sandbox-create-plan.test.ts b/src/lib/onboard/sandbox-create-plan.test.ts index fe736607334..4e2484bfcc7 100644 --- a/src/lib/onboard/sandbox-create-plan.test.ts +++ b/src/lib/onboard/sandbox-create-plan.test.ts @@ -92,6 +92,7 @@ function expectCredentialBindingFailure({ materializeSandboxCreatePlan({ intent, fromRef: "/tmp/nemoclaw-build-1/Dockerfile", + policyAuthority: "nemoclaw-managed", messagingTokenDefs: materializedTokenDefs, prepareInitialSandboxCreatePolicy: preparePolicy, runProviderPreDeleteCleanup: cleanupProviders, @@ -266,6 +267,7 @@ describe("resolveSandboxCreateIntent", () => { const plan = materializeSandboxCreatePlan({ intent, fromRef: "/tmp/nemoclaw-build-1/Dockerfile", + policyAuthority: "nemoclaw-managed", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: preparePolicy, runProviderPreDeleteCleanup: vi.fn(), @@ -321,6 +323,7 @@ describe("resolveSandboxCreateIntent", () => { const result = materializeSandboxCreatePlan({ intent, fromRef: "/tmp/nemoclaw-build-1/Dockerfile", + policyAuthority: "nemoclaw-managed", messagingTokenDefs: tokenDefs, prepareInitialSandboxCreatePolicy: vi.fn(() => { events.push("policy"); @@ -372,6 +375,44 @@ describe("resolveSandboxCreateIntent", () => { expect(JSON.stringify(intent)).toBe(serializedIntent); }); + it("omits caller policy when external authority owns sandbox policy (#9833)", () => { + const intent = resolveSandboxCreateIntent({ + basePolicyPath: "/repo/policy.yaml", + sandboxName: "sandbox", + channels: [], + enabledChannels: [], + disabledChannelNames: new Set(), + messagingProviderRequests: [], + primaryMessagingCredentialEnvKeys: [], + reusableMessagingChannels: [], + reusableMessagingProviders: [], + hermesToolGateways: [], + sandboxGpuConfig, + gpuCreateArgs: [], + gpuRoutePlan: "none", + sandboxGpuLogMessage: null, + policyTier: null, + }); + + const plan = materializeSandboxCreatePlan({ + intent, + fromRef: "example.invalid/image@sha256:abc", + policyAuthority: "externally-managed", + messagingTokenDefs: [], + prepareInitialSandboxCreatePolicy: () => ({ + policyPath: "/tmp/policy.yaml", + appliedPresets: ["github"], + }), + runProviderPreDeleteCleanup: vi.fn(), + upsertMessagingProviders: vi.fn(() => []), + getHermesToolGatewayProviderName: vi.fn(), + }); + + expect(plan.policyAuthority).toBe("externally-managed"); + expect(plan.createArgs).not.toContain("--policy"); + expect(plan.createArgs).not.toContain("/tmp/policy.yaml"); + }); + it("materializes a raw GPU UUID as Docker and Podman CDI driver config", () => { vi.stubEnv("NEMOCLAW_EXPERIMENTAL_PROFILE", "portable"); const intent = resolveSandboxCreateIntent({ @@ -399,6 +440,7 @@ describe("resolveSandboxCreateIntent", () => { const plan = materializeHermesPortableCreatePlan({ intent, fromRef: "ghcr.io/nvidia/nemoclaw/hermes:test", + policyAuthority: "nemoclaw-managed", }); const configIndex = plan.createArgs.indexOf("--driver-config-json"); @@ -437,6 +479,7 @@ describe("resolveSandboxCreateIntent", () => { materializeSandboxCreatePlan({ intent, fromRef: "/tmp/nemoclaw-build-1/Dockerfile", + policyAuthority: "nemoclaw-managed", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: vi.fn(), runProviderPreDeleteCleanup: vi.fn(), @@ -469,6 +512,7 @@ describe("resolveSandboxCreateIntent", () => { const plan = materializeSandboxCreatePlan({ intent, fromRef: "/tmp/nemoclaw-build-1/Dockerfile", + policyAuthority: "nemoclaw-managed", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: vi.fn(() => ({ policyPath: "/tmp/policy.yaml", @@ -522,6 +566,7 @@ describe("resolveSandboxCreateIntent", () => { const plan = materializeSandboxCreatePlan({ intent, fromRef: `ghcr.io/nvidia/nemoclaw/hermes@sha256:${"a".repeat(64)}`, + policyAuthority: "nemoclaw-managed", managedStateMount: { type: "volume", source: "nemoclaw-hermes-state-v1-hermes-box", @@ -578,6 +623,7 @@ describe("resolveSandboxCreateIntent", () => { materializeSandboxCreatePlan({ intent, fromRef: `ghcr.io/nvidia/nemoclaw/hermes@sha256:${"a".repeat(64)}`, + policyAuthority: "nemoclaw-managed", managedStateMount: { type: "volume", source: "nemoclaw-hermes-state-v1-hermes-box", @@ -622,6 +668,7 @@ describe("resolveSandboxCreateIntent", () => { materializeSandboxCreatePlan({ intent, fromRef: "/tmp/nemoclaw-build-1/Dockerfile", + policyAuthority: "nemoclaw-managed", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: vi.fn(() => ({ policyPath: "/tmp/policy.yaml", @@ -717,6 +764,7 @@ describe("resolveSandboxCreateIntent", () => { const plan = materializeSandboxCreatePlan({ intent, fromRef: reference, + policyAuthority: "nemoclaw-managed", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: vi.fn(() => ({ policyPath: "/tmp/policy.yaml", diff --git a/src/lib/onboard/sandbox-create-plan.ts b/src/lib/onboard/sandbox-create-plan.ts index 0c6911ad908..a725df8c1cb 100644 --- a/src/lib/onboard/sandbox-create-plan.ts +++ b/src/lib/onboard/sandbox-create-plan.ts @@ -16,6 +16,7 @@ export type { export type { SandboxCreatePlan } from "./sandbox-create-plan-materialization"; export { materializeSandboxCreatePlan, + prepareSandboxCreatePolicy, validateSandboxCreateIntentBindings, } from "./sandbox-create-plan-materialization"; diff --git a/src/lib/onboard/sandbox-create/orchestration.test.ts b/src/lib/onboard/sandbox-create/orchestration.test.ts index 1b2bcdf5aa2..cf3463f5045 100644 --- a/src/lib/onboard/sandbox-create/orchestration.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration.test.ts @@ -5,11 +5,11 @@ import { describe, expect, it, vi } from "vitest"; import type { SandboxEntry } from "../../state/registry"; import { - applyAbsentSandboxRebuildPolicyCarryForward, + applyManagedSandboxRebuildPolicyCarryForward, completeHermesPortableSandboxRegistration, hasManagedMcpRebuildHandoff, - proveRecreateSourceBeforePolicyCarryForward, readManagedDcodeCreateSelectionDrift, + runSandboxCreateWithPolicyAuthorityChecks, } from "./orchestration"; describe("managed MCP rebuild handoff", () => { @@ -49,34 +49,19 @@ describe("managed MCP rebuild handoff", () => { }); describe("authoritative rebuild policy carry-forward", () => { - it("proves the journaled source before mutating its preserved policy row (#9792)", () => { - const events: string[] = []; - const runtime = { acceptedTarget: false }; - - expect( - proveRecreateSourceBeforePolicyCarryForward({ - createRecreateRuntime: () => { - events.push("prove-source"); - return runtime; - }, - carryForward: () => events.push("carry-forward"), - }), - ).toBe(runtime); - expect(events).toEqual(["prove-source", "carry-forward"]); - }); - - it("replaces stale resumed presets after the outer rebuild deletes the source sandbox (#9792)", () => { + it("preserves an intentionally empty managed preset selection (#9792)", () => { const note = vi.fn(); const applyRecreatePolicyCarryForward = vi.fn(); - const filteredPolicyPresets = ["github"]; + const revalidatePolicyAuthority = vi.fn(); - applyAbsentSandboxRebuildPolicyCarryForward( + applyManagedSandboxRebuildPolicyCarryForward( { sandboxName: "alpha", - liveExists: false, + policyAuthority: "nemoclaw-managed", nonInteractive: true, note, - rebuildPolicyPresets: filteredPolicyPresets, + rebuildPolicyPresets: [], + revalidatePolicyAuthority, }, applyRecreatePolicyCarryForward, ); @@ -85,31 +70,50 @@ describe("authoritative rebuild policy carry-forward", () => { "alpha", true, note, - filteredPolicyPresets, + [], ); }); - it("preserves an intentionally empty preset selection after the outer delete (#9792)", () => { - const note = vi.fn(); + it("does not carry managed presets into a live external recreation (#9833)", () => { const applyRecreatePolicyCarryForward = vi.fn(); + const revalidatePolicyAuthority = vi.fn(); - applyAbsentSandboxRebuildPolicyCarryForward( + applyManagedSandboxRebuildPolicyCarryForward( { sandboxName: "alpha", - liveExists: false, + policyAuthority: "externally-managed", nonInteractive: true, - note, - rebuildPolicyPresets: [], + note: vi.fn(), + rebuildPolicyPresets: ["github"], + revalidatePolicyAuthority, }, applyRecreatePolicyCarryForward, ); - expect(applyRecreatePolicyCarryForward).toHaveBeenCalledExactlyOnceWith( - "alpha", - true, - note, - [], - ); + expect(revalidatePolicyAuthority).not.toHaveBeenCalled(); + expect(applyRecreatePolicyCarryForward).not.toHaveBeenCalled(); + }); + + it("revalidates managed authority before live recreate policy carry-forward (#9833)", () => { + const applyRecreatePolicyCarryForward = vi.fn(); + const revalidatePolicyAuthority = vi.fn(() => { + throw new Error("policy authority changed"); + }); + + expect(() => + applyManagedSandboxRebuildPolicyCarryForward( + { + sandboxName: "alpha", + policyAuthority: "nemoclaw-managed", + nonInteractive: true, + note: vi.fn(), + rebuildPolicyPresets: ["github"], + revalidatePolicyAuthority, + }, + applyRecreatePolicyCarryForward, + ), + ).toThrow("policy authority changed"); + expect(applyRecreatePolicyCarryForward).not.toHaveBeenCalled(); }); }); @@ -189,3 +193,555 @@ describe("Hermes portable registration adapter", () => { expect(readRegistry).toHaveBeenCalledExactlyOnceWith("alpha"); }); }); + +describe("sandbox create policy authority checks", () => { + const CREATED_IDENTITY = "a".repeat(64); + const REPLACEMENT_IDENTITY = "b".repeat(64); + const createdObservation = { + state: "ready" as const, + liveIdentityFingerprint: CREATED_IDENTITY, + }; + + it("refuses sandbox creation before mutation when the final check fails (#9833)", async () => { + const create = vi.fn(async () => "created"); + + await expect( + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate: () => { + throw new Error("external policy authority must supply the selected route"); + }, + create, + captureCreatedSandboxLiveIdentity: vi.fn(() => CREATED_IDENTITY), + observeCreatedSandbox: vi.fn(() => createdObservation), + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox: vi.fn(), + waitForCreatedSandboxAbsence: vi.fn(() => true), + }), + ).rejects.toThrow(/external policy authority must supply/u); + expect(create).not.toHaveBeenCalled(); + }); + + it("checks the named Ready sandbox before registration can continue (#9833)", async () => { + const events: string[] = []; + const result = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate: (sandboxIsLive) => events.push(sandboxIsLive ? "ready-check" : "create-check"), + create: async () => { + events.push("create"); + return "created"; + }, + captureCreatedSandboxLiveIdentity: () => { + events.push("capture-identity"); + return CREATED_IDENTITY; + }, + observeCreatedSandbox: vi.fn(() => createdObservation), + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox: vi.fn(), + waitForCreatedSandboxAbsence: vi.fn(() => true), + }); + events.push("register"); + + expect(result).toBe("created"); + expect(events).toEqual([ + "create-check", + "create", + "capture-identity", + "ready-check", + "register", + ]); + }); + + it("removes create sources and the live sandbox when final authority validation fails (#9833)", async () => { + const events: string[] = []; + const validationError = new Error("external policy authority changed"); + const revalidate = vi + .fn() + .mockImplementationOnce(() => events.push("create-check")) + .mockImplementationOnce(() => { + events.push("ready-check"); + throw validationError; + }); + + await expect( + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => { + events.push("create"); + return "created"; + }, + captureCreatedSandboxLiveIdentity: () => { + events.push("capture-identity"); + return CREATED_IDENTITY; + }, + observeCreatedSandbox: () => { + events.push("observe-created"); + return createdObservation; + }, + cleanupTemporarySources: () => { + events.push("cleanup-sources"); + }, + deleteCreatedSandbox: () => { + events.push("delete-created"); + }, + waitForCreatedSandboxAbsence: () => { + events.push("prove-absence"); + return true; + }, + }), + ).rejects.toBe(validationError); + + expect(events).toEqual([ + "create-check", + "create", + "capture-identity", + "ready-check", + "cleanup-sources", + "observe-created", + "delete-created", + "prove-absence", + ]); + }); + + it("attempts sandbox deletion when temporary source cleanup fails (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + await expect( + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, + observeCreatedSandbox: () => createdObservation, + cleanupTemporarySources: () => { + throw new Error("temporary source cleanup failed"); + }, + deleteCreatedSandbox, + waitForCreatedSandboxAbsence: () => true, + }), + ).rejects.toThrow("cleanup did not complete"); + + expect(deleteCreatedSandbox).toHaveBeenCalledOnce(); + }); + + it("reports incomplete cleanup when an accepted delete leaves the created identity live (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const observeCreatedSandbox = vi.fn(() => createdObservation); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, + observeCreatedSandbox, + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox, + waitForCreatedSandboxAbsence: () => false, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + message: expect.stringContaining("exact absence was not proven"), + }), + ]), + ); + expect(deleteCreatedSandbox).toHaveBeenCalledOnce(); + expect(observeCreatedSandbox).toHaveBeenCalledTimes(2); + }); + + it("does not delete a replacement observed before cleanup (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const waitForCreatedSandboxAbsence = vi.fn(() => true); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, + observeCreatedSandbox: () => ({ + state: "ready", + liveIdentityFingerprint: REPLACEMENT_IDENTITY, + }), + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox, + waitForCreatedSandboxAbsence, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ message: expect.stringContaining("live identity changed") }), + ]), + ); + expect(deleteCreatedSandbox).not.toHaveBeenCalled(); + expect(waitForCreatedSandboxAbsence).not.toHaveBeenCalled(); + }); + + it("does not delete a replacement observed after an accepted delete (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const observeCreatedSandbox = vi + .fn() + .mockReturnValueOnce(createdObservation) + .mockReturnValueOnce({ + state: "ready" as const, + liveIdentityFingerprint: REPLACEMENT_IDENTITY, + }); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, + observeCreatedSandbox, + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox, + waitForCreatedSandboxAbsence: () => false, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + message: expect.stringContaining("now identifies a replacement"), + }), + ]), + ); + expect(deleteCreatedSandbox).toHaveBeenCalledOnce(); + }); + + it("leaves the named sandbox in place when its created identity was not captured (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const observeCreatedSandbox = vi.fn(() => createdObservation); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => { + throw new Error("identity probe failed"); + }, + observeCreatedSandbox, + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox, + waitForCreatedSandboxAbsence: vi.fn(() => true), + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ message: expect.stringContaining("identity was not captured") }), + ]), + ); + expect(observeCreatedSandbox).not.toHaveBeenCalled(); + expect(deleteCreatedSandbox).not.toHaveBeenCalled(); + }); +}); + +describe("sandbox create policy authority checks", () => { + const CREATED_IDENTITY = "a".repeat(64); + const REPLACEMENT_IDENTITY = "b".repeat(64); + const createdObservation = { + state: "ready" as const, + liveIdentityFingerprint: CREATED_IDENTITY, + }; + + it("refuses sandbox creation before mutation when the final check fails (#9833)", async () => { + const create = vi.fn(async () => "created"); + + await expect( + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate: () => { + throw new Error("external policy authority must supply the selected route"); + }, + create, + captureCreatedSandboxLiveIdentity: vi.fn(() => CREATED_IDENTITY), + observeCreatedSandbox: vi.fn(() => createdObservation), + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox: vi.fn(), + waitForCreatedSandboxAbsence: vi.fn(() => true), + }), + ).rejects.toThrow(/external policy authority must supply/u); + expect(create).not.toHaveBeenCalled(); + }); + + it("checks the named Ready sandbox before registration can continue (#9833)", async () => { + const events: string[] = []; + const result = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate: (sandboxIsLive) => events.push(sandboxIsLive ? "ready-check" : "create-check"), + create: async () => { + events.push("create"); + return "created"; + }, + captureCreatedSandboxLiveIdentity: () => { + events.push("capture-identity"); + return CREATED_IDENTITY; + }, + observeCreatedSandbox: vi.fn(() => createdObservation), + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox: vi.fn(), + waitForCreatedSandboxAbsence: vi.fn(() => true), + }); + events.push("register"); + + expect(result).toBe("created"); + expect(events).toEqual([ + "create-check", + "create", + "capture-identity", + "ready-check", + "register", + ]); + }); + + it("removes create sources and the live sandbox when final authority validation fails (#9833)", async () => { + const events: string[] = []; + const validationError = new Error("external policy authority changed"); + const revalidate = vi + .fn() + .mockImplementationOnce(() => events.push("create-check")) + .mockImplementationOnce(() => { + events.push("ready-check"); + throw validationError; + }); + + await expect( + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => { + events.push("create"); + return "created"; + }, + captureCreatedSandboxLiveIdentity: () => { + events.push("capture-identity"); + return CREATED_IDENTITY; + }, + observeCreatedSandbox: () => { + events.push("observe-created"); + return createdObservation; + }, + cleanupTemporarySources: () => { + events.push("cleanup-sources"); + }, + deleteCreatedSandbox: () => { + events.push("delete-created"); + }, + waitForCreatedSandboxAbsence: () => { + events.push("prove-absence"); + return true; + }, + }), + ).rejects.toBe(validationError); + + expect(events).toEqual([ + "create-check", + "create", + "capture-identity", + "ready-check", + "cleanup-sources", + "observe-created", + "delete-created", + "prove-absence", + ]); + }); + + it("attempts sandbox deletion when temporary source cleanup fails (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + await expect( + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, + observeCreatedSandbox: () => createdObservation, + cleanupTemporarySources: () => { + throw new Error("temporary source cleanup failed"); + }, + deleteCreatedSandbox, + waitForCreatedSandboxAbsence: () => true, + }), + ).rejects.toThrow("cleanup did not complete"); + + expect(deleteCreatedSandbox).toHaveBeenCalledOnce(); + }); + + it("reports incomplete cleanup when an accepted delete leaves the created identity live (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const observeCreatedSandbox = vi.fn(() => createdObservation); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, + observeCreatedSandbox, + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox, + waitForCreatedSandboxAbsence: () => false, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + message: expect.stringContaining("exact absence was not proven"), + }), + ]), + ); + expect(deleteCreatedSandbox).toHaveBeenCalledOnce(); + expect(observeCreatedSandbox).toHaveBeenCalledTimes(2); + }); + + it("does not delete a replacement observed before cleanup (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const waitForCreatedSandboxAbsence = vi.fn(() => true); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, + observeCreatedSandbox: () => ({ + state: "ready", + liveIdentityFingerprint: REPLACEMENT_IDENTITY, + }), + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox, + waitForCreatedSandboxAbsence, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ message: expect.stringContaining("live identity changed") }), + ]), + ); + expect(deleteCreatedSandbox).not.toHaveBeenCalled(); + expect(waitForCreatedSandboxAbsence).not.toHaveBeenCalled(); + }); + + it("does not delete a replacement observed after an accepted delete (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const observeCreatedSandbox = vi + .fn() + .mockReturnValueOnce(createdObservation) + .mockReturnValueOnce({ + state: "ready" as const, + liveIdentityFingerprint: REPLACEMENT_IDENTITY, + }); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, + observeCreatedSandbox, + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox, + waitForCreatedSandboxAbsence: () => false, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + message: expect.stringContaining("now identifies a replacement"), + }), + ]), + ); + expect(deleteCreatedSandbox).toHaveBeenCalledOnce(); + }); + + it("leaves the named sandbox in place when its created identity was not captured (#9833)", async () => { + const deleteCreatedSandbox = vi.fn(); + const observeCreatedSandbox = vi.fn(() => createdObservation); + const revalidate = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority changed"); + }); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate, + create: async () => "created", + captureCreatedSandboxLiveIdentity: () => { + throw new Error("identity probe failed"); + }, + observeCreatedSandbox, + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox, + waitForCreatedSandboxAbsence: vi.fn(() => true), + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).errors).toEqual( + expect.arrayContaining([ + expect.objectContaining({ message: expect.stringContaining("identity was not captured") }), + ]), + ); + expect(observeCreatedSandbox).not.toHaveBeenCalled(); + expect(deleteCreatedSandbox).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 40a3026a19e..e7a78b0d34d 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -2,24 +2,30 @@ // SPDX-License-Identifier: Apache-2.0 import type { SandboxCreateOrchestrationRuntime } from "../../onboard"; +import { assertRecordedPolicyAuthority } from "../../adapters/openshell/policy-authority"; import { HERMES_PORTABLE_OPENSHELL_VERSION } from "../../adapters/openshell/resolve-shared"; import type { AgentDefinition } from "../../agent/defs"; import type { WebSearchConfig } from "../../inference/web-search"; import type { BackupResult } from "../../state/sandbox"; import type { SandboxEntry } from "../../state/registry"; import type { HermesAuthMethod } from "../hermes-auth"; +import * as policyAuthorityPreflight from "../policy-authority/preflight"; import type { PreparedSandboxBuildContext } from "../build-context-stage"; import type { DcodeSelectionDriftReader } from "../dcode-selection-drift"; import type { OwnedSandboxRecreateRuntime } from "../onboard-recreate-journal"; import type { SandboxGpuConfig } from "../sandbox-gpu-mode"; import type { PortableOnboardRuntimeContext } from "../session-bootstrap"; import type { InferenceRouteReservationAuthority, SandboxCreateIntent } from "../types"; +import type { SandboxRecreateObservation } from "../sandbox-recreate-transaction"; import * as sandboxCreatePlanMaterialization from "../sandbox-create-plan-materialization"; import { publishAttachedProvidersBeforeDockerSandboxCreation, validateAttachedMessagingProvidersBeforeSandboxCreation, } from "./provider-publication"; +export const createOnboardPolicyAuthorityBindings = + policyAuthorityPreflight.createOnboardPolicyAuthorityBindings; + type SandboxRecreateReasonInput = { sandboxName: string; recreateForAgentDrift: boolean; @@ -113,6 +119,110 @@ export async function completeHermesPortableSandboxRegistration(input: { return registered; } +/** Revalidate create-time authority before mutation and against the named Ready sandbox. */ +export async function runSandboxCreateWithPolicyAuthorityChecks(input: { + readonly sandboxName: string; + readonly revalidate: (sandboxIsLive: boolean, operation: string) => void; + readonly create: () => Promise; + readonly captureCreatedSandboxLiveIdentity: (created: Result) => string; + readonly observeCreatedSandbox: () => SandboxRecreateObservation; + readonly cleanupTemporarySources: () => void; + readonly deleteCreatedSandbox: () => void | Promise; + readonly waitForCreatedSandboxAbsence: () => boolean | Promise; +}): Promise { + input.revalidate(false, `creating sandbox '${input.sandboxName}'`); + const created = await input.create(); + let createdLiveIdentityFingerprint: string | null = null; + let createdIdentityCaptureError: unknown = null; + try { + const captured = input.captureCreatedSandboxLiveIdentity(created); + if (!/^[a-f0-9]{64}$/u.test(captured)) { + throw new Error("OpenShell did not return one exact durable sandbox identity."); + } + createdLiveIdentityFingerprint = captured; + } catch (error) { + createdIdentityCaptureError = error; + } + try { + input.revalidate(true, `finalizing sandbox '${input.sandboxName}'`); + } catch (validationError) { + const compensationErrors: unknown[] = []; + try { + input.cleanupTemporarySources(); + } catch (error) { + compensationErrors.push(error); + } + if (!createdLiveIdentityFingerprint) { + compensationErrors.push( + new Error( + `Cannot safely remove sandbox '${input.sandboxName}' after policy authority validation failed because its exact created identity was not captured. NemoClaw left the named sandbox in place.`, + createdIdentityCaptureError === null ? undefined : { cause: createdIdentityCaptureError }, + ), + ); + } else { + try { + const beforeDelete = input.observeCreatedSandbox(); + if (beforeDelete.state !== "missing") { + if (!beforeDelete.liveIdentityFingerprint) { + throw new Error( + `Cannot safely remove sandbox '${input.sandboxName}' after policy authority validation failed because its current identity is ambiguous. NemoClaw left the named sandbox in place.`, + ); + } + if (beforeDelete.liveIdentityFingerprint !== createdLiveIdentityFingerprint) { + throw new Error( + `Cannot safely remove sandbox '${input.sandboxName}' after policy authority validation failed because its live identity changed. NemoClaw left the replacement in place.`, + ); + } + await input.deleteCreatedSandbox(); + let absenceProven: boolean; + try { + absenceProven = await input.waitForCreatedSandboxAbsence(); + } catch (error) { + throw new Error( + `OpenShell accepted deletion of sandbox '${input.sandboxName}', but exact absence remained ambiguous.`, + { cause: error }, + ); + } + if (!absenceProven) { + const afterDelete = input.observeCreatedSandbox(); + if (afterDelete.state !== "missing") { + if ( + afterDelete.liveIdentityFingerprint && + afterDelete.liveIdentityFingerprint !== createdLiveIdentityFingerprint + ) { + throw new Error( + `OpenShell accepted deletion of sandbox '${input.sandboxName}', but the name now identifies a replacement. NemoClaw left the replacement in place.`, + ); + } + throw new Error( + `OpenShell accepted deletion of sandbox '${input.sandboxName}', but exact absence was not proven. NemoClaw left the remaining sandbox in place.`, + ); + } + } + } + } catch (error) { + compensationErrors.push(error); + } + } + if (compensationErrors.length > 0) { + throw new AggregateError( + [validationError, ...compensationErrors], + "Sandbox policy authority validation failed after creation, and cleanup did not complete.", + ); + } + throw validationError; + } + return created; +} + +function assertHermesPortablePolicyAuthority( + hermesPortableLifecycle: boolean, + policyAuthority: string, +): void { + if (!hermesPortableLifecycle || policyAuthority === "nemoclaw-managed") return; + throw new Error("Hermes portable sandbox creation requires NemoClaw-managed policy authority."); +} + export function hasManagedMcpRebuildHandoff( createIntent: SandboxCreateIntent | null | undefined, ): boolean { @@ -135,6 +245,21 @@ function hasPreservedManagedMcpRebuildHandoff( ): boolean { return Boolean(preservedMcpState) && hasManagedMcpRebuildHandoff(createIntent); } + +function backfillExistingSandboxPolicyAuthority(input: { + readonly sandboxName: string; + readonly existingEntry: SandboxEntry | null; + readonly policyAuthority: "nemoclaw-managed" | "externally-managed"; + readonly updateSandbox: ( + sandboxName: string, + updates: { policyAuthority: "nemoclaw-managed" | "externally-managed" }, + ) => boolean; +}): void { + if (!input.existingEntry || input.existingEntry.policyAuthority) return; + if (input.updateSandbox(input.sandboxName, { policyAuthority: input.policyAuthority })) return; + throw new Error(`Could not record policy authority for sandbox '${input.sandboxName}'.`); +} + type ApplyRecreatePolicyCarryForward = ( sandboxName: string, nonInteractive: boolean, @@ -142,18 +267,22 @@ type ApplyRecreatePolicyCarryForward = ( rebuildPolicyPresets?: readonly string[], ) => void; -/** Reseed an outer rebuild after its owned delete leaves no live source branch. */ -export function applyAbsentSandboxRebuildPolicyCarryForward( +/** Carry managed rebuild policy intent only while the recorded authority remains current. */ +export function applyManagedSandboxRebuildPolicyCarryForward( input: { readonly sandboxName: string; - readonly liveExists: boolean; + readonly policyAuthority: "nemoclaw-managed" | "externally-managed"; readonly nonInteractive: boolean; readonly note: (message: string) => void; readonly rebuildPolicyPresets?: readonly string[]; + readonly revalidatePolicyAuthority: (operation: string) => void; }, applyRecreatePolicyCarryForward: ApplyRecreatePolicyCarryForward, ): void { - if (input.liveExists || !Array.isArray(input.rebuildPolicyPresets)) return; + if (input.policyAuthority !== "nemoclaw-managed") return; + input.revalidatePolicyAuthority( + `carrying forward managed policy presets for sandbox '${input.sandboxName}'`, + ); applyRecreatePolicyCarryForward( input.sandboxName, input.nonInteractive, @@ -162,6 +291,32 @@ export function applyAbsentSandboxRebuildPolicyCarryForward( ); } +/** Reseed an outer rebuild after its owned delete leaves no live source branch. */ +export function applyAbsentSandboxRebuildPolicyCarryForward( + input: { + readonly sandboxName: string; + readonly liveExists: boolean; + readonly policyAuthority: "nemoclaw-managed" | "externally-managed"; + readonly nonInteractive: boolean; + readonly note: (message: string) => void; + readonly rebuildPolicyPresets?: readonly string[]; + readonly revalidatePolicyAuthority: (operation: string) => void; + }, + applyRecreatePolicyCarryForward: ApplyRecreatePolicyCarryForward, +): void { + if (input.liveExists || !Array.isArray(input.rebuildPolicyPresets)) return; + applyManagedSandboxRebuildPolicyCarryForward(input, applyRecreatePolicyCarryForward); +} + +async function validatePortableManagedWorkloadSelection(input: { + readonly portableLifecycle: boolean; + readonly selectionNeedsValidation: boolean; + readonly prepareWorkload: () => Promise; +}): Promise { + if (!input.portableLifecycle || !input.selectionNeedsValidation) return; + await input.prepareWorkload(); +} + export function proveRecreateSourceBeforePolicyCarryForward(input: { readonly createRecreateRuntime: () => T; readonly carryForward: () => void; @@ -346,6 +501,24 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche }, ); const resolvedCreateIntent = preparedCreateIntent.intent; + const policyRequirementIntent: typeof resolvedCreateIntent = { + ...resolvedCreateIntent, + policy: { + ...resolvedCreateIntent.policy, + options: { + ...resolvedCreateIntent.policy.options, + additionalPresets: policyAuthorityPreflight.requiredOnboardPolicyPresets({ + additionalPresets: resolvedCreateIntent.policy.options.additionalPresets, + provider, + webSearchConfig, + agentName: agent?.name, + observabilityEnabled: createIntent?.observabilityEnabled === true, + hostLocalInferenceRouteOnly: + resolvedCreateIntent.policy.options.hostLocalInferenceRouteOnly, + }), + }, + }, + }; const messagingCapabilities = preparedCreateIntent.messagingCapabilities; const manageDashboard = sandboxGpuCreateFlow.shouldManageHermesPortableDashboard( dashboardRuntime.shouldManageDashboardForAgent(agent), @@ -407,58 +580,6 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche inspectSandboxForCreate, createIntent?.toolDisclosure ?? null, ); - // Prove the preserved source row before replacing its stale preset list. - // Policy carry-forward is an owned post-delete mutation, but applying it - // before recreate recovery makes the journal correctly reject that row as - // changed before the replacement can be created. - let recreateRuntime: - | import("../sandbox-recreate-transaction").SandboxRecreateRuntime - | OwnedSandboxRecreateRuntime = proveRecreateSourceBeforePolicyCarryForward({ - createRecreateRuntime: () => - sandboxRecreateTransaction.createSandboxRecreateRuntime( - onboardSession, - createIntent?.recreateTransaction, - sandboxName, - GATEWAY_NAME, - existingEntry, - getSandboxRecreateObservation, - note, - ), - carryForward: () => - applyAbsentSandboxRebuildPolicyCarryForward( - { - sandboxName, - liveExists, - nonInteractive: isNonInteractive(), - note, - rebuildPolicyPresets: createIntent?.rebuildPolicyPresets, - }, - policyPresetCarry.applyRecreatePolicyCarryForward, - ), - }); - const restoreReusedSandboxDashboard = async (selectionVerified: boolean): Promise => { - await dashboardPortReservationScope.release(); - ({ chatUiUrl } = sandboxReuse.applyReusedSandboxDashboardState({ - sandboxName, - chatUiUrl, - env: process.env, - agent, - model, - provider, - selectionVerified, - sandboxGpuConfig: effectiveSandboxGpuConfig, - gatewayName: GATEWAY_NAME, - gatewayPort: GATEWAY_PORT, - manageDashboard, - ensureDashboardForward, - hermesDashboardForwarding, - updateReusedSandboxMetadata, - })); - }; - if (recreateRuntime.acceptedTarget) { - await restoreReusedSandboxDashboard(true); - return sandboxName; - } const observabilityDrift = observabilityPolicy.hasRegisteredDcodeObservabilityDrift( liveExists, isManagedDcodeAgent, @@ -545,6 +666,97 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche sandboxName, workloadKind: workload.source.kind, }); + await validatePortableManagedWorkloadSelection({ + portableLifecycle: agentCreateInput.portableLifecycle, + selectionNeedsValidation: tempManagedRuntime || managedWorkloadRebuild !== null, + prepareWorkload: ensurePreparedSandboxWorkload, + }); + const sessionPolicyAuthority = onboardSession.loadSession()?.policyAuthority ?? null; + const qualifyPolicyAuthority = ( + sandboxIsLive = liveExists, + operation = `prepare sandbox '${sandboxName}'`, + ) => + policyAuthorityPreflight.qualifySandboxPolicyAuthority({ + sandboxName, + gatewayName: GATEWAY_NAME, + liveExists: sandboxIsLive, + recordedAuthorities: [existingEntry?.policyAuthority, sessionPolicyAuthority], + prepareRequiredPolicy: () => + sandboxCreatePlanMaterialization.prepareSandboxCreatePolicy(policyRequirementIntent) + .initialSandboxPolicy, + operation, + }); + const policyAuthorityInspection = qualifyPolicyAuthority(); + const resolvedPolicyAuthority = policyAuthorityInspection.authority; + const revalidatePolicyAuthority = (sandboxIsLive: boolean, operation: string): void => { + const inspection = qualifyPolicyAuthority(sandboxIsLive, operation); + assertRecordedPolicyAuthority(resolvedPolicyAuthority, inspection.authority, operation); + }; + assertHermesPortablePolicyAuthority( + agentCreateInput.hermesPortableLifecycle, + resolvedPolicyAuthority, + ); + backfillExistingSandboxPolicyAuthority({ + sandboxName, + existingEntry, + policyAuthority: resolvedPolicyAuthority, + updateSandbox: registry.updateSandbox, + }); + onboardSession.updateSession((session) => { + session.policyAuthority = resolvedPolicyAuthority; + if (resolvedPolicyAuthority === "externally-managed") session.policyPresets = null; + }); + // Prove the preserved source row before replacing its stale preset list. + // Policy carry-forward is an owned post-delete mutation, but applying it + // before recreate recovery makes the journal correctly reject that row as + // changed before the replacement can be created. + let recreateRuntime: + | import("../sandbox-recreate-transaction").SandboxRecreateRuntime + | OwnedSandboxRecreateRuntime = sandboxRecreateTransaction.createSandboxRecreateRuntime( + onboardSession, + createIntent?.recreateTransaction, + sandboxName, + GATEWAY_NAME, + existingEntry, + getSandboxRecreateObservation, + note, + ); + applyAbsentSandboxRebuildPolicyCarryForward( + { + sandboxName, + liveExists, + policyAuthority: resolvedPolicyAuthority, + nonInteractive: isNonInteractive(), + note, + rebuildPolicyPresets: createIntent?.rebuildPolicyPresets, + revalidatePolicyAuthority: (operation) => revalidatePolicyAuthority(false, operation), + }, + policyPresetCarry.applyRecreatePolicyCarryForward, + ); + const restoreReusedSandboxDashboard = async (selectionVerified: boolean): Promise => { + ({ chatUiUrl } = await sandboxReuse.restoreReusedSandboxDashboardState({ + sandboxName, + chatUiUrl, + env: process.env, + agent, + model, + provider, + selectionVerified, + sandboxGpuConfig: effectiveSandboxGpuConfig, + gatewayName: GATEWAY_NAME, + gatewayPort: GATEWAY_PORT, + manageDashboard, + ensureDashboardForward, + hermesDashboardForwarding, + updateReusedSandboxMetadata, + releaseDashboardPort: dashboardPortReservationScope.release, + revalidatePolicyRequirements: (operation) => revalidatePolicyAuthority(true, operation), + })); + }; + if (recreateRuntime.acceptedTarget) { + await restoreReusedSandboxDashboard(true); + return sandboxName; + } // #4614: capture default AFTER prune so a stale registry row isn't read as a live sandbox. const sandboxWasLiveDefault = liveExists && wasSandboxDefault(registry.getDefault(), sandboxName); @@ -713,10 +925,14 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche if (actionableSelectionDrift) { note(" [non-interactive] Recreating sandbox due to provider/model drift."); } else { + revalidatePolicyAuthority(true, `reusing sandbox '${sandboxName}'`); policyPresetCarry.seedReusedSandboxPolicyPresets(sandboxName, isNonInteractive()); // Upsert messaging providers even on reuse so credential changes take // effect without requiring a full sandbox recreation. - upsertMessagingProviders(messagingTokenDefs); + upsertMessagingProviders(messagingTokenDefs, { + revalidatePolicyRequirements: (operation) => + revalidatePolicyAuthority(true, operation), + }); if (selectionDrift.unknown) { note( " [non-interactive] Existing provider/model selection is unreadable; reusing sandbox.", @@ -760,8 +976,12 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche console.log(` Sandbox '${sandboxName}' already exists.`); console.log(" Choosing 'n' will delete the existing sandbox and create a new one."); if (await promptYesNoOrDefault(" Reuse existing sandbox?", null, true)) { + revalidatePolicyAuthority(true, `reusing sandbox '${sandboxName}'`); policyPresetCarry.seedReusedSandboxPolicyPresets(sandboxName, isNonInteractive()); - upsertMessagingProviders(messagingTokenDefs); + upsertMessagingProviders(messagingTokenDefs, { + revalidatePolicyRequirements: (operation) => + revalidatePolicyAuthority(true, operation), + }); await restoreReusedSandboxDashboard(!selectionDrift.unknown); return sandboxName; } @@ -843,11 +1063,16 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche baseImageResolutionContext, previousEntry?.imageTag, ); - policyPresetCarry.applyRecreatePolicyCarryForward( - sandboxName, - isNonInteractive(), - note, - createIntent?.rebuildPolicyPresets, + applyManagedSandboxRebuildPolicyCarryForward( + { + sandboxName, + policyAuthority: resolvedPolicyAuthority, + nonInteractive: isNonInteractive(), + note, + rebuildPolicyPresets: createIntent?.rebuildPolicyPresets, + revalidatePolicyAuthority: (operation) => revalidatePolicyAuthority(true, operation), + }, + policyPresetCarry.applyRecreatePolicyCarryForward, ); const noRestorePending = @@ -871,8 +1096,11 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche hermesStateVolumeLifecycle = prepareHermesStateVolumeLifecycle(preparedSandboxWorkload); note(` Deleting and recreating sandbox '${sandboxName}'...`); + revalidatePolicyAuthority(true, `recreating sandbox '${sandboxName}'`); if (recreateRuntime.beginDelete() === "source") { + revalidatePolicyAuthority(true, `cleaning up providers for sandbox '${sandboxName}'`); runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, redact }); + revalidatePolicyAuthority(true, `deleting sandbox '${sandboxName}'`); runOpenshell( [ "sandbox", @@ -907,13 +1135,16 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche preparedSandboxWorkload = await ensurePreparedSandboxWorkload(); hermesStateVolumeLifecycle = prepareHermesStateVolumeLifecycle(preparedSandboxWorkload); } + revalidatePolicyAuthority(false, `creating sandbox '${sandboxName}'`); sandboxCreatePlanMaterialization.applyOrdinaryExtraProviderReconciliation( agentCreateInput.hermesPortableLifecycle, - () => + () => { + revalidatePolicyAuthority(false, `updating providers for sandbox '${sandboxName}'`); applyExtraProviderReconciliation({ extraProviders: resolvedCreateIntent.extraProviders, staleExtraProviders: resolvedCreateIntent.staleExtraProviders ?? [], - }), + }); + }, ); const preparedOnboardLaunch = await managedWorkloadOnboard.prepareSelectedOnboardSandboxWorkloadLaunch( @@ -921,6 +1152,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche () => managedWorkloadOnboard.prepareHermesPortableOnboardSandboxLaunch({ intent: resolvedCreateIntent, + policyAuthority: resolvedPolicyAuthority, fromRef: preparedSandboxWorkload.source.kind === "legacy-dockerfile" ? preparedSandboxWorkload.source.dockerfilePath @@ -981,8 +1213,13 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche }, plan: { intent: resolvedCreateIntent, - rebindMessagingTokenDefs: async () => - ( + policyAuthority: resolvedPolicyAuthority, + rebindMessagingTokenDefs: async () => { + revalidatePolicyAuthority( + false, + `registering credentials for sandbox '${sandboxName}'`, + ); + return ( await sandboxCreateIntentResolver.rebind( { sandboxName, @@ -995,14 +1232,25 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche }, resolvedCreateIntent, ) - ).messagingTokenDefs, - runProviderPreDeleteCleanup: () => + ).messagingTokenDefs; + }, + runProviderPreDeleteCleanup: () => { + revalidatePolicyAuthority( + false, + `cleaning up providers for sandbox '${sandboxName}'`, + ); runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, redact, tolerateMissingSandbox: true, + }); + }, + upsertMessagingProviders: (tokenDefs, options) => + upsertMessagingProviders(tokenDefs, { + ...options, + revalidatePolicyRequirements: (operation) => + revalidatePolicyAuthority(false, operation), }), - upsertMessagingProviders, getHermesToolGatewayProviderName: (targetSandbox) => getHermesToolGatewayBroker().getHermesToolGatewayProviderName(targetSandbox), discloseInitialSandboxPolicy, @@ -1104,42 +1352,70 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche : null; const createFlowEnvironment = hermesGpuAuthority?.env ?? sandboxEnv; const createGpuVerifier = hermesGpuAuthority?.verify ?? verifyDirectSandboxGpu; - const runCreateFlow = ( + const runCreateFlow = async ( attemptCreateArgv: string[], hermesPortableReadyCapture?: import("../sandbox-gpu-create-flow").HermesPortableReadyCapture, hermesPortableReadyRunner?: import("../sandbox-gpu-create-flow").HermesPortableReadyRunner, createWorkingDirectory?: string, ) => - sandboxGpuCreateFlow.runSandboxGpuCreateFlow( - { - sandboxName, - provider, - sandboxGpuConfig: effectiveSandboxGpuConfig, - gpuRoutePlan, - initialGpuRoute, - compatibilityPolicyPath, - gatewayPort: GATEWAY_PORT, - sandboxReadyTimeoutSecs, - createArgv: attemptCreateArgv, - ...(createWorkingDirectory ? { createWorkingDirectory } : {}), - sandboxEnv: createFlowEnvironment, - sandboxStartupCommand, - lifecycleGeneration: createdSandboxLifecycle.generation, - portableRuntimeAuthority, - prebuild, - restoreBackupPath, - terminalAgent: agentDefs.isTerminalAgent(agent), - managedBootstrap, - ...agentCreateInput, - }, - { - runOpenshell: hermesPortableReadyRunner ?? runOpenshell, - runCaptureOpenshell: hermesPortableReadyCapture ?? runCaptureOpenshell, - sleep: sleepSeconds, - openshellArgv, - verifyDirectSandboxGpu: createGpuVerifier, + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName, + revalidate: revalidatePolicyAuthority, + captureCreatedSandboxLiveIdentity: (created) => + createdSandboxLifecycle.capture(created.lifecycleRegistrationFields) + .lifecycleLiveIdentityFingerprint, + observeCreatedSandbox: () => getSandboxRecreateObservation(sandboxName, GATEWAY_NAME), + cleanupTemporarySources: cleanupSandboxCreateSources, + deleteCreatedSandbox: () => { + const deleteResult = hermesPortableReadyRunner + ? hermesPortableReadyRunner(["sandbox", "delete", sandboxName], { + ignoreError: true, + suppressOutput: true, + }) + : runOpenshell(["sandbox", "delete", "-g", GATEWAY_NAME, sandboxName], { + ignoreError: true, + suppressOutput: true, + }); + if (deleteResult.status !== 0) { + throw new Error( + `OpenShell did not remove sandbox '${sandboxName}' after final policy authority validation failed.`, + ); + } }, - ); + waitForCreatedSandboxAbsence: () => + waitForSandboxRecreateDeleteAbsence(sandboxName, GATEWAY_NAME, note), + create: () => + sandboxGpuCreateFlow.runSandboxGpuCreateFlow( + { + sandboxName, + provider, + sandboxGpuConfig: effectiveSandboxGpuConfig, + gpuRoutePlan, + initialGpuRoute, + compatibilityPolicyPath, + gatewayPort: GATEWAY_PORT, + sandboxReadyTimeoutSecs, + createArgv: attemptCreateArgv, + ...(createWorkingDirectory ? { createWorkingDirectory } : {}), + sandboxEnv: createFlowEnvironment, + sandboxStartupCommand, + lifecycleGeneration: createdSandboxLifecycle.generation, + portableRuntimeAuthority, + prebuild, + restoreBackupPath, + terminalAgent: agentDefs.isTerminalAgent(agent), + managedBootstrap, + ...agentCreateInput, + }, + { + runOpenshell: hermesPortableReadyRunner ?? runOpenshell, + runCaptureOpenshell: hermesPortableReadyCapture ?? runCaptureOpenshell, + sleep: sleepSeconds, + openshellArgv, + verifyDirectSandboxGpu: createGpuVerifier, + }, + ), + }); const cleanupBuildContext = sandboxGpuCreateFlow.createSandboxBuildContextCleanup(legacyBuildContext); @@ -1147,6 +1423,30 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche initialSandboxPolicy, agentCreateInput.hermesPortableLifecycle, ); + const cleanupSandboxCreateSources = (): void => { + const cleanupErrors: Error[] = []; + try { + if (!cleanupInitialCreateSource()) { + cleanupErrors.push( + new Error("The temporary sandbox create policy could not be removed."), + ); + } + } catch (error) { + cleanupErrors.push(error instanceof Error ? error : new Error(String(error))); + } + try { + if (!cleanupBuildContext()) { + cleanupErrors.push( + new Error("The temporary sandbox build context could not be removed."), + ); + } + } catch (error) { + cleanupErrors.push(error instanceof Error ? error : new Error(String(error))); + } + if (cleanupErrors.length > 0) { + throw new AggregateError(cleanupErrors, "Temporary sandbox create sources remain."); + } + }; const sandboxRuntimeFields = agentCreateInput.hermesPortableLifecycle ? sandboxRegistryMetadata.getHermesPortableSandboxRuntimeRegistryFields( effectiveSandboxGpuConfig, @@ -1172,7 +1472,13 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche { plannedMessagingState, preservedMcpState, hermesToolGateways }, hermesApiPortReservationScope.effectivePort, { gatewayName: GATEWAY_NAME, gatewayPort: GATEWAY_PORT }, - { initialSandboxPolicy, policyTier: resolvedCreatePolicyTier, dashboardRemoteBindPrepared }, + { + initialSandboxPolicy, + policyTier: resolvedCreatePolicyTier, + policyAuthority: resolvedPolicyAuthority, + revalidatePolicyAuthority: (operation) => revalidatePolicyAuthority(true, operation), + dashboardRemoteBindPrepared, + }, prebuild.imageRef, buildId, effectiveSandboxGpuConfig, @@ -1295,6 +1601,10 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche }); cleanupBuildContext(); } else { + revalidatePolicyAuthority( + false, + `publishing providers before creating sandbox gateway '${GATEWAY_NAME}'`, + ); publishAttachedProvidersBeforeDockerSandboxCreation( providerPreparationInput, providerPreparationDeps, @@ -1323,6 +1633,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche armCancelRollback: sandboxCancelRollback.arm, dockerInfoFormat, runCapture, + revalidatePolicyAuthority: (operation) => revalidatePolicyAuthority(true, operation), }, ); }; diff --git a/src/lib/onboard/sandbox-gpu-create-flow.ts b/src/lib/onboard/sandbox-gpu-create-flow.ts index 1a418758459..96eb0bcbb6e 100644 --- a/src/lib/onboard/sandbox-gpu-create-flow.ts +++ b/src/lib/onboard/sandbox-gpu-create-flow.ts @@ -101,16 +101,28 @@ export function createSandboxCreateSourceCleanup( source: { readonly cleanup?: () => boolean; readonly cleanupExact?: () => boolean }, requireExact: boolean, ): () => boolean { - return () => - cleanupSandboxCreateSource(source.cleanup, { exactCleanup: source.cleanupExact, requireExact }); + let completed = false; + return () => { + if (completed) return true; + completed = cleanupSandboxCreateSource(source.cleanup, { + exactCleanup: source.cleanupExact, + requireExact, + }); + return completed; + }; } /** Bind cleanup for the one staged build context owned by this create attempt. */ export function createSandboxBuildContextCleanup( context: { readonly cleanupBuildCtx?: () => boolean } | null, -): () => void { +): () => boolean { + let completed = false; return () => { - if (context?.cleanupBuildCtx?.()) process.removeListener("exit", context.cleanupBuildCtx); + if (completed) return true; + if (!context?.cleanupBuildCtx) return true; + completed = context.cleanupBuildCtx(); + if (completed) process.removeListener("exit", context.cleanupBuildCtx); + return completed; }; } diff --git a/src/lib/onboard/sandbox-recreate-probe.ts b/src/lib/onboard/sandbox-recreate-probe.ts index a631fea9227..d9602777c46 100644 --- a/src/lib/onboard/sandbox-recreate-probe.ts +++ b/src/lib/onboard/sandbox-recreate-probe.ts @@ -33,6 +33,10 @@ export interface SandboxRecreateTarget { readonly gatewayPort: number; } +export type SandboxGatewayPresence = "present" | "missing"; + +type SandboxGatewayPresenceTarget = Pick; + export type SandboxRecreateObserver = (target: SandboxRecreateTarget) => SandboxRecreateObservation; /** @@ -66,6 +70,29 @@ export function isExplicitMissingSandboxGatewayOutput( ); } +/** Observe only whether the named sandbox exists on its recorded gateway. */ +export function observeSandboxPresenceOnGateway( + target: SandboxGatewayPresenceTarget, +): SandboxGatewayPresence { + const probe = captureOpenshell(["sandbox", "get", "-g", target.gatewayName, target.sandboxName], { + ignoreError: true, + includeStderr: true, + includeStreams: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); + const stdout = String(probe.stdout ?? (probe.status === 0 ? probe.output : "")).trim(); + const combined = `${stdout}\n${String(probe.stderr ?? probe.output ?? "")}`.trim(); + const failedCleanly = + !probe.error && !probe.signal && probe.status !== null && probe.status !== 0; + if (failedCleanly && isExplicitMissingSandboxGatewayOutput(combined, target.sandboxName)) { + return "missing"; + } + if (probe.status === 0 && stdout.length > 0) return "present"; + throw new Error( + `Cannot inspect sandbox '${target.sandboxName}' on gateway '${target.gatewayName}': OpenShell reported neither presence nor explicit absence.`, + ); +} + export function observeSandboxOnGateway(target: SandboxRecreateTarget): SandboxRecreateObservation { const probe = captureOpenshell(["sandbox", "get", "-g", target.gatewayName, target.sandboxName], { ignoreError: true, diff --git a/src/lib/onboard/sandbox-registration.test.ts b/src/lib/onboard/sandbox-registration.test.ts index f59ff6eb39b..96d72bcb7aa 100644 --- a/src/lib/onboard/sandbox-registration.test.ts +++ b/src/lib/onboard/sandbox-registration.test.ts @@ -94,6 +94,14 @@ function createdRegistryEntryInput( } describe("buildCreatedSandboxRegistryEntry", () => { + it("copies policy authority into completed sandbox registration (#9833)", () => { + const entry = buildCreatedSandboxRegistryEntry( + createdRegistryEntryInput({ policyAuthority: "externally-managed" }), + ); + + expect(entry.policyAuthority).toBe("externally-managed"); + }); + it("records explicit OpenClaw identity for a managed workload receipt (#9356)", () => { const workload = managedWorkloadReceipt("openclaw"); const entry = buildCreatedSandboxRegistryEntry( diff --git a/src/lib/onboard/sandbox-registration.ts b/src/lib/onboard/sandbox-registration.ts index 35efb88639f..2d4a9492a71 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -3,6 +3,7 @@ import { isDeepStrictEqual } from "node:util"; +import type { SandboxPolicyAuthority } from "../adapters/openshell/policy-authority"; import type { AgentDefinition } from "../agent/defs"; import type { InferenceEndpointSource, InferenceSelection } from "../inference/selection"; import { inferenceSelectionRegistryFields } from "../inference/selection"; @@ -69,6 +70,7 @@ export interface CreatedSandboxRegistryEntryInput { hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; openclawImagePluginInstalls?: readonly OpenClawImagePluginInstall[]; appliedPolicies: string[]; + policyAuthority?: SandboxPolicyAuthority; toolDisclosure?: ToolDisclosure; observabilityEnabled?: boolean; dcodeAutoApprovalMode?: DcodeAutoApprovalMode; @@ -272,6 +274,7 @@ export function buildCreatedSandboxRegistryEntry( } : {}), policies: input.appliedPolicies, + ...(input.policyAuthority !== undefined ? { policyAuthority: input.policyAuthority } : {}), baselineExclusions: input.baselineExclusions?.map((exclusion) => ({ ...exclusion })), toolDisclosure: input.toolDisclosure ?? DEFAULT_TOOL_DISCLOSURE, observabilityEnabled: input.observabilityEnabled === true, diff --git a/src/lib/onboard/sandbox-registry-metadata.test.ts b/src/lib/onboard/sandbox-registry-metadata.test.ts index e8d3ad2c97d..c5f05767b44 100644 --- a/src/lib/onboard/sandbox-registry-metadata.test.ts +++ b/src/lib/onboard/sandbox-registry-metadata.test.ts @@ -241,6 +241,52 @@ describe("sandbox registry metadata", () => { expect(persisted.sandboxes.alpha.agent).toBe("hermes"); }); + it("rechecks authority between reused metadata and default registry writes (#9833)", async () => { + tmpDir = mkdtempSync(join(tmpdir(), "nemoclaw-reuse-policy-authority-")); + process.env.HOME = tmpDir; + vi.resetModules(); + + const configDir = join(tmpDir, ".nemoclaw"); + const registryFile = join(configDir, "sandboxes.json"); + mkdirSync(configDir, { recursive: true }); + writeFileSync( + registryFile, + JSON.stringify({ + sandboxes: { + alpha: { name: "alpha", model: "old-model", provider: "old-provider" }, + beta: { name: "beta", model: "model", provider: "provider" }, + }, + defaultSandbox: "beta", + }), + ); + + const helpers = await makeHelpers("docker"); + const revalidatePolicyAuthority = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("policy authority changed"); + }); + + expect(() => + helpers.updateReusedSandboxMetadata( + "alpha", + openclawAgent("2026.5.22"), + "new-model", + "nvidia-prod", + 18789, + true, + null, + revalidatePolicyAuthority, + ), + ).toThrow("policy authority changed"); + + const persisted = JSON.parse(readFileSync(registryFile, "utf8")); + expect(persisted.sandboxes.alpha.model).toBe("new-model"); + expect(persisted.defaultSandbox).toBe("beta"); + expect(revalidatePolicyAuthority).toHaveBeenCalledTimes(2); + }); + it("persists a reused terminal sandbox without a dashboard port for host allocation (#7020)", async () => { tmpDir = mkdtempSync(join(tmpdir(), "nemoclaw-reuse-terminal-metadata-")); process.env.HOME = tmpDir; diff --git a/src/lib/onboard/sandbox-registry-metadata.ts b/src/lib/onboard/sandbox-registry-metadata.ts index 29828d39fa0..25d87a2d5c1 100644 --- a/src/lib/onboard/sandbox-registry-metadata.ts +++ b/src/lib/onboard/sandbox-registry-metadata.ts @@ -37,6 +37,7 @@ export interface SandboxRegistryMetadataHelpers { dashboardPort: number, selectionVerified?: boolean, sandboxGpuConfig?: SandboxGpuConfig | null, + revalidatePolicyAuthority?: (operation: string) => void, ): void; } @@ -109,10 +110,12 @@ export function createSandboxRegistryMetadataHelpers( dashboardPort: number, selectionVerified = true, sandboxGpuConfig: SandboxGpuConfig | null = null, + revalidatePolicyAuthority?: (operation: string) => void, ): void { const existingEntry = registry.getSandbox(sandboxName); const agentFields = getSandboxAgentRegistryFields(agent, false); const selectionUpdates = selectionVerified ? { model, provider } : {}; + revalidatePolicyAuthority?.(`record reused sandbox metadata for '${sandboxName}'`); registry.updateSandbox(sandboxName, { ...selectionUpdates, dashboardPort, @@ -120,6 +123,7 @@ export function createSandboxRegistryMetadataHelpers( agentVersion: existingEntry?.agentVersion ?? null, ...(sandboxGpuConfig ? getSandboxRuntimeRegistryFields(sandboxGpuConfig) : {}), }); + revalidatePolicyAuthority?.(`make reused sandbox '${sandboxName}' the default`); registry.setDefault(sandboxName); } diff --git a/src/lib/onboard/sandbox-reuse.test.ts b/src/lib/onboard/sandbox-reuse.test.ts index 3e6369de1a6..ec1179c34c0 100644 --- a/src/lib/onboard/sandbox-reuse.test.ts +++ b/src/lib/onboard/sandbox-reuse.test.ts @@ -9,6 +9,7 @@ import { fingerprintSandboxRecreateValue } from "./sandbox-recreate-transaction" import { applyReusedSandboxDashboardState, createSandboxReuseHelpers, + restoreReusedSandboxDashboardState, type SandboxReuseDeps, } from "./sandbox-reuse"; @@ -30,82 +31,6 @@ describe("applyReusedSandboxDashboardState", () => { vi.restoreAllMocks(); }); - it("updates dashboard URL, Hermes forwarding, reuse metadata, and gateway registry fields", () => { - const updateSandbox = vi.fn(); - const env: NodeJS.ProcessEnv = {}; - const sandboxGpuConfig: SandboxGpuConfig = { - hostGpuDetected: true, - hostGpuPlatform: "linux", - sandboxGpuEnabled: true, - mode: "auto", - sandboxGpuDevice: null, - errors: [], - sandboxGpuProof: null, - }; - const hermesDashboardState = { - enabled: true, - config: { - enabled: true, - port: 9123, - internalPort: 19123, - tuiEnabled: true, - }, - }; - const hermesDashboardForwarding = { - resolveStateForPort: vi.fn(() => hermesDashboardState), - ensureForState: vi.fn(), - }; - const ensureDashboardForward = vi.fn(() => 18790); - const updateReusedSandboxMetadata = vi.fn(); - - const result = applyReusedSandboxDashboardState({ - sandboxName: "reuse-me", - chatUiUrl: "http://127.0.0.1:18789", - env, - agent: null, - model: "test-model", - provider: "openai-compatible", - selectionVerified: false, - sandboxGpuConfig, - gatewayName: "nemoclaw-19080", - gatewayPort: 19080, - ensureDashboardForward, - hermesDashboardForwarding, - updateSandbox, - updateReusedSandboxMetadata, - }); - - expect(ensureDashboardForward).toHaveBeenCalledWith("reuse-me", "http://127.0.0.1:18789"); - expect(env.CHAT_UI_URL).toBe("http://127.0.0.1:18790"); - expect(hermesDashboardForwarding.resolveStateForPort).toHaveBeenCalledWith(18790); - expect(hermesDashboardForwarding.ensureForState).toHaveBeenCalledWith( - hermesDashboardState, - "reuse-me", - ); - expect(updateReusedSandboxMetadata).toHaveBeenCalledWith( - "reuse-me", - null, - "test-model", - "openai-compatible", - 18790, - false, - sandboxGpuConfig, - ); - expect(updateSandbox).toHaveBeenCalledWith("reuse-me", { - hermesDashboardEnabled: true, - hermesDashboardPort: 9123, - hermesDashboardInternalPort: 19123, - hermesDashboardTui: true, - gatewayName: "nemoclaw-19080", - gatewayPort: 19080, - }); - expect(result).toEqual({ - chatUiUrl: "http://127.0.0.1:18790", - dashboardPort: 18790, - hermesDashboardState, - }); - }); - it("clears Hermes dashboard registry fields when the reused sandbox has it disabled", () => { const updateSandbox = vi.fn(); const sandboxGpuConfig: SandboxGpuConfig = { @@ -198,6 +123,7 @@ describe("applyReusedSandboxDashboardState", () => { 0, true, sandboxGpuConfig, + undefined, ); expect(updateSandbox).toHaveBeenCalledWith("terminal-box", { hermesDashboardEnabled: undefined, @@ -213,6 +139,114 @@ describe("applyReusedSandboxDashboardState", () => { hermesDashboardState: { enabled: false, config: null }, }); }); + + it("passes the receipt check into dashboard forwarding after release (#9833)", async () => { + const revalidatePolicyRequirements = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority must supply the dashboard entry"); + }); + const ensureDashboardForward = vi.fn( + ( + _sandboxName: string, + _chatUiUrl: string, + options?: { revalidatePolicyAuthority?: (operation: string) => void }, + ) => { + options?.revalidatePolicyAuthority?.("start the dashboard forward"); + return 18790; + }, + ); + const env: NodeJS.ProcessEnv = {}; + const ensureForState = vi.fn(); + const updateReusedSandboxMetadata = vi.fn(); + const updateSandbox = vi.fn(); + + await expect( + restoreReusedSandboxDashboardState({ + sandboxName: "reuse-me", + chatUiUrl: "http://127.0.0.1:18789", + env, + agent: null, + model: "test-model", + provider: "openai-compatible", + selectionVerified: true, + sandboxGpuConfig: { + hostGpuDetected: false, + hostGpuPlatform: null, + sandboxGpuEnabled: false, + mode: "auto", + sandboxGpuDevice: null, + errors: [], + }, + gatewayName: "nemoclaw", + gatewayPort: 8080, + releaseDashboardPort: vi.fn(async () => undefined), + ensureDashboardForward, + hermesDashboardForwarding: { + resolveStateForPort: vi.fn(() => ({ enabled: false, config: null })), + ensureForState, + }, + updateSandbox, + updateReusedSandboxMetadata, + revalidatePolicyRequirements, + }), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(ensureDashboardForward).toHaveBeenCalledOnce(); + expect(env.CHAT_UI_URL).toBeUndefined(); + expect(ensureForState).not.toHaveBeenCalled(); + expect(updateReusedSandboxMetadata).not.toHaveBeenCalled(); + expect(updateSandbox).not.toHaveBeenCalled(); + }); + + it("rechecks after Hermes forwarding before reuse metadata (#9833)", () => { + const revalidatePolicyRequirements = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("external policy authority must supply the dashboard entry"); + }); + const ensureForState = vi.fn(); + const updateReusedSandboxMetadata = vi.fn(); + const updateSandbox = vi.fn(); + + expect(() => + applyReusedSandboxDashboardState({ + sandboxName: "reuse-me", + chatUiUrl: "http://127.0.0.1:18789", + env: {}, + agent: null, + model: "test-model", + provider: "openai-compatible", + selectionVerified: true, + sandboxGpuConfig: { + hostGpuDetected: false, + hostGpuPlatform: null, + sandboxGpuEnabled: false, + mode: "auto", + sandboxGpuDevice: null, + errors: [], + }, + gatewayName: "nemoclaw", + gatewayPort: 8080, + ensureDashboardForward: vi.fn(() => 18790), + hermesDashboardForwarding: { + resolveStateForPort: vi.fn(() => ({ enabled: false, config: null })), + ensureForState, + }, + updateSandbox, + updateReusedSandboxMetadata, + revalidatePolicyRequirements, + }), + ).toThrow(/external policy authority must supply/u); + + expect(ensureForState).toHaveBeenCalledOnce(); + expect(updateReusedSandboxMetadata).not.toHaveBeenCalled(); + expect(updateSandbox).not.toHaveBeenCalled(); + }); }); describe("createSandboxReuseHelpers", () => { diff --git a/src/lib/onboard/sandbox-reuse.ts b/src/lib/onboard/sandbox-reuse.ts index 342167e5d35..7145301e02c 100644 --- a/src/lib/onboard/sandbox-reuse.ts +++ b/src/lib/onboard/sandbox-reuse.ts @@ -80,7 +80,12 @@ function isCleanFailedProbe(probe: SandboxCaptureResult): boolean { export interface ReusedSandboxDashboardForwarding { resolveStateForPort(effectivePort: number): HermesDashboardOnboardState; - ensureForState(state: HermesDashboardOnboardState, sandboxName: string): void; + ensureForState( + state: HermesDashboardOnboardState, + sandboxName: string, + rollback?: boolean, + revalidatePolicyAuthority?: (operation: string) => void, + ): void; } export interface ReusedSandboxDashboardStateInput { @@ -96,9 +101,14 @@ export interface ReusedSandboxDashboardStateInput { gatewayPort: number; manageDashboard?: boolean; getSandbox?(sandboxName: string): SandboxEntry | null; - ensureDashboardForward(sandboxName: string, chatUiUrl: string): number; + ensureDashboardForward( + sandboxName: string, + chatUiUrl: string, + options?: { revalidatePolicyAuthority?: (operation: string) => void }, + ): number; hermesDashboardForwarding: ReusedSandboxDashboardForwarding; updateSandbox?(sandboxName: string, updates: Partial): unknown; + revalidatePolicyRequirements?(operation: string): void; updateReusedSandboxMetadata( sandboxName: string, agent: AgentDefinition | null | undefined, @@ -107,6 +117,7 @@ export interface ReusedSandboxDashboardStateInput { dashboardPort: number, selectionVerified: boolean, sandboxGpuConfig: SandboxGpuConfig, + revalidatePolicyAuthority?: (operation: string) => void, ): void; } @@ -130,19 +141,40 @@ export function applyReusedSandboxDashboardState( `Sandbox '${input.sandboxName}' was created without remote dashboard exposure. Re-run onboarding with NEMOCLAW_DASHBOARD_BIND=0.0.0.0 and --recreate-sandbox before opening a remote bind.`, ); } + input.revalidatePolicyRequirements?.( + `restore dashboard state for sandbox ${JSON.stringify(input.sandboxName)}`, + ); const dashboardPort = manageDashboard - ? input.ensureDashboardForward(input.sandboxName, input.chatUiUrl) + ? input.revalidatePolicyRequirements + ? input.ensureDashboardForward(input.sandboxName, input.chatUiUrl, { + revalidatePolicyAuthority: input.revalidatePolicyRequirements, + }) + : input.ensureDashboardForward(input.sandboxName, input.chatUiUrl) : 0; const chatUiUrl = manageDashboard ? `http://127.0.0.1:${dashboardPort}` : input.chatUiUrl; if (manageDashboard) { + input.revalidatePolicyRequirements?.( + `record dashboard URL for sandbox ${JSON.stringify(input.sandboxName)}`, + ); input.env.CHAT_UI_URL = chatUiUrl; } const hermesDashboardState = manageDashboard ? input.hermesDashboardForwarding.resolveStateForPort(dashboardPort) : { enabled: false, config: null }; if (manageDashboard) { - input.hermesDashboardForwarding.ensureForState(hermesDashboardState, input.sandboxName); + input.revalidatePolicyRequirements?.( + `restore Hermes dashboard state for sandbox ${JSON.stringify(input.sandboxName)}`, + ); + input.hermesDashboardForwarding.ensureForState( + hermesDashboardState, + input.sandboxName, + false, + input.revalidatePolicyRequirements, + ); } + input.revalidatePolicyRequirements?.( + `update reused sandbox metadata for ${JSON.stringify(input.sandboxName)}`, + ); input.updateReusedSandboxMetadata( input.sandboxName, input.agent, @@ -151,6 +183,10 @@ export function applyReusedSandboxDashboardState( dashboardPort, input.selectionVerified, input.sandboxGpuConfig, + input.revalidatePolicyRequirements, + ); + input.revalidatePolicyRequirements?.( + `record reused dashboard state for sandbox ${JSON.stringify(input.sandboxName)}`, ); (input.updateSandbox ?? registry.updateSandbox)(input.sandboxName, { ...getHermesDashboardRegistryFields(hermesDashboardState), @@ -160,6 +196,13 @@ export function applyReusedSandboxDashboardState( return { chatUiUrl, dashboardPort, hermesDashboardState }; } +export async function restoreReusedSandboxDashboardState( + input: ReusedSandboxDashboardStateInput & { releaseDashboardPort(): Promise }, +): Promise { + await input.releaseDashboardPort(); + return applyReusedSandboxDashboardState(input); +} + export function createSandboxReuseHelpers(deps: SandboxReuseDeps): SandboxReuseHelpers { // A recorded gateway wins over the ambient one: a resumed replacement must // prove presence or absence on the gateway its journal names. diff --git a/src/lib/onboard/session-bootstrap.test.ts b/src/lib/onboard/session-bootstrap.test.ts index 3c71835bbf1..1266a3dd70b 100644 --- a/src/lib/onboard/session-bootstrap.test.ts +++ b/src/lib/onboard/session-bootstrap.test.ts @@ -92,6 +92,36 @@ function createDeps( } describe("prepareOnboardSession", () => { + it("stops resume before side effects when saved policy authority is invalid (#9833)", async () => { + const loadSession = vi.fn((): Session | null => { + throw new Error( + "Refusing to load the onboarding session: the saved policy authority is invalid.", + ); + }); + const { deps } = createDeps(null, { loadSession }); + + await expect( + prepareOnboardSession( + { + resume: true, + fresh: false, + requestedFromDockerfile: null, + requestedSandboxName: null, + cannotPrompt: true, + nonInteractive: true, + }, + deps, + ), + ).rejects.toThrow(/saved policy authority is invalid/u); + + expect(loadSession).toHaveBeenCalledOnce(); + expect(deps.requireHostMountRuntimeSupport).not.toHaveBeenCalled(); + expect(deps.setOnboardBrandingAgent).not.toHaveBeenCalled(); + expect(deps.updateSession).not.toHaveBeenCalled(); + expect(deps.saveSession).not.toHaveBeenCalled(); + expect(deps.clearSession).not.toHaveBeenCalled(); + }); + it("creates a fresh session and records the resolved Dockerfile", async () => { const existing = createSession({ sessionId: "old-session" }); const { deps, getSession } = createDeps(existing); diff --git a/src/lib/onboard/session-updates.ts b/src/lib/onboard/session-updates.ts index 53b927990b8..6f9b514be08 100644 --- a/src/lib/onboard/session-updates.ts +++ b/src/lib/onboard/session-updates.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { SandboxPolicyAuthority } from "../adapters/openshell/policy-authority"; import type { ServingProfileProvenance } from "../inference/serving/types"; import type { WebSearchConfig } from "../inference/web-search"; import type { SandboxMessagingPlan } from "../messaging/manifest"; @@ -24,6 +25,7 @@ export interface OnboardSessionUpdateInput { toolDisclosure?: ToolDisclosure | string; observabilityEnabled?: boolean; policyPresets?: string[] | null; + policyAuthority?: SandboxPolicyAuthority | null; messagingPlan?: SandboxMessagingPlan | null; hermesToolGateways?: string[] | null; /** Ephemeral vLLM checkpoint proof consumed by Station provider binding; never persisted. */ @@ -88,6 +90,7 @@ export function toSessionUpdates(updates: OnboardSessionUpdateInput = {}): Sessi normalized.observabilityEnabled = updates.observabilityEnabled; } if (updates.policyPresets !== undefined) normalized.policyPresets = updates.policyPresets; + if (updates.policyAuthority !== undefined) normalized.policyAuthority = updates.policyAuthority; if (updates.messagingPlan !== undefined) normalized.messagingPlan = updates.messagingPlan; if (updates.hermesToolGateways !== undefined) normalized.hermesToolGateways = updates.hermesToolGateways; diff --git a/src/lib/onboard/setup-inference-gateway-scope.test.ts b/src/lib/onboard/setup-inference-gateway-scope.test.ts index 7d06e0a808e..84935e88e26 100644 --- a/src/lib/onboard/setup-inference-gateway-scope.test.ts +++ b/src/lib/onboard/setup-inference-gateway-scope.test.ts @@ -70,20 +70,22 @@ describe("gateway-scoped onboarding OpenShell commands", () => { it.each([ ["--gateway-endpoint", "https://other.example.test"], ["--gateway-endpoint=https://other.example.test"], - ])("rejects an explicit endpoint override before the payload separator: %j", (...endpointArgs) => { - expect(() => - scopeGatewayOpenshellArgs(["provider", "get", ...endpointArgs, "openai-api"], GATEWAY), - ).toThrow(/--gateway-endpoint may bypass the gateway recorded/); - }); - - it.each([ - ["-g", GATEWAY], - ["--gateway", GATEWAY], - [`--gateway=${GATEWAY}`], - ])("accepts an identical existing target: %j", (...gatewayArgs) => { - const command = ["provider", "list", ...gatewayArgs]; - expect(scopeGatewayOpenshellArgs(command, GATEWAY)).toEqual(command); - }); + ])( + "rejects an explicit endpoint override before the payload separator: %j", + (...endpointArgs) => { + expect(() => + scopeGatewayOpenshellArgs(["provider", "get", ...endpointArgs, "openai-api"], GATEWAY), + ).toThrow(/--gateway-endpoint may bypass the gateway recorded/); + }, + ); + + it.each([["-g", GATEWAY], ["--gateway", GATEWAY], [`--gateway=${GATEWAY}`]])( + "accepts an identical existing target: %j", + (...gatewayArgs) => { + const command = ["provider", "list", ...gatewayArgs]; + expect(scopeGatewayOpenshellArgs(command, GATEWAY)).toEqual(command); + }, + ); it("rejects a conflicting, duplicate, missing, or selection-based target", () => { expect(() => @@ -131,6 +133,7 @@ describe("gateway-scoped onboarding OpenShell commands", () => { null, undefined, GATEWAY, + { revalidatePolicyRequirements: undefined }, ); }); diff --git a/src/lib/onboard/setup-inference-policy-authority.test.ts b/src/lib/onboard/setup-inference-policy-authority.test.ts new file mode 100644 index 00000000000..bd2a7ed0e8a --- /dev/null +++ b/src/lib/onboard/setup-inference-policy-authority.test.ts @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { createSetupInference, type SetupInferenceDeps } from "./setup-inference"; + +const refuseAuthorityChange = (): never => { + throw new Error("authority changed"); +}; + +function createSetupDeps(): SetupInferenceDeps { + return { + checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), + withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + step: vi.fn(), + getGatewayName: () => "nemoclaw", + runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), + updateSandbox: vi.fn(() => true), + upsertProvider: vi.fn(() => ({ ok: true as const })), + verifyInferenceRoute: vi.fn(), + verifyOnboardInferenceSmoke: vi.fn(), + resolveEndpointHost: vi.fn(async () => [{ address: "93.184.216.34", family: 4 }]), + isNonInteractive: () => true, + isRoutedInferenceProvider: () => false, + hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, + REMOTE_PROVIDER_CONFIG: { + custom: { + label: "Compatible endpoint", + providerName: "compatible-endpoint", + providerType: "openai", + credentialEnv: "COMPATIBLE_API_KEY", + endpointUrl: "https://endpoint.example/v1", + helpUrl: null, + modelMode: "input", + defaultModel: "model-a", + }, + }, + hydrateCredentialEnv: vi.fn(() => "secret"), + promptValidationRecovery: vi.fn(), + classifyApplyFailure: vi.fn(), + localInferenceTimeoutSecs: 60, + bedrockRuntimeOnboard: { + setupBedrockRuntimeInference: vi.fn(async () => ({ handled: false as const })), + }, + openrouterRuntimeOnboard: { + setupOpenRouterRuntimeInference: vi.fn(async () => ({ handled: false as const })), + }, + redact: (value: string) => value, + compactText: (value: string) => value, + log: vi.fn(), + error: vi.fn(), + exitProcess: vi.fn((code: number): never => { + throw new Error(`exit ${String(code)}`); + }), + } as unknown as SetupInferenceDeps; +} + +describe("onboard inference policy authority mutation edges", () => { + it("withholds success when authority changes after inference smoke (#9833)", async () => { + const deps = createSetupDeps(); + + await expect( + createSetupInference(deps)( + "sandbox-a", + "model-a", + "compatible-endpoint", + "https://endpoint.example/v1", + "COMPATIBLE_API_KEY", + null, + [], + { + endpointPinnedAddresses: ["93.184.216.34"], + revalidatePolicyRequirements: (operation) => + operation === "report successful inference provider setup" + ? refuseAuthorityChange() + : undefined, + }, + ), + ).rejects.toThrow("authority changed"); + + expect(deps.verifyOnboardInferenceSmoke).toHaveBeenCalledOnce(); + expect(deps.log).not.toHaveBeenCalledWith(expect.stringContaining("Inference route set")); + }); +}); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 7edc11234f2..244a0e0d773 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -19,10 +19,7 @@ import { withModelRouterPortLifecycleLock, } from "../inference/gateway-route-mutation-lock"; import { getManagedVllmProviderBinding } from "../inference/local"; -import { - type OllamaModelHolder, - supersededOllamaModel, -} from "../inference/ollama/model-ownership"; +import { type OllamaModelHolder, supersededOllamaModel } from "../inference/ollama/model-ownership"; import { getOllamaProxyToken, persistAndProbeOllamaProxy, @@ -202,6 +199,7 @@ export type SetupInferenceDeps = ProviderBranchDeps & { baseUrl: string | null, env: NodeJS.ProcessEnv | undefined, gatewayName: string, + options?: { revalidatePolicyRequirements?(operation: string): void }, ) => ReturnType; verifyInferenceRoute: (gatewayName: string, provider: string, model: string) => void; providerExistsInGateway: (name: string, gatewayName: string) => boolean; @@ -278,9 +276,12 @@ export function createGatewayScopedOpenshellRunner void, ): CommonDeps["upsertProvider"] { return (name, type, credentialEnv, baseUrl, env) => - upsertProvider(name, type, credentialEnv, baseUrl, env, gatewayName); + upsertProvider(name, type, credentialEnv, baseUrl, env, gatewayName, { + revalidatePolicyRequirements, + }); } export function selectGatewayForFollowupOrExit( @@ -301,13 +302,21 @@ export function selectGatewayForFollowupOrExit( function resolveLocalInferenceRouteApplier( deps: SetupInferenceDeps, runOpenshell: SetupInferenceDeps["runOpenshell"], + revalidatePolicyRequirements: (operation: string) => void, ) { return ( deps.applyLocalInferenceRoute ?? createLocalInferenceRouteApplier({ runOpenshell, isNonInteractive: deps.isNonInteractive, - promptValidationRecovery: deps.promptValidationRecovery, + promptValidationRecovery: (label, recovery, credentialEnv, helpUrl) => + deps.promptValidationRecovery( + label, + recovery, + credentialEnv, + helpUrl, + revalidatePolicyRequirements, + ), classifyApplyFailure: deps.classifyApplyFailure, compactText: deps.compactText, redact: deps.redact, @@ -480,22 +489,30 @@ function releaseSupersededOllamaModel( nextModel: string, result: SetupInferenceResult, deps: SetupInferenceDeps, + revalidatePolicyRequirements: (operation: string) => void, ): void { // A reselection retry left the recorded route untouched, so the sandbox // still owns its model. if (!previous || result.retry) return; + let authorityRefusal: unknown; try { - const withOwnershipLock = - deps.withOllamaModelOwnershipLock ?? withOllamaModelOwnershipLock; + const withOwnershipLock = deps.withOllamaModelOwnershipLock ?? withOllamaModelOwnershipLock; withOwnershipLock(() => { const peers = deps.listSandboxes?.().sandboxes ?? []; const superseded = supersededOllamaModel(previous, nextModel, peers); if (!superseded) return; + try { + revalidatePolicyRequirements("release the superseded Ollama model"); + } catch (error) { + authorityRefusal = error; + return; + } deps.unloadOllamaModels?.([superseded]); }); } catch { /* Best-effort: a failed unload must not fail an onboarding that already committed its route. */ } + if (authorityRefusal) throw authorityRefusal; } export function createSetupInference( @@ -515,6 +532,7 @@ export function createSetupInference( options: ProviderInferenceSetupOptions = {}, ): Promise { const gatewayName = options.gatewayName ?? deps.getGatewayName(); + const revalidatePolicyRequirements = options.revalidatePolicyRequirements ?? (() => {}); const endpointSource = options.endpointSource === undefined ? "onboard" : options.endpointSource; const routedProvider = deps.isRoutedInferenceProvider?.(provider) === true; @@ -529,6 +547,7 @@ export function createSetupInference( const mutateGatewayRoute = (): Promise => // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: provider onboarding centralizes route and two-phase transaction ordering. withInferenceMutationLocks(async () => { + revalidatePolicyRequirements("change the inference provider route"); if ( options.isRecordedProviderRecoveryAuthorized && !options.isRecordedProviderRecoveryAuthorized() @@ -595,11 +614,16 @@ export function createSetupInference( } endpointPinnedAddresses = preflight.addresses; endpointTrustedPrivateCapability = preflight.trustedPrivateCapability; + revalidatePolicyRequirements("change the inference provider route after DNS validation"); } - const runGatewayOpenshell = createGatewayScopedOpenshellRunner( + const runExactGatewayOpenshell = createGatewayScopedOpenshellRunner( deps.runOpenshell, gatewayName, ); + const runGatewayOpenshell: typeof runExactGatewayOpenshell = (...args) => { + revalidatePolicyRequirements("change the OpenShell inference provider route"); + return runExactGatewayOpenshell(...args); + }; let hostLocalRoute: HostLocalInferenceStartupRoute | null = null; let hostLocalGatewayMutation: HostLocalInferenceGatewayMutation | null = null; let hostLocalRollbackAttempted = false; @@ -615,6 +639,7 @@ export function createSetupInference( let hostLocalInferenceRuntimeProviderId: string | undefined; const reserveRoute = (name: string, selectedProvider: string, selectedModel: string) => { if (routeReserved) return true; + revalidatePolicyRequirements("reserve the sandbox inference route"); const reserved = deps.updateSandbox(name, { provider: selectedProvider, model: selectedModel, @@ -637,10 +662,15 @@ export function createSetupInference( return reserved; }; - const defaultUpsertProvider = bindGatewayUpsertProvider(deps.upsertProvider, gatewayName); + const defaultUpsertProvider = bindGatewayUpsertProvider( + deps.upsertProvider, + gatewayName, + revalidatePolicyRequirements, + ); const commonDeps = { runOpenshell: runGatewayOpenshell, upsertProvider: (...args: Parameters) => { + revalidatePolicyRequirements("register the inference provider"); const exactUpsertProvider = hostLocalGatewayMutation?.upsertProvider; return (exactUpsertProvider ?? defaultUpsertProvider)(...args); }, @@ -678,6 +708,7 @@ export function createSetupInference( if (options.hostLocalInference) { try { + revalidatePolicyRequirements("prepare the host-local inference runtime"); hostLocalRoute = resolveHostLocalInferenceRoute( sandboxName, model, @@ -699,6 +730,7 @@ export function createSetupInference( ); hostLocalInferenceRuntimeProviderId = options.hostLocalInference.runtimeProviderId; } + revalidatePolicyRequirements("prepare the host-local inference provider route"); hostLocalGatewayMutation = await options.hostLocalInference.prepareGatewayMutation({ gatewayName, sandboxName: sandboxName!, @@ -788,7 +820,14 @@ export function createSetupInference( ...commonDeps, REMOTE_PROVIDER_CONFIG: deps.REMOTE_PROVIDER_CONFIG, hydrateCredentialEnv: deps.hydrateCredentialEnv, - promptValidationRecovery: deps.promptValidationRecovery, + promptValidationRecovery: (label, recovery, selectedCredentialEnv, helpUrl) => + deps.promptValidationRecovery( + label, + recovery, + selectedCredentialEnv, + helpUrl, + revalidatePolicyRequirements, + ), classifyApplyFailure: deps.classifyApplyFailure, LOCAL_INFERENCE_TIMEOUT_SECS: deps.localInferenceTimeoutSecs, bedrockRuntimeOnboard: deps.bedrockRuntimeOnboard, @@ -822,6 +861,7 @@ export function createSetupInference( } : deps, runGatewayOpenshell, + revalidatePolicyRequirements, ), run: deps.run, VLLM_LOCAL_CREDENTIAL_ENV: deps.vllmLocalCredentialEnv, @@ -872,6 +912,7 @@ export function createSetupInference( } : deps, runGatewayOpenshell, + revalidatePolicyRequirements, ), getOllamaWarmupCommand: deps.getOllamaWarmupCommand, run: deps.run, @@ -966,6 +1007,7 @@ export function createSetupInference( } }; validatePreparedReceipt(); + revalidatePolicyRequirements("commit the host-local inference provider route"); await hostLocalGatewayMutation.commit(); // The awaited gateway commit is the only async gap between provider // proof and publication. Close it before registry or receipt entry. @@ -982,6 +1024,7 @@ export function createSetupInference( throw new Error("Host-local inference lost sandbox route reservation authority."); } } + revalidatePolicyRequirements("publish the host-local inference provider receipt"); const committed = normalizeHostLocalInferenceReceipt(hostLocalRoute.prepared.commit()); if ( serializeHostLocalInferenceReceipt(committed) !== @@ -992,6 +1035,7 @@ export function createSetupInference( ); } } + revalidatePolicyRequirements("report successful inference provider setup"); deps.log(` ✓ Inference route set: ${provider} / ${model}`); return { ok: true as const }; } catch (error) { @@ -1036,18 +1080,23 @@ export function createSetupInference( // happens before the lock opens, so a serialized re-onboard can neither // replace the row under the read nor select the captured model before // this cleanup runs. - const mutateGatewayRouteAndReleaseSupersededModel = - async (): Promise => { - let previousSandbox: OllamaModelHolder | null = null; - try { - previousSandbox = sandboxName ? (deps.getSandbox?.(sandboxName) ?? null) : null; - } catch { - /* An unreadable registry skips GPU release; it must not fail onboarding. */ - } - const result = await mutateGatewayRoute(); - releaseSupersededOllamaModel(previousSandbox, model, result, deps); - return result; - }; + const mutateGatewayRouteAndReleaseSupersededModel = async (): Promise => { + let previousSandbox: OllamaModelHolder | null = null; + try { + previousSandbox = sandboxName ? (deps.getSandbox?.(sandboxName) ?? null) : null; + } catch { + /* An unreadable registry skips GPU release; it must not fail onboarding. */ + } + const result = await mutateGatewayRoute(); + releaseSupersededOllamaModel( + previousSandbox, + model, + result, + deps, + revalidatePolicyRequirements, + ); + return result; + }; return sandboxName ? deps.withSandboxMutationLock(sandboxName, mutateGatewayRouteAndReleaseSupersededModel) : mutateGatewayRouteAndReleaseSupersededModel(); diff --git a/src/lib/onboard/setup-nim-flow-vllm-resume.test.ts b/src/lib/onboard/setup-nim-flow-vllm-resume.test.ts index b026680a3bf..c63ca5f5eb8 100644 --- a/src/lib/onboard/setup-nim-flow-vllm-resume.test.ts +++ b/src/lib/onboard/setup-nim-flow-vllm-resume.test.ts @@ -61,7 +61,7 @@ describe("createSetupNim vLLM resume", () => { expect(installVllm).toHaveBeenCalledWith( profile, expect.objectContaining({ - checkpointInstallIntent: checkpointVllmInstallModel, + checkpointInstallIntent: expect.any(Function), modelIntent: "nvidia/resumed-model", nonInteractive: true, }), @@ -69,6 +69,70 @@ describe("createSetupNim vLLM resume", () => { expect(prompt).not.toHaveBeenCalled(); }); + it("refuses checkpoint-first vLLM installation when policy authority changes (#9833)", async () => { + const profile = { name: "DGX Spark" } as VllmProfile; + const checkpointVllmInstallModel = vi.fn(); + const installEffect = vi.fn(); + const handleVllmSelection = vi.fn(); + vi.spyOn(onboardSession, "loadSession").mockReturnValue({ + vllmInstallModel: "nvidia/resumed-model", + steps: { provider_selection: { status: "failed" } }, + } as unknown as ReturnType); + const installVllm = vi.fn(async (_profile, options) => { + options.checkpointInstallIntent?.("nvidia/resumed-model"); + installEffect(); + options.beforeInstall?.("nvidia/resumed-model"); + return { ok: true }; + }); + const setupNim = createSetupNim( + makeDeps({ + isNonInteractive: () => true, + getNonInteractiveProvider: () => null, + checkpointVllmInstallModel, + detectInferenceProviderHostState: () => + makeHostState({ + vllmProfile: profile, + hasVllmImage: true, + vllmEntries: [{ key: "install-vllm", label: "Start vLLM (DGX Spark)" }], + }), + installVllm, + handleVllmSelection, + }), + ); + const revalidatePolicyRequirements = vi.fn(() => { + throw new Error("external policy authority must supply local inference"); + }); + + await expect( + setupNim( + null, + null, + null, + true, + null, + null, + undefined, + undefined, + undefined, + revalidatePolicyRequirements, + ), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(revalidatePolicyRequirements).toHaveBeenCalledWith( + expect.objectContaining({ + provider: "vllm-local", + model: "nvidia/resumed-model", + endpointUrl: null, + credentialEnv: null, + preferredInferenceApi: "openai-completions", + }), + "record managed vLLM install intent", + ); + expect(checkpointVllmInstallModel).not.toHaveBeenCalled(); + expect(installEffect).not.toHaveBeenCalled(); + expect(handleVllmSelection).not.toHaveBeenCalled(); + }); + it("uses the session fallback to checkpoint and retry a dedicated local profile (#9582)", async () => { vi.stubEnv(LOCAL_MODEL_PROFILE_ENABLED_ENV, "1"); vi.stubEnv(LOCAL_MODEL_PROFILE_RUNTIME_ENV, "vllm"); diff --git a/src/lib/onboard/setup-nim-flow.test.ts b/src/lib/onboard/setup-nim-flow.test.ts index ca9ac9f7a8e..c3f78bc64db 100644 --- a/src/lib/onboard/setup-nim-flow.test.ts +++ b/src/lib/onboard/setup-nim-flow.test.ts @@ -1266,6 +1266,7 @@ describe("createSetupNim", () => { expect(installManagedLlamaCpp).toHaveBeenCalledWith(selection, { sandboxName: "spark-agent", gatewayPort: 8091, + revalidatePolicyRequirements: expect.any(Function), runtimeProvider, }); expect(getRuntimeProvider).toHaveBeenCalledOnce(); diff --git a/src/lib/onboard/setup-nim-flow.ts b/src/lib/onboard/setup-nim-flow.ts index de9bf548096..9e9351f5b53 100644 --- a/src/lib/onboard/setup-nim-flow.ts +++ b/src/lib/onboard/setup-nim-flow.ts @@ -56,8 +56,9 @@ import { reportProviderSelectionFailure } from "./provider-selection-failure"; import { promptForInferenceProviderSelection } from "./provider-selection-prompt"; import type { RebuildRouteHandoff, RegistryInferenceRoute } from "./rebuild-route-handoff"; import type { RuntimeProviderBundle } from "./runtime-provider/contract"; +import { resolveCurrentRuntimeProviderBundle } from "./runtime-provider/current"; -export { resolveCurrentRuntimeProviderBundle } from "./runtime-provider/current"; +export { resolveCurrentRuntimeProviderBundle }; export { createHermesPortableOllamaInferenceResolver } from "./experimental/hermes-portable-ollama-inference"; import { prepareProviderDiscovery } from "./setup-nim-provider-discovery"; @@ -68,6 +69,16 @@ export { createLlamaCppSelectionHandler } from "./llama-cpp-selection"; export { createLocalModelProfileIntegration } from "./local-model-profile/integration"; export { resumeManagedLlamaCppRuntime }; +/** Bind managed llama.cpp resume to the selected runtime provider. */ +export function bindManagedLlamaCppResume(gatewayPort: number) { + return (sandboxName: string, revalidatePolicyRequirements?: (operation: string) => void) => + resumeManagedLlamaCppRuntime(sandboxName, { + gatewayPort, + runtimeProvider: resolveCurrentRuntimeProviderBundle(), + revalidatePolicyRequirements, + }); +} + export type SetupNimGpu = ReturnType; export type SetupNimSelectionState = BaseSetupNimSelectionState; export type SetupNimSelectionResult = "selected" | "retry-selection"; @@ -100,6 +111,7 @@ export type SetupNim = ( assertRouteCompatible?: (route: ProviderInferenceProbeRoute) => GatewayRouteDiscoveryConstraints, canProbeRoute?: (provider: string) => boolean, recoverySessionId?: string | null, + revalidatePolicyRequirements?: (route: ProviderInferenceProbeRoute, operation: string) => void, ) => Promise; export interface SetupNimFlowDeps { @@ -364,6 +376,23 @@ function isEndpointProviderSelection(deps: SetupNimFlowDeps, providerKey: string return providerKey === "llama-cpp" || Boolean(deps.remoteProviderConfig[providerKey]); } +function prepareEndpointProviderPolicyRoute( + deps: SetupNimFlowDeps, + selected: ProviderMenuChoice, + state: SetupNimSelectionState, +): void { + if (selected.key === "llama-cpp") { + state.provider = LLAMA_CPP_PROVIDER_NAME; + state.endpointUrl = LLAMA_CPP_HOST_OPENAI_BASE_URL; + state.credentialEnv = LLAMA_CPP_CREDENTIAL_ENV; + return; + } + const tentative = deps.remoteProviderConfig[selected.key]; + state.provider = tentative.providerName; + state.endpointUrl = tentative.endpointUrl; + state.credentialEnv = tentative.credentialEnv; +} + function resolveManagedLlamaCppSafely( deps: SetupNimFlowDeps, env?: NodeJS.ProcessEnv, @@ -672,6 +701,23 @@ async function resolveFreshHermesPortableOllamaSelection(input: { }; } +function policyCheckedVllmInstallRecovery( + recovery: ReturnType, + state: SetupNimSelectionState, + seedVllmInstallRoute: (modelId: string) => void, +): ReturnType { + const checkpointInstallIntent = recovery.checkpointInstallIntent; + if (!checkpointInstallIntent) return recovery; + return { + ...recovery, + checkpointInstallIntent: (modelId: string) => { + seedVllmInstallRoute(modelId); + state.revalidatePolicyRequirements?.("record managed vLLM install intent"); + checkpointInstallIntent(modelId); + }, + }; +} + /** Create the provider-selection flow and seed agent-specific Ollama defaults. */ export function createSetupNim( defaults: SetupNimFlowDeps, @@ -696,6 +742,7 @@ export function createSetupNim( ) => GatewayRouteDiscoveryConstraints, canProbeRoute?: (provider: string) => boolean, recoverySessionId?: string | null, + revalidatePolicyRequirements?: (route: ProviderInferenceProbeRoute, operation: string) => void, ): Promise { deps.step(3, 8, "Configuring inference provider"); @@ -740,20 +787,20 @@ export function createSetupNim( nvidiaFeaturedModels, openRouterFeaturedModels, }; + const effectiveInferenceApi = () => + deps.resolveAgentInferenceApi( + agent?.name ?? null, + state.provider, + deps.coerceAgentInferenceApi(agent, state.preferredInferenceApi), + ); + const route = (): ProviderInferenceProbeRoute => ({ + provider: state.provider, + model: typeof state.model === "string" && state.model.trim() ? state.model.trim() : null, + endpointUrl: state.endpointUrl, + preferredInferenceApi: effectiveInferenceApi(), + credentialEnv: state.credentialEnv, + }); state.assertRouteCompatible = () => { - const effectiveInferenceApi = () => - deps.resolveAgentInferenceApi( - agent?.name ?? null, - state.provider, - deps.coerceAgentInferenceApi(agent, state.preferredInferenceApi), - ); - const route = (): ProviderInferenceProbeRoute => ({ - provider: state.provider, - model: typeof state.model === "string" && state.model.trim() ? state.model.trim() : null, - endpointUrl: state.endpointUrl, - preferredInferenceApi: effectiveInferenceApi(), - credentialEnv: state.credentialEnv, - }); const constraints = assertRouteCompatible?.(route()) ?? { requiredModel: null, requiredEndpointUrl: null, @@ -763,6 +810,8 @@ export function createSetupNim( assertRouteCompatible?.(route()); return constraints; }; + state.revalidatePolicyRequirements = (operation) => + revalidatePolicyRequirements?.(route(), operation); return state; }; @@ -953,6 +1002,10 @@ export function createSetupNim( if (isEndpointProviderSelection(deps, selected.key)) { const state = createSelectionState(); + prepareEndpointProviderPolicyRoute(deps, selected, state); + state.revalidatePolicyRequirements?.( + `configure inference provider ${JSON.stringify(state.provider)}`, + ); const result = await handleEndpointProviderSelection({ deps, selected, @@ -1012,12 +1065,14 @@ export function createSetupNim( state.credentialEnv = LLAMA_CPP_CREDENTIAL_ENV; state.preferredInferenceApi = "openai-completions"; state.assertRouteCompatible?.(); + state.revalidatePolicyRequirements?.("install managed llama.cpp runtime"); const installed = await (deps.installManagedLlamaCpp ?? installManagedLlamaCpp)( resolved.selection, { sandboxName, gatewayPort: deps.getGatewayPort(), runtimeProvider: deps.getRuntimeProvider(), + revalidatePolicyRequirements: state.revalidatePolicyRequirements, }, ); if (!installed.ok) { @@ -1139,18 +1194,27 @@ export function createSetupNim( } const vllmState = createSelectionState(); preparedVllmState = vllmState; + const seedVllmInstallRoute = (modelId: string): void => { + vllmState.provider = "vllm-local"; + vllmState.model = modelId; + vllmState.endpointUrl = null; + vllmState.credentialEnv = null; + vllmState.preferredInferenceApi = "openai-completions"; + vllmState.assertRouteCompatible?.(); + }; + const vllmRecovery = policyCheckedVllmInstallRecovery( + vllmInstallRecoveryOptions(deps), + vllmState, + seedVllmInstallRoute, + ); const result = await deps.installVllm(vllmProfile, { hasImage: hasVllmImage, nonInteractive: deps.isNonInteractive(), promptFn: deps.prompt, - ...vllmInstallRecoveryOptions(deps), + ...vllmRecovery, beforeInstall: (modelId) => { - vllmState.provider = "vllm-local"; - vllmState.model = modelId; - vllmState.endpointUrl = null; - vllmState.credentialEnv = null; - vllmState.preferredInferenceApi = "openai-completions"; - vllmState.assertRouteCompatible?.(); + seedVllmInstallRoute(modelId); + vllmState.revalidatePolicyRequirements?.("install managed vLLM runtime"); }, }); if (!result.ok) { diff --git a/src/lib/onboard/setup-nim-ollama.test.ts b/src/lib/onboard/setup-nim-ollama.test.ts index df416f93eb2..f8355c2a91f 100644 --- a/src/lib/onboard/setup-nim-ollama.test.ts +++ b/src/lib/onboard/setup-nim-ollama.test.ts @@ -213,6 +213,32 @@ describe("createSetupNimOllamaHandlers", () => { expect(install).not.toHaveBeenCalled(); }); + it("stops before local Ollama install effects when policy authority changes (#9833)", async () => { + const selection = makeState(); + selection.revalidatePolicyRequirements = () => { + throw new Error("external policy authority must supply local inference"); + }; + const install = vi.fn(() => ({ ok: true })); + const start = vi.fn(() => ({ kind: "ready" as const })); + const { handleInstallOllamaSelection } = createSetupNimOllamaHandlers( + makeDeps({ + process: { ...process, platform: "linux" } as NodeJS.Process, + installOllamaOnLinux: install, + runOllamaStartupOrGate: start, + }), + ); + + await expect( + handleInstallOllamaSelection(null, "qwen3:8b", null, selection, { + hasUpgradableOllama: false, + binaryNeedsUpgrade: false, + }), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(install).not.toHaveBeenCalled(); + expect(start).not.toHaveBeenCalled(); + }); + it("installs a missing binary while recovering a stale daemon", async () => { const install = vi.fn(() => ({ ok: true })); const { handleInstallOllamaSelection } = createSetupNimOllamaHandlers( @@ -264,6 +290,36 @@ describe("createSetupNimOllamaHandlers", () => { expect(restart).not.toHaveBeenCalled(); }); + it("stops before Windows Ollama install effects when policy authority changes (#9833)", async () => { + const selection = makeState(); + selection.revalidatePolicyRequirements = () => { + throw new Error("external policy authority must supply local inference"); + }; + const install = vi.fn(async () => ({ ok: true, path: "C:/Ollama/ollama.exe" })); + const start = vi.fn(() => true); + const { handleWindowsHostOllamaSelection } = createSetupNimOllamaHandlers( + makeDeps({ + installOllamaOnWindowsHost: install, + setupWindowsOllamaWith0000Binding: start, + }), + ); + + await expect( + handleWindowsHostOllamaSelection( + null, + "install-windows-ollama", + "qwen3:8b", + false, + false, + null, + selection, + ), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(install).not.toHaveBeenCalled(); + expect(start).not.toHaveBeenCalled(); + }); + it("preserves accepted tools-incompatible state for running Ollama", async () => { const state = makeState(); const { handleRunningOllamaSelection } = createSetupNimOllamaHandlers(makeDeps()); diff --git a/src/lib/onboard/setup-nim-ollama.ts b/src/lib/onboard/setup-nim-ollama.ts index 8c058280afb..faaf1ac44d6 100644 --- a/src/lib/onboard/setup-nim-ollama.ts +++ b/src/lib/onboard/setup-nim-ollama.ts @@ -217,8 +217,10 @@ export function createSetupNimOllamaHandlers(deps: SetupNimOllamaDeps): { if (!proceed) return "retry-selection"; if (isSwitch) { + state.revalidatePolicyRequirements?.("switch to the Windows Ollama runtime"); deps.switchToWindowsOllamaHost(); } else if (isInstall) { + state.revalidatePolicyRequirements?.("install the Windows Ollama runtime"); const installResult = await deps.installOllamaOnWindowsHost(); if (!installResult.ok) { console.error( @@ -229,6 +231,7 @@ export function createSetupNimOllamaHandlers(deps: SetupNimOllamaDeps): { } if (!deps.awaitWindowsOllamaReady()) { console.log(" Installer did not leave a reachable Ollama daemon; restarting it..."); + state.revalidatePolicyRequirements?.("start the Windows Ollama runtime"); if (!deps.setupWindowsOllamaWith0000Binding({ installedPath: installResult.path })) { deps.printWindowsOllamaTimeoutDiagnostics(); if (deps.isNonInteractive()) deps.process.exit(1); @@ -237,6 +240,7 @@ export function createSetupNimOllamaHandlers(deps: SetupNimOllamaDeps): { } console.log(` ✓ Using Ollama on host.docker.internal:${deps.OLLAMA_PORT}`); } else { + state.revalidatePolicyRequirements?.("start the Windows Ollama runtime"); if ( !deps.setupWindowsOllamaWith0000Binding({ announceStop: isRestart, @@ -272,6 +276,7 @@ export function createSetupNimOllamaHandlers(deps: SetupNimOllamaDeps): { // Linux systemd service. Applying the loopback override targets an // unrelated local ollama.service and exits 1 (#8596, regression of #4208). if (!isWindowsHostOllama) { + state.revalidatePolicyRequirements?.("configure the local Ollama runtime"); const overrideState = deps.ensureOllamaLoopbackSystemdOverride({ isNonInteractive: deps.isNonInteractive, contextWindowFloor: state.ollamaContextWindowFloor, @@ -285,6 +290,7 @@ export function createSetupNimOllamaHandlers(deps: SetupNimOllamaDeps): { deps.process.exit(1); } } + state.revalidatePolicyRequirements?.("start the local Ollama runtime"); const startup = deps.runOllamaStartupOrGate({ ollamaReady, ollamaPort: deps.OLLAMA_PORT, @@ -328,6 +334,7 @@ export function createSetupNimOllamaHandlers(deps: SetupNimOllamaDeps): { } const lockedModel = preflightOllamaRoute(state, requestedModel, recoveredModel); const isUpgrade = ollamaInstallMenu.hasUpgradableOllama; + state.revalidatePolicyRequirements?.("install the local Ollama runtime"); const installResult = deps.process.platform === "darwin" ? deps.installOllamaOnMacOS({ diff --git a/src/lib/onboard/setup-nim-selection.ts b/src/lib/onboard/setup-nim-selection.ts index a846663e726..2ef65da29ec 100644 --- a/src/lib/onboard/setup-nim-selection.ts +++ b/src/lib/onboard/setup-nim-selection.ts @@ -61,8 +61,33 @@ export type SetupNimSelectionState = { openRouterFeaturedModels?: NvidiaFeaturedModelSession; /** Attempt-wide shared-gateway guard, invoked after identity selection and before probes. */ assertRouteCompatible?: () => GatewayRouteDiscoveryConstraints; + /** Receipt-bound policy check invoked immediately before provider or runtime mutations. */ + revalidatePolicyRequirements?: (operation: string) => void; }; +/** Revalidate the current provider selection before a policy-dependent mutation. */ +export function assertSelectionMutationAuthority( + state: SetupNimSelectionState, + operation: string, +): void { + state.revalidatePolicyRequirements?.(operation); +} + +/** Carry the attempt's exact mutation guard through a blocking credential prompt. */ +export function credentialMutationGuardFor( + state: SetupNimSelectionState, +): ((operation: string) => void) | undefined { + return state.revalidatePolicyRequirements; +} + +export function withCredentialMutationGuard( + state: SetupNimSelectionState, + options: T, +): T & { revalidatePolicyRequirements?: (operation: string) => void } { + const guard = credentialMutationGuardFor(state); + return guard ? { ...options, revalidatePolicyRequirements: guard } : options; +} + export type CloudFallbackConfig = { providerName: string; endpointUrl: string | null; @@ -216,6 +241,7 @@ type ProbeOptions = { extraHeaders?: readonly string[]; capabilityCache?: OnboardInferenceCapabilityCache; provider?: string; + revalidatePolicyRequirements?: (operation: string) => void; }; type ValidationResult = @@ -242,6 +268,7 @@ type RemoteModelValidatorDeps = { credentialEnv: string, helpUrl: string | null, capabilityCache?: OnboardInferenceCapabilityCache, + revalidatePolicyRequirements?: (operation: string) => void, ) => Promise; validateCustomAnthropicSelection: ( label: string, @@ -251,6 +278,7 @@ type RemoteModelValidatorDeps = { helpUrl: string | null, options?: { intendedApi?: "anthropic-messages" | "openai-completions"; + revalidatePolicyRequirements?: (operation: string) => void; }, ) => Promise; validateAnthropicSelectionWithRetryMessage: ( @@ -260,6 +288,7 @@ type RemoteModelValidatorDeps = { credentialEnv: string, retryMessage: string, helpUrl: string | null, + revalidatePolicyRequirements?: (operation: string) => void, ) => Promise; validateOpenAiLikeSelection: ( label: string, @@ -335,14 +364,18 @@ export function createRemoteModelValidator(deps: RemoteModelValidatorDeps): { " ⚠ Reasoning mode validates Chat Completions only; tools and streaming are unverified.", ); } - const validation = await deps.validateCustomOpenAiLikeSelection( + const validationArgs = [ remoteConfig.label, state.endpointUrl || deps.OPENAI_ENDPOINT_URL, selectedModel, selectedCredentialEnv, remoteConfig.helpUrl, state.inferenceCapabilityCache, - ); + ] as const; + const guard = credentialMutationGuardFor(state); + const validation = await (guard + ? deps.validateCustomOpenAiLikeSelection(...validationArgs, guard) + : deps.validateCustomOpenAiLikeSelection(...validationArgs)); if (validation.ok) { if (validation.pinnedAddresses) state.endpointPinnedAddresses = validation.pinnedAddresses; @@ -389,7 +422,7 @@ export function createRemoteModelValidator(deps: RemoteModelValidatorDeps): { selectedModel, selectedCredentialEnv, remoteConfig.helpUrl, - { intendedApi }, + withCredentialMutationGuard(state, { intendedApi }), ); if (validation.ok) { if (validation.pinnedAddresses) @@ -409,14 +442,18 @@ export function createRemoteModelValidator(deps: RemoteModelValidatorDeps): { const retryMessage = "Please choose a provider/model again."; if (selected.key === "anthropic") { - const validation = await deps.validateAnthropicSelectionWithRetryMessage( + const validationArgs = [ remoteConfig.label, state.endpointUrl || deps.ANTHROPIC_ENDPOINT_URL, selectedModel, selectedCredentialEnv, retryMessage, remoteConfig.helpUrl, - ); + ] as const; + const guard = credentialMutationGuardFor(state); + const validation = await (guard + ? deps.validateAnthropicSelectionWithRetryMessage(...validationArgs, guard) + : deps.validateAnthropicSelectionWithRetryMessage(...validationArgs)); if (validation.ok) { state.preferredInferenceApi = validation.api; return "selected"; @@ -434,7 +471,7 @@ export function createRemoteModelValidator(deps: RemoteModelValidatorDeps): { selectedCredentialEnv, retryMessage, remoteConfig.helpUrl, - { + withCredentialMutationGuard(state, { provider: state.provider, requireResponsesToolCalling: deps.shouldRequireResponsesToolCalling(state.provider), skipResponsesProbe: deps.shouldSkipResponsesProbe(state.provider), @@ -442,7 +479,7 @@ export function createRemoteModelValidator(deps: RemoteModelValidatorDeps): { extraHeaders: deps.getProbeExtraHeaders?.(state.provider) ?? getProbeExtraHeaders(state.provider), capabilityCache: state.inferenceCapabilityCache, - }, + }), ); if (validation.ok) { state.preferredInferenceApi = validation.api; diff --git a/src/lib/onboard/validation-recovery-prompt.test.ts b/src/lib/onboard/validation-recovery-prompt.test.ts index b7eb5383fe3..4970b6dce2e 100644 --- a/src/lib/onboard/validation-recovery-prompt.test.ts +++ b/src/lib/onboard/validation-recovery-prompt.test.ts @@ -147,4 +147,25 @@ describe("validation recovery credential prompt", () => { ); expectHelpBeforeSelectionReturn(log); }); + + it("rechecks policy authority after recovery input before credential persistence (#9833)", async () => { + vi.stubEnv("OPENAI_API_KEY", "sk-existing"); + vi.spyOn(console, "log").mockImplementation(() => undefined); + const { helpers, prompt } = createRecoveryPrompt(["retry", "sk-replacement"]); + + await expect( + helpers.promptValidationRecovery( + "OpenAI", + CREDENTIAL_RECOVERY, + "OPENAI_API_KEY", + null, + () => { + throw new Error("external policy authority must supply the selected route"); + }, + ), + ).rejects.toThrow(/external policy authority must supply/u); + + expect(prompt).toHaveBeenCalledTimes(2); + expect(process.env.OPENAI_API_KEY).toBe("sk-existing"); + }); }); diff --git a/src/lib/onboard/validation-recovery-prompt.ts b/src/lib/onboard/validation-recovery-prompt.ts index 5929e2f2c76..538d61137a6 100644 --- a/src/lib/onboard/validation-recovery-prompt.ts +++ b/src/lib/onboard/validation-recovery-prompt.ts @@ -22,12 +22,14 @@ export interface ValidationRecoveryPromptHelpers { label: string, helpUrl?: string | null, validator?: ((value: string) => string | null) | null, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise; promptValidationRecovery( label: string, recovery: ProbeRecovery, credentialEnv?: string | null, helpUrl?: string | null, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise<"credential" | "selection" | "retry" | "model">; } @@ -39,6 +41,7 @@ export function createValidationRecoveryPromptHelpers( label: string, helpUrl: string | null = null, validator: ((value: string) => string | null) | null = null, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise { if (helpUrl) { console.log(""); @@ -64,6 +67,7 @@ export function createValidationRecoveryPromptHelpers( console.error(validationError); continue; } + revalidatePolicyRequirements?.(`save ${label}`); saveCredential(envName, key); process.env[envName] = key; console.log(""); @@ -78,6 +82,7 @@ export function createValidationRecoveryPromptHelpers( recovery: ProbeRecovery, credentialEnv: string | null = null, helpUrl: string | null = null, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise<"credential" | "selection" | "retry" | "model"> { if (deps.isNonInteractive()) { process.exit(1); @@ -119,6 +124,7 @@ export function createValidationRecoveryPromptHelpers( `${label} API key`, helpUrl, validator, + revalidatePolicyRequirements, ); if (result.kind === "selection") { console.log(" Returning to provider selection."); @@ -141,6 +147,7 @@ export function createValidationRecoveryPromptHelpers( `${label} API key`, helpUrl, validator, + revalidatePolicyRequirements, ); if (result.kind === "selection") { console.log(" Returning to provider selection."); diff --git a/src/lib/onboard/vm-dns-monkeypatch.test.ts b/src/lib/onboard/vm-dns-monkeypatch.test.ts index b68cd5f3e92..0179dd7cf81 100644 --- a/src/lib/onboard/vm-dns-monkeypatch.test.ts +++ b/src/lib/onboard/vm-dns-monkeypatch.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { applyOpenShellVmDnsMonkeypatch } from "../actions/sandbox/vm-dns-monkeypatch"; import { applyOnboardVmDnsMonkeypatch } from "./vm-dns-monkeypatch"; @@ -45,6 +45,30 @@ describe("applyOnboardVmDnsMonkeypatch", () => { expect(unchangedLogs.join("\n")).not.toContain("Applied"); }); + it("withholds VM DNS success when authority changes after the helper returns (#9833)", () => { + const log = vi.fn(); + const apply = vi.fn(() => ({ + attempted: true, + changed: true, + ok: true, + status: "applied" as const, + })); + const revalidatePolicyAuthority = vi.fn(() => { + throw new Error("policy authority changed"); + }); + + expect(() => + applyOnboardVmDnsMonkeypatch( + "demo", + { openshellDriver: "vm" }, + { apply, log, revalidatePolicyAuthority }, + ), + ).toThrow("policy authority changed"); + + expect(apply).toHaveBeenCalledOnce(); + expect(log).not.toHaveBeenCalled(); + }); + it("logs skipped VM DNS monkeypatch state for VM sandboxes", () => { const logs: string[] = []; diff --git a/src/lib/onboard/vm-dns-monkeypatch.ts b/src/lib/onboard/vm-dns-monkeypatch.ts index 6ed57f7c0ab..7a7a48e2ed8 100644 --- a/src/lib/onboard/vm-dns-monkeypatch.ts +++ b/src/lib/onboard/vm-dns-monkeypatch.ts @@ -9,6 +9,7 @@ import { type OnboardVmDnsMonkeypatchDeps = { apply?: typeof applyOpenShellVmDnsMonkeypatch; log?: (message: string) => void; + revalidatePolicyAuthority?: (operation: string) => void; warn?: (message: string) => void; }; @@ -20,9 +21,20 @@ export function applyOnboardVmDnsMonkeypatch( const apply = deps.apply ?? applyOpenShellVmDnsMonkeypatch; const log = deps.log ?? console.log; const warn = deps.warn ?? console.error; - const vmDnsPatch: VmDnsMonkeypatchResult = apply(sandboxName, { - openshellDriver: runtime.openshellDriver, - }); + const vmDnsPatch: VmDnsMonkeypatchResult = apply( + sandboxName, + { + openshellDriver: runtime.openshellDriver, + }, + { + revalidatePolicyAuthority: deps.revalidatePolicyAuthority, + }, + ); + if (vmDnsPatch.ok) { + deps.revalidatePolicyAuthority?.( + `report VM DNS monkeypatch result for sandbox '${sandboxName}'`, + ); + } if (vmDnsPatch.ok && vmDnsPatch.changed) { log(" ✓ Applied OpenShell VM DNS monkeypatch"); } else if (vmDnsPatch.ok && vmDnsPatch.attempted) { diff --git a/src/lib/policy/commands.ts b/src/lib/policy/commands.ts index a042bbecb24..f3c182e9d7a 100644 --- a/src/lib/policy/commands.ts +++ b/src/lib/policy/commands.ts @@ -57,3 +57,28 @@ export function buildPolicyGetFullJsonCommand(sandboxName: string, gatewayName?: sandboxName, ]); } + +/** Read the global policy and its authority metadata as JSON. */ +export function buildGlobalPolicyGetFullJsonCommand(gatewayName?: string): string[] { + return buildOpenshellCommand([ + "policy", + "get", + ...policyGatewayArgs(gatewayName), + "--global", + "--full", + "--output", + "json", + ]); +} + +/** Check whether the global policy has revision history. */ +export function buildGlobalPolicyListCommand(gatewayName?: string): string[] { + return buildOpenshellCommand([ + "policy", + "list", + ...policyGatewayArgs(gatewayName), + "--global", + "--limit", + "1", + ]); +} diff --git a/src/lib/policy/merge.ts b/src/lib/policy/merge.ts index 9ad0d375f54..415eeeaf0c2 100644 --- a/src/lib/policy/merge.ts +++ b/src/lib/policy/merge.ts @@ -4,6 +4,7 @@ import { assertExternalPolicyRequirementContainment as assertCanonicalExternalPolicyRequirementContainment, assertMatchingPolicyAuthority as assertCanonicalMatchingPolicyAuthority, + parseGlobalPolicyAuthorityMetadata as parseCanonicalGlobalPolicyAuthorityMetadata, parseOpenShellPolicy as parseCanonicalOpenShellPolicy, parseSandboxPolicyAuthorityMetadata as parseCanonicalSandboxPolicyAuthorityMetadata, stripProviderComposedPolicies as stripCanonicalProviderComposedPolicies, @@ -19,6 +20,8 @@ import type { JsonObject } from "../core/json-types"; // CommonJS wrapper is compiled. Keep this file implementation-free. export const parseOpenShellPolicy = parseCanonicalOpenShellPolicy; export const stripProviderComposedPolicies = stripCanonicalProviderComposedPolicies; +export const parseGlobalPolicyAuthorityMetadata = + parseCanonicalGlobalPolicyAuthorityMetadata; export const parseSandboxPolicyAuthorityMetadata = parseCanonicalSandboxPolicyAuthorityMetadata; export const assertMatchingPolicyAuthority = assertCanonicalMatchingPolicyAuthority; diff --git a/src/lib/state/onboard-session-normalization.test.ts b/src/lib/state/onboard-session-normalization.test.ts index 6ac4afbfa59..6bc89368172 100644 --- a/src/lib/state/onboard-session-normalization.test.ts +++ b/src/lib/state/onboard-session-normalization.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; -import { createSession, normalizeSession } from "./onboard-session"; +import { createSession, filterSafeUpdates, normalizeSession } from "./onboard-session"; type LegacySession = Omit, "machine"> & { machine?: unknown; @@ -16,6 +16,43 @@ function requireNormalizedSession(legacy: LegacySession) { } describe("onboard session normalization", () => { + it("keeps recognized, absent, and legacy null policy authority values (#9833)", () => { + const external = createSession({ policyAuthority: "externally-managed" }); + expect(normalizeSession(external)?.policyAuthority).toBe("externally-managed"); + + const absent = { ...external } as Partial; + delete absent.policyAuthority; + expect( + normalizeSession(absent as Parameters[0])?.policyAuthority, + ).toBeNull(); + expect(normalizeSession({ ...external, policyAuthority: null })?.policyAuthority).toBeNull(); + }); + + it("refuses an invalid saved policy authority (#9833)", () => { + const external = createSession({ policyAuthority: "externally-managed" }); + const malformed = { ...external, policyAuthority: "unspecified" }; + expect(() => normalizeSession(malformed as Parameters[0])).toThrow( + /saved policy authority is invalid/u, + ); + }); + + it("clears NemoClaw preset attribution for external policy authority (#9833)", () => { + const external = createSession({ + policyAuthority: "externally-managed", + policyPresets: ["npm"], + }); + expect(external.policyPresets).toBeNull(); + + const legacy = { + ...createSession({ policyAuthority: "nemoclaw-managed", policyPresets: ["npm"] }), + policyAuthority: "externally-managed" as const, + }; + expect(normalizeSession(legacy)?.policyPresets).toBeNull(); + expect( + filterSafeUpdates({ policyAuthority: "externally-managed", policyPresets: ["npm"] }), + ).toMatchObject({ policyAuthority: "externally-managed", policyPresets: null }); + }); + it("normalizes old sessions without machine snapshots", () => { const legacy = createSession({ sessionId: "legacy-session", diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index de5894ba823..8a92750a619 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -11,6 +11,7 @@ import { createHash, randomUUID } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; +import type { SandboxPolicyAuthority } from "../adapters/openshell/policy-authority"; import { isErrnoException } from "../core/errno"; import { isObjectRecord, type JsonObject, type JsonValue } from "../core/json-types"; import { GATEWAY_PORT } from "../core/ports"; @@ -70,6 +71,8 @@ export const SESSION_FILE = path.join(SESSION_DIR, "onboard-session.json"); export const LOCK_FILE = path.join(SESSION_DIR, "onboard.lock"); const SAFE_VLLM_INSTALL_MODEL = /^[A-Za-z0-9._:/-]+$/; +export class InvalidPersistedPolicyAuthorityError extends Error {} + // Session-specific aliases for the shared JSON types. type SessionJsonValue = JsonValue; type UnknownRecord = JsonObject; @@ -237,6 +240,8 @@ export interface Session { observabilityRequestedExplicitly: boolean; hermesToolGateways: string[] | null; policyPresets: string[] | null; + /** Policy authority selected from OpenShell metadata before policy-dependent effects. */ + policyAuthority: SandboxPolicyAuthority | null; messagingPlan: SandboxMessagingPlan | null; /** Non-secret names of credential providers registered before sandbox setup completed. */ stagedCredentialProviders: string[]; @@ -314,6 +319,7 @@ export interface SessionUpdates { observabilityEnabled?: boolean; hermesToolGateways?: string[] | null; policyPresets?: string[] | null; + policyAuthority?: SandboxPolicyAuthority | null; messagingPlan?: SandboxMessagingPlan | null; migratedLegacyValueHashes?: Record; gpuPassthrough?: boolean; @@ -350,6 +356,7 @@ export interface DebugSessionSummary { observabilityRequestedExplicitly: boolean; hermesToolGateways: string[] | null; policyPresets: string[] | null; + policyAuthority: SandboxPolicyAuthority | null; gpuPassthrough: boolean; lastStepStarted: string | null; lastCompletedStep: string | null; @@ -414,6 +421,10 @@ function readHermesAuthMethod(value: SessionJsonValue | undefined): HermesAuthMe return value === "oauth" || value === "api_key" ? value : null; } +function readPolicyAuthority(value: unknown): SandboxPolicyAuthority | null { + return value === "nemoclaw-managed" || value === "externally-managed" ? value : null; +} + function readPositiveInteger(value: SessionJsonValue | undefined): number | null { return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null; } @@ -748,6 +759,7 @@ export function createSession(overrides: Partial = {}): Session { ...defaultSteps(), ...(overrides.steps ?? {}), }; + const policyAuthority = readPolicyAuthority(overrides.policyAuthority); const session: Session = { version: SESSION_VERSION, sessionId, @@ -793,7 +805,9 @@ export function createSession(overrides: Partial = {}): Session { observabilityEnabled: overrides.observabilityEnabled === true, observabilityRequestedExplicitly: overrides.observabilityRequestedExplicitly === true, hermesToolGateways: readStringArray(overrides.hermesToolGateways), - policyPresets: readStringArray(overrides.policyPresets), + policyPresets: + policyAuthority === "externally-managed" ? null : readStringArray(overrides.policyPresets), + policyAuthority, messagingPlan: parseSandboxMessagingPlan(overrides.messagingPlan), stagedCredentialProviders: readStringArray(overrides.stagedCredentialProviders) ?? [], migratedLegacyValueHashes: overrides.migratedLegacyValueHashes @@ -822,6 +836,12 @@ export function createSession(overrides: Partial = {}): Session { export function normalizeSession(data: Session | SessionJsonValue | undefined): Session | null { if (!isObject(data) || data.version !== SESSION_VERSION) return null; + const policyAuthority = readPolicyAuthority(data.policyAuthority); + if (hasOwn(data, "policyAuthority") && data.policyAuthority !== null && !policyAuthority) { + throw new InvalidPersistedPolicyAuthorityError( + "Refusing to load the onboarding session: the saved policy authority is invalid.", + ); + } const servingProfileProvenance = parseServingProfileProvenance(data.servingProfileProvenance); if ( hasOwn(data, "servingProfileProvenance") && @@ -899,6 +919,7 @@ export function normalizeSession(data: Session | SessionJsonValue | undefined): observabilityRequestedExplicitly: data.observabilityRequestedExplicitly === true, hermesToolGateways: readStringArray(data.hermesToolGateways), policyPresets: readStringArray(data.policyPresets), + policyAuthority, messagingPlan: parseSandboxMessagingPlan(data.messagingPlan), stagedCredentialProviders: readStringArray(data.stagedCredentialProviders) ?? [], migratedLegacyValueHashes: readStringRecord(data.migratedLegacyValueHashes), @@ -985,7 +1006,8 @@ export function loadSession(): Session | null { } const parsed = JSON.parse(fs.readFileSync(SESSION_FILE, "utf-8")); return normalizeSession(parsed); - } catch { + } catch (error) { + if (error instanceof InvalidPersistedPolicyAuthorityError) throw error; return null; } } @@ -1479,6 +1501,15 @@ export function filterSafeUpdates(updates: SessionUpdates): Partial { } else if (Array.isArray(updates.policyPresets)) { safe.policyPresets = updates.policyPresets.filter((value) => typeof value === "string"); } + if (updates.policyAuthority === null) { + safe.policyAuthority = null; + } else { + const policyAuthority = readPolicyAuthority(updates.policyAuthority); + if (policyAuthority) { + safe.policyAuthority = policyAuthority; + if (policyAuthority === "externally-managed") safe.policyPresets = null; + } + } if (updates.messagingPlan === null) { safe.messagingPlan = null; } else { @@ -1678,7 +1709,9 @@ export function checkpointVllmInstallModel(modelId: string): Session { return updateSession((session) => { const providerStep = session.steps.provider_selection; if (providerStep?.status !== "in_progress") { - throw new Error("Managed vLLM install intent can only be checkpointed during provider selection."); + throw new Error( + "Managed vLLM install intent can only be checkpointed during provider selection.", + ); } session.vllmInstallModel = model; }); @@ -1882,6 +1915,7 @@ export function summarizeForDebug( observabilityRequestedExplicitly: session.observabilityRequestedExplicitly, hermesToolGateways: session.hermesToolGateways, policyPresets: session.policyPresets, + policyAuthority: session.policyAuthority, gpuPassthrough: session.gpuPassthrough, lastStepStarted: session.lastStepStarted, lastCompletedStep: session.lastCompletedStep, diff --git a/test/install-hermes-portable-active.test.ts b/test/install-hermes-portable-active.test.ts index 6559bd6f677..c299eef36b1 100644 --- a/test/install-hermes-portable-active.test.ts +++ b/test/install-hermes-portable-active.test.ts @@ -237,6 +237,7 @@ describe("Hermes portable installer admission", testTimeoutOptions(60_000), () = const createPlan = materializeHermesPortableCreatePlan({ intent, fromRef: activeBuildContext.sourceDockerfilePath, + policyAuthority: "nemoclaw-managed", }); const startupArgv = [ "env", diff --git a/test/package-contract/openshell-policy-boundary.test.ts b/test/package-contract/openshell-policy-boundary.test.ts index 81ba9c855cc..e371843b0f6 100644 --- a/test/package-contract/openshell-policy-boundary.test.ts +++ b/test/package-contract/openshell-policy-boundary.test.ts @@ -47,6 +47,9 @@ describe("OpenShell policy boundary package contract", () => { yamlBody: string; policy: Record; }; + parseGlobalPolicyAuthorityMetadata: ( + raw: string, + ) => { authority: string; effectivePolicy: Record }; parseSandboxPolicyAuthorityMetadata: ( raw: string, sandboxName: string, @@ -71,6 +74,7 @@ describe("OpenShell policy boundary package contract", () => { yamlBody: string; policy: Record; }; + parseGlobalPolicyAuthorityMetadata: typeof cliPolicy.parseGlobalPolicyAuthorityMetadata; parseSandboxPolicyAuthorityMetadata: typeof cliPolicy.parseSandboxPolicyAuthorityMetadata; withoutProviderComposedPolicies: ( policies: Record, @@ -81,6 +85,7 @@ describe("OpenShell policy boundary package contract", () => { require("../../nemoclaw/dist/shared/openshell-policy-boundary.cjs") as { assertExternalPolicyRequirementContainment: typeof cliPolicy.assertExternalPolicyRequirementContainment; assertMatchingPolicyAuthority: typeof cliPolicy.assertMatchingPolicyAuthority; + parseGlobalPolicyAuthorityMetadata: typeof cliPolicy.parseGlobalPolicyAuthorityMetadata; parseOpenShellPolicy: typeof cliPolicy.parseOpenShellPolicy; parseSandboxPolicyAuthorityMetadata: typeof cliPolicy.parseSandboxPolicyAuthorityMetadata; stripProviderComposedPolicies: typeof cliPolicy.stripProviderComposedPolicies; @@ -108,6 +113,9 @@ describe("OpenShell policy boundary package contract", () => { expect(cliPolicy.stripProviderComposedPolicies).toBe( canonicalBoundary.stripProviderComposedPolicies, ); + expect(cliPolicy.parseGlobalPolicyAuthorityMetadata).toBe( + canonicalBoundary.parseGlobalPolicyAuthorityMetadata, + ); expect(cliPolicy.parseSandboxPolicyAuthorityMetadata).toBe( canonicalBoundary.parseSandboxPolicyAuthorityMetadata, ); @@ -127,6 +135,15 @@ describe("OpenShell policy boundary package contract", () => { expect(pluginBoundary.parseSandboxPolicyAuthorityMetadata(sandboxMetadata, "alpha")).toEqual( canonicalBoundary.parseSandboxPolicyAuthorityMetadata(sandboxMetadata, "alpha"), ); + const globalMetadata = JSON.stringify({ + scope: "global", + status: "loaded", + policy_source: "global", + policy: { version: 1, network_policies: {} }, + }); + expect(pluginBoundary.parseGlobalPolicyAuthorityMetadata(globalMetadata)).toEqual( + canonicalBoundary.parseGlobalPolicyAuthorityMetadata(globalMetadata), + ); const pluginRunner = await import( pathToFileURL(path.join(repoRoot, "nemoclaw", "dist", "blueprint", "runner.js")).href From 9fa334a2a4e702f5ef542db63299cefe2d732619 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 03:13:45 -0700 Subject: [PATCH 13/40] fix(onboard): close policy authority lifecycle gaps Signed-off-by: Apurv Kumaria --- .../src/shared/openshell-policy-boundary.cts | 2 +- .../shared/openshell-policy-boundary.test.ts | 1 + src/lib/actions/sandbox/launch-readiness.ts | 32 +- ...rtable-openclaw-pairing-settlement.test.ts | 149 ++++++++ src/lib/agent/onboard.test.ts | 46 +++ src/lib/agent/onboard.ts | 48 ++- src/lib/onboard.ts | 18 +- .../onboard/compatible-endpoint-smoke.test.ts | 28 ++ src/lib/onboard/compatible-endpoint-smoke.ts | 3 + src/lib/onboard/dashboard.ts | 17 +- .../docker-gpu-local-inference.test.ts | 3 + src/lib/onboard/docker-gpu-local-inference.ts | 11 +- .../inference-selection-validation.test.ts | 78 +++++ .../onboard/inference-selection-validation.ts | 4 + src/lib/onboard/machine/final-flow-phases.ts | 14 +- .../onboard/machine/finalization-deps.test.ts | 50 ++- src/lib/onboard/machine/finalization-deps.ts | 32 +- .../machine/handlers/agent-setup.test.ts | 90 ++++- .../onboard/machine/handlers/agent-setup.ts | 40 ++- .../machine/handlers/finalization.test.ts | 100 +++++- .../onboard/machine/handlers/finalization.ts | 51 ++- .../machine/handlers/policies-test-fixture.ts | 4 +- .../onboard/machine/handlers/policies.test.ts | 325 ++++++++++++------ src/lib/onboard/machine/handlers/policies.ts | 89 ++++- ...vider-inference-host-local-startup.test.ts | 58 +++- ...rovider-inference-policy-authority.test.ts | 29 ++ .../machine/handlers/provider-inference.ts | 153 ++++++++- .../onboard/machine/handlers/sandbox.test.ts | 3 + src/lib/onboard/machine/handlers/sandbox.ts | 2 + src/lib/onboard/openclaw-setup.test.ts | 30 ++ src/lib/onboard/openclaw-setup.ts | 2 + .../policy-authority/preflight.test.ts | 13 + src/lib/onboard/policy-authority/preflight.ts | 76 ++-- .../policy-selection-host-local-route.test.ts | 44 +++ src/lib/onboard/policy-selection.ts | 13 +- .../sandbox-create/orchestration.test.ts | 276 --------------- test/helpers/onboard-final-flow-phases.ts | 34 +- ...ernal-policy-authority-composition.test.ts | 285 +++++++++++++++ 38 files changed, 1736 insertions(+), 517 deletions(-) create mode 100644 test/onboard-external-policy-authority-composition.test.ts diff --git a/nemoclaw/src/shared/openshell-policy-boundary.cts b/nemoclaw/src/shared/openshell-policy-boundary.cts index 67e403225c4..d752f615c27 100644 --- a/nemoclaw/src/shared/openshell-policy-boundary.cts +++ b/nemoclaw/src/shared/openshell-policy-boundary.cts @@ -87,7 +87,7 @@ export function parseGlobalPolicyAuthorityMetadata( if ( metadata.scope !== "global" || Object.hasOwn(metadata, "sandbox") || - (metadata.policy_source !== undefined && metadata.policy_source !== "global") + metadata.policy_source !== "global" ) { throw new Error("OpenShell returned invalid global policy authority metadata"); } diff --git a/nemoclaw/src/shared/openshell-policy-boundary.test.ts b/nemoclaw/src/shared/openshell-policy-boundary.test.ts index f9c0cf62665..331267970af 100644 --- a/nemoclaw/src/shared/openshell-policy-boundary.test.ts +++ b/nemoclaw/src/shared/openshell-policy-boundary.test.ts @@ -227,6 +227,7 @@ describe("global policy authority boundary", () => { ["malformed", "{"], ["wrong scope", JSON.stringify({ scope: "sandbox", status: "loaded", policy })], ["sandbox identity", JSON.stringify({ scope: "global", sandbox: "alpha", status: "loaded", policy })], + ["missing source", JSON.stringify({ scope: "global", status: "loaded", policy })], ["unknown source", JSON.stringify({ scope: "global", status: "loaded", policy_source: "sandbox", policy })], ["unknown status", JSON.stringify({ scope: "global", status: "pending", policy })], ])("rejects %s global authority metadata", (_caseName, raw) => { diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index f84b447a656..2f41dee1328 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -935,8 +935,7 @@ function resolveOpenClawPairingSettlementTarget( // command shape, so its caller may preserve that unknown value as the empty // string while retaining the exact registry and live-lifecycle checks. const customDockerfile = normalizedString(entry.fromDockerfile); - const version = - recordedVersion ?? (allowUnknownCustomVersion && customDockerfile ? "" : null); + const version = recordedVersion ?? (allowUnknownCustomVersion && customDockerfile ? "" : null); const expectedVersion = normalizedString(agent.expected_version); const stateDirectory = normalizedString(agent.config?.dir); const lifecycleGeneration = normalizedString(entry.lifecycleGeneration); @@ -988,6 +987,7 @@ export async function settlePortableOpenClawPairing( sandboxName: string, options: { readonly portableRequired?: boolean; + readonly revalidatePolicyRequirements?: (operation: string) => void; } = {}, deps: LaunchReadinessDeps = {}, ): Promise { @@ -999,6 +999,7 @@ export async function settlePortableOpenClawPairing( const observePairing = deps.observeOpenClawPairingSettlement ?? observeOpenClawPairingSettlement; const runProducer = deps.runPortablePairingProducer ?? runPortableOpenClawPairingRequestProducer; const runApproval = deps.runPortablePairingApproval ?? runPortableOpenClawPairingApproval; + const revalidatePolicyRequirements = options.revalidatePolicyRequirements; return withSandboxLock(sandboxName, async () => { let firstEntry = getSandbox(sandboxName); @@ -1018,6 +1019,7 @@ export async function settlePortableOpenClawPairing( firstEntry.policyPresetsFinalized === true && portableLifecycleReceiptMatchesGeneration(firstReceipt, firstEntry.lifecycleGeneration) ) { + revalidatePolicyRequirements?.(`update the recorded agent for sandbox '${sandboxName}'`); if (!updateSandbox(sandboxName, { agent: "openclaw" })) { return incompletePortablePairing("portable-runtime-identity-invalid"); } @@ -1086,24 +1088,40 @@ export async function settlePortableOpenClawPairing( } catch { return incompletePortablePairing("portable-pairing-incomplete"); } - if (first.state === "settled") return { kind: "settled" }; + if (first.state === "settled") { + revalidatePolicyRequirements?.( + `publish settled Portable OpenClaw pairing for sandbox '${sandboxName}'`, + ); + return { kind: "settled" }; + } + revalidatePolicyRequirements?.( + `request Portable OpenClaw pairing for sandbox '${sandboxName}'`, + ); runProducer(sandboxName, target.gatewayName); + revalidatePolicyRequirements?.( + `approve Portable OpenClaw pairing for sandbox '${sandboxName}'`, + ); runApproval(sandboxName, target.gatewayName, first.deviceIdentitySha256); + let final: OpenClawPairingSettlementObservation; try { - const final = observePairing( + final = observePairing( sandboxName, target.gatewayName, target.version, target.stateDirectory, ); - return final.state === "settled" - ? { kind: "settled" } - : incompletePortablePairing("portable-pairing-incomplete"); } catch { return incompletePortablePairing("portable-pairing-incomplete"); } + if (final.state !== "settled") { + return incompletePortablePairing("portable-pairing-incomplete"); + } + revalidatePolicyRequirements?.( + `publish settled Portable OpenClaw pairing for sandbox '${sandboxName}'`, + ); + return { kind: "settled" }; }); }); } diff --git a/src/lib/actions/sandbox/launch-readiness/portable-openclaw-pairing-settlement.test.ts b/src/lib/actions/sandbox/launch-readiness/portable-openclaw-pairing-settlement.test.ts index 5fbb1ce6e2d..4ec9e497d02 100644 --- a/src/lib/actions/sandbox/launch-readiness/portable-openclaw-pairing-settlement.test.ts +++ b/src/lib/actions/sandbox/launch-readiness/portable-openclaw-pairing-settlement.test.ts @@ -248,6 +248,37 @@ describe("Portable OpenClaw pairing settlement", () => { expect(scope.runApproval).not.toHaveBeenCalled(); }); + it("does not repair a legacy registry row when authority changes while acquiring the lifecycle lock (#9833)", async () => { + let revalidatePolicyRequirements = () => undefined; + const updateSandbox = vi.fn(() => true); + const scope = settlementDeps({ + getSandbox: vi.fn(() => ({ ...ENTRY, agent: null })), + updateSandbox, + withSandboxLock: vi.fn(async (_name, operation) => { + revalidatePolicyRequirements = () => { + throw new Error("policy authority changed"); + }; + return operation(); + }), + }); + + await expect( + settlePortableOpenClawPairing( + "alpha", + { + portableRequired: true, + revalidatePolicyRequirements: () => revalidatePolicyRequirements(), + }, + scope.deps, + ), + ).rejects.toThrow("policy authority changed"); + + expect(updateSandbox).not.toHaveBeenCalled(); + expect(scope.observePairing).not.toHaveBeenCalled(); + expect(scope.runProducer).not.toHaveBeenCalled(); + expect(scope.runApproval).not.toHaveBeenCalled(); + }); + it.each<[string, boolean]>([ ["registry update fails", false], ["registry readback remains unchanged", true], @@ -350,6 +381,124 @@ describe("Portable OpenClaw pairing settlement", () => { expect(scope.observePairing).toHaveBeenCalledTimes(2); }); + it("does not produce or approve a request when authority changes during initial observation (#9833)", async () => { + let revalidatePolicyRequirements = () => undefined; + const scope = settlementDeps(); + scope.observePairing.mockImplementationOnce(() => { + revalidatePolicyRequirements = () => { + throw new Error("policy authority changed"); + }; + return { + state: "pairing-only", + deviceIdentitySha256: "b".repeat(64), + }; + }); + + await expect( + settlePortableOpenClawPairing( + "alpha", + { + revalidatePolicyRequirements: () => revalidatePolicyRequirements(), + }, + scope.deps, + ), + ).rejects.toThrow("policy authority changed"); + + expect(scope.runProducer).not.toHaveBeenCalled(); + expect(scope.runApproval).not.toHaveBeenCalled(); + expect(scope.observePairing).toHaveBeenCalledOnce(); + }); + + it("does not approve a request when authority changes during request production (#9833)", async () => { + let revalidatePolicyRequirements = () => undefined; + const scope = settlementDeps({ + runPortablePairingProducer: vi.fn(() => { + revalidatePolicyRequirements = () => { + throw new Error("policy authority changed"); + }; + }), + }); + scope.observePairing.mockReturnValueOnce({ + state: "pairing-only", + deviceIdentitySha256: "b".repeat(64), + }); + + await expect( + settlePortableOpenClawPairing( + "alpha", + { + revalidatePolicyRequirements: () => revalidatePolicyRequirements(), + }, + scope.deps, + ), + ).rejects.toThrow("policy authority changed"); + + expect(scope.deps.runPortablePairingProducer).toHaveBeenCalledOnce(); + expect(scope.runApproval).not.toHaveBeenCalled(); + expect(scope.observePairing).toHaveBeenCalledOnce(); + }); + + it("does not publish settled pairing when authority changes during initial observation (#9833)", async () => { + let revalidatePolicyRequirements = () => undefined; + const scope = settlementDeps(); + scope.observePairing.mockImplementationOnce(() => { + revalidatePolicyRequirements = () => { + throw new Error("policy authority changed"); + }; + return { + state: "settled", + deviceIdentitySha256: "b".repeat(64), + }; + }); + + await expect( + settlePortableOpenClawPairing( + "alpha", + { + revalidatePolicyRequirements: () => revalidatePolicyRequirements(), + }, + scope.deps, + ), + ).rejects.toThrow("policy authority changed"); + + expect(scope.runProducer).not.toHaveBeenCalled(); + expect(scope.runApproval).not.toHaveBeenCalled(); + expect(scope.observePairing).toHaveBeenCalledOnce(); + }); + + it("does not publish settled pairing when authority changes during final observation (#9833)", async () => { + let revalidatePolicyRequirements = () => undefined; + const scope = settlementDeps(); + scope.observePairing + .mockReturnValueOnce({ + state: "pairing-only", + deviceIdentitySha256: "b".repeat(64), + }) + .mockImplementationOnce(() => { + revalidatePolicyRequirements = () => { + throw new Error("policy authority changed"); + }; + return { + state: "settled", + deviceIdentitySha256: "b".repeat(64), + }; + }); + + await expect( + settlePortableOpenClawPairing( + "alpha", + { + revalidatePolicyRequirements: () => revalidatePolicyRequirements(), + }, + scope.deps, + ), + ).rejects.toThrow("policy authority changed"); + + expect(scope.runProducer).toHaveBeenCalledOnce(); + expect(scope.runApproval).toHaveBeenCalledOnce(); + expect(scope.observePairing).toHaveBeenCalledTimes(2); + }); + it.each(["ambiguous", "no-request", "rejected", "unavailable"] as const)( "does not retry a %s approval and reports incomplete after one re-observation (#9207)", async (receipt) => { diff --git a/src/lib/agent/onboard.test.ts b/src/lib/agent/onboard.test.ts index b22748ed062..965ef56ca71 100644 --- a/src/lib/agent/onboard.test.ts +++ b/src/lib/agent/onboard.test.ts @@ -307,6 +307,7 @@ describe("agent setup session boundaries", () => { function createAgentSetupContext( runCaptureOpenshell: OnboardContext["runCaptureOpenshell"] = vi.fn(() => ""), timing: Pick = {}, + policyRequirements: Pick = {}, ) { return { context: { @@ -319,6 +320,7 @@ describe("agent setup session boundaries", () => { recordStepFailed: vi.fn(async () => undefined), skippedStepMessage: vi.fn(), ...timing, + ...policyRequirements, }, }; } @@ -430,6 +432,50 @@ describe("agent setup session boundaries", () => { expect(context.recordStepFailed).not.toHaveBeenCalled(); }); + it("refuses completion when policy authority changes during the gateway wait (#9833)", async () => { + let nowMs = 0; + const sleepSeconds = vi.fn((seconds: number) => { + nowMs += seconds * 1000; + }); + const runCaptureOpenshell = vi + .fn(() => "ok") + .mockReturnValueOnce("NEMOCLAW_AGENT_BINARY_CHECK:ok") + .mockReturnValueOnce(""); + const refuseCompletion = () => { + throw new Error("policy authority changed"); + }; + const policyChecks = new Map([ + ["record completed agent setup for sandbox 'sandbox-x'", refuseCompletion], + ]); + const revalidatePolicyRequirements = vi.fn((operation: string) => + policyChecks.get(operation)?.(), + ); + const { context } = createAgentSetupContext( + runCaptureOpenshell, + { now: () => nowMs, sleepSeconds }, + { revalidatePolicyRequirements }, + ); + const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); + + await expect( + handleAgentSetup( + "sandbox-x", + "model-x", + "provider-x", + makeAgent({ + healthProbe: { url: "http://127.0.0.1:19000/", port: 19000, timeout_seconds: 1 }, + }), + false, + null, + context, + ), + ).rejects.toThrow("policy authority changed"); + + expect(sleepSeconds).toHaveBeenCalledWith(0.25); + expect(context.recordStepComplete).not.toHaveBeenCalled(); + expect(logSpy.mock.calls.flat().join("\n")).not.toContain("gateway is healthy"); + }); + it("records gateway failure when the configured deadline expires", async () => { let nowMs = 0; const sleepSeconds = vi.fn((seconds: number) => { diff --git a/src/lib/agent/onboard.ts b/src/lib/agent/onboard.ts index a9dc98ceb3d..9c9fe58ee76 100644 --- a/src/lib/agent/onboard.ts +++ b/src/lib/agent/onboard.ts @@ -62,6 +62,7 @@ export interface OnboardContext { recordStepComplete: (stepName: string, updates: LooseObject) => Promise; recordStepFailed: (stepName: string, message: string | null) => Promise; skippedStepMessage: (stepName: string, sandboxName: string) => void; + revalidatePolicyRequirements?: (operation: string) => void; now?: () => number; sleepSeconds?: (seconds: number) => void; } @@ -247,7 +248,9 @@ async function failAgentSetup( message: string, recordStepFailed: OnboardContext["recordStepFailed"], details: string[] = [], + revalidatePolicyRequirements?: OnboardContext["revalidatePolicyRequirements"], ): Promise { + revalidatePolicyRequirements?.(`record failed agent setup for sandbox '${sandboxName}'`); await recordStepFailed( "agent_setup", details.length > 0 ? `${message}\n${details.join("\n")}` : message, @@ -316,6 +319,7 @@ export async function handleAgentSetup( recordStepComplete, recordStepFailed, skippedStepMessage, + revalidatePolicyRequirements, } = ctx; const runSmokeCapture = @@ -324,6 +328,7 @@ export async function handleAgentSetup( : runCaptureOpenshell; const syncNemoClawConfig = (): void => { + revalidatePolicyRequirements?.(`synchronize agent configuration in sandbox '${sandboxName}'`); runSandboxConfigSync(sandboxName, { getSelectionConfig: () => { const cfg = getProviderSelectionConfig(provider, model); @@ -350,9 +355,25 @@ export async function handleAgentSetup( const smokeResult = runAgentSmokeCommands(sandboxName, agent, runSmokeCapture); if (smokeResult.ok) { await enforceTerminalAgentVersion(sandboxName, agent, runCaptureOpenshell, { - beforeFailure: () => startRecordedStep("agent_setup", { sandboxName, provider, model }), - onFailure: (message) => failAgentSetup(sandboxName, agent, message, recordStepFailed), + beforeFailure: () => { + revalidatePolicyRequirements?.( + `start failed agent setup recording for sandbox '${sandboxName}'`, + ); + return startRecordedStep("agent_setup", { sandboxName, provider, model }); + }, + onFailure: (message) => + failAgentSetup( + sandboxName, + agent, + message, + recordStepFailed, + [], + revalidatePolicyRequirements, + ), }); + revalidatePolicyRequirements?.( + `record resumed agent setup for sandbox '${sandboxName}'`, + ); skippedStepMessage("agent_setup", sandboxName); await recordStepComplete("agent_setup", { sandboxName, provider, model }); return; @@ -376,18 +397,22 @@ export async function handleAgentSetup( { ignoreError: true }, ); if (isHealthProbeOk(result)) { - skippedStepMessage("agent_setup", sandboxName); // Re-sync `~/.nemoclaw/config.json` even on the resume skip path — // a rebuild destroys/recreates the container and the file reverts // to the Dockerfile's zero-byte placeholder. Mirrors the OpenClaw // path in src/lib/onboard.ts. Fixes #3999 for non-OpenClaw agents. syncNemoClawConfig(); + revalidatePolicyRequirements?.( + `record resumed agent setup for sandbox '${sandboxName}'`, + ); + skippedStepMessage("agent_setup", sandboxName); await recordStepComplete("agent_setup", { sandboxName, provider, model }); return; } } } + revalidatePolicyRequirements?.(`start agent setup for sandbox '${sandboxName}'`); await startRecordedStep("agent_setup", { sandboxName, provider, model }); step(7, 8, `Setting up ${agent.displayName} inside sandbox`); @@ -398,6 +423,8 @@ export async function handleAgentSetup( agent, describeAgentBinaryFailure(sandboxName, agent, binaryAvailability), recordStepFailed, + [], + revalidatePolicyRequirements, ); } @@ -412,11 +439,21 @@ export async function handleAgentSetup( `${agent.displayName} terminal smoke command failed: ${smokeResult.command}`, recordStepFailed, smokeResult.output ? [String(redact(smokeResult.output)).slice(0, 500)] : [], + revalidatePolicyRequirements, ); } await enforceTerminalAgentVersion(sandboxName, agent, runCaptureOpenshell, { - onFailure: (message) => failAgentSetup(sandboxName, agent, message, recordStepFailed), + onFailure: (message) => + failAgentSetup( + sandboxName, + agent, + message, + recordStepFailed, + [], + revalidatePolicyRequirements, + ), }); + revalidatePolicyRequirements?.(`record completed agent setup for sandbox '${sandboxName}'`); console.log(` \u2713 ${agent.displayName} terminal runtime is ready`); await recordStepComplete("agent_setup", { sandboxName, provider, model }); return; @@ -448,6 +485,7 @@ export async function handleAgentSetup( }, }); if (healthy) { + revalidatePolicyRequirements?.(`record completed agent setup for sandbox '${sandboxName}'`); console.log(` \u2713 ${agent.displayName} gateway is healthy`); } else { const diagnostics = @@ -460,9 +498,11 @@ export async function handleAgentSetup( `${agent.displayName} gateway did not respond within ${timeoutSecs}s`, recordStepFailed, diagnostics, + revalidatePolicyRequirements, ); } } else { + revalidatePolicyRequirements?.(`record completed agent setup for sandbox '${sandboxName}'`); console.log(` \u2713 ${agent.displayName} configured inside sandbox`); } diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index c98430a8c82..6837a84504a 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -3346,8 +3346,8 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { revalidatePolicyRequirements: policyAuthorityBindings.revalidatePolicyRequirements, agentSetupDeps: { handleAgentSetup: agentOnboard.handleAgentSetup, - agentSetupContext: () => ({ - ...{ step, runCaptureOpenshell, captureOpenshell }, + agentSetupContext: (revalidatePolicyRequirements) => ({ + ...{ step, runCaptureOpenshell, captureOpenshell, revalidatePolicyRequirements }, openshellShellCommand, openshellBinary: getOpenshellBinary(), buildSandboxConfigSyncScript, @@ -3358,13 +3358,13 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { recordStepFailed, skippedStepMessage, }), - ensureAgentDashboardForward: (name, selectedAgent) => - selectedAgent - ? ensureAgentDashboardForward(name, selectedAgent, { - beforeForwardPort: (port) => - hermesApiPortReservationScope.releaseBeforeForward(selectedAgent.name, port), - }) - : 0, + ensureAgentDashboardForward: (name, selectedAgent, revalidate) => + ensureFinalizationAgentDashboardForward( + name, + selectedAgent, + revalidate, + hermesApiPortReservationScope, + ), persistDashboardPort: (name, port) => registry.updateSandbox(name, { dashboardPort: port }), recordStepSkipped, diff --git a/src/lib/onboard/compatible-endpoint-smoke.test.ts b/src/lib/onboard/compatible-endpoint-smoke.test.ts index 90c849767ab..ef54c56ac79 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.test.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.test.ts @@ -230,6 +230,34 @@ describe("compatible endpoint sandbox smoke helpers", () => { ); }); + it("withholds sandbox-route success output when policy authority changes during proof (#9833)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 0, stdout: "provider ready" }) + .mockReturnValueOnce({ status: 0, stdout: "INFERENCE_SMOKE_OK PONG" }); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + + expect(() => + verifyCompatibleEndpointSandboxSmoke({ + sandboxName: "smoke-sandbox", + provider: "compatible-endpoint", + model: "nvidia/nemotron-3-ultra", + runOpenshell, + redact: (value) => value, + messagingChannels: ["telegram"], + beforeSuccess: () => { + throw new Error("policy authority changed"); + }, + }), + ).toThrow("policy authority changed"); + + expect(runOpenshell).toHaveBeenCalledTimes(2); + expect(log.mock.calls.flat().join("\n")).not.toContain( + "Compatible endpoint responds through inference.local", + ); + log.mockRestore(); + }); + it("budgets the canonical outer timeout for both tool proofs and direct denial", () => { const runOpenshell = vi .fn() diff --git a/src/lib/onboard/compatible-endpoint-smoke.ts b/src/lib/onboard/compatible-endpoint-smoke.ts index f73fe10a8e5..2fac77f2fe8 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.ts @@ -129,6 +129,8 @@ export function verifyCompatibleEndpointSandboxSmoke(options: { /** Force the provider-neutral inference.local proof for any supported agent. */ forceCanonicalRoute?: boolean; hostLocalInferenceProofAuthority?: HostLocalInferenceSandboxProofAuthority; + /** Recheck policy authority after the sandbox proof and before success output. */ + beforeSuccess?: () => void; }): void { if ( options.forceCanonicalRoute !== true && @@ -239,6 +241,7 @@ export function verifyCompatibleEndpointSandboxSmoke(options: { process.exit(smokeResult.status || 1); } + options.beforeSuccess?.(); console.log( options.forceCanonicalRoute ? " \u2713 Provider responds through inference.local inside the sandbox" diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index d8882aca6c6..6dca3a95cd4 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -133,8 +133,11 @@ export interface OnboardDashboardHelpers { ): number; ensureFinalizationAgentDashboardForward( sandboxName: string, - agent: { forwardPort?: number | null; forward_ports?: number[] | null } | null, + agent: { name: string; forwardPort?: number | null; forward_ports?: number[] | null } | null, revalidatePolicyAuthority?: (operation: string) => void, + portReservation?: { + releaseBeforeForward(agentName: string, port: number): Promise | void; + }, ): Promise | number; ensureAgentFixedForward( sandboxName: string, @@ -570,11 +573,19 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa function ensureFinalizationAgentDashboardForward( sandboxName: string, - agent: { forwardPort?: number | null; forward_ports?: number[] | null } | null, + agent: { name: string; forwardPort?: number | null; forward_ports?: number[] | null } | null, revalidatePolicyAuthority?: (operation: string) => void, + portReservation?: { + releaseBeforeForward(agentName: string, port: number): Promise | void; + }, ): Promise | number { return agent - ? ensureAgentDashboardForward(sandboxName, agent, { revalidatePolicyAuthority }) + ? ensureAgentDashboardForward(sandboxName, agent, { + revalidatePolicyAuthority, + beforeForwardPort: portReservation + ? (port) => portReservation.releaseBeforeForward(agent.name, port) + : undefined, + }) : ensureFinalizationDashboardForward(sandboxName, revalidatePolicyAuthority); } diff --git a/src/lib/onboard/docker-gpu-local-inference.test.ts b/src/lib/onboard/docker-gpu-local-inference.test.ts index 8e8f8dc10f4..c3d1d52e0ef 100644 --- a/src/lib/onboard/docker-gpu-local-inference.test.ts +++ b/src/lib/onboard/docker-gpu-local-inference.test.ts @@ -455,6 +455,7 @@ describe("verifyGpuSandboxLocalInferenceAndCommitAfterReady", () => { commitAfterReady: vi.fn(), rollbackManagedStartupAfterCreateFailure: vi.fn(), }; + const log = vi.fn(); await expect( verifyGpuSandboxLocalInferenceAndCommitAfterReady( @@ -462,6 +463,7 @@ describe("verifyGpuSandboxLocalInferenceAndCommitAfterReady", () => { "ollama-local", { ...options(), + log, deps: { execInSandbox: execEmitting("HTTP_200"), sleep: vi.fn() }, }, runtimePatch, @@ -473,6 +475,7 @@ describe("verifyGpuSandboxLocalInferenceAndCommitAfterReady", () => { expect(runtimePatch.commitAfterReady).not.toHaveBeenCalled(); expect(runtimePatch.rollbackManagedStartupAfterCreateFailure).toHaveBeenCalledOnce(); + expect(log).not.toHaveBeenCalledWith(expect.stringContaining("reached local inference")); }); }); diff --git a/src/lib/onboard/docker-gpu-local-inference.ts b/src/lib/onboard/docker-gpu-local-inference.ts index 051c5013a48..8758b0c8ba5 100644 --- a/src/lib/onboard/docker-gpu-local-inference.ts +++ b/src/lib/onboard/docker-gpu-local-inference.ts @@ -467,7 +467,9 @@ export async function verifyGpuSandboxAccessAfterReady( export function verifyGpuSandboxLocalInferenceAfterReady( config: DockerGpuLocalInferenceConfig, provider: string | null | undefined, - options: Omit, + options: Omit & { + beforeSuccess?: () => void; + }, ): void { if (options.selectedRoute !== "compatibility") return; const verification = verifyDockerGpuSandboxLocalInference(config, provider, { @@ -481,6 +483,7 @@ export function verifyGpuSandboxLocalInferenceAfterReady( }); const log = options.log ?? console.log; if (verification.status === "ok") { + options.beforeSuccess?.(); log( ` ✓ GPU sandbox runtime reached local inference: ${verification.endpoint} (HTTP ${verification.httpCode})`, ); @@ -515,8 +518,10 @@ export async function verifyGpuSandboxLocalInferenceAndCommitAfterReady( revalidateBeforeCommit?: () => void, ): Promise { try { - verifyGpuSandboxLocalInferenceAfterReady(config, provider, options); - revalidateBeforeCommit?.(); + verifyGpuSandboxLocalInferenceAfterReady(config, provider, { + ...options, + beforeSuccess: revalidateBeforeCommit, + }); } catch (error) { const failure = error instanceof Error ? error : new Error(String(error)); try { diff --git a/src/lib/onboard/inference-selection-validation.test.ts b/src/lib/onboard/inference-selection-validation.test.ts index fadcb3fdb89..63f5f89dee8 100644 --- a/src/lib/onboard/inference-selection-validation.test.ts +++ b/src/lib/onboard/inference-selection-validation.test.ts @@ -170,6 +170,84 @@ describe("inference selection validation", () => { } }); + it("withholds OpenAI-like availability and capability caching when policy authority changes during the probe (#9833)", async () => { + const capabilityCache = new OnboardInferenceCapabilityCache(); + const helpers = createInferenceSelectionValidationHelpers({ + isNonInteractive: () => false, + agentProductName: () => "OpenClaw", + getCredential: () => "test-key", + probeOpenAiLikeEndpoint: vi.fn(async () => ({ + ok: true, + api: "openai-completions", + label: "Chat Completions API", + })), + promptValidationRecovery: vi.fn(async () => "selection" as const), + }); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + try { + await expect( + helpers.validateOpenAiLikeSelection( + "OpenAI", + "https://api.example.test/v1", + "model-a", + "OPENAI_API_KEY", + undefined, + undefined, + { + capabilityCache, + revalidatePolicyRequirements: () => { + throw new Error("policy authority changed"); + }, + }, + ), + ).rejects.toThrow("policy authority changed"); + expect(log.mock.calls.flat().join("\n")).not.toContain("available"); + expect( + capabilityCache.takeCompletedOpenAiChat({ + endpointUrl: "https://api.example.test/v1", + model: "model-a", + }), + ).toBe(false); + } finally { + log.mockRestore(); + } + }); + + it("withholds Anthropic availability when policy authority changes during the probe (#9833)", async () => { + const helpers = createInferenceSelectionValidationHelpers({ + isNonInteractive: () => false, + agentProductName: () => "OpenClaw", + getCredential: () => "test-key", + probeAnthropicEndpoint: vi.fn(() => ({ + ok: true, + api: "anthropic-messages", + label: "Anthropic Messages API", + })), + promptValidationRecovery: vi.fn(async () => "selection" as const), + }); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + try { + await expect( + helpers.validateAnthropicSelectionWithRetryMessage( + "Anthropic", + "https://api.anthropic.example.test", + "model-a", + "ANTHROPIC_API_KEY", + undefined, + undefined, + () => { + throw new Error("policy authority changed"); + }, + ), + ).rejects.toThrow("policy authority changed"); + expect(log.mock.calls.flat().join("\n")).not.toContain("available"); + } finally { + log.mockRestore(); + } + }); + it("distinguishes a Gemini runtime 404 from native model catalog validation (#9298)", async () => { const apiKey = "gemini-test-secret"; const probeOpenAiLikeEndpoint = vi.fn(() => ({ diff --git a/src/lib/onboard/inference-selection-validation.ts b/src/lib/onboard/inference-selection-validation.ts index be538dfc6b8..d3c1e5cef1d 100644 --- a/src/lib/onboard/inference-selection-validation.ts +++ b/src/lib/onboard/inference-selection-validation.ts @@ -342,6 +342,7 @@ export function createInferenceSelectionValidationHelpers( } return { ok: false, retry }; } + options.revalidatePolicyRequirements?.("report validated inference endpoint"); if (probe.note) { console.log(` ℹ ${probe.note}`); } else { @@ -391,6 +392,7 @@ export function createInferenceSelectionValidationHelpers( } return { ok: false, retry }; } + revalidatePolicyRequirements?.("report validated inference endpoint"); console.log(` ${probe.label} available — ${deps.agentProductName()} will use ${probe.api}.`); return { ok: true, api: probe.api }; } @@ -426,6 +428,7 @@ export function createInferenceSelectionValidationHelpers( trustedPrivateCapability, }); if (probe.ok) { + revalidatePolicyRequirements?.("report validated inference endpoint"); if (probe.note) { console.log(` ℹ ${probe.note}`); } else { @@ -517,6 +520,7 @@ export function createInferenceSelectionValidationHelpers( trustedPrivateCapability, }); if (probe.ok) { + options.revalidatePolicyRequirements?.("report validated inference endpoint"); if (probe.note) { console.log(` ℹ ${probe.note}`); } else { diff --git a/src/lib/onboard/machine/final-flow-phases.ts b/src/lib/onboard/machine/final-flow-phases.ts index 76fdc6f7f4c..c4ddc81811d 100644 --- a/src/lib/onboard/machine/final-flow-phases.ts +++ b/src/lib/onboard/machine/final-flow-phases.ts @@ -63,6 +63,9 @@ export function createFinalOnboardFlowPhases< ...options.finalizationDeps, persistDashboardPort: options.agentSetupDeps.persistDashboardPort, }; + const revalidationFor = (context: Context) => + options.revalidatePolicyRequirements?.bind(null, context) ?? + finalizationDeps.revalidatePolicyRequirements; const createBranchPhase = options.branchState === "agent_setup" ? createAgentSetupPhase : createOpenclawSetupPhase; const branchSetupPhase = createBranchPhase(async (context) => { @@ -76,6 +79,7 @@ export function createFinalOnboardFlowPhases< session: context.session, hermesAuthMethod: context.hermesAuthMethod, hermesToolGateways: context.hermesToolGateways, + revalidatePolicyRequirements: revalidationFor(context), deps: options.agentSetupDeps, }); return { @@ -103,6 +107,7 @@ export function createFinalOnboardFlowPhases< webSearchSupported: context.webSearchSupported, hermesToolGateways: context.hermesToolGateways, agent: context.agent, + revalidatePolicyRequirements: revalidationFor(context), deps: options.policiesDeps, }); return { @@ -117,9 +122,7 @@ export function createFinalOnboardFlowPhases< const finalizationPhase = createFinalizationPhase(async (context) => { assertSandboxCreatedContext(context, "finalization"); const webSearchEnabled = options.finalization.webSearchEnabled(context.webSearchConfig); - const revalidatePolicyRequirements = - options.revalidatePolicyRequirements?.bind(null, context) ?? - finalizationDeps.revalidatePolicyRequirements; + const revalidatePolicyRequirements = revalidationFor(context); const finalizationResult = await handleFinalizationState({ sandboxName: context.sandboxName, model: context.model, @@ -162,7 +165,10 @@ export function createFinalOnboardFlowPhases< : null, portableProfileSelected: context.session?.checkpoint?.profile.value === "portable", recreateJournalHandoff: context.recreateJournalHandoff, - deps: finalizationDeps, + deps: { + ...finalizationDeps, + revalidatePolicyRequirements: revalidationFor(context), + }, }); return { result: postVerifyResult.stateResult }; }); diff --git a/src/lib/onboard/machine/finalization-deps.test.ts b/src/lib/onboard/machine/finalization-deps.test.ts index 457e38f5a31..9423fa67a5c 100644 --- a/src/lib/onboard/machine/finalization-deps.test.ts +++ b/src/lib/onboard/machine/finalization-deps.test.ts @@ -109,6 +109,51 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); + it("stops before warm-up and approval when authority changes during pairing observation (#9833)", async () => { + let revalidatePolicyRequirements = () => undefined; + const scope = ordinaryPairingDeps({ + observePairing: vi + .fn() + .mockImplementationOnce(() => { + throw new Error("not published"); + }) + .mockImplementationOnce(() => { + revalidatePolicyRequirements = () => { + throw new Error("policy authority changed"); + }; + return PAIRING_ONLY; + }), + revalidatePolicyRequirements: vi.fn(() => revalidatePolicyRequirements()), + }); + + await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).rejects.toThrow( + "policy authority changed", + ); + + expect(scope.deps.runWarmup).not.toHaveBeenCalled(); + expect(scope.deps.runApproval).not.toHaveBeenCalled(); + }); + + it("does not publish settled pairing when authority changes during observation (#9833)", async () => { + let revalidatePolicyRequirements = () => undefined; + const scope = ordinaryPairingDeps({ + observePairing: vi.fn(() => { + revalidatePolicyRequirements = () => { + throw new Error("policy authority changed"); + }; + return SETTLED; + }), + revalidatePolicyRequirements: vi.fn(() => revalidatePolicyRequirements()), + }); + + await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).rejects.toThrow( + "policy authority changed", + ); + + expect(scope.deps.runWarmup).not.toHaveBeenCalled(); + expect(scope.deps.runApproval).not.toHaveBeenCalled(); + }); + it("holds lifecycle then gateway-route ownership across the full settlement (#9844)", async () => { const events: string[] = []; const scope = ordinaryPairingDeps({ @@ -489,10 +534,7 @@ describe("ordinary OpenClaw pairing settlement", () => { }); it("wires default warm-up and approval adapters to the finalized gateway (#9844)", async () => { - const observePairing = vi - .fn() - .mockReturnValueOnce(PAIRING_ONLY) - .mockReturnValueOnce(SETTLED); + const observePairing = vi.fn().mockReturnValueOnce(PAIRING_ONLY).mockReturnValueOnce(SETTLED); const runSandboxScopeWarmupRun = vi.fn(); const runConnectAutoPairApprovalPass = vi.fn(); vi.spyOn(finalizationHandlerRuntime, "loadLaunchReadiness").mockReturnValue({ diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index e842ae3370f..a8cd76ee9ea 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -70,6 +70,7 @@ interface OrdinaryOpenClawPairingSettlementDeps { runApproval(name: string, gatewayName: string): Promise | void; withSandboxLock: SandboxLifecycleLock; withGatewayLock: GatewayRouteLock; + revalidatePolicyRequirements?(operation: string): void; now(): number; sleep(milliseconds: number): Promise; } @@ -219,7 +220,12 @@ export async function settleOrdinaryOpenClawPairing( if (baseline.kind === "timeout") { return { kind: "incomplete", reason: "pairing-unavailable" }; } - if (baseline.value.state === "settled") return { kind: "settled" }; + if (baseline.value.state === "settled") { + deps.revalidatePolicyRequirements?.( + `publish settled OpenClaw pairing for sandbox '${name}'`, + ); + return { kind: "settled" }; + } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } @@ -227,6 +233,7 @@ export async function settleOrdinaryOpenClawPairing( return { kind: "incomplete", reason: "scope-upgrade-incomplete" }; } + deps.revalidatePolicyRequirements?.(`run OpenClaw pairing warm-up for sandbox '${name}'`); let warmupFailed = false; try { await deps.runWarmup(name); @@ -240,6 +247,7 @@ export async function settleOrdinaryOpenClawPairing( return { kind: "incomplete", reason: "scope-upgrade-incomplete" }; } + deps.revalidatePolicyRequirements?.(`approve OpenClaw pairing for sandbox '${name}'`); let approvalFailed = false; try { await deps.runApproval(name, target.gatewayName); @@ -269,9 +277,13 @@ export async function settleOrdinaryOpenClawPairing( if (final.kind === "target-changed") { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } - return final.kind === "observed" - ? { kind: "settled" } - : { kind: "incomplete", reason: "scope-upgrade-incomplete" }; + if (final.kind !== "observed") { + return { kind: "incomplete", reason: "scope-upgrade-incomplete" }; + } + deps.revalidatePolicyRequirements?.( + `publish settled OpenClaw pairing for sandbox '${name}'`, + ); + return { kind: "settled" }; }); } catch (error) { if (gatewayBodyEntered) throw error; @@ -302,7 +314,16 @@ export const finalizationHandlerDeps = { const processRecovery = finalizationHandlerRuntime.loadProcessRecovery(); processRecovery.checkAndRecoverSandboxProcesses(name, options); }, - settleOrdinaryOpenClawPairing, + settleOrdinaryOpenClawPairing( + name: string, + revalidatePolicyRequirements?: (operation: string) => void, + ): Promise { + const deps = defaultPairingSettlementDeps(); + return settleOrdinaryOpenClawPairing( + name, + revalidatePolicyRequirements ? { ...deps, revalidatePolicyRequirements } : deps, + ); + }, ordinaryOpenClawPairingIncompleteMessage, readRegistryAgent(name: string): string | null { try { @@ -318,6 +339,7 @@ export const finalizationHandlerDeps = { name: string, options: { readonly portableRequired: true; + readonly revalidatePolicyRequirements?: (operation: string) => void; }, ): ReturnType< (typeof import("../../actions/sandbox/launch-readiness"))["settlePortableOpenClawPairing"] diff --git a/src/lib/onboard/machine/handlers/agent-setup.test.ts b/src/lib/onboard/machine/handlers/agent-setup.test.ts index 968183c2438..7d6854a21bb 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.test.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.test.ts @@ -12,7 +12,10 @@ function createDeps(overrides: Partial["deps"]> = let session = createSession(); const calls = { handleAgentSetup: vi.fn(async () => undefined), - context: vi.fn(() => ({ ctx: true })), + context: vi.fn((revalidatePolicyRequirements?: (operation: string) => void) => ({ + ctx: true, + revalidatePolicyRequirements, + })), ensureDashboard: vi.fn(() => 18789), persistDashboardPort: vi.fn(), skipped: vi.fn(async (stepName: string) => { @@ -70,6 +73,25 @@ function baseOptions( } describe("handleAgentSetupState", () => { + it("refuses agent setup before its first effect when policy authority drifts (#9833)", async () => { + const { deps, calls } = createDeps(); + const revalidatePolicyRequirements = vi.fn(() => { + throw new Error("policy authority changed"); + }); + + await expect( + handleAgentSetupState({ + ...baseOptions(deps, { name: "hermes", displayName: "Hermes" }), + revalidatePolicyRequirements, + }), + ).rejects.toThrow("policy authority changed"); + + expect(calls.handleAgentSetup).not.toHaveBeenCalled(); + expect(calls.ensureDashboard).not.toHaveBeenCalled(); + expect(calls.persistDashboardPort).not.toHaveBeenCalled(); + expect(calls.skipped).not.toHaveBeenCalled(); + }); + it("delegates non-OpenClaw agent setup and skips openclaw", async () => { const { deps, calls } = createDeps(); const agent = { name: "hermes", displayName: "Hermes" }; @@ -88,9 +110,9 @@ describe("handleAgentSetupState", () => { agent, true, session, - { ctx: true }, + { ctx: true, revalidatePolicyRequirements: undefined }, ); - expect(calls.ensureDashboard).toHaveBeenCalledWith("my-assistant", agent); + expect(calls.ensureDashboard).toHaveBeenCalledWith("my-assistant", agent, undefined); expect(calls.skipped).toHaveBeenCalledWith("openclaw"); expect(calls.setupOpenclaw).not.toHaveBeenCalled(); expect(result.session?.steps.openclaw.status).toBe("skipped"); @@ -103,6 +125,59 @@ describe("handleAgentSetupState", () => { }); }); + it("passes policy revalidation into non-OpenClaw agent setup (#9833)", async () => { + const { deps, calls } = createDeps(); + const revalidatePolicyRequirements = vi.fn(); + + await handleAgentSetupState({ + ...baseOptions(deps, { name: "hermes", displayName: "Hermes" }), + revalidatePolicyRequirements, + }); + + expect(calls.context).toHaveBeenCalledWith(revalidatePolicyRequirements); + expect(calls.handleAgentSetup).toHaveBeenCalledWith( + "my-assistant", + "model", + "provider", + { name: "hermes", displayName: "Hermes" }, + false, + expect.anything(), + { ctx: true, revalidatePolicyRequirements }, + ); + }); + + it("stops dashboard forwarding when authority changes during the first forward (#9833)", async () => { + const refuseDashboardForward = () => { + throw new Error("policy authority changed"); + }; + const policyChecks = new Map([["start optional dashboard forward", refuseDashboardForward]]); + const revalidatePolicyRequirements = vi.fn<(operation: string) => void>((operation) => + policyChecks.get(operation)?.(), + ); + const ensureAgentDashboardForward = vi.fn( + async (_sandboxName: string, _agent: Agent, revalidate?: (operation: string) => void) => { + revalidate?.("start optional dashboard forward"); + return 18791; + }, + ); + const { deps, calls } = createDeps({ ensureAgentDashboardForward }); + + await expect( + handleAgentSetupState({ + ...baseOptions(deps, { name: "hermes", displayName: "Hermes" }), + revalidatePolicyRequirements, + }), + ).rejects.toThrow("policy authority changed"); + + expect(ensureAgentDashboardForward).toHaveBeenCalledWith( + "my-assistant", + { name: "hermes", displayName: "Hermes" }, + revalidatePolicyRequirements, + ); + expect(calls.persistDashboardPort).not.toHaveBeenCalled(); + expect(calls.skipped).not.toHaveBeenCalled(); + }); + it("persists the bumped dashboard port returned by the forward (#8214)", async () => { const { deps, calls } = createDeps({}); calls.ensureDashboard.mockReturnValue(18791); @@ -110,7 +185,7 @@ describe("handleAgentSetupState", () => { await handleAgentSetupState({ ...baseOptions(deps, agent), resume: true }); - expect(calls.ensureDashboard).toHaveBeenCalledWith("my-assistant", agent); + expect(calls.ensureDashboard).toHaveBeenCalledWith("my-assistant", agent, undefined); expect(calls.persistDashboardPort).toHaveBeenCalledWith("my-assistant", 18791); }); @@ -175,7 +250,12 @@ describe("handleAgentSetupState", () => { provider: "provider", model: "model", }); - expect(calls.setupOpenclaw).toHaveBeenCalledWith("my-assistant", "model", "provider"); + expect(calls.setupOpenclaw).toHaveBeenCalledWith( + "my-assistant", + "model", + "provider", + undefined, + ); expect(calls.syncConfig).not.toHaveBeenCalled(); expect(calls.complete).toHaveBeenCalledWith( "openclaw", diff --git a/src/lib/onboard/machine/handlers/agent-setup.ts b/src/lib/onboard/machine/handlers/agent-setup.ts index fbde990101d..d81853afe0f 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.ts @@ -13,6 +13,7 @@ export interface AgentSetupStateOptions { session: Session | null; hermesAuthMethod: string | null; hermesToolGateways: string[]; + revalidatePolicyRequirements?: (operation: string) => void; deps: { handleAgentSetup( sandboxName: string, @@ -23,8 +24,12 @@ export interface AgentSetupStateOptions { session: Session | null, context: unknown, ): Promise; - agentSetupContext(): unknown; - ensureAgentDashboardForward(sandboxName: string, agent: Agent): Promise | number; + agentSetupContext(revalidatePolicyRequirements?: (operation: string) => void): unknown; + ensureAgentDashboardForward( + sandboxName: string, + agent: Agent, + revalidatePolicyRequirements?: (operation: string) => void, + ): Promise | number; persistDashboardPort(sandboxName: string, dashboardPort: number): void; recordStepSkipped(stepName: string): Promise; isOpenclawReady(sandboxName: string): boolean; @@ -37,7 +42,12 @@ export interface AgentSetupStateOptions { stepName: string, updates: { sandboxName: string; provider: string; model: string }, ): Promise; - setupOpenclaw(sandboxName: string, model: string, provider: string): Promise; + setupOpenclaw( + sandboxName: string, + model: string, + provider: string, + revalidatePolicyRequirements?: (operation: string) => void, + ): Promise; syncNemoClawConfigInSandbox(sandboxName: string, provider: string, model: string): void; recordStepComplete(stepName: string, updates: SessionUpdates): Promise; toSessionUpdates(updates: Record): SessionUpdates; @@ -58,9 +68,11 @@ export async function handleAgentSetupState({ session, hermesAuthMethod, hermesToolGateways, + revalidatePolicyRequirements, deps, }: AgentSetupStateOptions): Promise { if (agent) { + revalidatePolicyRequirements?.(`configure the selected agent in sandbox '${sandboxName}'`); await deps.handleAgentSetup( sandboxName, model, @@ -68,17 +80,26 @@ export async function handleAgentSetupState({ agent, resume, session, - deps.agentSetupContext(), + deps.agentSetupContext(revalidatePolicyRequirements), ); // ensureAgentDashboardForward returns the port the dashboard forward was // actually established on, which may be bumped when the default is already // taken by another sandbox. Persist it to the registry so `dashboard-url` // reports the live port instead of the default. Discarding the return here // regressed multi-sandbox onboarding in the machine handler path (#8214). - const dashboardPort = await deps.ensureAgentDashboardForward(sandboxName, agent); + revalidatePolicyRequirements?.(`configure the agent dashboard for sandbox '${sandboxName}'`); + const dashboardPort = await deps.ensureAgentDashboardForward( + sandboxName, + agent, + revalidatePolicyRequirements, + ); if (dashboardPort > 0) { + revalidatePolicyRequirements?.( + `record the agent dashboard port for sandbox '${sandboxName}'`, + ); deps.persistDashboardPort(sandboxName, dashboardPort); } + revalidatePolicyRequirements?.(`record agent setup for sandbox '${sandboxName}'`); session = await deps.recordStepSkipped("openclaw"); return { session, stateResult: advanceTo("policies", { metadata: { state: "agent_setup" } }) }; } @@ -86,20 +107,27 @@ export async function handleAgentSetupState({ const resumeOpenclaw = resume && sandboxName && deps.isOpenclawReady(sandboxName); if (resumeOpenclaw) { deps.skippedStepMessage("openclaw", sandboxName); + revalidatePolicyRequirements?.(`synchronize OpenClaw in sandbox '${sandboxName}'`); deps.syncNemoClawConfigInSandbox(sandboxName, provider, model); + revalidatePolicyRequirements?.(`record resumed OpenClaw setup for sandbox '${sandboxName}'`); await deps.recordStateSkipped("openclaw", { reason: "resume", sandboxName }); + revalidatePolicyRequirements?.(`complete resumed OpenClaw setup for sandbox '${sandboxName}'`); await deps.recordStepComplete( "openclaw", deps.toSessionUpdates({ sandboxName, provider, model, hermesAuthMethod, hermesToolGateways }), ); } else { + revalidatePolicyRequirements?.(`start OpenClaw setup for sandbox '${sandboxName}'`); await deps.startRecordedStep("openclaw", { sandboxName, provider, model }); - await deps.setupOpenclaw(sandboxName, model, provider); + revalidatePolicyRequirements?.(`configure OpenClaw in sandbox '${sandboxName}'`); + await deps.setupOpenclaw(sandboxName, model, provider, revalidatePolicyRequirements); + revalidatePolicyRequirements?.(`complete OpenClaw setup for sandbox '${sandboxName}'`); await deps.recordStepComplete( "openclaw", deps.toSessionUpdates({ sandboxName, provider, model, hermesAuthMethod, hermesToolGateways }), ); } + revalidatePolicyRequirements?.(`record agent setup for sandbox '${sandboxName}'`); session = await deps.recordStepSkipped("agent_setup"); return { session, stateResult: advanceTo("policies", { metadata: { state: "openclaw" } }) }; } diff --git a/src/lib/onboard/machine/handlers/finalization.test.ts b/src/lib/onboard/machine/handlers/finalization.test.ts index 794adf88d86..6774636c927 100644 --- a/src/lib/onboard/machine/handlers/finalization.test.ts +++ b/src/lib/onboard/machine/handlers/finalization.test.ts @@ -115,6 +115,42 @@ async function runFinalizationHandlers( } describe("finalization handlers", () => { + it("refuses finalization before its first mutation when policy authority drifts (#9833)", async () => { + const revalidatePolicyRequirements = vi.fn(() => { + throw new Error("policy authority changed"); + }); + const { deps, calls } = createDeps({ revalidatePolicyRequirements }); + + await expect(handleFinalizationPhase(baseOptions(deps))).rejects.toThrow( + "policy authority changed", + ); + + expect(calls.setDefaultSandbox).not.toHaveBeenCalled(); + expect(calls.removeLegacy).not.toHaveBeenCalled(); + expect(calls.cleanupHost).not.toHaveBeenCalled(); + expect(calls.recoverProcesses).not.toHaveBeenCalled(); + }); + + it("refuses post-verification before pairing or success publication after drift (#9833)", async () => { + const revalidatePolicyRequirements = vi.fn(() => { + throw new Error("policy authority changed"); + }); + const { deps, calls } = createDeps({ revalidatePolicyRequirements }); + + await expect( + handlePostVerifyState({ + ...baseOptions(deps), + agent: { name: "openclaw" }, + portableProfileSelected: true, + }), + ).rejects.toThrow("policy authority changed"); + + expect(calls.settlePortablePairing).not.toHaveBeenCalled(); + expect(calls.verify).not.toHaveBeenCalled(); + expect(calls.dashboard).not.toHaveBeenCalled(); + expect(calls.reportReadiness).not.toHaveBeenCalled(); + }); + it("advances to post verification before deployment verification runs", async () => { const { deps, calls } = createDeps(); @@ -204,6 +240,30 @@ describe("finalization handlers", () => { }); }); + it("passes the bound policy check through pairing settlement (#9833)", async () => { + const revalidatePolicyRequirements = vi.fn(); + const portable = createDeps({ revalidatePolicyRequirements }); + + await runFinalizationHandlers({ + ...baseOptions(portable.deps), + agent: { name: "openclaw" }, + portableProfileSelected: true, + }); + + expect(portable.calls.settlePortablePairing).toHaveBeenCalledExactlyOnceWith("my-assistant", { + portableRequired: true, + revalidatePolicyRequirements, + }); + + const ordinary = createDeps({ revalidatePolicyRequirements }); + await runFinalizationHandlers(baseOptions(ordinary.deps)); + + expect(ordinary.calls.settleOrdinaryPairing).toHaveBeenCalledExactlyOnceWith( + "my-assistant", + revalidatePolicyRequirements, + ); + }); + it("fails selected Portable OpenClaw closed before ordinary writers when registry identity is invalid (#9207)", async () => { const { deps, calls } = createDeps({ settlePortablePairing: vi.fn(async () => ({ @@ -349,12 +409,15 @@ describe("finalization handlers", () => { it("withholds dashboard-port persistence when authority drifts after forwarding (#9833)", async () => { const persistDashboardPort = vi.fn(); - const revalidatePolicyRequirements = vi - .fn<(operation: string) => void>() - .mockImplementationOnce(() => undefined) - .mockImplementationOnce(() => { - throw new Error("policy authority changed"); - }); + const refuseDashboardPersistence = () => { + throw new Error("policy authority changed"); + }; + const policyChecks = new Map([ + ["persist the dashboard port for sandbox 'my-assistant'", refuseDashboardPersistence], + ]); + const revalidatePolicyRequirements = vi.fn<(operation: string) => void>((operation) => + policyChecks.get(operation)?.(), + ); const ensureAgentDashboardForward = vi.fn( (_sandboxName, _agent, revalidate?: (operation: string) => void) => { revalidate?.("start dashboard forward"); @@ -497,6 +560,31 @@ describe("finalization handlers", () => { expect(calls.setDefaultSandbox).toHaveBeenCalledWith("my-assistant"); }); + it("withholds verified deployment output when authority drifts during the probe (#9833)", async () => { + const refuseStatusPublication = () => { + throw new Error("policy authority changed"); + }; + const policyChecks = new Map([ + ["publish deployment status for sandbox 'my-assistant'", refuseStatusPublication], + ]); + const revalidatePolicyRequirements = vi.fn<(operation: string) => void>((operation) => + policyChecks.get(operation)?.(), + ); + const { deps, calls } = createDeps({ revalidatePolicyRequirements }); + + await expect(runFinalizationHandlers(baseOptions(deps))).rejects.toThrow( + "policy authority changed", + ); + + expect(calls.verify).toHaveBeenCalledOnce(); + expect(calls.log).not.toHaveBeenCalled(); + expect(calls.dashboard).not.toHaveBeenCalled(); + expect(calls.reportReadiness).not.toHaveBeenCalled(); + expect(revalidatePolicyRequirements).not.toHaveBeenCalledWith( + "complete onboarding for sandbox 'my-assistant'", + ); + }); + it("removes legacy credentials only when all staged values migrated", async () => { const { deps, calls } = createDeps(); diff --git a/src/lib/onboard/machine/handlers/finalization.ts b/src/lib/onboard/machine/handlers/finalization.ts index cc421b7a033..ed012e74aa3 100644 --- a/src/lib/onboard/machine/handlers/finalization.ts +++ b/src/lib/onboard/machine/handlers/finalization.ts @@ -51,6 +51,7 @@ export interface FinalizationStateOptions void, ): Promise; ordinaryOpenClawPairingIncompleteMessage( sandboxName: string, @@ -61,6 +62,7 @@ export interface FinalizationStateOptions void; }, ): Promise; portablePairingIncompleteMessage( @@ -203,15 +205,18 @@ export async function handleFinalizationState deps.revalidatePolicyRequirements?.(operation); // Reaching finalization means the policy-preset step was confirmed, so it is // now safe to register this sandbox as the default (#4614). + revalidate(`set sandbox '${sandboxName}' as the default`); deps.setDefaultSandbox(sandboxName); const allStagedMigrated = stagedLegacyKeys.length > 0 && stagedLegacyKeys.every((key) => migratedLegacyKeys.has(key)); const unmigratedLegacyKeys = stagedLegacyKeys.filter((key) => !migratedLegacyKeys.has(key)); if (allStagedMigrated) { + revalidate(`remove migrated legacy credentials for sandbox '${sandboxName}'`); deps.removeLegacyCredentialsFile(); } else if (stagedLegacyKeys.length > 0) { deps.error( @@ -223,17 +228,21 @@ export async function handleFinalizationState deps.revalidatePolicyRequirements?.(operation); let verificationDiagnostics: string[] = []; let deploymentHealthy = true; if (portableAgent !== "ordinary") { + revalidate(`settle portable pairing for sandbox '${sandboxName}'`); const pairing = portableAgent === "strict-openclaw" - ? await deps.settlePortablePairing(sandboxName, { - portableRequired: true, - }) + ? await deps.settlePortablePairing( + sandboxName, + deps.revalidatePolicyRequirements + ? { + portableRequired: true, + revalidatePolicyRequirements: deps.revalidatePolicyRequirements, + } + : { portableRequired: true }, + ) : ({ kind: "incomplete", reason: "portable-runtime-identity-invalid", @@ -302,6 +320,7 @@ export async function handlePostVerifyState 0) deps.persistDashboardPort(sandboxName, dashboardPort); + revalidate(`configure the dashboard forward for sandbox '${sandboxName}'`); + const dashboardPort = deps.revalidatePolicyRequirements + ? await deps.ensureAgentDashboardForward( + sandboxName, + agent, + deps.revalidatePolicyRequirements, + ) + : await deps.ensureAgentDashboardForward(sandboxName, agent); + if (dashboardPort > 0) { + revalidate(`record the dashboard port for sandbox '${sandboxName}'`); + deps.persistDashboardPort(sandboxName, dashboardPort); + } } } if (manageDashboard) { @@ -355,23 +389,28 @@ export async function handlePostVerifyState["deps"]> = {}, ) { - let session = createSession(); + let session = createSession({ policyAuthority: "nemoclaw-managed" }); const calls = { load: vi.fn(() => session), activeSandbox: vi.fn(() => ({ messaging: { plan: makeMessagingPlan({ channels: ["telegram"] }) }, + policyAuthority: "nemoclaw-managed" as const, })), mergeChannels: vi.fn( (selected: string[], recorded: string[], active: string[] | null | undefined) => @@ -80,6 +81,7 @@ export function createPolicyHandlerDeps( ...overrides, }, setSession(next: Session) { + if (!next.policyAuthority) next.policyAuthority = "nemoclaw-managed"; session = next; }, getSession: () => session, diff --git a/src/lib/onboard/machine/handlers/policies.test.ts b/src/lib/onboard/machine/handlers/policies.test.ts index eef99efeaff..0a18f35753b 100644 --- a/src/lib/onboard/machine/handlers/policies.test.ts +++ b/src/lib/onboard/machine/handlers/policies.test.ts @@ -25,15 +25,18 @@ describe("handlePoliciesState", () => { const result = await handlePoliciesState(baseOptions(deps)); - expect(calls.smoke).toHaveBeenCalledWith({ - sandboxName: "my-assistant", - provider: "provider", - model: "model", - endpointUrl: "https://example.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", - messagingChannels: ["telegram"], - agent: null, - }); + expect(calls.smoke).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "my-assistant", + provider: "provider", + model: "model", + endpointUrl: "https://example.com/v1", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + messagingChannels: ["telegram"], + agent: null, + beforeSuccess: expect.any(Function), + }), + ); expect(calls.startStep).toHaveBeenCalledWith("policies", { sandboxName: "my-assistant", provider: "provider", @@ -106,9 +109,9 @@ describe("handlePoliciesState", () => { messaging: null, policies: ["npm", "pypi", "discord"], })), - detectUnconfiguredMessagingChannels: vi.fn( - (planChannels: readonly string[]) => [...planChannels], - ), + detectUnconfiguredMessagingChannels: vi.fn((planChannels: readonly string[]) => [ + ...planChannels, + ]), }); await handlePoliciesState({ ...baseOptions(deps), selectedMessagingChannels: [] }); @@ -278,62 +281,65 @@ describe("handlePoliciesState", () => { [null, "openclaw"], [{ name: "hermes" }, "hermes"], [{ name: "langchain-deepagents-code" }, "langchain-deepagents-code"], - ] as const)("reconciles stale local-inference policy for %s while retaining the real provider attachment", async (agent, expectedAgent) => { - const session = createSession({ policyPresets: ["local-inference", "npm"] }); - const { deps, calls, setSession } = createDeps({ - arePolicyPresetsApplied: vi.fn(() => true), - }); - setSession(session); - - await handlePoliciesState({ - ...baseOptions(deps), - resume: true, - provider: "vllm-local", - model: "qwen3.5-9b", - endpointUrl: "https://inference.local/v1", - credentialEnv: null, - hostLocalInferenceRouteOnly: true, - hostLocalInferenceSandboxProofAuthority: { - service: "vllm", - directHostPort: 8000, - directHealthPath: "/health", - toolCallingRequired: true, - }, - agent, - }); - - expect(calls.smoke).toHaveBeenCalledWith( - expect.objectContaining({ + ] as const)( + "reconciles stale local-inference policy for %s while retaining the real provider attachment", + async (agent, expectedAgent) => { + const session = createSession({ policyPresets: ["local-inference", "npm"] }); + const { deps, calls, setSession } = createDeps({ + arePolicyPresetsApplied: vi.fn(() => true), + }); + setSession(session); + + await handlePoliciesState({ + ...baseOptions(deps), + resume: true, provider: "vllm-local", + model: "qwen3.5-9b", endpointUrl: "https://inference.local/v1", - agent, - forceCanonicalRoute: true, - hostLocalInferenceProofAuthority: { + credentialEnv: null, + hostLocalInferenceRouteOnly: true, + hostLocalInferenceSandboxProofAuthority: { service: "vllm", directHostPort: 8000, directHealthPath: "/health", toolCallingRequired: true, }, - }), - ); - expect(calls.prepareResume).toHaveBeenCalledWith( - "my-assistant", - expect.objectContaining({ recordedPolicyPresets: ["npm"], agent: expectedAgent }), - ); - expect(calls.setupPolicies).toHaveBeenCalledWith( - "my-assistant", - expect.objectContaining({ - selectedPresets: ["npm"], - provider: null, - excludedPresets: ["local-inference"], - agent: expectedAgent, - }), - ); - expect(calls.setupPolicies.mock.invocationCallOrder[0]).toBeLessThan( - calls.smoke.mock.invocationCallOrder[0], - ); - expect(calls.skipped).not.toHaveBeenCalled(); - }); + agent, + }); + + expect(calls.smoke).toHaveBeenCalledWith( + expect.objectContaining({ + provider: "vllm-local", + endpointUrl: "https://inference.local/v1", + agent, + forceCanonicalRoute: true, + hostLocalInferenceProofAuthority: { + service: "vllm", + directHostPort: 8000, + directHealthPath: "/health", + toolCallingRequired: true, + }, + }), + ); + expect(calls.prepareResume).toHaveBeenCalledWith( + "my-assistant", + expect.objectContaining({ recordedPolicyPresets: ["npm"], agent: expectedAgent }), + ); + expect(calls.setupPolicies).toHaveBeenCalledWith( + "my-assistant", + expect.objectContaining({ + selectedPresets: ["npm"], + provider: null, + excludedPresets: ["local-inference"], + agent: expectedAgent, + }), + ); + expect(calls.setupPolicies.mock.invocationCallOrder[0]).toBeLessThan( + calls.smoke.mock.invocationCallOrder[0], + ); + expect(calls.skipped).not.toHaveBeenCalled(); + }, + ); it("forces route-only reconciliation when only the live sandbox has stale local-inference", async () => { const { deps, calls } = createDeps({ @@ -369,40 +375,39 @@ describe("handlePoliciesState", () => { expect(calls.skipped).not.toHaveBeenCalled(); }); - it.each([ - null, - { name: "hermes" }, - { name: "langchain-deepagents-code" }, - ] as const)("keeps the inference step recoverable when the post-policy route proof fails for %s", async (agent) => { - const smokeFailure = new Error("exact model route proof failed"); - const { deps, calls } = createDeps({ - verifyCompatibleEndpointSandboxSmoke: vi.fn(() => { - throw smokeFailure; - }), - }); - - await expect( - handlePoliciesState({ - ...baseOptions(deps), - provider: "vllm-local", - model: "qwen3.5-9b", - endpointUrl: "https://inference.local/v1", - credentialEnv: null, - hostLocalInferenceRouteOnly: true, - hostLocalInferenceSandboxProofAuthority: { - service: "vllm", - directHostPort: 8000, - directHealthPath: "/health", - toolCallingRequired: true, - }, - agent, - }), - ).rejects.toBe(smokeFailure); - - expect(calls.setupPolicies).toHaveBeenCalledOnce(); - expect(calls.complete).not.toHaveBeenCalled(); - expect(calls.recordSkip).not.toHaveBeenCalled(); - }); + it.each([null, { name: "hermes" }, { name: "langchain-deepagents-code" }] as const)( + "keeps the inference step recoverable when the post-policy route proof fails for %s", + async (agent) => { + const smokeFailure = new Error("exact model route proof failed"); + const { deps, calls } = createDeps({ + verifyCompatibleEndpointSandboxSmoke: vi.fn(() => { + throw smokeFailure; + }), + }); + + await expect( + handlePoliciesState({ + ...baseOptions(deps), + provider: "vllm-local", + model: "qwen3.5-9b", + endpointUrl: "https://inference.local/v1", + credentialEnv: null, + hostLocalInferenceRouteOnly: true, + hostLocalInferenceSandboxProofAuthority: { + service: "vllm", + directHostPort: 8000, + directHealthPath: "/health", + toolCallingRequired: true, + }, + agent, + }), + ).rejects.toBe(smokeFailure); + + expect(calls.setupPolicies).toHaveBeenCalledOnce(); + expect(calls.complete).not.toHaveBeenCalled(); + expect(calls.recordSkip).not.toHaveBeenCalled(); + }, + ); // Regression for #4621: the sandbox is registered with only create-time/boot // presets, so the effective interactive selection must be written back to the @@ -437,28 +442,144 @@ describe("handlePoliciesState", () => { }); it("verifies external selections without recording NemoClaw preset ownership (#9833)", async () => { - const setupPolicies = vi.fn(async (_name: string, options: SetupOptions) => { - options.onSelection(["dns", "github"]); - return ["dns", "github"]; - }); - const { deps, calls } = createDeps({ + const setupPolicies = vi.fn(async () => ["dns", "github"]); + const revalidatePolicyRequirements = vi.fn(); + const verifySandboxSmoke = vi.fn((options: { beforeSuccess?: () => void }) => + options.beforeSuccess?.(), + ); + const { deps, calls, setSession } = createDeps({ getActiveSandbox: vi.fn(() => ({ messaging: null, policyAuthority: "externally-managed" as const, })), setupPoliciesWithSelection: setupPolicies, + verifyCompatibleEndpointSandboxSmoke: verifySandboxSmoke, }); + setSession(createSession({ policyAuthority: "externally-managed" })); - const result = await handlePoliciesState({ ...baseOptions(deps), resume: true }); + const result = await handlePoliciesState({ + ...baseOptions(deps), + resume: true, + revalidatePolicyRequirements, + }); - expect(setupPolicies).toHaveBeenCalledOnce(); + expect(setupPolicies).not.toHaveBeenCalled(); + expect(calls.prepareResume).not.toHaveBeenCalled(); expect(calls.persistPolicies).not.toHaveBeenCalled(); expect(calls.updateSession).not.toHaveBeenCalled(); + expect(calls.recordSkip).toHaveBeenCalledWith("policies", { + reason: "externally_managed", + }); + expect(verifySandboxSmoke).toHaveBeenCalledWith( + expect.objectContaining({ beforeSuccess: expect.any(Function) }), + ); + expect(revalidatePolicyRequirements).toHaveBeenCalledTimes(4); expect(calls.complete).toHaveBeenCalledWith( "policies", expect.objectContaining({ policyPresets: null }), ); expect(result.appliedPolicyPresets).toEqual([]); + expect(result.stateResult).toEqual( + expect.objectContaining({ metadata: { state: "policies" } }), + ); + }); + + it("refuses managed policy setup before policy mutation when authority drifts (#9833)", async () => { + const refusePolicyMutation = () => { + throw new Error("policy authority changed"); + }; + const policyChecks = new Map([ + ["apply policy presets to sandbox 'my-assistant'", refusePolicyMutation], + ]); + const revalidatePolicyRequirements = vi.fn((operation: string) => + policyChecks.get(operation)?.(), + ); + const { deps, calls } = createDeps(); + + await expect( + handlePoliciesState({ + ...baseOptions(deps), + revalidatePolicyRequirements, + }), + ).rejects.toThrow("policy authority changed"); + + expect(calls.setupPolicies).not.toHaveBeenCalled(); + expect(calls.persistPolicies).not.toHaveBeenCalled(); + expect(calls.complete).not.toHaveBeenCalled(); + }); + + it("uses external session authority when the registry row is missing (#9833)", async () => { + const { deps, calls, setSession } = createDeps({ + getActiveSandbox: vi.fn(() => null), + }); + setSession(createSession({ policyAuthority: "externally-managed" })); + + await handlePoliciesState(baseOptions(deps)); + + expect(calls.setupPolicies).not.toHaveBeenCalled(); + expect(calls.persistPolicies).not.toHaveBeenCalled(); + expect(calls.complete).toHaveBeenCalledWith( + "policies", + expect.objectContaining({ policyPresets: null }), + ); + }); + + it("refuses legacy policy state when no authority is recorded (#9833)", async () => { + const { deps, calls } = createDeps({ + loadSession: () => createSession(), + getActiveSandbox: vi.fn(() => null), + }); + + await expect(handlePoliciesState(baseOptions(deps))).rejects.toThrow( + /policy authority is not recorded/u, + ); + + expect(calls.setupPolicies).not.toHaveBeenCalled(); + expect(calls.persistPolicies).not.toHaveBeenCalled(); + }); + + it("verifies the canonical host-local route under external authority (#9833)", async () => { + const agent = { name: "openclaw" }; + const { deps, calls, setSession } = createDeps({ + getActiveSandbox: vi.fn(() => ({ + messaging: null, + policyAuthority: "externally-managed" as const, + })), + }); + setSession(createSession({ policyAuthority: "externally-managed" })); + + await handlePoliciesState({ + ...baseOptions(deps), + provider: "vllm-local", + model: "qwen3.5-9b", + endpointUrl: "https://inference.local/v1", + credentialEnv: null, + hostLocalInferenceRouteOnly: true, + hostLocalInferenceSandboxProofAuthority: { + service: "vllm", + directHostPort: 8000, + directHealthPath: "/health", + toolCallingRequired: true, + }, + agent, + }); + + expect(calls.smoke).toHaveBeenCalledWith( + expect.objectContaining({ + provider: "vllm-local", + endpointUrl: "https://inference.local/v1", + agent, + forceCanonicalRoute: true, + hostLocalInferenceProofAuthority: { + service: "vllm", + directHostPort: 8000, + directHealthPath: "/health", + toolCallingRequired: true, + }, + }), + ); + expect(calls.setupPolicies).not.toHaveBeenCalled(); + expect(calls.persistPolicies).not.toHaveBeenCalled(); }); it("re-onboard carries the persisted set forward without re-adding removed defaults (#4621)", async () => { diff --git a/src/lib/onboard/machine/handlers/policies.ts b/src/lib/onboard/machine/handlers/policies.ts index 3c5927fc9d8..d8ca4d797af 100644 --- a/src/lib/onboard/machine/handlers/policies.ts +++ b/src/lib/onboard/machine/handlers/policies.ts @@ -2,7 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 import type { SandboxMessagingPlan } from "../../../messaging/manifest"; -import type { SandboxPolicyAuthority } from "../../../adapters/openshell/policy-authority"; +import { + assertRecordedPolicyAuthority, + PolicyAuthorityRefusalError, + type SandboxPolicyAuthority, +} from "../../../adapters/openshell/policy-authority"; import type { Session, SessionUpdates } from "../../../state/onboard-session"; import { getActiveChannelsFromPlan, @@ -57,6 +61,7 @@ export interface PoliciesStateOptions { webSearchSupported: boolean; hermesToolGateways: string[]; agent: Agent; + revalidatePolicyRequirements?: (operation: string) => void; deps: { loadSession(): Session | null; getActiveSandbox(sandboxName: string): ActiveSandboxPolicyState | null | undefined; @@ -81,6 +86,7 @@ export interface PoliciesStateOptions { agent: Agent; forceCanonicalRoute?: boolean; hostLocalInferenceProofAuthority?: HostLocalInferenceSandboxProofAuthority; + beforeSuccess?: () => void; }): void; preparePolicyPresetResumeSelection( sandboxName: string, @@ -122,6 +128,7 @@ export interface PoliciesStateOptions { webSearchSupported: boolean; hermesToolGateways: string[]; onSelection: (policyPresets: string[]) => void; + revalidatePolicyRequirements?: (operation: string) => void; }, ): Promise; updateSession(mutator: (session: Session) => Session | void): Session; @@ -161,6 +168,7 @@ export async function handlePoliciesState({ webSearchSupported, hermesToolGateways, agent, + revalidatePolicyRequirements, deps, }: PoliciesStateOptions): Promise { const latestSession = deps.loadSession(); @@ -173,7 +181,23 @@ export async function handlePoliciesState({ : rawRecordedPolicyPresets; const recordedMessagingChannels = getActiveChannelsFromPlan(latestSession?.messagingPlan); const activeSandbox = deps.getActiveSandbox(sandboxName); - const externallyManagedPolicy = activeSandbox?.policyAuthority === "externally-managed"; + const sessionPolicyAuthority = latestSession?.policyAuthority ?? null; + const registryPolicyAuthority = activeSandbox?.policyAuthority ?? null; + const authorityOperation = `continue policy setup for sandbox '${sandboxName}'`; + if (sessionPolicyAuthority && registryPolicyAuthority) { + assertRecordedPolicyAuthority( + sessionPolicyAuthority, + registryPolicyAuthority, + authorityOperation, + ); + } + const policyAuthority = registryPolicyAuthority ?? sessionPolicyAuthority; + if (!policyAuthority) { + throw new PolicyAuthorityRefusalError( + `Refusing to ${authorityOperation}: policy authority is not recorded. Resume onboarding so NemoClaw can inspect and bind the live authority.`, + ); + } + const externallyManagedPolicy = policyAuthority === "externally-managed"; const effectivePolicyTier = authoritativePolicyTier ?? activeSandbox?.policyTier ?? null; const activePlan = activeSandbox?.messaging?.plan; const activeMessagingChannels = getActiveChannelsFromPlan(activePlan); @@ -217,7 +241,40 @@ export async function handlePoliciesState({ ...(hostLocalInferenceRouteOnly ? { hostLocalInferenceProofAuthority: hostLocalInferenceSandboxProofAuthority ?? undefined } : {}), + beforeSuccess: () => + revalidatePolicyRequirements?.( + `publish verified inference route for sandbox '${sandboxName}'`, + ), + }); + if (externallyManagedPolicy) { + revalidatePolicyRequirements?.( + `verify the externally managed policy for sandbox '${sandboxName}'`, + ); + verifySandboxInferenceRoute(); + revalidatePolicyRequirements?.( + `record verified external policy for sandbox '${sandboxName}'`, + ); + deps.skippedStepMessage("policies", "externally managed"); + await deps.recordStateSkipped("policies", { + reason: "externally_managed", }); + revalidatePolicyRequirements?.( + `record verified external policy for sandbox '${sandboxName}'`, + ); + const session = await deps.recordStepComplete( + "policies", + deps.toSessionUpdates({ sandboxName, provider, model, policyPresets: null }), + ); + return { + session, + recordedMessagingChannels, + selectedMessagingChannels: policyMessagingChannels, + appliedPolicyPresets: [], + stateResult: advanceTo("finalizing", { + metadata: { state: "policies" }, + }), + }; + } if (!hostLocalInferenceRouteOnly) verifySandboxInferenceRoute(); const policyResumeSelection = deps.preparePolicyPresetResumeSelection(sandboxName, { @@ -238,7 +295,6 @@ export async function handlePoliciesState({ (rawRecordedPolicyPresets?.includes("local-inference") === true || deps.arePolicyPresetsApplied(sandboxName, ["local-inference"])); const resumePolicies = - !externallyManagedPolicy && resume && !staleLocalInferencePolicy && !policyResumeSelection.recordedPolicyPresetsNeedReconcile && @@ -263,12 +319,14 @@ export async function handlePoliciesState({ // See #4621. let reflectsLiveAppliedSet = false; if (resumePolicies) { + if (hostLocalInferenceRouteOnly) verifySandboxInferenceRoute(); + revalidatePolicyRequirements?.(`record resumed policy setup for sandbox '${sandboxName}'`); deps.skippedStepMessage("policies", recordedPolicyPresetsForSupport.join(", ")); await deps.recordStateSkipped("policies", { reason: "resume", policyPresets: recordedPolicyPresetsForSupport, }); - if (hostLocalInferenceRouteOnly) verifySandboxInferenceRoute(); + revalidatePolicyRequirements?.(`complete resumed policy setup for sandbox '${sandboxName}'`); session = await deps.recordStepComplete( "policies", deps.toSessionUpdates({ @@ -279,12 +337,14 @@ export async function handlePoliciesState({ }), ); } else { + revalidatePolicyRequirements?.(`start policy setup for sandbox '${sandboxName}'`); await deps.startRecordedStep("policies", { sandboxName, provider, model, policyPresets: recordedPolicyPresetsForSupport, }); + revalidatePolicyRequirements?.(`apply policy presets to sandbox '${sandboxName}'`); appliedPolicyPresets = await deps.setupPoliciesWithSelection(sandboxName, { selectedPresets: Array.isArray(recordedPolicyPresets) ? recordedPolicyPresetsForSupport @@ -303,21 +363,22 @@ export async function handlePoliciesState({ tierName: effectivePolicyTier, webSearchSupported, hermesToolGateways, + revalidatePolicyRequirements, onSelection: (policyPresets) => { // onSelection fires only when a selection was reconciled to the live // gateway (resume reapply, non-interactive custom/suggested, the // interactive tier selector, or exclusion cleanup during skip). An // ordinary skip without exclusions returns before calling it. - if (!externallyManagedPolicy) { - reflectsLiveAppliedSet = true; - deps.updateSession((current) => { - current.policyPresets = policyPresets; - return current; - }); - } + revalidatePolicyRequirements?.( + `record selected policy presets for sandbox '${sandboxName}'`, + ); + reflectsLiveAppliedSet = true; + deps.updateSession((current) => { + current.policyPresets = policyPresets; + return current; + }); }, }); - if (externallyManagedPolicy) appliedPolicyPresets = []; // Reconcile the registry with the *effective* preset selection so a later // recreate/re-onboard carries the operator's exact set forward instead of // reapplying stale tier defaults. Done *before* recordStepComplete so an @@ -328,16 +389,18 @@ export async function handlePoliciesState({ // applied set untouched and would otherwise be clobbered with []. See // #4621. if (reflectsLiveAppliedSet) { + revalidatePolicyRequirements?.(`persist policy presets for sandbox '${sandboxName}'`); deps.persistAppliedPolicyPresets(sandboxName, appliedPolicyPresets); } if (hostLocalInferenceRouteOnly) verifySandboxInferenceRoute(); + revalidatePolicyRequirements?.(`complete policy setup for sandbox '${sandboxName}'`); session = await deps.recordStepComplete( "policies", deps.toSessionUpdates({ sandboxName, provider, model, - policyPresets: externallyManagedPolicy ? null : appliedPolicyPresets, + policyPresets: appliedPolicyPresets, }), ); } diff --git a/src/lib/onboard/machine/handlers/provider-inference-host-local-startup.test.ts b/src/lib/onboard/machine/handlers/provider-inference-host-local-startup.test.ts index 6a177709960..a66fa0ae315 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-host-local-startup.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-host-local-startup.test.ts @@ -409,21 +409,54 @@ describe("provider inference host-local startup selection", () => { async ({ application, service }) => { const model = "qwen3.5-9b"; const provider = service === "ollama" ? "ollama-local" : "vllm-local"; - const setupNim = vi.fn(async () => ({ - ...baseSelection, - provider, - model, - acceleration: "nvidia-gpu", - endpointUrl: null, - credentialEnv: null, - preferredInferenceApi: "openai-completions", - })); + const setupNim = vi.fn(async (...args: unknown[]) => { + const selection = { + ...baseSelection, + provider, + model, + acceleration: "nvidia-gpu" as const, + endpointUrl: null, + credentialEnv: null, + preferredInferenceApi: "openai-completions", + }; + const revalidatePolicyRequirements = args[8] as + | (( + route: { + provider: string; + model: string; + endpointUrl: string | null; + credentialEnv: string | null; + preferredInferenceApi: string | null; + }, + operation: string, + ) => void) + | undefined; + revalidatePolicyRequirements?.( + { + provider, + model, + endpointUrl: null, + credentialEnv: null, + preferredInferenceApi: "openai-completions", + }, + "install managed local runtime", + ); + return selection; + }); const resolver = vi.fn((input: HostLocalInferenceStartupSelectionInput) => hostLocalStartupSelection(input, service), ); + const preflightPolicyRequirements = vi.fn( + (requirements: { provider: string | null; hostLocalInferenceRouteOnly?: boolean }) => { + expect( + requirements.provider !== provider || requirements.hostLocalInferenceRouteOnly === true, + ).toBe(true); + }, + ); const { deps, calls } = createDeps({ setupNim, resolveHostLocalInferenceStartupSelection: resolver, + preflightPolicyRequirements, }); const session = createSession(); calls.complete.mockResolvedValue(session); @@ -465,6 +498,13 @@ describe("provider inference host-local startup selection", () => { : null, ); expect(calls.prepareLocalProviderForInference).not.toHaveBeenCalled(); + expect(preflightPolicyRequirements).toHaveBeenCalledWith( + expect.objectContaining({ + provider, + hostLocalInferenceRouteOnly: true, + operation: "finish successful inference configuration", + }), + ); expect(result).toMatchObject({ endpointUrl: "https://inference.local/v1", endpointSource: "inference-set", diff --git a/src/lib/onboard/machine/handlers/provider-inference-policy-authority.test.ts b/src/lib/onboard/machine/handlers/provider-inference-policy-authority.test.ts index adafc940b3a..e5707c6223e 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-policy-authority.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-policy-authority.test.ts @@ -111,4 +111,33 @@ describe("provider inference policy authority", () => { expect(calls.complete).toHaveBeenCalledWith("provider_selection", expect.any(Object)); expect(calls.complete).not.toHaveBeenCalledWith("inference", expect.any(Object)); }); + + it("withholds resumed provider reuse output when policy authority changes (#9833)", async () => { + const session = createSession({ + provider: "ollama-local", + model: "llama3.1", + credentialEnv: null, + }); + session.steps.provider_selection.status = "complete"; + const refuseReusePublication = () => { + throw new Error("policy authority changed"); + }; + const policyChecks = new Map([["record resumed provider selection", refuseReusePublication]]); + const { deps, calls } = createDeps({ + isInferenceRouteReady: vi.fn(() => true), + preflightPolicyRequirements: (input) => policyChecks.get(input.operation)?.(), + }); + + await expect( + handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + sandboxName: "my-assistant", + }), + ).rejects.toThrow("policy authority changed"); + + expect(calls.skipped).not.toHaveBeenCalled(); + expect(calls.log).not.toHaveBeenCalledWith(expect.stringContaining("Reusing sandbox name")); + expect(calls.recordSkip).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 9cf48fa871a..d52177b83bb 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -169,6 +169,7 @@ export interface ProviderInferenceStateOptions { hermesToolGateways: readonly string[]; gpuPassthrough: boolean; provider: string | null; + hostLocalInferenceRouteOnly?: boolean; webSearchConfig: WebSearchConfig | null; observabilityEnabled: boolean; operation: string; @@ -709,6 +710,32 @@ function endpointSourceForCurrentUrl( : endpointSource; } +function resolvedHostLocalPolicyRouteEvidence( + setupOptions: HostLocalInferenceSetupOptions, + provider: string, + route: { + endpointUrl: string | null; + endpointSource: InferenceEndpointSource | null; + onboardEndpointUrl: string | null; + }, +): { + routeOnly: boolean; + proofAuthority: HostLocalInferenceSandboxProofAuthority | null; + routeKnown: boolean; +} | null { + if (setupOptions.hostLocalInference) { + const resolvedRoute = resolvedHostLocalInferenceRoute(setupOptions.hostLocalInference, route); + return { + routeOnly: resolvedRoute.routeOnly, + proofAuthority: resolvedRoute.proofAuthority, + routeKnown: true, + }; + } + return isHostLocalInferenceProvider(provider) + ? { routeOnly: false, proofAuthority: null, routeKnown: true } + : null; +} + function hasActiveMessagingChannels( selectedMessagingChannels: string[], session: Session | null, @@ -1060,9 +1087,74 @@ export async function handleProviderInferenceState({ let endpointTrustedPrivateCapability: TrustedPrivateEndpointCapability | undefined; let inferenceCapabilityCache: OnboardInferenceCapabilityCache | undefined; let vllmModelIdentity: string | undefined; - let hostLocalInferenceRouteOnly = false; - let hostLocalInferenceProofAuthority: HostLocalInferenceSandboxProofAuthority | null = null; const effectiveResume = resume && !fresh; + let hostLocalInferenceRouteOnly = isCanonicalHostLocalResume({ + effectiveResume, + provider: provider ?? "", + endpointUrl, + endpointSource, + }); + let hostLocalInferenceRouteKnown = + !isHostLocalInferenceProvider(provider ?? "") || hostLocalInferenceRouteOnly; + let hostLocalInferenceProofAuthority: HostLocalInferenceSandboxProofAuthority | null = null; + const hostLocalInferenceResolutionCache = new Map< + string, + HostLocalInferenceStartupSelection | null + >(); + const resolveHostLocalInferenceStartupSelection: HostLocalInferenceStartupSelectionResolver = ( + input, + ) => { + const key = JSON.stringify(input); + if (hostLocalInferenceResolutionCache.has(key)) { + return hostLocalInferenceResolutionCache.get(key) ?? null; + } + const selection = deps.resolveHostLocalInferenceStartupSelection(input); + hostLocalInferenceResolutionCache.set(key, selection); + return selection; + }; + let prospectiveHostLocalPolicyRoute: { + sandboxName: string; + provider: string; + model: string; + setupOptions: HostLocalInferenceSetupOptions; + } | null = null; + const readProspectiveHostLocalPolicyRoute = () => prospectiveHostLocalPolicyRoute; + const resolveProspectiveHostLocalPolicyRoute = (route: ProviderInferenceProbeRoute): void => { + const routeProvider = route.provider?.trim() ?? ""; + const routeModel = route.model?.trim() ?? ""; + if (!isHostLocalInferenceProvider(routeProvider) || !sandboxName || !routeModel) { + hostLocalInferenceRouteOnly = false; + hostLocalInferenceProofAuthority = null; + hostLocalInferenceRouteKnown = true; + prospectiveHostLocalPolicyRoute = null; + return; + } + const setupOptions = hostLocalInferenceSetupOptions(resolveHostLocalInferenceStartupSelection, { + application: agentName(agent), + sandboxName, + provider: routeProvider, + model: routeModel, + acceleration: selectedHostLocalOllamaAcceleration(gpu, gpuPassthrough), + requireToolCalling: true, + freshRequireToolCalling: true, + allowPublishedResume: false, + recover: false, + }); + const resolvedRoute = resolvedHostLocalInferenceRoute(setupOptions.hostLocalInference, { + endpointUrl: route.endpointUrl ?? null, + endpointSource, + onboardEndpointUrl, + }); + hostLocalInferenceRouteOnly = resolvedRoute.routeOnly; + hostLocalInferenceProofAuthority = resolvedRoute.proofAuthority; + hostLocalInferenceRouteKnown = true; + prospectiveHostLocalPolicyRoute = { + sandboxName, + provider: routeProvider, + model: routeModel, + setupOptions, + }; + }; const reusableResumeSandboxName = provenResumeSandboxName( session, sandboxName, @@ -1076,7 +1168,11 @@ export async function handleProviderInferenceState({ const revalidatePolicyRequirements = ( operation: string, requiredProvider: string | null = provider, - ): void => + ): void => { + const routeKnownForProvider = + requiredProvider === provider + ? hostLocalInferenceRouteKnown + : prospectiveHostLocalPolicyRoute?.provider === requiredProvider; deps.preflightPolicyRequirements({ gatewayName, sandboxName, @@ -1085,10 +1181,12 @@ export async function handleProviderInferenceState({ hermesToolGateways, gpuPassthrough, provider: requiredProvider, + hostLocalInferenceRouteOnly: routeKnownForProvider && hostLocalInferenceRouteOnly, webSearchConfig, observabilityEnabled, operation, }); + }; revalidatePolicyRequirements("select an inference provider"); @@ -1133,7 +1231,7 @@ export async function handleProviderInferenceState({ effectiveResume, endpointUrl, endpointSource, - resolver: deps.resolveHostLocalInferenceStartupSelection, + resolver: resolveHostLocalInferenceStartupSelection, }); let shouldRecordProviderSelection = false; // A review interruption selected a provider but did not configure its @@ -1229,12 +1327,12 @@ export async function handleProviderInferenceState({ forceInferenceSetup = true; deps.log(" [resume] Refreshing compatible-endpoint inference route for messaging."); } + revalidatePolicyRequirements("record resumed provider selection"); deps.skippedStepMessage("provider_selection", `${provider} / ${model}`); const selectedAgentName = (agent as { name?: string } | null)?.name; if ((!selectedAgentName || selectedAgentName === "openclaw") && reusableResumeSandboxName) { deps.log(` [resume] Reusing sandbox name: ${reusableResumeSandboxName}.`); } - revalidatePolicyRequirements("record resumed provider selection"); await deps.recordStateSkipped("provider_selection", { reason: "resume", provider, @@ -1296,11 +1394,24 @@ export async function handleProviderInferenceState({ return preflight.ok || isAdvisoryGatewayRouteConflict(preflight.result); }, providerRecovery.sessionId, - (route, operation) => revalidatePolicyRequirements(operation, route.provider), + (route, operation) => { + resolveProspectiveHostLocalPolicyRoute(route); + revalidatePolicyRequirements(operation, route.provider ?? null); + }, ), ); model = selection.model; provider = selection.provider; + const selectedProspectiveHostLocalPolicyRoute = readProspectiveHostLocalPolicyRoute(); + if ( + selectedProspectiveHostLocalPolicyRoute?.provider !== provider || + selectedProspectiveHostLocalPolicyRoute.model !== model + ) { + hostLocalInferenceRouteOnly = false; + hostLocalInferenceProofAuthority = null; + hostLocalInferenceRouteKnown = !isHostLocalInferenceProvider(provider); + prospectiveHostLocalPolicyRoute = null; + } endpointUrl = selection.endpointUrl; credentialEnv = selection.credentialEnv; hermesAuthMethod = selection.hermesAuthMethod; @@ -1411,9 +1522,10 @@ export async function handleProviderInferenceState({ }); const acceptedHostLocalResume = effectiveResume && resumeProviderSelection && isHostLocalInferenceProvider(selectedProvider); + const cachedProspectiveHostLocalPolicyRoute = readProspectiveHostLocalPolicyRoute(); const resolveCachedHostLocalInferenceSetupOptions = createCachedHostLocalInferenceSetupResolver( { - resolver: deps.resolveHostLocalInferenceStartupSelection, + resolver: resolveHostLocalInferenceStartupSelection, application: agentName(agent), provider: selectedProvider, model: selectedModel, @@ -1428,7 +1540,15 @@ export async function handleProviderInferenceState({ recordToolCallingRequirement: (required) => { allowToolsIncompatible = !required; }, - initial: earlyManagedLlamaLifecycleSelection ?? undefined, + initial: + earlyManagedLlamaLifecycleSelection ?? + (cachedProspectiveHostLocalPolicyRoute?.provider === selectedProvider && + cachedProspectiveHostLocalPolicyRoute.model === selectedModel + ? { + sandboxName: cachedProspectiveHostLocalPolicyRoute.sandboxName, + setupOptions: cachedProspectiveHostLocalPolicyRoute.setupOptions, + } + : undefined), }, ); const hostLocalResume = await resolveHostLocalResumeSetup({ @@ -1441,6 +1561,16 @@ export async function handleProviderInferenceState({ }); sandboxName = hostLocalResume.sandboxName; const resumeHostLocalInferenceSetupOptions = hostLocalResume.setupOptions; + const resumedHostLocalPolicyRouteEvidence = resolvedHostLocalPolicyRouteEvidence( + resumeHostLocalInferenceSetupOptions, + selectedProvider, + { endpointUrl, endpointSource, onboardEndpointUrl }, + ); + if (resumedHostLocalPolicyRouteEvidence) { + hostLocalInferenceRouteOnly = resumedHostLocalPolicyRouteEvidence.routeOnly; + hostLocalInferenceProofAuthority = resumedHostLocalPolicyRouteEvidence.proofAuthority; + hostLocalInferenceRouteKnown = resumedHostLocalPolicyRouteEvidence.routeKnown; + } const resumeInference = canResumeInferenceRoute({ needsBedrockRuntimeAdapter, hasHostLocalInference: Boolean(resumeHostLocalInferenceSetupOptions.hostLocalInference), @@ -1692,6 +1822,13 @@ export async function handleProviderInferenceState({ const confirmedSandboxName = review.sandboxName; activeHostLocalInferenceSetupOptions = resolveCachedHostLocalInferenceSetupOptions(confirmedSandboxName); + const prospectiveHostLocalRoute = resolvedHostLocalInferenceRoute( + activeHostLocalInferenceSetupOptions.hostLocalInference, + { endpointUrl, endpointSource, onboardEndpointUrl }, + ); + hostLocalInferenceRouteOnly = prospectiveHostLocalRoute.routeOnly; + hostLocalInferenceProofAuthority = prospectiveHostLocalRoute.proofAuthority; + hostLocalInferenceRouteKnown = true; const freshManagedOllama = activeHostLocalInferenceSetupOptions.hostLocalInference?.request.service === "ollama" && "managed" in activeHostLocalInferenceSetupOptions.hostLocalInference.request; diff --git a/src/lib/onboard/machine/handlers/sandbox.test.ts b/src/lib/onboard/machine/handlers/sandbox.test.ts index c81c482e04a..73199d9c65b 100644 --- a/src/lib/onboard/machine/handlers/sandbox.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox.test.ts @@ -134,6 +134,9 @@ describe("handleSandboxState", () => { }); expect(calls.createSandbox.mock.calls[0]?.at(-1)).toMatchObject({ endpointSource: null }); + expect(calls.preflightPolicyRequirements).toHaveBeenCalledWith( + expect.objectContaining({ hostLocalInferenceRouteOnly: true }), + ); }); it("records credential-provider bindings and the resource-profile decision in the checkpoint (#7022)", async () => { diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index e0d0e9aafe6..ba6a799d4e1 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -313,6 +313,7 @@ export interface SandboxStateOptions< hermesToolGateways: readonly string[]; gpuPassthrough: boolean; provider: string | null; + hostLocalInferenceRouteOnly?: boolean; webSearchConfig: WebSearchConfig | null; observabilityEnabled: boolean; operation: string; @@ -1481,6 +1482,7 @@ class SandboxStateFlow< ), gpuPassthrough: session?.gpuPassthrough === true, provider: this.options.provider, + hostLocalInferenceRouteOnly: this.options.hostLocalInferenceRouteOnly === true, webSearchConfig, observabilityEnabled: session?.observabilityEnabled === true, operation, diff --git a/src/lib/onboard/openclaw-setup.test.ts b/src/lib/onboard/openclaw-setup.test.ts index 924e825f7aa..c984d96cf22 100644 --- a/src/lib/onboard/openclaw-setup.test.ts +++ b/src/lib/onboard/openclaw-setup.test.ts @@ -48,4 +48,34 @@ describe("OpenClaw sandbox setup", () => { fs.rmSync(tempDir, { force: true, recursive: true }); } }); + + it("withholds setup success when policy authority changes during config sync (#9833)", async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-setup-")); + const scriptFile = path.join(tempDir, "sync.sh"); + fs.writeFileSync(scriptFile, "set -e\n", { mode: 0o600 }); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + try { + const setup = createOpenclawSetup({ + step: vi.fn(), + agentProductName: () => "OpenClaw", + getProviderSelectionConfig: () => ({ provider: "vllm-local" }), + buildSandboxConfigSyncScript: () => "set -e", + writeSandboxConfigSyncFile: () => scriptFile, + run: vi.fn(), + openshellArgv: (args) => ["/usr/bin/openshell", ...args], + cleanupTempDir: vi.fn(), + }); + + await expect( + setup("spark-box", "model", "provider", () => { + throw new Error("policy authority changed"); + }), + ).rejects.toThrow("policy authority changed"); + + expect(log.mock.calls.flat().join("\n")).not.toContain("gateway launched"); + } finally { + log.mockRestore(); + fs.rmSync(tempDir, { force: true, recursive: true }); + } + }); }); diff --git a/src/lib/onboard/openclaw-setup.ts b/src/lib/onboard/openclaw-setup.ts index 4772134fc96..121a1667677 100644 --- a/src/lib/onboard/openclaw-setup.ts +++ b/src/lib/onboard/openclaw-setup.ts @@ -21,6 +21,7 @@ export function createOpenclawSetup(deps: OpenclawSetupDeps) { sandboxName: string, model: string, provider: string, + revalidatePolicyRequirements?: (operation: string) => void, ): Promise { deps.step(7, 8, `Setting up ${deps.agentProductName()} inside sandbox`); @@ -43,6 +44,7 @@ export function createOpenclawSetup(deps: OpenclawSetupDeps) { } } + revalidatePolicyRequirements?.(`publish OpenClaw setup for sandbox '${sandboxName}'`); console.log(` ✓ ${deps.agentProductName()} gateway launched inside sandbox`); }; } diff --git a/src/lib/onboard/policy-authority/preflight.test.ts b/src/lib/onboard/policy-authority/preflight.test.ts index bf7811fff8a..bff3b1834b4 100644 --- a/src/lib/onboard/policy-authority/preflight.test.ts +++ b/src/lib/onboard/policy-authority/preflight.test.ts @@ -26,6 +26,19 @@ describe("sandbox policy authority preflight", () => { ).toEqual(["github", "local-inference", "tavily", "observability-otlp-local"]); }); + it("does not require a local-inference preset for a proven route-only provider (#9833)", () => { + expect( + requiredOnboardPolicyPresets({ + additionalPresets: ["github"], + provider: "vllm-local", + hostLocalInferenceRouteOnly: true, + webSearchConfig: null, + agentName: "openclaw", + observabilityEnabled: false, + }), + ).toEqual(["github"]); + }); + it("uses live sandbox metadata and accepts externally supplied requirements (#9833)", () => { const inspectSandbox = vi.fn(() => ({ authority: "externally-managed" as const, diff --git a/src/lib/onboard/policy-authority/preflight.ts b/src/lib/onboard/policy-authority/preflight.ts index 44eaea7dd19..5d40defb8c4 100644 --- a/src/lib/onboard/policy-authority/preflight.ts +++ b/src/lib/onboard/policy-authority/preflight.ts @@ -142,6 +142,7 @@ type ProviderPolicyRequirements = { readonly hermesToolGateways: readonly string[]; readonly gpuPassthrough: boolean; readonly provider: string | null; + readonly hostLocalInferenceRouteOnly?: boolean; readonly webSearchConfig: WebSearchConfig | null; readonly observabilityEnabled: boolean; readonly operation: string; @@ -210,6 +211,7 @@ export function createOnboardPolicyAuthorityBindings Promise; readonly preflightPolicyRequirements: (requirements: ProviderPolicyRequirements) => void; @@ -222,43 +224,50 @@ export function createOnboardPolicyAuthorityBindings - prepareInitialSandboxCreatePolicy( - runtime.agentOnboard.getAgentPolicyPath(requirements.agent) ?? - path.join(runtime.ROOT, "nemoclaw-blueprint", "policies", "openclaw-sandbox.yaml"), - [...requirements.selectedMessagingChannels], - { - directGpu: requirements.gpuPassthrough, - additionalPresets: requiredOnboardPolicyPresets({ - additionalPresets: requirements.hermesToolGateways, - provider: requirements.provider, - webSearchConfig: requirements.webSearchConfig, + qualifySandboxPolicyAuthority( + { + sandboxName, + gatewayName: requirements.gatewayName, + liveExists: observed.liveExists, + recordedAuthorities: [ + observed.existingEntry?.policyAuthority, + runtime.onboardSession.loadSession()?.policyAuthority, + ], + operation: requirements.operation, + prepareRequiredPolicy: () => + prepareInitialSandboxCreatePolicy( + runtime.agentOnboard.getAgentPolicyPath(requirements.agent) ?? + path.join(runtime.ROOT, "nemoclaw-blueprint", "policies", "openclaw-sandbox.yaml"), + [...requirements.selectedMessagingChannels], + { + directGpu: requirements.gpuPassthrough, + additionalPresets: requiredOnboardPolicyPresets({ + additionalPresets: requirements.hermesToolGateways, + provider: requirements.provider, + hostLocalInferenceRouteOnly: requirements.hostLocalInferenceRouteOnly, + webSearchConfig: requirements.webSearchConfig, + agentName: requirements.agent.name, + observabilityEnabled: requirements.observabilityEnabled, + }), agentName: requirements.agent.name, - observabilityEnabled: requirements.observabilityEnabled, - }), - agentName: requirements.agent.name, - policyTier: observed.existingEntry?.policyTier ?? policyTier, - baselineExclusions: observed.existingEntry?.baselineExclusions ?? [], - }, - ), - }); + policyTier: observed.existingEntry?.policyTier ?? policyTier, + baselineExclusions: observed.existingEntry?.baselineExclusions ?? [], + }, + ), + }, + inspectionDeps, + ); }; return { async bindPolicyAuthority(gatewayName, session) { - const inspection = qualifyGlobalPolicyAuthority({ - gatewayName, - recordedAuthority: session?.policyAuthority, - operation: "continue onboarding after gateway setup", - }); + const inspection = qualifyGlobalPolicyAuthority( + { + gatewayName, + recordedAuthority: session?.policyAuthority, + operation: "continue onboarding after gateway setup", + }, + inspectionDeps, + ); return runtime.onboardSession.updateSession((current) => { current.policyAuthority = inspection.authority; if (inspection.authority === "externally-managed") current.policyPresets = null; @@ -274,6 +283,7 @@ export function createOnboardPolicyAuthorityBindings { }); }); + it("refuses tier attribution when authority changes during the prompt (#9833)", async () => { + const { deps, syncPresetSelection } = createHarness(); + deps.isNonInteractive.mockReturnValue(false); + const refuseTierAttribution = () => { + throw new Error("policy authority changed"); + }; + const policyChecks = new Map([ + ["record the policy tier for sandbox 'alpha'", refuseTierAttribution], + ]); + 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.selectPolicyTier).toHaveBeenCalledOnce(); + expect(deps.setPolicyTier).not.toHaveBeenCalled(); + 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(); + syncPresetSelection.mockImplementation(() => { + throw new Error("policy authority changed"); + }); + + await expect( + setupPoliciesWithSelection(deps, "alpha", { + selectedPresets: ["npm"], + onSelection, + }), + ).rejects.toThrow("policy authority changed"); + + expect(onSelection).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/policy-selection.ts b/src/lib/onboard/policy-selection.ts index ed31518d272..33700ed335c 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -122,6 +122,7 @@ export type SetupPolicySelectionOptions = { disabledChannels?: string[] | null; /** Process-local exclusions imposed by a narrower runtime route authority. */ excludedPresets?: readonly string[]; + revalidatePolicyRequirements?: (operation: string) => void; }; export type SetupPolicySelectionDeps = { @@ -424,6 +425,9 @@ async function setupPoliciesWithSelectionInner( OBSERVABILITY_OTLP_LOCAL_POLICY_PRESET, ) === true; if (customOwnsObservability) { + options.revalidatePolicyRequirements?.( + `remove built-in policy attribution from sandbox '${sandboxName}'`, + ); deps.policies.removeBuiltinPresetAttribution?.( sandboxName, OBSERVABILITY_OTLP_LOCAL_POLICY_PRESET, @@ -509,11 +513,11 @@ async function setupPoliciesWithSelectionInner( if (selectedPresets !== null) { const resumeSelection = chosen || []; refuseInPlacePersonalRemoval(personalAlreadyActive, resumeSelection); - if (onSelection) onSelection(resumeSelection); requireSandboxReady(deps, sandboxName, "before"); deps.note(` [resume] Reapplying policy presets: ${resumeSelection.join(", ")}`); deps.syncPresetSelection(sandboxName, currentAppliedPresets, resumeSelection); requireSandboxReady(deps, sandboxName, "after"); + if (onSelection) onSelection(resumeSelection); return resumeSelection; } @@ -521,6 +525,7 @@ async function setupPoliciesWithSelectionInner( if (personalAlreadyActive && tierName !== PERSONAL_POLICY_TIER_NAME) { refuseInPlacePersonalRemoval(personalAlreadyActive, []); } + options.revalidatePolicyRequirements?.(`record the policy tier for sandbox '${sandboxName}'`); deps.setPolicyTier?.(sandboxName, tierName); const personalTier = tierName === PERSONAL_POLICY_TIER_NAME; const suggestions = excludePresets( @@ -562,7 +567,6 @@ async function setupPoliciesWithSelectionInner( retainedPresets.some((name, index) => name !== currentAppliedPresets[index]); if (selectionChanged) { refuseInPlacePersonalRemoval(personalAlreadyActive, retainedPresets); - if (onSelection) onSelection(retainedPresets); requireSandboxReady(deps, sandboxName, "before"); deps.note( personalTier @@ -571,6 +575,7 @@ async function setupPoliciesWithSelectionInner( ); deps.syncPresetSelection(sandboxName, currentAppliedPresets, retainedPresets); requireSandboxReady(deps, sandboxName, "after"); + if (onSelection) onSelection(retainedPresets); return retainedPresets; } deps.note(" [non-interactive] Skipping optional policy presets."); @@ -649,11 +654,11 @@ async function setupPoliciesWithSelectionInner( } refuseInPlacePersonalRemoval(personalAlreadyActive, chosen); - if (onSelection) onSelection(chosen); requireSandboxReady(deps, sandboxName, "before"); deps.note(` [non-interactive] Applying policy presets: ${chosen.join(", ")}`); deps.syncPresetSelection(sandboxName, currentAppliedPresets, chosen); requireSandboxReady(deps, sandboxName, "after"); + if (onSelection) onSelection(chosen); return chosen; } @@ -692,7 +697,6 @@ async function setupPoliciesWithSelectionInner( ); refuseInPlacePersonalRemoval(personalAlreadyActive, interactiveChoice); - if (onSelection) onSelection(interactiveChoice); requireSandboxReady(deps, sandboxName, "before"); const accessByName: Record = {}; @@ -702,5 +706,6 @@ async function setupPoliciesWithSelectionInner( } deps.syncPresetSelection(sandboxName, currentAppliedPresets, interactiveChoice, accessByName); requireSandboxReady(deps, sandboxName, "after"); + if (onSelection) onSelection(interactiveChoice); return interactiveChoice; } diff --git a/src/lib/onboard/sandbox-create/orchestration.test.ts b/src/lib/onboard/sandbox-create/orchestration.test.ts index cf3463f5045..548e60b7386 100644 --- a/src/lib/onboard/sandbox-create/orchestration.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration.test.ts @@ -469,279 +469,3 @@ describe("sandbox create policy authority checks", () => { expect(deleteCreatedSandbox).not.toHaveBeenCalled(); }); }); - -describe("sandbox create policy authority checks", () => { - const CREATED_IDENTITY = "a".repeat(64); - const REPLACEMENT_IDENTITY = "b".repeat(64); - const createdObservation = { - state: "ready" as const, - liveIdentityFingerprint: CREATED_IDENTITY, - }; - - it("refuses sandbox creation before mutation when the final check fails (#9833)", async () => { - const create = vi.fn(async () => "created"); - - await expect( - runSandboxCreateWithPolicyAuthorityChecks({ - sandboxName: "alpha", - revalidate: () => { - throw new Error("external policy authority must supply the selected route"); - }, - create, - captureCreatedSandboxLiveIdentity: vi.fn(() => CREATED_IDENTITY), - observeCreatedSandbox: vi.fn(() => createdObservation), - cleanupTemporarySources: vi.fn(), - deleteCreatedSandbox: vi.fn(), - waitForCreatedSandboxAbsence: vi.fn(() => true), - }), - ).rejects.toThrow(/external policy authority must supply/u); - expect(create).not.toHaveBeenCalled(); - }); - - it("checks the named Ready sandbox before registration can continue (#9833)", async () => { - const events: string[] = []; - const result = await runSandboxCreateWithPolicyAuthorityChecks({ - sandboxName: "alpha", - revalidate: (sandboxIsLive) => events.push(sandboxIsLive ? "ready-check" : "create-check"), - create: async () => { - events.push("create"); - return "created"; - }, - captureCreatedSandboxLiveIdentity: () => { - events.push("capture-identity"); - return CREATED_IDENTITY; - }, - observeCreatedSandbox: vi.fn(() => createdObservation), - cleanupTemporarySources: vi.fn(), - deleteCreatedSandbox: vi.fn(), - waitForCreatedSandboxAbsence: vi.fn(() => true), - }); - events.push("register"); - - expect(result).toBe("created"); - expect(events).toEqual([ - "create-check", - "create", - "capture-identity", - "ready-check", - "register", - ]); - }); - - it("removes create sources and the live sandbox when final authority validation fails (#9833)", async () => { - const events: string[] = []; - const validationError = new Error("external policy authority changed"); - const revalidate = vi - .fn() - .mockImplementationOnce(() => events.push("create-check")) - .mockImplementationOnce(() => { - events.push("ready-check"); - throw validationError; - }); - - await expect( - runSandboxCreateWithPolicyAuthorityChecks({ - sandboxName: "alpha", - revalidate, - create: async () => { - events.push("create"); - return "created"; - }, - captureCreatedSandboxLiveIdentity: () => { - events.push("capture-identity"); - return CREATED_IDENTITY; - }, - observeCreatedSandbox: () => { - events.push("observe-created"); - return createdObservation; - }, - cleanupTemporarySources: () => { - events.push("cleanup-sources"); - }, - deleteCreatedSandbox: () => { - events.push("delete-created"); - }, - waitForCreatedSandboxAbsence: () => { - events.push("prove-absence"); - return true; - }, - }), - ).rejects.toBe(validationError); - - expect(events).toEqual([ - "create-check", - "create", - "capture-identity", - "ready-check", - "cleanup-sources", - "observe-created", - "delete-created", - "prove-absence", - ]); - }); - - it("attempts sandbox deletion when temporary source cleanup fails (#9833)", async () => { - const deleteCreatedSandbox = vi.fn(); - const revalidate = vi - .fn() - .mockImplementationOnce(() => undefined) - .mockImplementationOnce(() => { - throw new Error("external policy authority changed"); - }); - - await expect( - runSandboxCreateWithPolicyAuthorityChecks({ - sandboxName: "alpha", - revalidate, - create: async () => "created", - captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, - observeCreatedSandbox: () => createdObservation, - cleanupTemporarySources: () => { - throw new Error("temporary source cleanup failed"); - }, - deleteCreatedSandbox, - waitForCreatedSandboxAbsence: () => true, - }), - ).rejects.toThrow("cleanup did not complete"); - - expect(deleteCreatedSandbox).toHaveBeenCalledOnce(); - }); - - it("reports incomplete cleanup when an accepted delete leaves the created identity live (#9833)", async () => { - const deleteCreatedSandbox = vi.fn(); - const observeCreatedSandbox = vi.fn(() => createdObservation); - const revalidate = vi - .fn() - .mockImplementationOnce(() => undefined) - .mockImplementationOnce(() => { - throw new Error("external policy authority changed"); - }); - - const error = await runSandboxCreateWithPolicyAuthorityChecks({ - sandboxName: "alpha", - revalidate, - create: async () => "created", - captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, - observeCreatedSandbox, - cleanupTemporarySources: vi.fn(), - deleteCreatedSandbox, - waitForCreatedSandboxAbsence: () => false, - }).catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(AggregateError); - expect((error as AggregateError).errors).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - message: expect.stringContaining("exact absence was not proven"), - }), - ]), - ); - expect(deleteCreatedSandbox).toHaveBeenCalledOnce(); - expect(observeCreatedSandbox).toHaveBeenCalledTimes(2); - }); - - it("does not delete a replacement observed before cleanup (#9833)", async () => { - const deleteCreatedSandbox = vi.fn(); - const waitForCreatedSandboxAbsence = vi.fn(() => true); - const revalidate = vi - .fn() - .mockImplementationOnce(() => undefined) - .mockImplementationOnce(() => { - throw new Error("external policy authority changed"); - }); - - const error = await runSandboxCreateWithPolicyAuthorityChecks({ - sandboxName: "alpha", - revalidate, - create: async () => "created", - captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, - observeCreatedSandbox: () => ({ - state: "ready", - liveIdentityFingerprint: REPLACEMENT_IDENTITY, - }), - cleanupTemporarySources: vi.fn(), - deleteCreatedSandbox, - waitForCreatedSandboxAbsence, - }).catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(AggregateError); - expect((error as AggregateError).errors).toEqual( - expect.arrayContaining([ - expect.objectContaining({ message: expect.stringContaining("live identity changed") }), - ]), - ); - expect(deleteCreatedSandbox).not.toHaveBeenCalled(); - expect(waitForCreatedSandboxAbsence).not.toHaveBeenCalled(); - }); - - it("does not delete a replacement observed after an accepted delete (#9833)", async () => { - const deleteCreatedSandbox = vi.fn(); - const observeCreatedSandbox = vi - .fn() - .mockReturnValueOnce(createdObservation) - .mockReturnValueOnce({ - state: "ready" as const, - liveIdentityFingerprint: REPLACEMENT_IDENTITY, - }); - const revalidate = vi - .fn() - .mockImplementationOnce(() => undefined) - .mockImplementationOnce(() => { - throw new Error("external policy authority changed"); - }); - - const error = await runSandboxCreateWithPolicyAuthorityChecks({ - sandboxName: "alpha", - revalidate, - create: async () => "created", - captureCreatedSandboxLiveIdentity: () => CREATED_IDENTITY, - observeCreatedSandbox, - cleanupTemporarySources: vi.fn(), - deleteCreatedSandbox, - waitForCreatedSandboxAbsence: () => false, - }).catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(AggregateError); - expect((error as AggregateError).errors).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - message: expect.stringContaining("now identifies a replacement"), - }), - ]), - ); - expect(deleteCreatedSandbox).toHaveBeenCalledOnce(); - }); - - it("leaves the named sandbox in place when its created identity was not captured (#9833)", async () => { - const deleteCreatedSandbox = vi.fn(); - const observeCreatedSandbox = vi.fn(() => createdObservation); - const revalidate = vi - .fn() - .mockImplementationOnce(() => undefined) - .mockImplementationOnce(() => { - throw new Error("external policy authority changed"); - }); - - const error = await runSandboxCreateWithPolicyAuthorityChecks({ - sandboxName: "alpha", - revalidate, - create: async () => "created", - captureCreatedSandboxLiveIdentity: () => { - throw new Error("identity probe failed"); - }, - observeCreatedSandbox, - cleanupTemporarySources: vi.fn(), - deleteCreatedSandbox, - waitForCreatedSandboxAbsence: vi.fn(() => true), - }).catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(AggregateError); - expect((error as AggregateError).errors).toEqual( - expect.arrayContaining([ - expect.objectContaining({ message: expect.stringContaining("identity was not captured") }), - ]), - ); - expect(observeCreatedSandbox).not.toHaveBeenCalled(); - expect(deleteCreatedSandbox).not.toHaveBeenCalled(); - }); -}); diff --git a/test/helpers/onboard-final-flow-phases.ts b/test/helpers/onboard-final-flow-phases.ts index f304f42c43f..6308b75c007 100644 --- a/test/helpers/onboard-final-flow-phases.ts +++ b/test/helpers/onboard-final-flow-phases.ts @@ -57,6 +57,20 @@ export type RecorderOverrides = { nimContainer: string | null, agent: Agent | null, ) => void; + reportDeploymentReadiness?: (healthy: boolean) => void; + getActiveSandbox?: PoliciesStateOptions["deps"]["getActiveSandbox"]; + setupPoliciesWithSelection?: PoliciesStateOptions< + Agent | null, + WebSearchConfig + >["deps"]["setupPoliciesWithSelection"]; + persistAppliedPolicyPresets?: PoliciesStateOptions< + Agent | null, + WebSearchConfig + >["deps"]["persistAppliedPolicyPresets"]; + revalidatePolicyRequirements?: ( + context: OnboardFlowContext, + operation: string, + ) => void; }; function cloneSession(session: Session): Session { @@ -183,6 +197,7 @@ export function createPhases( VerifyDeploymentResult >({ branchState, + revalidatePolicyRequirements: recorders.revalidatePolicyRequirements, agentSetupDeps: { handleAgentSetup: vi.fn(async () => { order.push("agent-setup"); @@ -210,8 +225,9 @@ export function createPhases( toSessionUpdates: (updates) => updates as SessionUpdates, }, policiesDeps: { - loadSession: recorders.loadSession ?? (() => createSession()), - getActiveSandbox: () => null, + loadSession: + recorders.loadSession ?? (() => createSession({ policyAuthority: "nemoclaw-managed" })), + getActiveSandbox: recorders.getActiveSandbox ?? (() => null), mergePolicyMessagingChannels: recorders.mergePolicyMessagingChannels ?? ((selected) => selected), detectUnconfiguredMessagingChannels: () => [], @@ -226,10 +242,12 @@ export function createPhases( skippedStepMessage: vi.fn(), recordStateSkipped: recorders.recordStateSkipped ?? vi.fn(async () => createSession()), startRecordedStep: recorders.startRecordedStep ?? vi.fn(async () => undefined), - setupPoliciesWithSelection: vi.fn(async () => { - order.push("policies"); - return ["balanced"]; - }), + setupPoliciesWithSelection: + recorders.setupPoliciesWithSelection ?? + vi.fn(async () => { + order.push("policies"); + return ["balanced"]; + }), updateSession: recorders.updateSession ?? vi.fn((mutator) => mutator(createSession()) ?? createSession()), recordStepComplete: @@ -238,7 +256,7 @@ export function createPhases( sessionWithUpdates(updates), ), toSessionUpdates: (updates) => updates as SessionUpdates, - persistAppliedPolicyPresets: vi.fn(), + persistAppliedPolicyPresets: recorders.persistAppliedPolicyPresets ?? vi.fn(), }, finalization: { stagedLegacyKeys: [], @@ -269,7 +287,7 @@ export function createPhases( ), isDeploymentHealthy: recorders.isDeploymentHealthy ?? ((result: VerifyDeploymentResult) => result.healthy), - reportDeploymentReadiness: vi.fn(), + reportDeploymentReadiness: recorders.reportDeploymentReadiness ?? vi.fn(), getChatUiUrl: () => "http://127.0.0.1:45123", buildVerifyChain: (): DashboardDeliveryChain => ({ accessUrl: "http://127.0.0.1:45123", diff --git a/test/onboard-external-policy-authority-composition.test.ts b/test/onboard-external-policy-authority-composition.test.ts new file mode 100644 index 00000000000..90203f3bc26 --- /dev/null +++ b/test/onboard-external-policy-authority-composition.test.ts @@ -0,0 +1,285 @@ +// 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 { describe, expect, it, vi } from "vitest"; +import YAML from "yaml"; +import { loadAgent } from "../src/lib/agent/defs"; +import { prepareInitialSandboxCreatePolicy } from "../src/lib/onboard/initial-policy"; +import { runFinalOnboardFlowSlice } from "../src/lib/onboard/machine/final-flow-phases"; +import { + createOnboardPolicyAuthorityBindings, + requiredOnboardPolicyPresets, +} from "../src/lib/onboard/policy-authority/preflight"; +import { prepareSandboxCreateLaunch } from "../src/lib/onboard/sandbox-create-launch"; +import { + materializeSandboxCreatePlan, + resolveSandboxCreateIntent, +} from "../src/lib/onboard/sandbox-create-plan"; +import { runSandboxCreateWithPolicyAuthorityChecks } from "../src/lib/onboard/sandbox-create/orchestration"; +import type { SandboxEntry } from "../src/lib/state/registry"; +import { createSession } from "../src/lib/state/onboard-session"; +import { context, createPhases, createRuntimeHarness } from "./helpers/onboard-final-flow-phases"; + +const REPO_ROOT = path.join(import.meta.dirname, ".."); + +describe("external policy authority onboarding composition", () => { + it("completes a fresh flow without policy mutation or attribution (#9833)", async () => { + const sandboxName = "fresh-external"; + const gatewayName = "nemoclaw"; + const provider = "ollama-local"; + const model = "llama3.1"; + const policyTier = "balanced"; + const selectedMessagingChannels = ["slack"]; + const webSearchConfig = { provider: "tavily" as const, fetchEnabled: true }; + const agent = loadAgent("openclaw"); + const basePolicyPath = path.join( + REPO_ROOT, + "nemoclaw-blueprint", + "policies", + "openclaw-sandbox.yaml", + ); + const additionalPresets = requiredOnboardPolicyPresets({ + additionalPresets: [], + provider, + webSearchConfig, + agentName: agent.name, + observabilityEnabled: false, + }); + expect(additionalPresets).toEqual(["local-inference", "tavily"]); + const prepareRequiredPolicy = () => + prepareInitialSandboxCreatePolicy(basePolicyPath, selectedMessagingChannels, { + directGpu: false, + additionalPresets, + agentName: agent.name, + policyTier, + }); + const effectivePolicySource = prepareRequiredPolicy(); + const effectivePolicy = YAML.parse( + fs.readFileSync(effectivePolicySource.policyPath, "utf8"), + ) as { + network_policies: Record; + }; + expect(effectivePolicySource.appliedPresets).toEqual( + expect.arrayContaining(["slack", "local-inference", "tavily"]), + ); + expect(effectivePolicySource.cleanup?.()).toBe(true); + expect(Object.keys(effectivePolicy.network_policies)).toEqual( + expect.arrayContaining(["slack", "local_inference", "tavily"]), + ); + effectivePolicy.network_policies.operator_audit = { + name: "operator_audit", + endpoints: [{ host: "operator.example.test", port: 443, protocol: "rest" }], + }; + + const externalInspection = { + authority: "externally-managed" as const, + effectivePolicy, + }; + const inspectGlobalPolicyAuthority = vi.fn(() => externalInspection); + const inspectSandboxPolicyAuthority = vi.fn(() => externalInspection); + let liveExists = false; + let existingEntry: SandboxEntry | null = null; + let durableSession = createSession({ policyPresets: ["balanced"] }); + const updateSession = vi.fn((mutator: (session: typeof durableSession) => void) => { + mutator(durableSession); + return durableSession; + }); + const bindings = createOnboardPolicyAuthorityBindings( + { + GATEWAY_NAME: gatewayName, + ROOT: REPO_ROOT, + agentDefs: { loadAgent }, + agentOnboard: { getAgentPolicyPath: () => basePolicyPath }, + inspectSandboxForCreate: () => ({ existingEntry, liveExists }), + onboardSession: { + loadSession: () => durableSession, + updateSession, + }, + }, + policyTier, + { inspectGlobalPolicyAuthority, inspectSandboxPolicyAuthority }, + ); + + durableSession = await bindings.bindPolicyAuthority(gatewayName, durableSession); + expect(durableSession.policyAuthority).toBe("externally-managed"); + expect(durableSession.policyPresets).toBeNull(); + + const policyRequirements = { + gatewayName, + sandboxName, + agent, + selectedMessagingChannels, + hermesToolGateways: [], + gpuPassthrough: false, + provider, + webSearchConfig, + observabilityEnabled: false, + operation: `prepare sandbox '${sandboxName}'`, + }; + bindings.preflightPolicyRequirements(policyRequirements); + expect(inspectGlobalPolicyAuthority).toHaveBeenCalledTimes(2); + expect(inspectSandboxPolicyAuthority).not.toHaveBeenCalled(); + + const intent = resolveSandboxCreateIntent({ + basePolicyPath, + sandboxName, + inferenceProvider: provider, + channels: [ + { + name: "slack", + envKey: "SLACK_BOT_TOKEN", + appTokenEnvKey: "SLACK_APP_TOKEN", + label: "Slack", + description: "Slack", + help: "Slack", + }, + ], + enabledChannels: selectedMessagingChannels, + disabledChannelNames: new Set(), + messagingProviderRequests: [], + primaryMessagingCredentialEnvKeys: [], + reusableMessagingChannels: [], + reusableMessagingProviders: [], + hermesToolGateways: [], + sandboxGpuConfig: { sandboxGpuEnabled: false }, + gpuCreateArgs: [], + gpuRoutePlan: "none", + sandboxGpuLogMessage: null, + agentName: agent.name, + policyTier, + }); + const discloseInitialSandboxPolicy = vi.fn(); + const plan = materializeSandboxCreatePlan({ + intent, + fromRef: "example.invalid/openclaw@sha256:abc", + policyAuthority: "externally-managed", + messagingTokenDefs: [], + runProviderPreDeleteCleanup: vi.fn(), + upsertMessagingProviders: vi.fn(() => []), + getHermesToolGatewayProviderName: vi.fn(), + discloseInitialSandboxPolicy, + }); + const launch = prepareSandboxCreateLaunch({ + agent, + chatUiUrl: "", + createArgs: plan.createArgs, + extraPlaceholderKeys: [], + getDashboardForwardPort: () => "", + hermesDashboardState: { config: null, enabled: false }, + manageDashboard: false, + openshellShellCommand: (args) => args.join(" "), + buildEnv: () => ({ OPENSHELL_SANDBOX_POLICY: "/tmp/inherited-policy.yaml" }), + }); + + await expect( + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName, + revalidate: (_sandboxIsLive, operation) => + bindings.preflightPolicyRequirements({ ...policyRequirements, operation }), + create: async () => { + liveExists = true; + existingEntry = { + name: sandboxName, + policyAuthority: "externally-managed", + policyTier, + policies: [], + } as SandboxEntry; + return launch; + }, + captureCreatedSandboxLiveIdentity: () => "a".repeat(64), + observeCreatedSandbox: () => ({ + state: "ready" as const, + liveIdentityFingerprint: "a".repeat(64), + }), + cleanupTemporarySources: vi.fn(), + deleteCreatedSandbox: vi.fn(), + waitForCreatedSandboxAbsence: vi.fn(() => true), + }), + ).resolves.toBe(launch); + + expect(plan.createArgs).not.toContain("--policy"); + expect(plan.createArgs).not.toContain(plan.initialSandboxPolicy.policyPath); + expect(launch.sandboxEnv).not.toHaveProperty("OPENSHELL_SANDBOX_POLICY"); + expect(discloseInitialSandboxPolicy).not.toHaveBeenCalled(); + + Object.assign(durableSession, { + sandboxName, + provider, + model, + observabilityEnabled: false, + machine: { + version: 1, + state: "openclaw", + stateEnteredAt: "2026-08-24T00:00:00.000Z", + revision: 0, + }, + }); + const runtime = createRuntimeHarness(durableSession); + const setupPoliciesWithSelection = vi.fn(async () => ["balanced"]); + const persistAppliedPolicyPresets = vi.fn(); + const policyUpdateSession = vi.fn(() => durableSession); + const reportDeploymentReadiness = vi.fn(); + const revalidationOperations: string[] = []; + const recordStepComplete = vi.fn(async (_stepName: string, updates = {}) => { + Object.assign(durableSession, updates); + return durableSession; + }); + const phases = createPhases("openclaw", [], { + loadSession: () => durableSession, + updateSession: policyUpdateSession, + recordStepComplete, + getActiveSandbox: () => existingEntry, + setupPoliciesWithSelection, + persistAppliedPolicyPresets, + reportDeploymentReadiness, + revalidatePolicyRequirements: (flowContext, operation) => { + revalidationOperations.push(operation); + bindings.revalidatePolicyRequirements( + { ...flowContext, agent: null, session: durableSession }, + operation, + ); + }, + }); + + const finalResult = await runFinalOnboardFlowSlice({ + context: context({ + session: durableSession, + sandboxName, + provider, + model, + selectedMessagingChannels, + hermesToolGateways: [], + webSearchConfig, + }), + runtime: runtime.boundary.getRuntime(), + phases, + recordRepairEvent: vi.fn(async () => durableSession), + }); + + expect(runtime.getSession()).toMatchObject({ + status: "complete", + policyAuthority: "externally-managed", + policyPresets: null, + }); + expect(setupPoliciesWithSelection).not.toHaveBeenCalled(); + expect(persistAppliedPolicyPresets).not.toHaveBeenCalled(); + expect(policyUpdateSession).not.toHaveBeenCalled(); + expect(updateSession).toHaveBeenCalledTimes(1); + expect(inspectSandboxPolicyAuthority).toHaveBeenCalled(); + expect(revalidationOperations).toEqual( + expect.arrayContaining([ + `configure OpenClaw in sandbox '${sandboxName}'`, + `verify the externally managed policy for sandbox '${sandboxName}'`, + `set sandbox '${sandboxName}' as the default`, + `publish deployment status for sandbox '${sandboxName}'`, + `complete onboarding for sandbox '${sandboxName}'`, + ]), + ); + expect(reportDeploymentReadiness).toHaveBeenCalledWith(true); + expect(finalResult.session.status).toBe("complete"); + expect(plan.initialSandboxPolicy.cleanup?.() ?? true).toBe(true); + }); +}); From f71fbf7a73239037a0f4148c12da8d83ac3f7bcd Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 04:21:01 -0700 Subject: [PATCH 14/40] fix(rebuild): preserve external policy authority Signed-off-by: Apurv Kumaria --- .../actions/sandbox/mcp-bridge-contracts.ts | 8 +- ...cp-bridge-rebuild-policy-authority.test.ts | 169 +++++++++ src/lib/actions/sandbox/mcp-bridge-rebuild.ts | 41 ++- src/lib/actions/sandbox/mcp-bridge.ts | 8 +- .../messaging-host-forward-lifecycle.ts | 3 +- .../policy-authority/mcp-requirements.test.ts | 64 ++++ .../policy-authority/mcp-requirements.ts | 83 +++++ .../policy-authority/preflight.test.ts | 185 ++++++++++ .../sandbox/policy-authority/preflight.ts | 191 ++++++++++ .../sandbox/policy-authority/rebuild.test.ts | 335 ++++++++++++++++++ .../sandbox/policy-authority/rebuild.ts | 286 +++++++++++++++ .../sandbox/rebuild-backup-phase.test.ts | 39 ++ .../actions/sandbox/rebuild-backup-phase.ts | 71 ++-- .../rebuild-dcode-mutation-edge.test.ts | 12 +- .../rebuild-dcode-pre-delete-drift.test.ts | 3 +- .../sandbox/rebuild-dcode-preflight.test.ts | 46 +-- .../sandbox/rebuild-dcode-recovery.test.ts | 159 ++++++--- .../sandbox/rebuild-destroy-phase.test.ts | 97 ++--- .../actions/sandbox/rebuild-destroy-phase.ts | 152 +++++++- .../actions/sandbox/rebuild-durable-config.ts | 8 +- .../rebuild-flow-credential-preflight.test.ts | 39 +- .../actions/sandbox/rebuild-flow-helpers.ts | 15 +- .../sandbox/rebuild-flow-lifecycle.test.ts | 212 +++++++++-- .../sandbox/rebuild-flow-recovery.test.ts | 8 +- .../rebuild-flow-shields-window.test.ts | 27 +- .../rebuild-flow-target-credentials.test.ts | 5 +- .../rebuild-hermes-accepted-target.test.ts | 39 ++ .../rebuild-hermes-cron-restore.test.ts | 67 ++-- .../rebuild-hermes-post-restore.test.ts | 99 +++--- .../sandbox/rebuild-hermes-post-restore.ts | 8 +- .../actions/sandbox/rebuild-mcp-phase.test.ts | 137 +++++-- src/lib/actions/sandbox/rebuild-mcp-phase.ts | 24 +- .../sandbox/rebuild-messaging-phase.ts | 4 + ...rebuild-messaging-policy-authority.test.ts | 39 ++ .../sandbox/rebuild-onboard-dependencies.ts | 2 + src/lib/actions/sandbox/rebuild-pipeline.ts | 99 ++++-- .../rebuild-post-restore-phase.test.ts | 109 +++++- .../sandbox/rebuild-post-restore-phase.ts | 97 ++++- .../sandbox/rebuild-preflight-guards.ts | 6 +- .../sandbox/rebuild-preflight-phase.ts | 30 +- .../sandbox/rebuild-recreate-journal.test.ts | 35 ++ .../rebuild-recreate-observability.test.ts | 16 + .../actions/sandbox/rebuild-recreate-phase.ts | 39 +- .../rebuild-recreate-reasoning.test.ts | 1 + .../rebuild-restore-forwarding.test.ts | 6 +- .../sandbox/rebuild-restore-phase.test.ts | 117 ++++-- .../actions/sandbox/rebuild-restore-phase.ts | 108 ++++-- .../sandbox/rebuild-resume-snapshot.test.ts | 10 + .../sandbox/rebuild-shields-finally.test.ts | 36 ++ .../sandbox/rebuild-shields-phase.test.ts | 23 +- .../actions/sandbox/rebuild-shields-phase.ts | 11 +- .../actions/sandbox/rebuild-shields.test.ts | 52 +++ src/lib/actions/sandbox/rebuild-shields.ts | 70 +++- src/lib/agent/definition-types.ts | 4 + src/lib/shields/index.ts | 35 ++ test/helpers/rebuild-flow-dcode-harness.ts | 60 +++- test/helpers/rebuild-flow-generic-harness.ts | 30 +- test/helpers/rebuild-flow-harness.ts | 2 + test/helpers/rebuild-flow-test-support.ts | 5 + 59 files changed, 3181 insertions(+), 505 deletions(-) create mode 100644 src/lib/actions/sandbox/mcp-bridge-rebuild-policy-authority.test.ts create mode 100644 src/lib/actions/sandbox/policy-authority/mcp-requirements.test.ts create mode 100644 src/lib/actions/sandbox/policy-authority/mcp-requirements.ts create mode 100644 src/lib/actions/sandbox/policy-authority/preflight.test.ts create mode 100644 src/lib/actions/sandbox/policy-authority/preflight.ts create mode 100644 src/lib/actions/sandbox/policy-authority/rebuild.test.ts create mode 100644 src/lib/actions/sandbox/policy-authority/rebuild.ts create mode 100644 src/lib/actions/sandbox/rebuild-messaging-policy-authority.test.ts create mode 100644 src/lib/actions/sandbox/rebuild-shields.test.ts 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..fadbbeb5158 --- /dev/null +++ b/src/lib/actions/sandbox/mcp-bridge-rebuild-policy-authority.test.ts @@ -0,0 +1,169 @@ +// 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(), + bridgeState: vi.fn(), + detachProvider: vi.fn(), + discardSafeIncompleteAdds: vi.fn(), + ensureSandboxGatewaySelected: vi.fn(), + getSandboxOrThrow: vi.fn(), + inspectExactDestroyProvider: vi.fn(), + preflightEntryTargets: vi.fn(), + removeGeneratedPolicy: vi.fn(), + restoreRuntime: vi.fn(), + rollbackScrubbedAdapters: vi.fn(), + scrubAdapter: vi.fn(), + setBridgeState: vi.fn(), + waitForDetachedCredential: 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(), + detachProvider: mocks.detachProvider, + preflightMcpEntryTargets: mocks.preflightEntryTargets, + 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"); + +const entry: McpBridgeEntry = { + 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", +}; + +const sandbox: SandboxEntry = { + name: "alpha", + agent: "openclaw", + policyAuthority: "externally-managed", + mcp: { bridges: { github: entry } }, +}; + +describe("MCP rebuild policy authority", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.getSandboxOrThrow.mockReturnValue(sandbox); + mocks.bridgeState.mockImplementation((current: SandboxEntry) => current.mcp?.bridges ?? {}); + mocks.discardSafeIncompleteAdds.mockResolvedValue(sandbox); + mocks.detachProvider.mockReturnValue("detached"); + mocks.rollbackScrubbedAdapters.mockReturnValue([]); + }); + + 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("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 f5dcf11f8a7..eddb28ed1f7 100644 --- a/src/lib/actions/sandbox/mcp-bridge-rebuild.ts +++ b/src/lib/actions/sandbox/mcp-bridge-rebuild.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { McpBridgeEntry } from "../../state/registry"; +import { isPolicyAuthorityRefusalError } from "../../adapters/openshell/policy-authority"; import { rollbackScrubbedMcpAdapters, scrubManagedMcpAdapterOrThrow, @@ -54,6 +55,7 @@ export { prepareMcpBridgesForExecUnavailableRebuild } from "./mcp-bridge-rebuild async function getCompleteMcpRebuildEntries( sandboxName: string, options: { sandboxAbsent?: boolean } = {}, + validatePolicyAuthority?: () => Promise, ): Promise { validateSandboxName(sandboxName); const currentSandbox = getSandboxOrThrow(sandboxName); @@ -72,6 +74,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); @@ -116,9 +119,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: [], @@ -140,6 +148,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?.(); scrubManagedMcpAdapterOrThrow(sandboxName, sandbox, entry); scrubbedAdapters.push(entry); } @@ -148,12 +157,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 +181,12 @@ export async function prepareMcpBridgesForRebuild( detached.push(entry); } } catch (error) { + if (isPolicyAuthorityRefusalError(error)) throw error; const rollbackFailures: string[] = []; let runtimeRestored = false; if (removedPolicies.length > 0) { try { + await validatePolicyAuthority?.(); await restoreExistingMcpBridgeRuntime(sandboxName, removedPolicies, { lifecyclePhase: "teardown-rollback", }); @@ -183,9 +198,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 +227,7 @@ export async function reattachMcpProvidersAfterRebuildAbort( sandboxName: string, entries: readonly McpBridgeEntry[], scrubbedAdapterEntries: readonly McpBridgeEntry[] = [], + validatePolicyAuthority?: () => Promise, ): Promise { if (entries.length === 0 && scrubbedAdapterEntries.length === 0) return; await ensureSandboxGatewaySelected(sandboxName); @@ -218,6 +241,7 @@ export async function reattachMcpProvidersAfterRebuildAbort( let runtimeRestored = false; if (entries.length > 0) { try { + await validatePolicyAuthority?.(); await restoreExistingMcpBridgeRuntime(sandboxName, entries, { lifecyclePhase: "teardown-rollback", }); @@ -227,6 +251,7 @@ export async function reattachMcpProvidersAfterRebuildAbort( } } if (!runtimeRestored) { + await validatePolicyAuthority?.(); failures.push(...rollbackScrubbedMcpAdapters(sandboxName, sandbox, scrubbedAdapterEntries)); } if (failures.length > 0) { @@ -237,6 +262,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 +271,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 ff2b5a783e8..6b4a2d464f7 100644 --- a/src/lib/actions/sandbox/mcp-bridge.ts +++ b/src/lib/actions/sandbox/mcp-bridge.ts @@ -148,27 +148,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 McpBridgeEntry[] = [], + 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..68ffbd53845 --- /dev/null +++ b/src/lib/actions/sandbox/policy-authority/preflight.test.ts @@ -0,0 +1,185 @@ +// 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 }], + }, + }, + }, + }); + + 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: {} }, + }); + + 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: {} }, + }); + + 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: {} }, + }); + + 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: {}, + }); + + 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..2d4f008314d --- /dev/null +++ b/src/lib/actions/sandbox/policy-authority/preflight.ts @@ -0,0 +1,191 @@ +// 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, + assertRecordedPolicyAuthority, + inspectGlobalPolicyAuthority, + inspectSandboxPolicyAuthority, + type SandboxPolicyAuthority, + type SandboxPolicyAuthorityInspection, +} from "../../../adapters/openshell/policy-authority"; +import { isPresetPolicyMap, parseNetworkPolicies } from "../../../policy/preset-parsing"; +import * as registry from "../../../policy/policy-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 interface PolicyAuthorityInspectionDeps { + readonly inspectGlobalPolicyAuthority?: typeof inspectGlobalPolicyAuthority; + readonly inspectSandboxPolicyAuthority?: typeof inspectSandboxPolicyAuthority; +} + +export interface PolicyAuthorityInspectionOptions { + readonly gatewayName: string; + readonly inspectLiveSource: boolean; + readonly operation: string; + readonly recordedAuthority: unknown; + readonly requiredPolicies: readonly RequiredPolicy[]; + readonly sandboxName: string; + readonly verifyGlobalCreatePolicy: boolean; +} + +export function parseRequiredPolicyDocument(content: string, operation: string): RequiredPolicy { + try { + const parsed: unknown = YAML.parse(content); + if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) { + return parsed as RequiredPolicy; + } + } 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[] = []; + if (options.inspectLiveSource) { + inspections.push( + (deps.inspectSandboxPolicyAuthority ?? inspectSandboxPolicyAuthority)({ + sandboxName: options.sandboxName, + gatewayName: options.gatewayName, + }), + ); + } + if (options.verifyGlobalCreatePolicy) { + inspections.push( + (deps.inspectGlobalPolicyAuthority ?? inspectGlobalPolicyAuthority)({ + gatewayName: options.gatewayName, + }), + ); + } + const [inspection, ...additionalInspections] = inspections; + if (!inspection) { + throw new Error(`Refusing to ${options.operation}: policy authority could not be inspected.`); + } + const { authority } = inspection; + if (options.recordedAuthority !== undefined) { + assertRecordedPolicyAuthority(options.recordedAuthority, authority, options.operation); + } + for (const additional of additionalInspections) { + assertRecordedPolicyAuthority(authority, additional.authority, options.operation); + } + return { + authority, + liveInspection: options.inspectLiveSource ? inspection : null, + verifyRequirements: () => assertPolicyAuthorityRequirements(options, inspections), + }; +} + +function assertPolicyAuthorityRequirements( + options: PolicyAuthorityInspectionOptions, + inspections: readonly SandboxPolicyAuthorityInspection[], +): void { + for (const inspection of inspections) { + for (const requiredPolicy of options.requiredPolicies) { + assertExternalPolicyRequirements({ + 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: SandboxPolicyAuthority, + 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): SandboxPolicyAuthority { + 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..4c0114310ca --- /dev/null +++ b/src/lib/actions/sandbox/policy-authority/rebuild.test.ts @@ -0,0 +1,335 @@ +// 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(), + }; + 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), + inspectGlobalPolicyAuthority: vi.fn(() => inspection), + }, + ); + + expect(receipt.authority).toBe("externally-managed"); + expect(receipt.requiredPolicies).toHaveLength(2); + expect(updateSandbox).not.toHaveBeenCalled(); + }); + + 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), + }; + 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), + inspectGlobalPolicyAuthority: vi.fn(() => 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(), + }; + 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), + inspectGlobalPolicyAuthority: vi.fn(() => 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(), + }; + const inspectSandbox = vi.fn(); + + const receipt = await qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "missing" as const), + inspectSandboxPolicyAuthority: inspectSandbox, + inspectGlobalPolicyAuthority: vi.fn(() => 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, + }, + }, + }; + + const receipt = await qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: vi.fn(() => inspection), + inspectGlobalPolicyAuthority: vi.fn(() => 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(), + }; + const inspectSandbox = vi.fn(() => inspection); + const inspectGlobal = vi.fn(() => inspection); + + await expect( + qualifyRebuildPolicyAuthority( + { + sandboxName: "alpha", + sandboxEntry: entry, + manifest: { + ...makePreparedRecoveryManifest(), + policyPresets: ["retired-custom-policy"], + }, + }, + { + observeSandboxPresence: vi.fn(() => "present" as const), + inspectSandboxPolicyAuthority: inspectSandbox, + inspectGlobalPolicyAuthority: 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 an absent legacy source without recording current global authority (#9833)", async () => { + const entry = sandboxEntry(undefined); + const inspection = { + authority: "nemoclaw-managed" as const, + effectivePolicy: {}, + }; + 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, + inspectGlobalPolicyAuthority: vi.fn(() => inspection), + }, + ), + ).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), + }; + const inspectSandbox = vi.fn(); + + await expect( + qualifyRebuildPolicyAuthority( + { sandboxName: "alpha", sandboxEntry: entry, manifest: null }, + { + observeSandboxPresence: vi.fn(() => "missing" as const), + inspectSandboxPolicyAuthority: inspectSandbox, + inspectGlobalPolicyAuthority: vi.fn(() => 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..cf560a6321f --- /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, + type SandboxPolicyAuthority, +} 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 "../../../policy/policy-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 RequiredPolicy, +} from "./preflight"; + +export interface RebuildPolicyAuthorityReceipt { + readonly authority: SandboxPolicyAuthority; + 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) continue; + 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.sourcePath === MCP_BRIDGE_POLICY_SOURCE) continue; + 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.`); + } + 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 2d0a8ad2ee2..90fbf0cfd8f 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("records when --force skips a total backup failure", () => { vi.spyOn(console, "warn").mockImplementation(() => undefined); vi.spyOn(console, "log").mockImplementation(() => undefined); diff --git a/src/lib/actions/sandbox/rebuild-backup-phase.ts b/src/lib/actions/sandbox/rebuild-backup-phase.ts index 4e6db352d1b..3c9de5a845c 100644 --- a/src/lib/actions/sandbox/rebuild-backup-phase.ts +++ b/src/lib/actions/sandbox/rebuild-backup-phase.ts @@ -52,9 +52,7 @@ export function excludePolicyPresetsByName( excludedNames: readonly (string | undefined)[], ): string[] { const excluded = new Set( - excludedNames.filter( - (name): name is string => typeof name === "string" && name.length > 0, - ), + excludedNames.filter((name): name is string => typeof name === "string" && name.length > 0), ); return presets.filter((name) => !excluded.has(name)); } @@ -213,35 +211,48 @@ 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 = 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, + disabledChannels, ) : []; - 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 policyPresets = normalizeRebuildTargetPolicyPresets( - mergedPolicyPresets, - 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 policyPresets = carriesManagedPolicyPresets + ? normalizeRebuildTargetPolicyPresets( + mergedPolicyPresets, + input.sandboxEntry, + input.webSearchConfig, + ) + : []; + 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..c7bf3ac552d 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 @@ -183,7 +183,8 @@ describe("rebuildSandbox DCode flow: pre-delete drift", () => { originalEntry, // Messaging config hydration. originalEntry, // Messaging-conflict gateway lookup (#5954). originalEntry, // Final pre-backup target verification. - driftedEntry, // Registry reread at the destructive boundary. + driftedEntry, // Policy-authority reread at the destructive boundary. + driftedEntry, // Exact target 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..d80ae42327b 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({ @@ -124,7 +127,10 @@ describe("rebuildSandbox DCode flow: preflight", () => { harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), ).rejects.toThrow("Recorded DCode auto-approval state is invalid"); - expect(harness.registryUpdateSpy).not.toHaveBeenCalled(); + expect(harness.registryUpdateSpy).toHaveBeenCalledOnce(); + expect(harness.registryUpdateSpy).toHaveBeenCalledWith("alpha", { + policyAuthority: "nemoclaw-managed", + }); expect(harness.prepareManagedDcodeRebuildImageSpy).not.toHaveBeenCalled(); expectNoDcodeMutation(harness); }); diff --git a/src/lib/actions/sandbox/rebuild-dcode-recovery.test.ts b/src/lib/actions/sandbox/rebuild-dcode-recovery.test.ts index a6a8312fd40..8d09bef6e07 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 { @@ -51,6 +52,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, + }, + sandboxListOutput: "", + 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", @@ -62,6 +87,7 @@ describe("rebuildSandbox DCode flow: recovery", () => { sandboxEntry: { ...makeDcodeSandboxEntry(), customPolicies: [customPolicy], + policyAuthority: "nemoclaw-managed", policyPresetsFinalized: true, }, sandboxListOutput: "", @@ -179,68 +205,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..b896021db23 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(); @@ -1001,6 +1005,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..99330ad145b 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,24 @@ 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) { + input.onDeleteStateAmbiguous?.(); + 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 b8048ecb79a..fcdc99c6831 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", @@ -207,6 +208,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", @@ -238,6 +240,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: () => { @@ -278,6 +281,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", @@ -310,6 +314,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, @@ -390,25 +395,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 c3217515e7c..fbaa8087047 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.ts @@ -6,6 +6,7 @@ import { detectOpenShellStateRpcResultIssue, printOpenShellStateRpcIssue, } from "../../adapters/openshell/gateway-drift"; +import type { SandboxPolicyAuthority } from "../../adapters/openshell/policy-authority"; import { loadAgent } from "../../agent/defs"; import { bindLocalAgentBaseImageHandoffToResolution, @@ -49,7 +50,11 @@ import { 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[] }; @@ -266,16 +271,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 8a7b2c54391..06be93ae261 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,98 @@ 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: {} }, + }, + }); + + 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, + }, + }); + + 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: "nemoclaw-managed" as const, + effectivePolicy: {}, + }; + const harness = createRebuildFlowHarness({ + onboard: () => { + authorityFlipped = true; + }, + }); + const inspectChangedAuthority = () => + authorityFlipped + ? { authority: "externally-managed", effectivePolicy: {} } + : managedInspection; + harness.inspectSandboxPolicyAuthoritySpy.mockImplementation(inspectChangedAuthority); + harness.inspectGlobalPolicyAuthoritySpy.mockImplementation(inspectChangedAuthority); + + 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 +171,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 +194,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 +242,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 +301,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 +313,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,12 +355,15 @@ 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.registryUpdateSpy).toHaveBeenCalledOnce(); + expect(harness.registryUpdateSpy).toHaveBeenCalledWith("alpha", { + policyAuthority: "nemoclaw-managed", + }); expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); expect(harness.prepareMcpBridgesForRebuildSpy).not.toHaveBeenCalled(); expect(harness.removeSandboxRegistryEntryWithReceiptSpy).not.toHaveBeenCalled(); @@ -265,7 +379,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 +404,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 +445,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 +550,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"); }); @@ -454,6 +583,7 @@ network_policies: it("relocks as present when shields postwork throws after successful onboard", async () => { const harness = createRebuildFlowHarness({ staleRecovery: true, + sandboxEntry: { policyAuthority: "nemoclaw-managed" }, clearShieldsState: () => { throw new Error("post-onboard shields cleanup failed"); }, @@ -490,7 +620,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", @@ -519,7 +652,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(); @@ -531,6 +668,7 @@ network_policies: const harness = createRebuildFlowHarness({ sandboxListOutput: "", 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)}`, @@ -606,7 +744,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..d18fb8f2f13 100644 --- a/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts @@ -230,6 +230,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 +495,7 @@ describe("rebuildSandbox flow: recovery", () => { "alpha", [attached], undefined, + expect.any(Function), ); expect(harness.onboardSpy).not.toHaveBeenCalled(); }); @@ -540,7 +542,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 4d9ea46a55a..68d0e771e92 100644 --- a/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts +++ b/src/lib/actions/sandbox/rebuild-hermes-post-restore.ts @@ -695,14 +695,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 202d8ddddea..dc34ead47d8 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 eb2c9dd742e..097110c850c 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-phase.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-phase.ts @@ -15,10 +15,7 @@ import type { Session } from "../../state/onboard-session"; import * as onboardSession from "../../state/onboard-session"; import * as registry from "../../state/registry"; import { cloneSandboxHostMounts } from "../../state/registry/host-mount"; -import { - excludePolicyPresetsByName, - type RebuildBackupManifest, -} from "./rebuild-backup-phase"; +import { excludePolicyPresetsByName, type RebuildBackupManifest } from "./rebuild-backup-phase"; import type { RebuildBail, RebuildLog } from "./rebuild-credential-preflight"; import type { RebuildDurableConfig } from "./rebuild-durable-config"; import { isolateAmbientRecreateEnv } from "./rebuild-env-isolation"; @@ -66,6 +63,7 @@ export interface RebuildRecreatePhaseInput { mcpEntries: McpRebuildPreparation["entries"]; rebuildShieldsWindow: RebuildShieldsWindow; relockShieldsIfNeeded: (sandboxStillExists: boolean) => boolean; + validatePolicyAuthority: () => Promise; onCreated: () => void; log: RebuildLog; bail: RebuildBail; @@ -101,6 +99,7 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): mcpEntries: rebuildMcpEntries, rebuildShieldsWindow, relockShieldsIfNeeded, + validatePolicyAuthority, onCreated, log, bail, @@ -159,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, @@ -167,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, @@ -210,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; @@ -248,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; @@ -288,7 +291,9 @@ export async function runRebuildRecreatePhase(input: RebuildRecreatePhaseInput): await rebuildOnboardDependencies.onboard({ ...recreateOptions, rebuildGatewayAuthority, - ...(Array.isArray(recreatePolicyPresets) ? { rebuildPolicyPresets: recreatePolicyPresets } : {}), + ...(Array.isArray(recreatePolicyPresets) + ? { rebuildPolicyPresets: recreatePolicyPresets } + : {}), ...(rebuildsHermesSandbox && backupManifest?.preservedEnv ? { rebuildPreservedEnv: backupManifest.preservedEnv } : {}), @@ -297,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") log(`onboard() threw: ${message}`); @@ -313,8 +319,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 { @@ -368,12 +380,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 0709b09b695..2cb47232ae6 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"; @@ -151,8 +152,17 @@ describe("rebuild resume snapshot repair", () => { dashboardPort: 18789, gatewayName: "nemoclaw", gatewayPort: 8080, + policyAuthority: "nemoclaw-managed", } as never), vi.spyOn(registry, "updateSandbox").mockReturnValue(true), + vi.spyOn(policyAuthority, "inspectSandboxPolicyAuthority").mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }), + vi.spyOn(policyAuthority, "inspectGlobalPolicyAuthority").mockReturnValue({ + authority: "nemoclaw-managed", + effectivePolicy: {}, + }), 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/shields/index.ts b/src/lib/shields/index.ts index 9e872cf0f1a..fa754fba4ca 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -4047,6 +4047,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" @@ -6265,6 +6299,7 @@ export { MAX_TIMEOUT_SECONDS, parseDuration, prepareAutoRestoreTransitionTakeover, + rebindReplacementConfigLock, repairMutableConfigPerms, resolvePersistedAutoRestoreTarget, restoreLockedStateDirStartupAccess, diff --git a/test/helpers/rebuild-flow-dcode-harness.ts b/test/helpers/rebuild-flow-dcode-harness.ts index c1b2f8fab2f..f454a67eee1 100644 --- a/test/helpers/rebuild-flow-dcode-harness.ts +++ b/test/helpers/rebuild-flow-dcode-harness.ts @@ -2,6 +2,7 @@ // 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 { makePreparedRecoveryManifest } from "../../src/lib/actions/sandbox/rebuild-flow-test-fixtures"; import { @@ -25,6 +26,7 @@ import { onboardCredentialEnv, onboardSession, openshellRuntime, + policyAuthority, policies, processRecovery, purgeRebuildModule, @@ -42,6 +44,7 @@ import { registryPersistence, resolve, sandboxList, + sandboxRecreateProbe, sandboxSession, sandboxState, sandboxVersion, @@ -92,6 +95,7 @@ export type RebuildFlowOverrides = { }; buildMessagingRebuildPlan?: () => Promise | unknown; sandboxEntry?: Record; + policyAuthorityInspection?: SandboxPolicyAuthorityInspection; sandboxEntryReads?: Array | null>; sessionSandboxName?: string; sandboxListOutput?: string; @@ -146,6 +150,8 @@ export type RebuildFlowHarness = { checkAndRecoverSandboxProcessesSpy: MockInstance; restartSandboxGatewaySpy: MockInstance; ensureMessagingHostForwardAfterRebuildSpy: MockInstance; + inspectGlobalPolicyAuthoritySpy: MockInstance; + inspectSandboxPolicyAuthoritySpy: MockInstance; logSpy: MockInstance; finalizeIncompleteOnboardStepSpy: MockInstance; openShieldsSpy: MockInstance; @@ -350,16 +356,50 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): nimContainer: null, ...(overrides.sandboxEntry ?? {}), }; + const recordedPolicyAuthority = ( + sandboxEntry as typeof sandboxEntry & { policyAuthority?: unknown } + ).policyAuthority; + const policyAuthorityInspection = + overrides.policyAuthorityInspection ?? + ({ + authority: + recordedPolicyAuthority === "externally-managed" + ? "externally-managed" + : "nemoclaw-managed", + effectivePolicy: {}, + } as const); + const inspectGlobalPolicyAuthoritySpy = vi + .spyOn(policyAuthority, "inspectGlobalPolicyAuthority") + .mockReturnValue(policyAuthorityInspection); + const inspectSandboxPolicyAuthoritySpy = vi + .spyOn(policyAuthority, "inspectSandboxPolicyAuthority") + .mockReturnValue(policyAuthorityInspection); + vi.spyOn(sandboxRecreateProbe, "observeSandboxPresenceOnGateway").mockReturnValue( + overrides.sandboxListOutput === "" || + 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(() => { @@ -376,7 +416,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 { @@ -517,7 +562,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.sandboxListOutput === "" || + overrides.reconciledSandboxGatewayState?.state === "missing"; + return probedGateway && !sourceInitiallyMissing && !deletedSourceGateways.has(probedGateway) ? { status: 0, output: liveSource, stdout: liveSource, stderr: "" } : { status: 1, @@ -751,6 +799,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 4dc7812dac9..e8756f6c7c1 100644 --- a/test/helpers/rebuild-flow-generic-harness.ts +++ b/test/helpers/rebuild-flow-generic-harness.ts @@ -27,6 +27,7 @@ import { onboardCredentialEnv, onboardSession, openshellRuntime, + policyAuthority, policies, processRecovery, purgeRebuildModule, @@ -43,6 +44,7 @@ import { registryPersistence, resolve, sandboxList, + sandboxRecreateProbe, sandboxSession, sandboxState, sandboxVersion, @@ -253,6 +255,27 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): ...customOpenClawPluginProvenance, ...(overrides.sandboxEntry ?? {}), }; + const recordedPolicyAuthority = ( + currentSandboxEntry as typeof currentSandboxEntry & { policyAuthority?: unknown } + ).policyAuthority; + const policyAuthorityInspection = + overrides.policyAuthorityInspection ?? + ({ + authority: + recordedPolicyAuthority === "externally-managed" + ? "externally-managed" + : "nemoclaw-managed", + effectivePolicy: {}, + } as const); + const inspectGlobalPolicyAuthoritySpy = vi + .spyOn(policyAuthority, "inspectGlobalPolicyAuthority") + .mockReturnValue(policyAuthorityInspection); + const inspectSandboxPolicyAuthoritySpy = vi + .spyOn(policyAuthority, "inspectSandboxPolicyAuthority") + .mockReturnValue(policyAuthorityInspection); + vi.spyOn(sandboxRecreateProbe, "observeSandboxPresenceOnGateway").mockReturnValue( + overrides.staleRecovery || overrides.sandboxListOutput === "" ? "missing" : "present", + ); const readCurrentSandboxEntry = () => structuredClone(currentSandboxEntry); vi.spyOn(registry, "getSandbox").mockImplementation(readCurrentSandboxEntry); const initialDefaultSandbox = overrides.defaultSandbox ?? null; @@ -392,7 +415,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[]) => { @@ -670,9 +695,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 57b2dd7e9f5..02498b6ee37 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 { finalizePreparedRebuildImageMessagingPlan, RebuildImagePreflightResult, @@ -74,6 +75,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 }; @@ -144,9 +146,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; From 6f71bdbf5799d38a44f149d1c81270da2dc1ec86 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 09:51:48 -0700 Subject: [PATCH 15/40] fix(policy): close authority review gaps Signed-off-by: Apurv Kumaria --- src/lib/policy/README.md | 10 +++-- src/lib/policy/context-builder.ts | 42 +++++++++++++------ src/lib/policy/context.test.ts | 32 +++++++++----- src/lib/policy/index.ts | 1 + .../policy-authority-integration.test.ts | 16 +++++++ src/lib/shields/index.ts | 7 ++-- src/lib/shields/policy-transition.test.ts | 17 ++++---- test/e2e-test.sh | 25 ++++++++--- 8 files changed, 106 insertions(+), 44 deletions(-) diff --git a/src/lib/policy/README.md b/src/lib/policy/README.md index 3340ecc814e..e0a1bdd6a92 100644 --- a/src/lib/policy/README.md +++ b/src/lib/policy/README.md @@ -27,10 +27,12 @@ NemoClaw does not set policy or record preset or custom-policy attribution. The external authority must supply a missing or changed entry. If policy authority becomes external while Shields is down, NemoClaw keeps the -saved restrictive policy snapshot and refuses to restore it. Ask the external -policy authority to restore the restrictive policy. Then run -`nemoclaw shields up` to retry Shields reconciliation. `shields status` -reports this recovery requirement while the sandbox remains unlocked. +saved restrictive policy snapshot and refuses to restore it. The external +policy authority must keep the restrictive policy active until it returns +policy authority to NemoClaw management. Then run +`nemoclaw shields up` to restore the saved snapshot and finish the +Shields transition. `shields status` reports this recovery requirement while +the sandbox remains unlocked. A legacy sandbox record retains the first qualified `policyAuthority` after a later operation fails. An inspection that cannot determine authority does not change the record. diff --git a/src/lib/policy/context-builder.ts b/src/lib/policy/context-builder.ts index 3a68e4e30cb..ce28e712db6 100644 --- a/src/lib/policy/context-builder.ts +++ b/src/lib/policy/context-builder.ts @@ -111,7 +111,12 @@ export interface PolicyContext { } const POLICY_DOC_URL = "docs/network-policy/customize-network-policy.mdx"; -const EXTERNAL_POLICY_CHANGE_PATH = "Ask the external policy authority to supply a changed entry."; +const EXTERNAL_POLICY_ADD_PATH = + "Ask the external policy authority to add or replace the policy entries required by ``."; +const EXTERNAL_POLICY_REMOVE_PATH = + "Ask the external policy authority to remove the policy entries supplied by ``."; +const EXTERNAL_POLICY_RESTORE_PATH = + "Ask the external policy authority to restore baseline policy entry ``."; function hostStemsFromContent(content: string | null | undefined): { public: string[]; @@ -267,14 +272,14 @@ function buildApprovalPath( return { inspect: `nemoclaw ${sandboxName} policy list`, add: externallyManaged - ? EXTERNAL_POLICY_CHANGE_PATH + ? EXTERNAL_POLICY_ADD_PATH : `nemoclaw ${sandboxName} policy add `, remove: externallyManaged - ? EXTERNAL_POLICY_CHANGE_PATH + ? EXTERNAL_POLICY_REMOVE_PATH : `nemoclaw ${sandboxName} policy remove `, excludeBaseline: `nemoclaw ${sandboxName} policy exclude --dry-run`, restoreBaseline: externallyManaged - ? EXTERNAL_POLICY_CHANGE_PATH + ? EXTERNAL_POLICY_RESTORE_PATH : `nemoclaw ${sandboxName} policy restore `, documentation: POLICY_DOC_URL, }; @@ -289,7 +294,7 @@ function buildSupportBoundaries( capability: "preset selection", owner: externallyManaged ? "external" : "nemoclaw", note: externallyManaged - ? "the external policy authority must supply a changed entry" + ? "the external policy authority applies each requested add or remove action to the live policy" : tier ? `tier: ${tier.label}` : "no tier recorded", @@ -299,13 +304,26 @@ function buildSupportBoundaries( owner: "openshell", note: "policy is enforced by the OpenShell gateway", }, - { - capability: "shields toggle", - owner: externallyManaged ? "external" : "nemoclaw", - note: externallyManaged - ? "the external authority controls live policy changes; restrictive NemoClaw-owned configuration protection and cleanup may still proceed" - : "shields up locks down mutable config", - }, + ...(externallyManaged + ? [ + { + capability: "Shields network policy", + owner: "external" as const, + note: "the external policy authority controls live network policy changes while authority remains external", + }, + { + capability: "Shields state, configuration protection, and cleanup", + owner: "nemoclaw" as const, + note: "NemoClaw retains Shields state, configuration protection, and cleanup. Saved snapshot restoration requires NemoClaw-managed authority.", + }, + ] + : [ + { + capability: "Shields transition", + owner: "nemoclaw" as const, + note: "Shields up locks down mutable configuration", + }, + ]), { capability: "credential storage", owner: "nemoclaw", diff --git a/src/lib/policy/context.test.ts b/src/lib/policy/context.test.ts index 1b4316ce554..ef998899594 100644 --- a/src/lib/policy/context.test.ts +++ b/src/lib/policy/context.test.ts @@ -152,9 +152,9 @@ describe("buildPolicyContext", () => { true, ); expect(ctx.supportBoundaries).toContainEqual({ - capability: "shields toggle", + capability: "Shields transition", owner: "nemoclaw", - note: "shields up locks down mutable config", + note: "Shields up locks down mutable configuration", }); }); @@ -186,29 +186,39 @@ describe("buildPolicyContext", () => { expect(context.supportBoundaries).toContainEqual({ capability: "preset selection", owner: "external", - note: "the external policy authority must supply a changed entry", + note: "the external policy authority applies each requested add or remove action to the live policy", }); expect(context.supportBoundaries).toContainEqual({ - capability: "shields toggle", + capability: "Shields network policy", owner: "external", - note: "the external authority controls live policy changes; restrictive NemoClaw-owned configuration protection and cleanup may still proceed", + note: "the external policy authority controls live network policy changes while authority remains external", + }); + expect(context.supportBoundaries).toContainEqual({ + capability: "Shields state, configuration protection, and cleanup", + owner: "nemoclaw", + note: "NemoClaw retains Shields state, configuration protection, and cleanup. Saved snapshot restoration requires NemoClaw-managed authority.", }); expect(context.approvalPath).toEqual({ inspect: "nemoclaw alpha policy list", - add: "Ask the external policy authority to supply a changed entry.", - remove: "Ask the external policy authority to supply a changed entry.", + add: "Ask the external policy authority to add or replace the policy entries required by ``.", + remove: + "Ask the external policy authority to remove the policy entries supplied by ``.", excludeBaseline: "nemoclaw alpha policy exclude --dry-run", - restoreBaseline: "Ask the external policy authority to supply a changed entry.", + restoreBaseline: + "Ask the external policy authority to restore baseline policy entry ``.", documentation: "docs/network-policy/customize-network-policy.mdx", }); expect(markdown).toContain( - "restore: Ask the external policy authority to supply a changed entry.", + "restore: Ask the external policy authority to restore baseline policy entry ``.", + ); + expect(markdown).toContain( + "- restore a baseline entry: Ask the external policy authority to restore baseline policy entry ``.", ); expect(markdown).toContain( - "- restore a baseline entry: Ask the external policy authority to supply a changed entry.", + "- Shields network policy (owner: external) — the external policy authority controls live network policy changes while authority remains external", ); expect(markdown).toContain( - "- shields toggle (owner: external) — the external authority controls live policy changes; restrictive NemoClaw-owned configuration protection and cleanup may still proceed", + "- Shields state, configuration protection, and cleanup (owner: nemoclaw) — NemoClaw retains Shields state, configuration protection, and cleanup. Saved snapshot restoration requires NemoClaw-managed authority.", ); expect(markdown).toContain("`nemoclaw alpha policy exclude --dry-run`"); expect(markdown).not.toMatch(/nemoclaw alpha policy (?:add|remove|restore)(?:\s|`)/u); diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index 27aadccda60..00144d6b867 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -3330,6 +3330,7 @@ function applyPermissivePolicy(sandboxName: string): void { console.log(" Applying permissive policy..."); assertOpenshellResolvable(); + if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return; setPolicyDocument(sandboxName, materializedPolicy, { gatewayName: authority.gatewayName }); const observed = inspectPolicyAuthority(sandboxName, operation, authority.gatewayName, true); registry.assertRecordedPolicyAuthority(authority.authority, observed.authority, operation); diff --git a/src/lib/policy/policy-authority-integration.test.ts b/src/lib/policy/policy-authority-integration.test.ts index 5a29c646b62..bf107681e13 100644 --- a/src/lib/policy/policy-authority-integration.test.ts +++ b/src/lib/policy/policy-authority-integration.test.ts @@ -231,6 +231,7 @@ describe("sandbox policy authority ownership", () => { it("throws when permissive policy authority changes after the policy set (#9833)", () => { sandbox = { ...sandbox, policyAuthority: "nemoclaw-managed" }; mocks.inspectSandboxPolicyAuthority + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) .mockReturnValueOnce({ authority: "externally-managed", effectivePolicy: {} }); @@ -240,4 +241,19 @@ describe("sandbox policy authority ownership", () => { expect(mocks.run).toHaveBeenCalledOnce(); expect(console.log).not.toHaveBeenCalledWith(" Applied permissive policy."); }); + + it("refuses a permissive policy set when authority changes before submission (#9833)", () => { + sandbox = { ...sandbox, policyAuthority: "nemoclaw-managed" }; + mocks.inspectSandboxPolicyAuthority + .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) + .mockReturnValueOnce({ authority: "externally-managed", effectivePolicy: {} }); + + expect(applyPermissivePolicy(SANDBOX)).toBeUndefined(); + + expect(mocks.inspectSandboxPolicyAuthority).toHaveBeenCalledTimes(2); + expect(mocks.run).not.toHaveBeenCalled(); + expect(console.log).not.toHaveBeenCalledWith(" Applied permissive policy."); + expect(reportedErrors()).toContain("policy authority changed"); + expect(reportedErrors()).toContain("external policy authority"); + }); }); diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index 9e872cf0f1a..7b8b900bef3 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -155,9 +155,10 @@ function assertShieldsPolicyMutationAuthority( function externalPolicyRecoveryHandoff(sandboxName: string): string { return ( - `NemoClaw cannot restore the externally managed policy for sandbox '${sandboxName}' ` + - "from its saved Shields policy snapshot. Ask the external policy authority to restore " + - `the restrictive policy, then run \`${CLI_NAME} ${sandboxName} shields up\` to retry Shields reconciliation.` + `NemoClaw cannot restore or reconcile the saved Shields policy snapshot for sandbox '${sandboxName}' ` + + "while an external authority manages policy. The external policy authority must keep the restrictive " + + "policy active and return policy authority to NemoClaw management. " + + `Then run \`${CLI_NAME} ${sandboxName} shields up\` to restore the saved snapshot and finish the Shields transition.` ); } diff --git a/src/lib/shields/policy-transition.test.ts b/src/lib/shields/policy-transition.test.ts index 8c673ceadb1..e747deb545d 100644 --- a/src/lib/shields/policy-transition.test.ts +++ b/src/lib/shields/policy-transition.test.ts @@ -11,6 +11,7 @@ import YAML from "yaml"; import { createShieldsFlowHarness, externalPolicyAuthorityInspection, + managedPolicyMutationAuthority, type ShieldsFlowHarnessOptions, } from "../../../test/helpers/shields-flow-harness"; @@ -157,9 +158,7 @@ describe("shields policy transition", () => { }); expect(() => shields.applyShieldsPolicySnapshot(sandboxName, snapshotPath)).toThrow( - "NemoClaw cannot restore the externally managed policy for sandbox 'openclaw' from its " + - "saved Shields policy snapshot. Ask the external policy authority to restore the " + - "restrictive policy, then run `nemoclaw openclaw shields up` to retry Shields reconciliation.", + "return policy authority to NemoClaw management", ); expect(runSpy).not.toHaveBeenCalled(); }); @@ -234,7 +233,7 @@ describe("shields down policy rejection", () => { expect(harness.dockerSpawnCalls).toEqual([]); }); - it("hands external policy restoration to its authority after Shields down (#9833)", () => { + it("restores the Shields snapshot after policy authority returns to NemoClaw (#9833)", () => { const sandboxName = "openclaw"; const harness = createShieldsFlowHarness(requireSource, tmpDir, { confirmOpenClawInodeFlags: true, @@ -253,10 +252,7 @@ describe("shields down policy rejection", () => { gatewayName: "nemoclaw", inspection: externalPolicyAuthorityInspection, }); - const recovery = - "NemoClaw cannot restore the externally managed policy for sandbox 'openclaw' from its " + - "saved Shields policy snapshot. Ask the external policy authority to restore the " + - "restrictive policy, then run `nemoclaw openclaw shields up` to retry Shields reconciliation."; + const recovery = "return policy authority to NemoClaw management"; expect(() => harness.shieldsUp(sandboxName, { throwOnError: true })).toThrow(recovery); expect(policySetCount()).toBe(policySetsAfterDown); expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain(recovery); @@ -272,6 +268,11 @@ describe("shields down policy rejection", () => { "Shields: DOWN (RECOVERY REQUIRED — policy is externally managed)", ); expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain(recovery); + + harness.policyAuthoritySpy.mockReturnValue(managedPolicyMutationAuthority); + harness.shieldsUp(sandboxName, { throwOnError: true }); + expect(harness.isShieldsDown(sandboxName)).toBe(false); + expect(policySetCount()).toBeGreaterThan(policySetsAfterDown); }); it("pins Shields policy inspection, reads, and writes to the recorded gateway (#9833)", () => { diff --git a/test/e2e-test.sh b/test/e2e-test.sh index b2c11b6ed0e..7962df819f0 100755 --- a/test/e2e-test.sh +++ b/test/e2e-test.sh @@ -149,9 +149,10 @@ info "4b. Verify blueprint runner apply smoke test" # response is intentionally rejected by the runner. FAKE_OPENSHELL_BIN=$(mktemp -d) APPLY_OUTPUT=$(mktemp) +APPLY_CALLS=$(mktemp) cleanup_apply_fixture() { rm -rf "$FAKE_OPENSHELL_BIN" - rm -f "$APPLY_OUTPUT" + rm -f "$APPLY_OUTPUT" "$APPLY_CALLS" } trap cleanup_apply_fixture EXIT cat >"$FAKE_OPENSHELL_BIN/openshell" <<'SH' @@ -164,24 +165,31 @@ fi if [ "${1:-} ${2:-}" = "policy list" ]; then exit 0 fi +if [ "${1:-} ${2:-}" = "policy get" ]; then + printf '%s\n' "$*" >>"$NEMOCLAW_E2E_OPENSHELL_CALLS" +fi if [ "${1:-} ${2:-}" = "policy get" ] && [[ " $* " == *" --output json "* ]]; then sandbox="${@: -1}" printf '{"scope":"sandbox","sandbox":"%s","status":"effective","policy_source":"sandbox","policy":{}}\n' "$sandbox" exit 0 fi -case "${1:-} ${2:-} ${3:-}" in - "policy get --base") +case "$*" in + "policy get -g fixture-gateway --base "*) + if [ "$#" -ne 6 ] || [ -z "${6:-}" ]; then + echo "unexpected policy read: expected policy get -g fixture-gateway --base " >&2 + exit 64 + fi printf '%s\n' 'Policy for sandbox fixture' '---' cat /opt/nemoclaw-blueprint/policies/openclaw-sandbox.yaml ;; "policy get "*) - echo "unexpected policy read: expected policy get --base" >&2 + echo "unexpected policy read: expected policy get -g fixture-gateway --base " >&2 exit 64 ;; esac SH chmod 0755 "$FAKE_OPENSHELL_BIN/openshell" -PATH="$FAKE_OPENSHELL_BIN:$PATH" NEMOCLAW_BLUEPRINT_PATH=/opt/nemoclaw-blueprint node --input-type=module -e " +PATH="$FAKE_OPENSHELL_BIN:$PATH" NEMOCLAW_BLUEPRINT_PATH=/opt/nemoclaw-blueprint NEMOCLAW_E2E_OPENSHELL_CALLS="$APPLY_CALLS" node --input-type=module -e " const { main } = await import('/opt/nemoclaw/dist/blueprint/runner.js'); await main(['apply', '--profile', 'ncp']); " 2>&1 | tee "$APPLY_OUTPUT" @@ -206,6 +214,11 @@ if grep -q "PROGRESS:100:Apply complete" "$APPLY_OUTPUT"; then else fail "Apply did not complete" fi +if grep -Eq '^policy get -g fixture-gateway --base [^ ]+$' "$APPLY_CALLS"; then + pass "Apply reads base policy through the active gateway" +else + fail "Apply did not use the gateway-pinned base-policy read" +fi # Verify run state was persisted to disk RUN_ID=$(grep -o 'nc-[0-9]*-[0-9]*-[a-f0-9]*' "$APPLY_OUTPUT" | head -1) if [ -f "$HOME/.nemoclaw/state/runs/$RUN_ID/plan.json" ]; then @@ -213,7 +226,7 @@ if [ -f "$HOME/.nemoclaw/state/runs/$RUN_ID/plan.json" ]; then else fail "Apply did not persist run state (plan.json missing for $RUN_ID)" fi -rm -f "$APPLY_OUTPUT" +rm -f "$APPLY_OUTPUT" "$APPLY_CALLS" trap - EXIT # ------------------------------------------------------- From 6cf16bb49836229c654b7688728d02d8d4fa16e3 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 11:39:05 -0700 Subject: [PATCH 16/40] test(e2e): retain blueprint policy call evidence Signed-off-by: Apurv Kumaria --- test/e2e-test.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/e2e-test.sh b/test/e2e-test.sh index 7962df819f0..70a3ccb2bd4 100755 --- a/test/e2e-test.sh +++ b/test/e2e-test.sh @@ -149,7 +149,7 @@ info "4b. Verify blueprint runner apply smoke test" # response is intentionally rejected by the runner. FAKE_OPENSHELL_BIN=$(mktemp -d) APPLY_OUTPUT=$(mktemp) -APPLY_CALLS=$(mktemp) +APPLY_CALLS="$FAKE_OPENSHELL_BIN/calls" cleanup_apply_fixture() { rm -rf "$FAKE_OPENSHELL_BIN" rm -f "$APPLY_OUTPUT" "$APPLY_CALLS" @@ -166,7 +166,7 @@ if [ "${1:-} ${2:-}" = "policy list" ]; then exit 0 fi if [ "${1:-} ${2:-}" = "policy get" ]; then - printf '%s\n' "$*" >>"$NEMOCLAW_E2E_OPENSHELL_CALLS" + printf '%s\n' "$*" >>"${BASH_SOURCE[0]%/*}/calls" fi if [ "${1:-} ${2:-}" = "policy get" ] && [[ " $* " == *" --output json "* ]]; then sandbox="${@: -1}" @@ -189,7 +189,7 @@ case "$*" in esac SH chmod 0755 "$FAKE_OPENSHELL_BIN/openshell" -PATH="$FAKE_OPENSHELL_BIN:$PATH" NEMOCLAW_BLUEPRINT_PATH=/opt/nemoclaw-blueprint NEMOCLAW_E2E_OPENSHELL_CALLS="$APPLY_CALLS" node --input-type=module -e " +PATH="$FAKE_OPENSHELL_BIN:$PATH" NEMOCLAW_BLUEPRINT_PATH=/opt/nemoclaw-blueprint node --input-type=module -e " const { main } = await import('/opt/nemoclaw/dist/blueprint/runner.js'); await main(['apply', '--profile', 'ncp']); " 2>&1 | tee "$APPLY_OUTPUT" From adcb4388cb77ae747ac9f4b154a47e6c9bc73825 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 11:46:07 -0700 Subject: [PATCH 17/40] test(rebuild): qualify policy authority fixtures Signed-off-by: Apurv Kumaria --- test/gateway-state-reconcile-2276.test.ts | 1 + test/helpers/rebuild-flow-generic-harness.ts | 6 +++--- test/rebuild-credential-preflight.test.ts | 11 +++++++++++ test/rebuild-messaging-conflict-preflight.test.ts | 6 ++++++ 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/test/gateway-state-reconcile-2276.test.ts b/test/gateway-state-reconcile-2276.test.ts index a34a73a15ef..05b02d6e956 100644 --- a/test/gateway-state-reconcile-2276.test.ts +++ b/test/gateway-state-reconcile-2276.test.ts @@ -82,6 +82,7 @@ function writeDefaultRegistry(gatewayName: string, gatewayPort: number) { dashboardPort: 28790, fromDockerfile: null, policies: [], + policyAuthority: "nemoclaw-managed", }, }, }), diff --git a/test/helpers/rebuild-flow-generic-harness.ts b/test/helpers/rebuild-flow-generic-harness.ts index e8756f6c7c1..1c5d21bd6b3 100644 --- a/test/helpers/rebuild-flow-generic-harness.ts +++ b/test/helpers/rebuild-flow-generic-harness.ts @@ -252,12 +252,12 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): dashboardPort: 18789, gatewayName: "nemoclaw", gatewayPort: 8080, + policyAuthority: "nemoclaw-managed" as const, ...customOpenClawPluginProvenance, ...(overrides.sandboxEntry ?? {}), }; - const recordedPolicyAuthority = ( - currentSandboxEntry as typeof currentSandboxEntry & { policyAuthority?: unknown } - ).policyAuthority; + const recordedPolicyAuthority = (currentSandboxEntry as Record) + .policyAuthority; const policyAuthorityInspection = overrides.policyAuthorityInspection ?? ({ diff --git a/test/rebuild-credential-preflight.test.ts b/test/rebuild-credential-preflight.test.ts index 351312732b5..2f7c52d8539 100644 --- a/test/rebuild-credential-preflight.test.ts +++ b/test/rebuild-credential-preflight.test.ts @@ -103,6 +103,7 @@ wait();`, dashboardPort: agent === "langchain-deepagents-code" ? 0 : 18789, fromDockerfile: null, policies: [], + policyAuthority: "nemoclaw-managed", agent, ...(agent === "langchain-deepagents-code" ? { @@ -195,6 +196,16 @@ if (a[0] === "sandbox" && a[1] === "get") { process.stdout.write("Sandbox: ${sandboxName}\\nPhase: Ready\\n"); process.exit(0); } +if (a[0] === "policy" && a[1] === "get" && a.includes("--output") && a.includes("json")) { + process.stdout.write(JSON.stringify({ + scope: "sandbox", + sandbox: "${sandboxName}", + status: "effective", + policy_source: "sandbox", + policy: {}, + }) + "\\n"); + process.exit(0); +} if (a[0] === "sandbox" && a[1] === "delete") { fs.writeFileSync(${JSON.stringify(deleteMarker)}, "deleted\\n"); process.exit(0); } if (a[0] === "sandbox" && a[1] === "exec") { const command = a.join(" "); diff --git a/test/rebuild-messaging-conflict-preflight.test.ts b/test/rebuild-messaging-conflict-preflight.test.ts index b74e124612f..2e9bd0cf28e 100644 --- a/test/rebuild-messaging-conflict-preflight.test.ts +++ b/test/rebuild-messaging-conflict-preflight.test.ts @@ -127,6 +127,7 @@ function createConflictFixture() { dashboardPort: 18789, fromDockerfile: null, policies: [], + policyAuthority: "nemoclaw-managed", agent: null, messaging: { schemaVersion: 1, plan: teamsPlan(name, "shared-teams-hash") }, }); @@ -163,7 +164,12 @@ 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[0]==="sandbox" && a[1]==="get") { process.stdout.write("Name: " + a.at(-1) + "\\nId: sbx-fixture\\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]==="get" && a.includes("--output") && a.includes("json")) { + process.stdout.write(JSON.stringify({scope:"sandbox",sandbox:a.at(-1),status:"effective",policy_source:"sandbox",policy:{}}) + "\\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); } From 53798927657a7cf289110313188a6249c558477f Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 12:41:52 -0700 Subject: [PATCH 18/40] test(e2e): retain blueprint policy call trace Signed-off-by: Apurv Kumaria --- test/e2e-test.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/test/e2e-test.sh b/test/e2e-test.sh index 70a3ccb2bd4..293a4481c86 100755 --- a/test/e2e-test.sh +++ b/test/e2e-test.sh @@ -193,7 +193,6 @@ PATH="$FAKE_OPENSHELL_BIN:$PATH" NEMOCLAW_BLUEPRINT_PATH=/opt/nemoclaw-blueprint const { main } = await import('/opt/nemoclaw/dist/blueprint/runner.js'); await main(['apply', '--profile', 'ncp']); " 2>&1 | tee "$APPLY_OUTPUT" -rm -rf "$FAKE_OPENSHELL_BIN" if grep -q "RUN_ID:" "$APPLY_OUTPUT"; then pass "Apply generates run ID" else From ae0c6e931a5dd2844b6d395fe7d0a2815a691ecd Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 12:42:02 -0700 Subject: [PATCH 19/40] test(ci): rebalance policy authority coverage shard Signed-off-by: Apurv Kumaria --- ...ty-integration.test.ts => policy-authority-mutation.test.ts} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/lib/policy/{policy-authority-integration.test.ts => policy-authority-mutation.test.ts} (99%) diff --git a/src/lib/policy/policy-authority-integration.test.ts b/src/lib/policy/policy-authority-mutation.test.ts similarity index 99% rename from src/lib/policy/policy-authority-integration.test.ts rename to src/lib/policy/policy-authority-mutation.test.ts index bf107681e13..875e5eb2600 100644 --- a/src/lib/policy/policy-authority-integration.test.ts +++ b/src/lib/policy/policy-authority-mutation.test.ts @@ -83,7 +83,7 @@ function reportedErrors(): string { .join("\n"); } -describe("sandbox policy authority ownership", () => { +describe("policy authority mutation ownership", () => { let sandbox: Record; beforeEach(() => { From 977c91ce412f14df65470a75361a0162ce401ab8 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 13:00:44 -0700 Subject: [PATCH 20/40] test(ci): rebalance policy coverage shards Signed-off-by: Apurv Kumaria --- ci/cli-test-timing-hints.json | 2 +- ...ority-mutation.test.ts => policy-mutation-authority.test.ts} | 2 +- ...inality.test.ts => policy-mutation-process-finality.test.ts} | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename src/lib/policy/{policy-authority-mutation.test.ts => policy-mutation-authority.test.ts} (99%) rename test/{portable-policy-failure-finality.test.ts => policy-mutation-process-finality.test.ts} (99%) diff --git a/ci/cli-test-timing-hints.json b/ci/cli-test-timing-hints.json index 40b2ffac005..58cda4b2884 100644 --- a/ci/cli-test-timing-hints.json +++ b/ci/cli-test-timing-hints.json @@ -188,12 +188,12 @@ "test/policy-add-remove-session-sync.test.ts": 10393, "test/policy-channel-agent-resolution.test.ts": 8083, "test/policy-explain-cli.test.ts": 5249, + "test/policy-mutation-process-finality.test.ts": 8392, "test/policy-openclaw-npm-compatibility.test.ts": 14295, "test/policy-preset-noop-disclosure.test.ts": 9796, "test/policy-tiers-onboard-restricted-stale-otel.test.ts": 5808, "test/policy-tiers-onboard.test.ts": 8804, "test/portable-cpu-delegation-docs.test.ts": 39159, - "test/portable-policy-failure-finality.test.ts": 8392, "test/pr-review-advisor-security-boundaries.test.ts": 24108, "test/pr-review-advisor-submission-tools.test.ts": 5422, "test/pr-review-advisor-writing-guide.test.ts": 8835, diff --git a/src/lib/policy/policy-authority-mutation.test.ts b/src/lib/policy/policy-mutation-authority.test.ts similarity index 99% rename from src/lib/policy/policy-authority-mutation.test.ts rename to src/lib/policy/policy-mutation-authority.test.ts index 875e5eb2600..987fc47d19b 100644 --- a/src/lib/policy/policy-authority-mutation.test.ts +++ b/src/lib/policy/policy-mutation-authority.test.ts @@ -83,7 +83,7 @@ function reportedErrors(): string { .join("\n"); } -describe("policy authority mutation ownership", () => { +describe("policy mutation authority boundary", () => { let sandbox: Record; beforeEach(() => { diff --git a/test/portable-policy-failure-finality.test.ts b/test/policy-mutation-process-finality.test.ts similarity index 99% rename from test/portable-policy-failure-finality.test.ts rename to test/policy-mutation-process-finality.test.ts index ff6d8fdad66..63ab87db6b9 100644 --- a/test/portable-policy-failure-finality.test.ts +++ b/test/policy-mutation-process-finality.test.ts @@ -327,7 +327,7 @@ describe.each(POLICY_SET_FAILURES)( }, ); -describe("applyPresets when openshell policy set succeeds", () => { +describe("applyPresets when OpenShell policy set succeeds", () => { let run: ChildRun; beforeAll(() => { From 173e5841141fde00b90dfee0e514d964ec0cf89a Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 13:26:12 -0700 Subject: [PATCH 21/40] fix(policy): close authority recovery review gaps Signed-off-by: Apurv Kumaria --- src/lib/policy/README.md | 11 +- src/lib/policy/context-builder.ts | 20 +- src/lib/policy/context.test.ts | 25 +-- src/lib/policy/index.ts | 57 +++++- .../policy/policy-mutation-authority.test.ts | 26 ++- src/lib/shields/index.ts | 151 +++++++++++++-- src/lib/shields/openclaw-transition.test.ts | 113 +++++++++++ src/lib/shields/policy-transition.test.ts | 181 +++++++----------- test/e2e-test.sh | 2 +- test/helpers/shields-flow-harness.ts | 5 + 10 files changed, 424 insertions(+), 167 deletions(-) diff --git a/src/lib/policy/README.md b/src/lib/policy/README.md index e0a1bdd6a92..83724d60749 100644 --- a/src/lib/policy/README.md +++ b/src/lib/policy/README.md @@ -27,12 +27,11 @@ NemoClaw does not set policy or record preset or custom-policy attribution. The external authority must supply a missing or changed entry. If policy authority becomes external while Shields is down, NemoClaw keeps the -saved restrictive policy snapshot and refuses to restore it. The external -policy authority must keep the restrictive policy active until it returns -policy authority to NemoClaw management. Then run -`nemoclaw shields up` to restore the saved snapshot and finish the -Shields transition. `shields status` reports this recovery requirement while -the sandbox remains unlocked. +saved restrictive policy snapshot and refuses to set policy. The external +policy authority must apply that exact snapshot as the sandbox policy. Then run +`nemoclaw shields up`. NemoClaw verifies the exact live policy and +locks configuration without changing policy authority. `shields status` +reports this recovery requirement while the sandbox remains unlocked. A legacy sandbox record retains the first qualified `policyAuthority` after a later operation fails. An inspection that cannot determine authority does not change the record. diff --git a/src/lib/policy/context-builder.ts b/src/lib/policy/context-builder.ts index ce28e712db6..5c7abae914c 100644 --- a/src/lib/policy/context-builder.ts +++ b/src/lib/policy/context-builder.ts @@ -117,6 +117,8 @@ const EXTERNAL_POLICY_REMOVE_PATH = "Ask the external policy authority to remove the policy entries supplied by ``."; const EXTERNAL_POLICY_RESTORE_PATH = "Ask the external policy authority to restore baseline policy entry ``."; +const EXTERNAL_POLICY_EXCLUDE_PATH = + "Run `nemoclaw policy exclude --dry-run`, then ask the external policy authority to remove baseline policy entry ``."; function hostStemsFromContent(content: string | null | undefined): { public: string[]; @@ -277,7 +279,9 @@ function buildApprovalPath( remove: externallyManaged ? EXTERNAL_POLICY_REMOVE_PATH : `nemoclaw ${sandboxName} policy remove `, - excludeBaseline: `nemoclaw ${sandboxName} policy exclude --dry-run`, + excludeBaseline: externallyManaged + ? EXTERNAL_POLICY_EXCLUDE_PATH.replace("", sandboxName) + : `nemoclaw ${sandboxName} policy exclude --dry-run`, restoreBaseline: externallyManaged ? EXTERNAL_POLICY_RESTORE_PATH : `nemoclaw ${sandboxName} policy restore `, @@ -291,10 +295,10 @@ function buildSupportBoundaries( ): PolicyContextSupportBoundary[] { return [ { - capability: "preset selection", - owner: externallyManaged ? "external" : "nemoclaw", + capability: "policy requirement selection and verification", + owner: "nemoclaw", note: externallyManaged - ? "the external policy authority applies each requested add or remove action to the live policy" + ? "NemoClaw selects preset and baseline requirements and verifies the live policy" : tier ? `tier: ${tier.label}` : "no tier recorded", @@ -307,14 +311,14 @@ function buildSupportBoundaries( ...(externallyManaged ? [ { - capability: "Shields network policy", + capability: "policy mutation", owner: "external" as const, - note: "the external policy authority controls live network policy changes while authority remains external", + note: "the external policy authority applies each required add, remove, restore, or baseline exclusion to the live policy", }, { - capability: "Shields state, configuration protection, and cleanup", + capability: "Shields state and configuration lock", owner: "nemoclaw" as const, - note: "NemoClaw retains Shields state, configuration protection, and cleanup. Saved snapshot restoration requires NemoClaw-managed authority.", + note: "NemoClaw retains Shields state and locks configuration after it verifies restrictive policy", }, ] : [ diff --git a/src/lib/policy/context.test.ts b/src/lib/policy/context.test.ts index ef998899594..be3fe6be802 100644 --- a/src/lib/policy/context.test.ts +++ b/src/lib/policy/context.test.ts @@ -184,26 +184,27 @@ describe("buildPolicyContext", () => { expect(context.tier).toBeNull(); expect(getTier).not.toHaveBeenCalled(); expect(context.supportBoundaries).toContainEqual({ - capability: "preset selection", - owner: "external", - note: "the external policy authority applies each requested add or remove action to the live policy", + capability: "policy requirement selection and verification", + owner: "nemoclaw", + note: "NemoClaw selects preset and baseline requirements and verifies the live policy", }); expect(context.supportBoundaries).toContainEqual({ - capability: "Shields network policy", + capability: "policy mutation", owner: "external", - note: "the external policy authority controls live network policy changes while authority remains external", + note: "the external policy authority applies each required add, remove, restore, or baseline exclusion to the live policy", }); expect(context.supportBoundaries).toContainEqual({ - capability: "Shields state, configuration protection, and cleanup", + capability: "Shields state and configuration lock", owner: "nemoclaw", - note: "NemoClaw retains Shields state, configuration protection, and cleanup. Saved snapshot restoration requires NemoClaw-managed authority.", + note: "NemoClaw retains Shields state and locks configuration after it verifies restrictive policy", }); expect(context.approvalPath).toEqual({ inspect: "nemoclaw alpha policy list", add: "Ask the external policy authority to add or replace the policy entries required by ``.", remove: "Ask the external policy authority to remove the policy entries supplied by ``.", - excludeBaseline: "nemoclaw alpha policy exclude --dry-run", + excludeBaseline: + "Run `nemoclaw alpha policy exclude --dry-run`, then ask the external policy authority to remove baseline policy entry ``.", restoreBaseline: "Ask the external policy authority to restore baseline policy entry ``.", documentation: "docs/network-policy/customize-network-policy.mdx", @@ -215,12 +216,14 @@ describe("buildPolicyContext", () => { "- restore a baseline entry: Ask the external policy authority to restore baseline policy entry ``.", ); expect(markdown).toContain( - "- Shields network policy (owner: external) — the external policy authority controls live network policy changes while authority remains external", + "- policy mutation (owner: external) — the external policy authority applies each required add, remove, restore, or baseline exclusion to the live policy", + ); + expect(markdown).toContain( + "- Shields state and configuration lock (owner: nemoclaw) — NemoClaw retains Shields state and locks configuration after it verifies restrictive policy", ); expect(markdown).toContain( - "- Shields state, configuration protection, and cleanup (owner: nemoclaw) — NemoClaw retains Shields state, configuration protection, and cleanup. Saved snapshot restoration requires NemoClaw-managed authority.", + "Run `nemoclaw alpha policy exclude --dry-run`, then ask the external policy authority to remove baseline policy entry ``.", ); - expect(markdown).toContain("`nemoclaw alpha policy exclude --dry-run`"); expect(markdown).not.toMatch(/nemoclaw alpha policy (?:add|remove|restore)(?:\s|`)/u); }); diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index 00144d6b867..8848aa9a865 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -582,16 +582,16 @@ export interface PolicyMutationAuthority { } export const isPolicyAuthorityRefusalError = registry.isPolicyAuthorityRefusalError; -export const isExternalPolicyAuthorityRefusalError = - registry.isExternalPolicyAuthorityRefusalError; +export const isExternalPolicyAuthorityRefusalError = registry.isExternalPolicyAuthorityRefusalError; -/** Inspect and, when needed, persist the authority that owns one sandbox policy. */ -export function inspectPolicyMutationAuthority( +function inspectLivePolicyAuthority( sandboxName: string, operation: string, requestedGatewayName?: string, - requireRecordedAuthority = false, -): PolicyMutationAuthority { +): { + sandbox: ReturnType; + authority: PolicyMutationAuthority; +} { let sandbox: ReturnType; try { sandbox = registry.getSandbox(sandboxName); @@ -616,7 +616,8 @@ export function inspectPolicyMutationAuthority( } let gatewayName: string; try { - gatewayName = recordedGatewayName ?? requestedGatewayName ?? resolveSandboxGatewayName(undefined); + gatewayName = + recordedGatewayName ?? requestedGatewayName ?? resolveSandboxGatewayName(undefined); } catch { throw new registry.PolicyAuthorityRefusalError( `Refusing to ${operation}: the sandbox gateway is unavailable or invalid.`, @@ -627,6 +628,42 @@ export function inspectPolicyMutationAuthority( gatewayName, runCaptureEx, }); + return { + sandbox, + authority: { + authority: inspection.authority, + authorityRecordedNow: false, + gatewayName, + inspection, + }, + }; +} + +/** Read live authority for Shields recovery without changing its durable owner. */ +export function inspectPolicyRecoveryAuthority( + sandboxName: string, + operation: string, + requestedGatewayName?: string, +): PolicyMutationAuthority { + const live = inspectLivePolicyAuthority(sandboxName, operation, requestedGatewayName); + if (!live.sandbox) { + throw new registry.PolicyAuthorityRefusalError( + `Refusing to ${operation}: sandbox policy authority is unavailable.`, + ); + } + return live.authority; +} + +/** Inspect and, when needed, persist the authority that owns one sandbox policy. */ +export function inspectPolicyMutationAuthority( + sandboxName: string, + operation: string, + requestedGatewayName?: string, + requireRecordedAuthority = false, +): PolicyMutationAuthority { + const live = inspectLivePolicyAuthority(sandboxName, operation, requestedGatewayName); + const { sandbox } = live; + const { gatewayName, inspection } = live.authority; if (sandbox?.policyAuthority !== undefined) { try { registry.assertRecordedPolicyAuthority( @@ -640,7 +677,7 @@ export function inspectPolicyMutationAuthority( inspection.authority === "externally-managed" ) { throw new registry.PolicyAuthorityRefusalError( - `${policyAuthorityError(error)} Ask the external policy authority to change the required entry.`, + `${policyAuthorityError(error)} The external policy authority must perform the requested policy mutation.`, inspection.authority, ); } @@ -691,7 +728,7 @@ export function assertNemoClawManagedPolicy( if (authority.authority === "nemoclaw-managed") return; throw new registry.PolicyAuthorityRefusalError( `Refusing to ${operation}: this sandbox policy is externally managed. ` + - "Ask the external policy authority to change the required entry.", + "The external policy authority must perform the requested policy mutation.", authority.authority, ); } @@ -3330,7 +3367,7 @@ function applyPermissivePolicy(sandboxName: string): void { console.log(" Applying permissive policy..."); assertOpenshellResolvable(); - if (!recheckNemoClawManagedPolicy(sandboxName, operation, authority)) return; + recheckPolicyMutationAuthority(sandboxName, operation, authority); setPolicyDocument(sandboxName, materializedPolicy, { gatewayName: authority.gatewayName }); const observed = inspectPolicyAuthority(sandboxName, operation, authority.gatewayName, true); registry.assertRecordedPolicyAuthority(authority.authority, observed.authority, operation); diff --git a/src/lib/policy/policy-mutation-authority.test.ts b/src/lib/policy/policy-mutation-authority.test.ts index 987fc47d19b..ad36acf3990 100644 --- a/src/lib/policy/policy-mutation-authority.test.ts +++ b/src/lib/policy/policy-mutation-authority.test.ts @@ -47,9 +47,11 @@ import { applyPermissivePolicy, applyPresetContent, excludeBaselineEntry, + inspectPolicyRecoveryAuthority, removePreset, restoreBaselineEntry, } from "./index"; +import { PolicyAuthorityRefusalError } from "./policy-registry"; const SANDBOX = "authority-9833"; const BASE_POLICY = `version: 1 @@ -83,7 +85,7 @@ function reportedErrors(): string { .join("\n"); } -describe("policy mutation authority boundary", () => { +describe("PolicyMutationAuthority", () => { let sandbox: Record; beforeEach(() => { @@ -153,6 +155,21 @@ describe("policy mutation authority boundary", () => { ); }); + it("reads external recovery authority without replacing the durable owner (#9833)", () => { + sandbox = { ...sandbox, policyAuthority: "nemoclaw-managed" }; + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { network_policies: { weather: WEATHER_POLICY } }, + }); + + expect(inspectPolicyRecoveryAuthority(SANDBOX, "verify Shields recovery")).toMatchObject({ + authority: "externally-managed", + authorityRecordedNow: false, + gatewayName: "nemoclaw", + }); + expect(mocks.updateSandbox).not.toHaveBeenCalled(); + }); + it("rechecks authority before policy set and refuses an ownership change (#9833)", () => { mocks.inspectSandboxPolicyAuthority .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) @@ -242,18 +259,17 @@ describe("policy mutation authority boundary", () => { expect(console.log).not.toHaveBeenCalledWith(" Applied permissive policy."); }); - it("refuses a permissive policy set when authority changes before submission (#9833)", () => { + it("throws a typed refusal when permissive policy authority changes before submission (#9833)", () => { sandbox = { ...sandbox, policyAuthority: "nemoclaw-managed" }; mocks.inspectSandboxPolicyAuthority .mockReturnValueOnce({ authority: "nemoclaw-managed", effectivePolicy: {} }) .mockReturnValueOnce({ authority: "externally-managed", effectivePolicy: {} }); - expect(applyPermissivePolicy(SANDBOX)).toBeUndefined(); + expect(() => applyPermissivePolicy(SANDBOX)).toThrow(PolicyAuthorityRefusalError); expect(mocks.inspectSandboxPolicyAuthority).toHaveBeenCalledTimes(2); expect(mocks.run).not.toHaveBeenCalled(); expect(console.log).not.toHaveBeenCalledWith(" Applied permissive policy."); - expect(reportedErrors()).toContain("policy authority changed"); - expect(reportedErrors()).toContain("external policy authority"); + expect(reportedErrors()).toBe(""); }); }); diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index 7b8b900bef3..0719ff65d8a 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -25,6 +25,8 @@ const fs = require("fs"); const path = require("path"); const { fork } = require("child_process"); const { createHash, randomBytes } = require("crypto"); +const { isDeepStrictEqual } = require("util"); +const YAML: typeof import("yaml") = require("yaml"); const { CLI_NAME }: typeof import("../cli/branding") = require("../cli/branding"); const { isObjectRecord }: typeof import("../core/json-types") = require("../core/json-types"); const { @@ -43,6 +45,7 @@ const { resolvePermissivePolicyPath, assertNemoClawManagedPolicy, inspectPolicyMutationAuthority, + inspectPolicyRecoveryAuthority, isExternalPolicyAuthorityRefusalError, isPolicyAuthorityRefusalError, recheckPolicyMutationAuthority, @@ -153,29 +156,85 @@ function assertShieldsPolicyMutationAuthority( return authority; } -function externalPolicyRecoveryHandoff(sandboxName: string): string { - return ( - `NemoClaw cannot restore or reconcile the saved Shields policy snapshot for sandbox '${sandboxName}' ` + - "while an external authority manages policy. The external policy authority must keep the restrictive " + - "policy active and return policy authority to NemoClaw management. " + - `Then run \`${CLI_NAME} ${sandboxName} shields up\` to restore the saved snapshot and finish the Shields transition.` +function readShieldsPolicySnapshot(snapshotPath: string): Record { + let parsed: unknown; + try { + parsed = YAML.parse(fs.readFileSync(snapshotPath, "utf-8")); + } catch (error) { + throw new Error("The saved restrictive Shields policy snapshot is unreadable or invalid", { + cause: error, + }); + } + if (!isObjectRecord(parsed)) { + throw new Error("The saved restrictive Shields policy snapshot is not a policy mapping"); + } + return parsed; +} + +function externalPolicyMatchesShieldsSnapshot( + authority: PolicyMutationAuthority, + snapshotPath: string, +): boolean { + return isDeepStrictEqual( + authority.inspection.effectivePolicy, + readShieldsPolicySnapshot(snapshotPath), ); } -function assertShieldsPolicySnapshotRestoreAuthority( +function externalPolicyRecoveryHandoff( + sandboxName: string, + snapshotPath: string, + restrictivePolicyVerified: boolean, +): string { + return restrictivePolicyVerified + ? `NemoClaw verified the saved restrictive policy for sandbox '${sandboxName}' under external policy authority. ` + + `Run \`${CLI_NAME} ${sandboxName} shields up\` to lock configuration and finish the Shields transition without changing policy.` + : `NemoClaw cannot finish the Shields transition for sandbox '${sandboxName}' while its external policy differs from the saved restrictive snapshot. ` + + `The external policy authority must apply '${snapshotPath}' as the sandbox policy. Then run \`${CLI_NAME} ${sandboxName} shields up\`. ` + + "NemoClaw will verify the exact live policy and lock configuration without changing policy."; +} + +type ShieldsPolicySnapshotRestoreAuthority = { + authority: PolicyMutationAuthority; + policyMutationAllowed: boolean; +}; + +function resolveShieldsPolicySnapshotRestoreAuthority( sandboxName: string, + snapshotPath: string, recorded?: PolicyMutationAuthority, -): PolicyMutationAuthority { +): ShieldsPolicySnapshotRestoreAuthority { + let authority: PolicyMutationAuthority; try { - return assertShieldsPolicyMutationAuthority( - sandboxName, - "restore the Shields policy snapshot", - recorded, - ); + authority = recorded + ? recheckPolicyMutationAuthority(sandboxName, "restore the Shields policy snapshot", recorded) + : inspectPolicyMutationAuthority(sandboxName, "restore the Shields policy snapshot"); } catch (error) { if (!isExternalPolicyAuthorityRefusalError(error)) throw error; - throw new Error(externalPolicyRecoveryHandoff(sandboxName), { cause: error }); + authority = inspectPolicyRecoveryAuthority( + sandboxName, + "verify the externally restored Shields policy snapshot", + recorded?.gatewayName, + ); + } + if (authority.authority === "nemoclaw-managed") { + return { authority, policyMutationAllowed: true }; + } + if (!externalPolicyMatchesShieldsSnapshot(authority, snapshotPath)) { + throw new Error(externalPolicyRecoveryHandoff(sandboxName, snapshotPath, false)); + } + const revalidated = inspectPolicyRecoveryAuthority( + sandboxName, + "finish the externally restored Shields policy snapshot verification", + authority.gatewayName, + ); + if ( + revalidated.authority !== "externally-managed" || + !externalPolicyMatchesShieldsSnapshot(revalidated, snapshotPath) + ) { + throw new Error(externalPolicyRecoveryHandoff(sandboxName, snapshotPath, false)); } + return { authority: revalidated, policyMutationAllowed: false }; } type ShieldsPolicyRecoveryInspection = @@ -189,7 +248,34 @@ function inspectShieldsPolicyRecovery(sandboxName: string): ShieldsPolicyRecover return { status: "ready" }; } catch (error) { if (isExternalPolicyAuthorityRefusalError(error)) { - return { status: "external", handoff: externalPolicyRecoveryHandoff(sandboxName) }; + const snapshotPath = loadShieldsState(sandboxName).shieldsPolicySnapshotPath; + if (!snapshotPath || !fs.existsSync(snapshotPath)) { + return { + status: "external", + handoff: `The saved restrictive policy snapshot for sandbox '${sandboxName}' is unavailable. Rebuild the sandbox before finishing the Shields transition.`, + }; + } + try { + const authority = inspectPolicyRecoveryAuthority( + sandboxName, + "inspect externally managed Shields policy recovery", + ); + return { + status: "external", + handoff: externalPolicyRecoveryHandoff( + sandboxName, + snapshotPath, + authority.authority === "externally-managed" && + externalPolicyMatchesShieldsSnapshot(authority, snapshotPath), + ), + }; + } catch (inspectionError) { + return { + status: "unavailable", + detail: + inspectionError instanceof Error ? inspectionError.message : String(inspectionError), + }; + } } return { status: "unavailable", @@ -4141,7 +4227,6 @@ function applyShieldsPolicySnapshot( snapshotPath: string, options: ShieldsPolicySnapshotRestoreOptions = {}, ): ShieldsPolicySnapshotRestoreResult { - const policyAuthority = assertShieldsPolicySnapshotRestoreAuthority(sandboxName); const buildPolicySet = options.buildPolicySet ?? buildPolicySetCommand; const runPolicySet = options.runPolicySet ?? run; const state = loadShieldsState(sandboxName); @@ -4194,6 +4279,18 @@ function applyShieldsPolicySnapshot( throw new Error("Shields state does not match the policy snapshot being restored"); } const persistedSnapshotMatches = state.shieldsPolicySnapshotPath === snapshotPath; + const restoreAuthority = resolveShieldsPolicySnapshotRestoreAuthority(sandboxName, snapshotPath); + const policyAuthority = restoreAuthority.authority; + if (!restoreAuthority.policyMutationAllowed) { + return { + pid: process.pid, + output: [null, "", ""], + stdout: "", + stderr: "", + status: 0, + signal: null, + }; + } const ownershipOmissions: ManagedMcpPolicyOmission[] = []; if ( transition?.managedMcpPolicyKeys !== undefined && @@ -4229,7 +4326,11 @@ function applyShieldsPolicySnapshot( fs.readFileSync(snapshotPath, "utf-8"), hasManagedMcpPolicyClaims(sandboxName), ); - assertShieldsPolicySnapshotRestoreAuthority(sandboxName, policyAuthority); + assertShieldsPolicyMutationAuthority( + sandboxName, + "restore the Shields policy snapshot", + policyAuthority, + ); const result = runPolicySet( buildPolicySet(snapshotPath, sandboxName, policyAuthority.gatewayName), { @@ -4268,7 +4369,11 @@ function applyShieldsPolicySnapshot( } const runtimePolicyIsTemp = runtimePolicyPath !== snapshotPath; try { - assertShieldsPolicySnapshotRestoreAuthority(sandboxName, policyAuthority); + assertShieldsPolicyMutationAuthority( + sandboxName, + "restore the Shields policy snapshot", + policyAuthority, + ); const result = runPolicySet( buildPolicySet(runtimePolicyPath, sandboxName, policyAuthority.gatewayName), { @@ -4448,6 +4553,16 @@ function activateLockdownFromSnapshot( error: relock.error ?? "config re-lock did not re-confirm after the settle window", }; } + try { + resolveShieldsPolicySnapshotRestoreAuthority(sandboxName, snapshotPath); + } catch (error) { + return { + ok: false, + error: `policy verification after config lock failed: ${ + error instanceof Error ? error.message : String(error) + }`, + }; + } return { ok: true, chattrApplied: relock.lastResult.chattrApplied, diff --git a/src/lib/shields/openclaw-transition.test.ts b/src/lib/shields/openclaw-transition.test.ts index d41ba56aa06..4a08c0759d4 100644 --- a/src/lib/shields/openclaw-transition.test.ts +++ b/src/lib/shields/openclaw-transition.test.ts @@ -7,6 +7,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; +import YAML from "yaml"; import { createHermesUnsafeConfigHarness, expectHermesShieldsUpRecord, @@ -15,6 +16,8 @@ import { } from "../../../test/helpers/hermes-unsafe-config-shields-harness"; import { createShieldsFlowHarness, + externalPolicyAuthorityInspection, + type ShieldsFlowHarness, type ShieldsFlowHarnessOptions, } from "../../../test/helpers/shields-flow-harness"; import type { AgentConfigTarget } from "../sandbox/agent-config"; @@ -1365,3 +1368,113 @@ describe("Hermes Shields down unsafe config path (#8804)", () => { expect(errors).not.toContain("provisional Shields down cleared"); }); }); + +function countPolicySets(harness: ShieldsFlowHarness): number { + return harness.runSpy.mock.calls.filter( + ([command]) => Array.isArray(command) && command.includes("policy") && command.includes("set"), + ).length; +} + +function externalAuthority(effectivePolicy: Record) { + return { + authority: "externally-managed" as const, + authorityRecordedNow: false, + gatewayName: "nemoclaw", + inspection: { + authority: "externally-managed" as const, + effectivePolicy, + }, + }; +} + +function readRestrictivePolicy(harness: ShieldsFlowHarness, sandboxName: string) { + const state = harness.getShieldsPosture(sandboxName, false).state; + return YAML.parse(fs.readFileSync(String(state.shieldsPolicySnapshotPath), "utf-8")) as Record< + string, + unknown + >; +} + +describe("external Shields policy recovery", () => { + let externalTmpDir: string; + + beforeEach(() => { + externalTmpDir = fs.mkdtempSync(`${os.tmpdir()}/nemoclaw-external-shields-recovery-`); + vi.stubEnv("HOME", externalTmpDir); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + fs.rmSync(externalTmpDir, { recursive: true, force: true }); + }); + + it("locks configuration only after external authority restores the exact snapshot (#9833)", () => { + const sandboxName = "openclaw"; + const harness = createShieldsFlowHarness(requireSource, externalTmpDir, { + confirmOpenClawInodeFlags: true, + initialOpenClawPosture: "locked", + }); + harness.shieldsDown(sandboxName, { throwOnError: true }); + const policySetsAfterDown = countPolicySets(harness); + const mismatchedExternalAuthority = { + authority: "externally-managed", + authorityRecordedNow: false, + gatewayName: "nemoclaw", + inspection: externalPolicyAuthorityInspection, + } as const; + harness.policyAuthoritySpy.mockReturnValue(mismatchedExternalAuthority); + harness.policyRecoveryAuthoritySpy.mockReturnValue(mismatchedExternalAuthority); + + expect(() => harness.shieldsUp(sandboxName, { throwOnError: true })).toThrow("must apply"); + expect(countPolicySets(harness)).toBe(policySetsAfterDown); + expect(harness.getOpenClawPosture()).toBe("mutable"); + + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process exit ${String(code)}`); + }) as typeof process.exit); + expect(() => harness.shieldsStatus(sandboxName, false)).toThrow("process exit 2"); + expect(exitSpy).toHaveBeenCalledWith(2); + expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain("must apply"); + + const restoredExternalAuthority = externalAuthority( + readRestrictivePolicy(harness, sandboxName), + ); + harness.policyAuthoritySpy.mockReturnValue(restoredExternalAuthority); + harness.policyRecoveryAuthoritySpy.mockReturnValue(restoredExternalAuthority); + + harness.shieldsUp(sandboxName, { throwOnError: true }); + + expect(harness.isShieldsDown(sandboxName)).toBe(false); + expect(harness.getOpenClawPosture()).toBe("locked"); + expect(countPolicySets(harness)).toBe(policySetsAfterDown); + }); + + it("withholds Shields success when external policy changes during config locking (#9833)", () => { + const sandboxName = "openclaw"; + const harness = createShieldsFlowHarness(requireSource, externalTmpDir, { + confirmOpenClawInodeFlags: true, + initialOpenClawPosture: "locked", + }); + harness.shieldsDown(sandboxName, { throwOnError: true }); + const policySetsAfterDown = countPolicySets(harness); + const restoredExternalAuthority = externalAuthority( + readRestrictivePolicy(harness, sandboxName), + ); + const changedExternalAuthority = externalAuthority({ version: 1, network_policies: {} }); + harness.policyAuthoritySpy.mockReturnValue(restoredExternalAuthority); + harness.policyRecoveryAuthoritySpy + .mockReturnValueOnce(restoredExternalAuthority) + .mockReturnValue(changedExternalAuthority); + + expect(() => harness.shieldsUp(sandboxName, { throwOnError: true })).toThrow( + "policy verification after config lock failed", + ); + + expect(harness.isShieldsDown(sandboxName)).toBe(true); + expect(countPolicySets(harness)).toBe(policySetsAfterDown); + expect(harness.auditSpy).not.toHaveBeenCalledWith( + expect.objectContaining({ action: "shields_up" }), + ); + }); +}); diff --git a/src/lib/shields/policy-transition.test.ts b/src/lib/shields/policy-transition.test.ts index e747deb545d..e273cebfaef 100644 --- a/src/lib/shields/policy-transition.test.ts +++ b/src/lib/shields/policy-transition.test.ts @@ -11,7 +11,6 @@ import YAML from "yaml"; import { createShieldsFlowHarness, externalPolicyAuthorityInspection, - managedPolicyMutationAuthority, type ShieldsFlowHarnessOptions, } from "../../../test/helpers/shields-flow-harness"; @@ -158,7 +157,7 @@ describe("shields policy transition", () => { }); expect(() => shields.applyShieldsPolicySnapshot(sandboxName, snapshotPath)).toThrow( - "return policy authority to NemoClaw management", + "must apply", ); expect(runSpy).not.toHaveBeenCalled(); }); @@ -233,48 +232,6 @@ describe("shields down policy rejection", () => { expect(harness.dockerSpawnCalls).toEqual([]); }); - it("restores the Shields snapshot after policy authority returns to NemoClaw (#9833)", () => { - const sandboxName = "openclaw"; - const harness = createShieldsFlowHarness(requireSource, tmpDir, { - confirmOpenClawInodeFlags: true, - initialOpenClawPosture: "locked", - }); - harness.shieldsDown(sandboxName, { throwOnError: true }); - const policySetCount = () => - harness.runSpy.mock.calls.filter( - ([command]) => - Array.isArray(command) && command.includes("policy") && command.includes("set"), - ).length; - const policySetsAfterDown = policySetCount(); - harness.policyAuthoritySpy.mockReturnValue({ - authority: "externally-managed", - authorityRecordedNow: false, - gatewayName: "nemoclaw", - inspection: externalPolicyAuthorityInspection, - }); - const recovery = "return policy authority to NemoClaw management"; - expect(() => harness.shieldsUp(sandboxName, { throwOnError: true })).toThrow(recovery); - expect(policySetCount()).toBe(policySetsAfterDown); - expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain(recovery); - harness.logSpy.mockClear(); - harness.errorSpy.mockClear(); - const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { - throw new Error(`process exit ${String(code)}`); - }) as typeof process.exit); - expect(() => harness.shieldsStatus(sandboxName, false)).toThrow("process exit 2"); - expect(exitSpy).toHaveBeenCalledWith(2); - expect(policySetCount()).toBe(policySetsAfterDown); - expect(harness.logSpy.mock.calls.flat().join("\n")).toContain( - "Shields: DOWN (RECOVERY REQUIRED — policy is externally managed)", - ); - expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain(recovery); - - harness.policyAuthoritySpy.mockReturnValue(managedPolicyMutationAuthority); - harness.shieldsUp(sandboxName, { throwOnError: true }); - expect(harness.isShieldsDown(sandboxName)).toBe(false); - expect(policySetCount()).toBeGreaterThan(policySetsAfterDown); - }); - it("pins Shields policy inspection, reads, and writes to the recorded gateway (#9833)", () => { const gatewayName = "nemoclaw-18080"; const harness = createShieldsFlowHarness(requireSource, tmpDir, { @@ -790,26 +747,31 @@ describe("shields config lock without a shipped config hash", () => { "rollback-failed", " CRITICAL: Deep Agents config lock transaction could not restore its original posture. Restore this sandbox from a trusted snapshot or recreate it before retrying. rollback failed", ], - ] as const)("maps the anchored %s child protocol to exact bounded guidance (#7995)", (status, expectedGuidance) => { - const stderr = - status === "sandbox-parent" ? Buffer.from(lockFailure(status), "utf8") : lockFailure(status); - commandHandlers.set( - "python3", - rejectConfigLock( - sandboxCommandFailure( - stderr, - `hostile argv marker ${lockFailure("incomplete")}`, - lockFailure("config-root"), + ] as const)( + "maps the anchored %s child protocol to exact bounded guidance (#7995)", + (status, expectedGuidance) => { + const stderr = + status === "sandbox-parent" + ? Buffer.from(lockFailure(status), "utf8") + : lockFailure(status); + commandHandlers.set( + "python3", + rejectConfigLock( + sandboxCommandFailure( + stderr, + `hostile argv marker ${lockFailure("incomplete")}`, + lockFailure("config-root"), + ), ), - ), - ); + ); - expect(() => shields.lockAgentConfig("dcode-safety", target(), false)).toThrow( - DEEP_AGENTS_LOCK_GENERIC_ERROR, - ); - expect(errorSpy).toHaveBeenCalledWith(expectedGuidance); - expect(errorSpy).toHaveBeenCalledTimes(1); - }); + expect(() => shields.lockAgentConfig("dcode-safety", target(), false)).toThrow( + DEEP_AGENTS_LOCK_GENERIC_ERROR, + ); + expect(errorSpy).toHaveBeenCalledWith(expectedGuidance); + expect(errorSpy).toHaveBeenCalledTimes(1); + }, + ); it("accepts transaction-failed without inventing a containment or rollback claim (#7995)", () => { commandHandlers.set( @@ -919,54 +881,57 @@ describe("shields config lock without a shipped config hash", () => { format: "json", }), ], - ])("pins expired inline recovery to Deep Agents when the registry %s (#7995)", (_scenario, resolveTarget) => { - const sandboxName = "dcode-safety"; - const stateDir = path.join(homeDir, ".nemoclaw", "state"); - const snapshotPath = path.join(stateDir, "policy-snapshot-inline-recovery.yaml"); - const markerPath = path.join(stateDir, `shields-timer-${sandboxName}.json`); - fs.mkdirSync(stateDir, { recursive: true }); - fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies: {}\n", { mode: 0o600 }); - fs.writeFileSync( - path.join(stateDir, `shields-${sandboxName}.json`), - JSON.stringify({ - shieldsDown: true, - shieldsDownAt: new Date(Date.now() - 120_000).toISOString(), - shieldsDownTimeout: 60, - shieldsDownReason: "identity coverage", - shieldsDownPolicy: "permissive", - shieldsPolicySnapshotPath: snapshotPath, - }), - { mode: 0o600 }, - ); - fs.writeFileSync( - markerPath, - JSON.stringify({ - pid: 4242, - sandboxName, - snapshotPath, - restoreAt: new Date(Date.now() - 30_000).toISOString(), - processToken: "7".repeat(32), - agentName: "langchain-deepagents-code", - configPath: CONFIG_PATH, - configDir: CONFIG_DIR, - }), - { mode: 0o600 }, - ); - vi.spyOn(process, "kill").mockImplementation(reportMissingTimerProcess); - resolveAgentConfigSpy.mockImplementation(resolveTarget); + ])( + "pins expired inline recovery to Deep Agents when the registry %s (#7995)", + (_scenario, resolveTarget) => { + const sandboxName = "dcode-safety"; + const stateDir = path.join(homeDir, ".nemoclaw", "state"); + const snapshotPath = path.join(stateDir, "policy-snapshot-inline-recovery.yaml"); + const markerPath = path.join(stateDir, `shields-timer-${sandboxName}.json`); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies: {}\n", { mode: 0o600 }); + fs.writeFileSync( + path.join(stateDir, `shields-${sandboxName}.json`), + JSON.stringify({ + shieldsDown: true, + shieldsDownAt: new Date(Date.now() - 120_000).toISOString(), + shieldsDownTimeout: 60, + shieldsDownReason: "identity coverage", + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: snapshotPath, + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + markerPath, + JSON.stringify({ + pid: 4242, + sandboxName, + snapshotPath, + restoreAt: new Date(Date.now() - 30_000).toISOString(), + processToken: "7".repeat(32), + agentName: "langchain-deepagents-code", + configPath: CONFIG_PATH, + configDir: CONFIG_DIR, + }), + { mode: 0o600 }, + ); + vi.spyOn(process, "kill").mockImplementation(reportMissingTimerProcess); + resolveAgentConfigSpy.mockImplementation(resolveTarget); - const posture = shields.getShieldsPosture(sandboxName, true); - const state = JSON.parse( - fs.readFileSync(path.join(stateDir, `shields-${sandboxName}.json`), "utf-8"), - ); + const posture = shields.getShieldsPosture(sandboxName, true); + const state = JSON.parse( + fs.readFileSync(path.join(stateDir, `shields-${sandboxName}.json`), "utf-8"), + ); - expect(posture.mode).toBe("locked"); - expect(lockCalls).toHaveLength(2); - expect(lockCalls.every((command) => command[4] === CONFIG_DIR)).toBe(true); - expect(lockCalls.every((command) => command[5] === CONFIG_PATH)).toBe(true); - expect(Object.keys(state.fileHashes)).toEqual([CONFIG_PATH, HASH_PATH]); - expect(fs.existsSync(markerPath)).toBe(false); - }); + expect(posture.mode).toBe("locked"); + expect(lockCalls).toHaveLength(2); + expect(lockCalls.every((command) => command[4] === CONFIG_DIR)).toBe(true); + expect(lockCalls.every((command) => command[5] === CONFIG_PATH)).toBe(true); + expect(Object.keys(state.fileHashes)).toEqual([CONFIG_PATH, HASH_PATH]); + expect(fs.existsSync(markerPath)).toBe(false); + }, + ); it("restores the managed sandbox parent when the config is unlocked", () => { entries.set(CONFIG_DIR, { mode: "755", owner: "root:root" }); diff --git a/test/e2e-test.sh b/test/e2e-test.sh index 293a4481c86..5a72d5a17b1 100755 --- a/test/e2e-test.sh +++ b/test/e2e-test.sh @@ -225,7 +225,7 @@ if [ -f "$HOME/.nemoclaw/state/runs/$RUN_ID/plan.json" ]; then else fail "Apply did not persist run state (plan.json missing for $RUN_ID)" fi -rm -f "$APPLY_OUTPUT" "$APPLY_CALLS" +cleanup_apply_fixture trap - EXIT # ------------------------------------------------------- diff --git a/test/helpers/shields-flow-harness.ts b/test/helpers/shields-flow-harness.ts index 51e195641bb..89cc41f1611 100644 --- a/test/helpers/shields-flow-harness.ts +++ b/test/helpers/shields-flow-harness.ts @@ -38,6 +38,7 @@ export type ShieldsFlowHarness = { getOpenClawPosture: () => "locked" | "mutable"; logSpy: MockInstance; policyAuthoritySpy: MockInstance; + policyRecoveryAuthoritySpy: MockInstance; policySetBodies: string[]; runCaptureSpy: MockInstance; runSpy: MockInstance; @@ -369,6 +370,9 @@ export function createShieldsFlowHarness( const policyAuthoritySpy = vi .spyOn(policy, "inspectPolicyMutationAuthority") .mockReturnValue(policyMutationAuthority); + const policyRecoveryAuthoritySpy = vi + .spyOn(policy, "inspectPolicyRecoveryAuthority") + .mockReturnValue(policyMutationAuthority); vi.spyOn(policy, "recheckPolicyMutationAuthority").mockReturnValue(policyMutationAuthority); vi.spyOn(registry, "listSandboxes").mockReturnValue({ sandboxes: [{ name: options.sandboxName ?? "openclaw", agent: resolvedAgentConfig.agentName }], @@ -640,6 +644,7 @@ export function createShieldsFlowHarness( getOpenClawPosture: () => openClawPosture, logSpy, policyAuthoritySpy, + policyRecoveryAuthoritySpy, policySetBodies, runCaptureSpy, runSpy, From a098118ceb1ecbd40123516fe73d0f7a19f6bbe9 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 13:34:33 -0700 Subject: [PATCH 22/40] test(onboard): return policy authority metadata Signed-off-by: Apurv Kumaria --- test/helpers/onboard-openshell-fixture.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/helpers/onboard-openshell-fixture.ts b/test/helpers/onboard-openshell-fixture.ts index 9508afbf988..8179a9fcd42 100644 --- a/test/helpers/onboard-openshell-fixture.ts +++ b/test/helpers/onboard-openshell-fixture.ts @@ -17,7 +17,7 @@ export function writeOkOpenshell( : ""; writeExecutable( path.join(fakeBin, "openshell"), - `#!/usr/bin/env bash\n${sandboxGet}if [ "\${1:-}" = sandbox ] && [ "\${2:-}" = ssh-config ]; then printf "Host openshell-%s.default\\n HostName 127.0.0.1\\n User sandbox\\n" "\${3:-sandbox}"; fi\nexit 0\n`, + `#!/usr/bin/env bash\n${sandboxGet}if [ "\${1:-}" = policy ] && [ "\${2:-}" = get ]; then printf '{"scope":"sandbox","sandbox":"%s","status":"effective","policy_source":"sandbox","policy":{}}\\n' "\${!#}"; fi\nif [ "\${1:-}" = sandbox ] && [ "\${2:-}" = ssh-config ]; then printf "Host openshell-%s.default\\n HostName 127.0.0.1\\n User sandbox\\n" "\${3:-sandbox}"; fi\nexit 0\n`, ); writeExecutable( path.join(fakeBin, "ssh"), From e5ee4a5c609ff4702ff8a0d9e783abb272ba14c0 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 15:06:59 -0700 Subject: [PATCH 23/40] test(onboard): repair policy authority fixtures Signed-off-by: Apurv Kumaria --- ci/test-file-size-budget.json | 2 +- .../handlers/policies-observability.test.ts | 3 ++- test/cli-coverage-sequencer.test.ts | 6 ++--- test/helpers/cli-coverage-sequencer.ts | 2 +- test/helpers/managed-image-buildless-e2e.ts | 22 ++++++++++++++----- test/helpers/onboard-final-flow-phases.ts | 1 + test/onboard-installer-restore-intent.test.ts | 6 ++--- ...onboard-mcp-observability-redirect.test.ts | 6 ++--- test/onboard-messaging.test.ts | 6 ++--- test/onboard-prepared-build-context.test.ts | 7 ++---- test/onboard-sandbox-recreation.test.ts | 20 ++++++++--------- test/onboard-terminal-dashboard.test.ts | 7 +++--- test/onboard.test.ts | 2 +- 13 files changed, 49 insertions(+), 41 deletions(-) diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index a23988624db..4f89ccb204e 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -8,7 +8,7 @@ "test/generate-openclaw-config.test.ts": 1907, "test/installer-integration/install-preflight.test.ts": 3025, "test/nemoclaw-start.test.ts": 4671, - "test/onboard-messaging.test.ts": 2023, + "test/onboard-messaging.test.ts": 2021, "test/onboard-selection.test.ts": 4177 } } diff --git a/src/lib/onboard/machine/handlers/policies-observability.test.ts b/src/lib/onboard/machine/handlers/policies-observability.test.ts index 4f5d85564b8..8fb0c76a073 100644 --- a/src/lib/onboard/machine/handlers/policies-observability.test.ts +++ b/src/lib/onboard/machine/handlers/policies-observability.test.ts @@ -10,7 +10,7 @@ type Agent = { name: string }; describe("handlePoliciesState observability", () => { it("threads durable observability intent into policy reconciliation", async () => { - const session = createSession({ observabilityEnabled: true }); + const session = createSession({ observabilityEnabled: true, policyAuthority: "nemoclaw-managed" }); const prepareResume = vi.fn(() => ({ policyPresets: [], recordedPolicyPresetsNeedReconcile: false, @@ -64,6 +64,7 @@ describe("handlePoliciesState observability", () => { it("keeps an authoritative rebuild tier through resume preparation and policy setup", async () => { const session = createSession({ observabilityEnabled: true, + policyAuthority: "nemoclaw-managed", policyPresets: ["observability-otlp-local"], }); const prepareResume = vi.fn(() => ({ diff --git a/test/cli-coverage-sequencer.test.ts b/test/cli-coverage-sequencer.test.ts index 5304e8ef83c..8f2fb2f90ca 100644 --- a/test/cli-coverage-sequencer.test.ts +++ b/test/cli-coverage-sequencer.test.ts @@ -117,9 +117,9 @@ describe("stable CLI coverage sharding", () => { expect(Object.fromEntries(owners)).toEqual({ "cli:src/lib/example.test.ts": 6, "e2e-support:test/e2e/support/example.test.ts": 8, - "integration:test/hermes-restart-config-seal-write-lock.test.ts": 1, - "integration:test/local-credential-helper-fields.test.ts": 2, - "integration:test/regular-0.test.ts": 8, + "integration:test/hermes-restart-config-seal-write-lock.test.ts": 5, + "integration:test/local-credential-helper-fields.test.ts": 6, + "integration:test/regular-0.test.ts": 3, }); }); diff --git a/test/helpers/cli-coverage-sequencer.ts b/test/helpers/cli-coverage-sequencer.ts index 8f92bba15b8..821237ee492 100644 --- a/test/helpers/cli-coverage-sequencer.ts +++ b/test/helpers/cli-coverage-sequencer.ts @@ -42,7 +42,7 @@ const cliCoverageProjects = new Set(["cli", "integration", "e2e-support"]); // Integration coverage is serialized, so it needs an independent salt instead // of relying on combined weight from the parallel CLI and E2E-support lanes. const stableShardSalt = "7257"; -const integrationShardSalt = "2015"; +const integrationShardSalt = "44308"; const e2eSupportShardSalt = "13930"; // Only measured outliers are stored; new and ordinary files share the // conservative fallback used to estimate each stable shard's load. diff --git a/test/helpers/managed-image-buildless-e2e.ts b/test/helpers/managed-image-buildless-e2e.ts index 32f2e8c105c..3d733717ba8 100644 --- a/test/helpers/managed-image-buildless-e2e.ts +++ b/test/helpers/managed-image-buildless-e2e.ts @@ -478,11 +478,22 @@ runner.runCapture = (command) => { .mockOnboardRunCapture(command); return mocked === null ? "" : mocked; }; -runner.runCaptureEx = (command) => ({ - status: 0, - stdout: runner.runCapture(command), - stderr: "", -}); +runner.runCaptureEx = (command) => { + const normalized = normalize(command); + const sandboxPolicy = { + scope: "sandbox", + sandbox: sandboxName, + status: "effective", + policy_source: "sandbox", + policy: {}, + }; + const stdout = normalized.includes("policy list") && normalized.includes("--global") + ? "" + : normalized.includes("policy get") + ? JSON.stringify(sandboxPolicy) + : runner.runCapture(command); + return { status: 0, stdout, stderr: "", exitCode: 0, timedOut: false }; +}; const registry = require(${source("src/lib/state/registry.ts")}); const sourceEntry = recreate ? { @@ -493,6 +504,7 @@ const sourceEntry = recreate ? { imageTag: catalogTemplate.hermes.reference, model, provider, + policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive", workload: { schemaVersion: 1, diff --git a/test/helpers/onboard-final-flow-phases.ts b/test/helpers/onboard-final-flow-phases.ts index 6308b75c007..fd5081e4a7b 100644 --- a/test/helpers/onboard-final-flow-phases.ts +++ b/test/helpers/onboard-final-flow-phases.ts @@ -89,6 +89,7 @@ export function sessionAt(state: OnboardMachineState): Session { sandboxName: "my-sandbox", provider: "nim", model: "nvidia/test", + policyAuthority: "nemoclaw-managed", machine: { version: MACHINE_SNAPSHOT_VERSION, state, diff --git a/test/onboard-installer-restore-intent.test.ts b/test/onboard-installer-restore-intent.test.ts index 9e5544631db..20488e238fc 100644 --- a/test/onboard-installer-restore-intent.test.ts +++ b/test/onboard-installer-restore-intent.test.ts @@ -91,7 +91,7 @@ runner.runCapture = (command) => { }; registry.getSandbox = () => ({ name: "my-assistant", - gpuEnabled: false, + gpuEnabled: false, policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive", }); registry.registerSandbox = () => true; @@ -292,7 +292,7 @@ const sourceEntry = { agent: "openclaw", gpuEnabled: false, imageTag: "nemoclaw/my-assistant:1", - toolDisclosure: "progressive", + policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive", }; const racedEntry = process.env.NEMOCLAW_TEST_REGISTRY_RACE === "removed" @@ -421,7 +421,7 @@ runner.runCapture = (command) => { }; registry.getSandbox = () => ({ name: "my-assistant", - gpuEnabled: false, + gpuEnabled: false, policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive", }); sandboxState.getLatestBackup = () => { diff --git a/test/onboard-mcp-observability-redirect.test.ts b/test/onboard-mcp-observability-redirect.test.ts index 5bd9da7c4b6..cc471bdae1a 100644 --- a/test/onboard-mcp-observability-redirect.test.ts +++ b/test/onboard-mcp-observability-redirect.test.ts @@ -7,6 +7,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, it } from "vitest"; +import { writeOkOpenshell } from "./helpers/onboard-openshell-fixture"; const repoRoot = path.join(import.meta.dirname, ".."); @@ -16,9 +17,7 @@ describe("onboard managed MCP recreation redirect", () => { const fakeBin = path.join(tmpDir, "bin"); const scriptPath = path.join(tmpDir, "redirect.js"); fs.mkdirSync(fakeBin, { recursive: true }); - fs.writeFileSync(path.join(fakeBin, "openshell"), "#!/usr/bin/env bash\nexit 0\n", { - mode: 0o755, - }); + writeOkOpenshell(fakeBin); const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); @@ -52,6 +51,7 @@ registry.getSandbox = () => ({ preferredInferenceApi: "openai-completions", toolDisclosure: "progressive", observabilityEnabled: true, + policyAuthority: "nemoclaw-managed", mcp: { version: 1, bridges: { diff --git a/test/onboard-messaging.test.ts b/test/onboard-messaging.test.ts index 6c7a95beaa6..d6c2e102d89 100644 --- a/test/onboard-messaging.test.ts +++ b/test/onboard-messaging.test.ts @@ -1223,9 +1223,7 @@ const { createSandbox } = require(${onboardPath}); ); fs.mkdirSync(fakeBin, { recursive: true }); - fs.writeFileSync(path.join(fakeBin, "openshell"), "#!/usr/bin/env bash\nexit 0\n", { - mode: 0o755, - }); + writeOkOpenshell(fakeBin); const script = String.raw` const runner = require(${runnerPath}); @@ -1250,7 +1248,7 @@ runner.runCapture = (command) => { if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running\nmy-assistant 127.0.0.1 8642 12346 running"; return ""; }; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); +registry.getSandbox = () => ({ name: "my-assistant", policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive" }); const { createSandbox } = require(${onboardPath}); (async () => { diff --git a/test/onboard-prepared-build-context.test.ts b/test/onboard-prepared-build-context.test.ts index bf7ad7c39cf..57114c786a7 100644 --- a/test/onboard-prepared-build-context.test.ts +++ b/test/onboard-prepared-build-context.test.ts @@ -7,6 +7,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, it } from "vitest"; +import { writeOkOpenshell } from "./helpers/onboard-openshell-fixture"; type PreparedContextScenario = "create" | "custom-dockerfile"; @@ -35,11 +36,7 @@ function runPreparedContextScenario(scenario: PreparedContextScenario): Prepared fs.mkdirSync(fakeBin, { recursive: true }); fs.mkdirSync(preparedBuildCtx, { recursive: true }); - fs.writeFileSync( - path.join(fakeBin, "openshell"), - '#!/usr/bin/env bash\nif [ "${1:-}" = sandbox ] && [ "${2:-}" = get ]; then printf "Sandbox:\\n\\n Id: fixture-prepared-sandbox\\n Name: %s\\n Phase: Ready\\n" "${!#}"; fi\nexit 0\n', - { mode: 0o755 }, - ); + writeOkOpenshell(fakeBin, { readySandboxGet: true }); fs.writeFileSync( path.join(preparedBuildCtx, "Dockerfile"), ["FROM scratch", `ARG NEMOCLAW_BUILD_ID=${buildId}`, 'CMD ["/bin/true"]', ""].join("\n"), diff --git a/test/onboard-sandbox-recreation.test.ts b/test/onboard-sandbox-recreation.test.ts index 93f14d892b5..882d11af3e6 100644 --- a/test/onboard-sandbox-recreation.test.ts +++ b/test/onboard-sandbox-recreation.test.ts @@ -57,7 +57,7 @@ runner.runCapture = (command) => { if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; return ""; }; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); +registry.getSandbox = () => ({ name: "my-assistant", policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive" }); childProcess.spawn = () => { throw new Error("unexpected sandbox create"); }; @@ -129,7 +129,7 @@ const { EventEmitter } = require("node:events"); const commands = []; let registeredSandbox = null; const sourceSandbox = { name: "my-assistant", - gpuEnabled: false, + gpuEnabled: false, policyAuthority: "nemoclaw-managed", openshellDriver: "docker", imageTag: "openshell/sandbox-from:source", workload: { @@ -300,7 +300,7 @@ runner.runCapture = (command) => { } return ""; }; -registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); +registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false, policyAuthority: "nemoclaw-managed" }); registry.registerSandbox = () => true; registry.updateSandbox = () => true; registry.setDefault = () => true; @@ -457,7 +457,7 @@ runner.runCapture = (command) => { } return ""; }; -registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); +registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false, policyAuthority: "nemoclaw-managed" }); registry.registerSandbox = () => true; registry.updateSandbox = () => true; registry.setDefault = () => true; @@ -593,7 +593,7 @@ runner.runCapture = (command) => { } return ""; }; -registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); +registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false, policyAuthority: "nemoclaw-managed" }); registry.registerSandbox = () => true; registry.updateSandbox = () => true; registry.setDefault = () => true; @@ -748,7 +748,7 @@ runner.runCapture = (command) => { // customisation rather than reverting to the tier defaults. registry.getSandbox = () => ({ name: "my-assistant", - gpuEnabled: false, + gpuEnabled: false, policyAuthority: "nemoclaw-managed", policies: ["npm"], policyTier: "balanced", }); @@ -886,7 +886,7 @@ runner.runCapture = (command) => { if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; return ""; }; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); +registry.getSandbox = () => ({ name: "my-assistant", policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive" }); // Mock prompt to return "y" (reuse) credentials.prompt = async () => "y"; @@ -1031,7 +1031,7 @@ runner.runCapture = (command) => { } return ""; }; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); +registry.getSandbox = () => ({ name: "my-assistant", policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive" }); registry.registerSandbox = () => true; registry.updateSandbox = () => true; registry.setDefault = () => true; @@ -1167,7 +1167,7 @@ runner.runCapture = (command) => { } return ""; }; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); +registry.getSandbox = () => ({ name: "my-assistant", policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive" }); registry.registerSandbox = () => true; registry.updateSandbox = () => true; registry.setDefault = () => true; @@ -1444,7 +1444,7 @@ const { createSandbox } = require(${onboardPath}); const ownerScopedObservations = payload.lifecycleObservationCommands.filter( (command: string) => command.includes("-g nemoclaw"), ); - assert.equal(ownerScopedObservations.length, 4); + assert.equal(ownerScopedObservations.length, 6); assert.ok( ownerScopedObservations.every( (command: string) => diff --git a/test/onboard-terminal-dashboard.test.ts b/test/onboard-terminal-dashboard.test.ts index d6ea33b75c9..7808d68b4c2 100644 --- a/test/onboard-terminal-dashboard.test.ts +++ b/test/onboard-terminal-dashboard.test.ts @@ -7,6 +7,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, it } from "vitest"; +import { writeOkOpenshell } from "./helpers/onboard-openshell-fixture"; type CommandEntry = { command: string; @@ -43,10 +44,7 @@ function runTerminalDashboardScenario(scenario: "create" | "reuse") { ); fs.mkdirSync(fakeBin, { recursive: true }); - writeExecutable( - path.join(fakeBin, "openshell"), - '#!/usr/bin/env bash\nif [ "${1:-}" = sandbox ] && [ "${2:-}" = get ]; then printf "Sandbox:\\n\\n Id: fixture-terminal-sandbox\\n Name: %s\\n Phase: Ready\\n" "${!#}"; fi\nexit 0\n', - ); + writeOkOpenshell(fakeBin, { readySandboxGet: true }); const script = String.raw` const fs = require("node:fs"); @@ -137,6 +135,7 @@ registry.getSandbox = () => agent: "langchain-deepagents-code", dashboardPort: 18789, observabilityEnabled: false, + policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive", } : null; diff --git a/test/onboard.test.ts b/test/onboard.test.ts index 017d3675a05..2518eb23b70 100644 --- a/test/onboard.test.ts +++ b/test/onboard.test.ts @@ -694,7 +694,7 @@ runner.runCapture = (command) => { if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; return ""; }; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); +registry.getSandbox = () => ({ name: "my-assistant", policyAuthority: "nemoclaw-managed", toolDisclosure: "progressive" }); childProcess.spawn = (...args) => { const child = new EventEmitter(); From a0fa36d7a9750f1eef06cfb87b993fa74278c257 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 16:08:59 -0700 Subject: [PATCH 24/40] fix(policy): preserve external Shields recovery Signed-off-by: Apurv Kumaria --- src/lib/policy/README.md | 9 +- src/lib/policy/context-builder.ts | 4 +- src/lib/policy/context.test.ts | 5 +- src/lib/shields/flow.test.ts | 18 +++ src/lib/shields/index.ts | 158 ++++++++++++++------ src/lib/shields/openclaw-transition.test.ts | 20 ++- src/lib/shields/policy-transition.test.ts | 2 +- test/helpers/shields-flow-harness.ts | 44 ++++++ 8 files changed, 204 insertions(+), 56 deletions(-) diff --git a/src/lib/policy/README.md b/src/lib/policy/README.md index 83724d60749..d426258eec7 100644 --- a/src/lib/policy/README.md +++ b/src/lib/policy/README.md @@ -28,10 +28,11 @@ The external authority must supply a missing or changed entry. If policy authority becomes external while Shields is down, NemoClaw keeps the saved restrictive policy snapshot and refuses to set policy. The external -policy authority must apply that exact snapshot as the sandbox policy. Then run -`nemoclaw shields up`. NemoClaw verifies the exact live policy and -locks configuration without changing policy authority. `shields status` -reports this recovery requirement while the sandbox remains unlocked. +policy authority must make the effective policy for the named sandbox match the +saved restrictive snapshot and current managed MCP entries without changing +policy authority. Then run `nemoclaw shields up`. NemoClaw verifies +the exact effective policy and locks configuration. `shields status` reports +this recovery requirement while the sandbox remains unlocked. A legacy sandbox record retains the first qualified `policyAuthority` after a later operation fails. An inspection that cannot determine authority does not change the record. diff --git a/src/lib/policy/context-builder.ts b/src/lib/policy/context-builder.ts index 5c7abae914c..b07894602ff 100644 --- a/src/lib/policy/context-builder.ts +++ b/src/lib/policy/context-builder.ts @@ -562,7 +562,9 @@ export function renderPolicyContextMarkdown(ctx: PolicyContext): string { lines.push(`- inspect: \`${ctx.approvalPath.inspect}\``); lines.push(`- add a preset: ${formatApprovalAction(ctx.approvalPath.add)}`); lines.push(`- remove a preset: ${formatApprovalAction(ctx.approvalPath.remove)}`); - lines.push(`- preview a baseline exclusion: \`${ctx.approvalPath.excludeBaseline}\``); + lines.push( + `- preview a baseline exclusion: ${formatApprovalAction(ctx.approvalPath.excludeBaseline)}`, + ); lines.push( `- restore a baseline entry: ${formatApprovalAction(ctx.approvalPath.restoreBaseline)}`, ); diff --git a/src/lib/policy/context.test.ts b/src/lib/policy/context.test.ts index be3fe6be802..96a067fff42 100644 --- a/src/lib/policy/context.test.ts +++ b/src/lib/policy/context.test.ts @@ -222,7 +222,10 @@ describe("buildPolicyContext", () => { "- Shields state and configuration lock (owner: nemoclaw) — NemoClaw retains Shields state and locks configuration after it verifies restrictive policy", ); expect(markdown).toContain( - "Run `nemoclaw alpha policy exclude --dry-run`, then ask the external policy authority to remove baseline policy entry ``.", + "- preview a baseline exclusion: Run `nemoclaw alpha policy exclude --dry-run`, then ask the external policy authority to remove baseline policy entry ``.", + ); + expect(markdown).not.toContain( + "- preview a baseline exclusion: `Run `nemoclaw alpha policy exclude --dry-run`", ); expect(markdown).not.toMatch(/nemoclaw alpha policy (?:add|remove|restore)(?:\s|`)/u); }); diff --git a/src/lib/shields/flow.test.ts b/src/lib/shields/flow.test.ts index 33923017e3b..292470a190f 100644 --- a/src/lib/shields/flow.test.ts +++ b/src/lib/shields/flow.test.ts @@ -10,9 +10,11 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; import YAML from "yaml"; import { + bindExternalPolicyRecovery, createShieldsFlowHarness, managedMcpPolicy, managedMcpSandbox, + prepareExternalMcpRecoveryFixture, type ShieldsFlowHarnessOptions, writeShieldsTimerAuthorizationProof, } from "../../../test/helpers/shields-flow-harness"; @@ -157,6 +159,22 @@ describe("shields command flow", () => { expect(applied.network_policies).not.toHaveProperty("restrictive_baseline"); }); + it("requires current managed MCP entries during external policy recovery (#9833)", () => { + const { alpha, beta, harness, savedPolicy, snapshotPath } = prepareExternalMcpRecoveryFixture( + requireDist, + tmpDir, + ); + bindExternalPolicyRecovery(harness, savedPolicy); + expect(() => harness.applyShieldsPolicySnapshot("openclaw", snapshotPath)).toThrow( + /managed MCP/iu, + ); + const requiredPolicy = structuredClone(savedPolicy); + delete requiredPolicy.network_policies[alpha.key]; + requiredPolicy.network_policies[beta.key] = beta.networkPolicy; + bindExternalPolicyRecovery(harness, requiredPolicy); + expect(harness.applyShieldsPolicySnapshot("openclaw", snapshotPath).status).toBe(0); + }); + it("isolates same-millisecond policy snapshots and cleanup across sandboxes", () => { const fixedNow = Date.now(); vi.spyOn(Date, "now").mockReturnValue(fixedNow); diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index 0719ff65d8a..45cd5c08ade 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -171,27 +171,19 @@ function readShieldsPolicySnapshot(snapshotPath: string): Record, ): boolean { - return isDeepStrictEqual( - authority.inspection.effectivePolicy, - readShieldsPolicySnapshot(snapshotPath), - ); + return isDeepStrictEqual(authority.inspection.effectivePolicy, requiredPolicy); } -function externalPolicyRecoveryHandoff( - sandboxName: string, - snapshotPath: string, - restrictivePolicyVerified: boolean, -): string { - return restrictivePolicyVerified - ? `NemoClaw verified the saved restrictive policy for sandbox '${sandboxName}' under external policy authority. ` + - `Run \`${CLI_NAME} ${sandboxName} shields up\` to lock configuration and finish the Shields transition without changing policy.` - : `NemoClaw cannot finish the Shields transition for sandbox '${sandboxName}' while its external policy differs from the saved restrictive snapshot. ` + - `The external policy authority must apply '${snapshotPath}' as the sandbox policy. Then run \`${CLI_NAME} ${sandboxName} shields up\`. ` + - "NemoClaw will verify the exact live policy and lock configuration without changing policy."; +function externalPolicyRecoveryHandoff(sandboxName: string): string { + return ( + `NemoClaw cannot finish the Shields transition for sandbox '${sandboxName}' while its effective policy differs from the required restrictive policy. ` + + "The external policy authority must make the effective policy for this named sandbox match the saved restrictive snapshot and current managed MCP entries without changing policy authority. " + + `Then run \`${CLI_NAME} ${sandboxName} shields up\`. NemoClaw will verify the exact effective policy and lock configuration.` + ); } type ShieldsPolicySnapshotRestoreAuthority = { @@ -199,11 +191,17 @@ type ShieldsPolicySnapshotRestoreAuthority = { policyMutationAllowed: boolean; }; -function resolveShieldsPolicySnapshotRestoreAuthority( +function inspectShieldsPolicySnapshotRestoreAuthority( sandboxName: string, - snapshotPath: string, recorded?: PolicyMutationAuthority, -): ShieldsPolicySnapshotRestoreAuthority { +): PolicyMutationAuthority { + if (recorded?.authority === "externally-managed") { + return inspectPolicyRecoveryAuthority( + sandboxName, + "verify the externally restored Shields policy snapshot", + recorded.gatewayName, + ); + } let authority: PolicyMutationAuthority; try { authority = recorded @@ -217,11 +215,23 @@ function resolveShieldsPolicySnapshotRestoreAuthority( recorded?.gatewayName, ); } + return authority; +} + +function resolveShieldsPolicySnapshotRestoreAuthority( + sandboxName: string, + requiredPolicy: Record, + recorded?: PolicyMutationAuthority, +): ShieldsPolicySnapshotRestoreAuthority { + const authority = inspectShieldsPolicySnapshotRestoreAuthority(sandboxName, recorded); + if (recorded && authority.authority !== recorded.authority) { + throw new Error(externalPolicyRecoveryHandoff(sandboxName)); + } if (authority.authority === "nemoclaw-managed") { return { authority, policyMutationAllowed: true }; } - if (!externalPolicyMatchesShieldsSnapshot(authority, snapshotPath)) { - throw new Error(externalPolicyRecoveryHandoff(sandboxName, snapshotPath, false)); + if (!externalPolicyMatchesShieldsPolicy(authority, requiredPolicy)) { + throw new Error(externalPolicyRecoveryHandoff(sandboxName)); } const revalidated = inspectPolicyRecoveryAuthority( sandboxName, @@ -230,9 +240,9 @@ function resolveShieldsPolicySnapshotRestoreAuthority( ); if ( revalidated.authority !== "externally-managed" || - !externalPolicyMatchesShieldsSnapshot(revalidated, snapshotPath) + !externalPolicyMatchesShieldsPolicy(revalidated, requiredPolicy) ) { - throw new Error(externalPolicyRecoveryHandoff(sandboxName, snapshotPath, false)); + throw new Error(externalPolicyRecoveryHandoff(sandboxName)); } return { authority: revalidated, policyMutationAllowed: false }; } @@ -256,18 +266,13 @@ function inspectShieldsPolicyRecovery(sandboxName: string): ShieldsPolicyRecover }; } try { - const authority = inspectPolicyRecoveryAuthority( + inspectPolicyRecoveryAuthority( sandboxName, "inspect externally managed Shields policy recovery", ); return { status: "external", - handoff: externalPolicyRecoveryHandoff( - sandboxName, - snapshotPath, - authority.authority === "externally-managed" && - externalPolicyMatchesShieldsSnapshot(authority, snapshotPath), - ), + handoff: externalPolicyRecoveryHandoff(sandboxName), }; } catch (inspectionError) { return { @@ -4214,12 +4219,14 @@ interface ShieldsPolicySnapshotRestoreOptions { transitionProcessToken?: string; deadlineAuthoritative?: boolean; expiredTimerRecovery?: boolean; + externalVerificationOnly?: boolean; buildPolicySet?: typeof buildPolicySetCommand; runPolicySet?: typeof run; } type ShieldsPolicySnapshotRestoreResult = ReturnType & { managedMcpOmissions?: ManagedMcpPolicyOmission[]; + externalPolicyVerified?: true; }; function applyShieldsPolicySnapshot( @@ -4279,17 +4286,10 @@ function applyShieldsPolicySnapshot( throw new Error("Shields state does not match the policy snapshot being restored"); } const persistedSnapshotMatches = state.shieldsPolicySnapshotPath === snapshotPath; - const restoreAuthority = resolveShieldsPolicySnapshotRestoreAuthority(sandboxName, snapshotPath); - const policyAuthority = restoreAuthority.authority; - if (!restoreAuthority.policyMutationAllowed) { - return { - pid: process.pid, - output: [null, "", ""], - stdout: "", - stderr: "", - status: 0, - signal: null, - }; + const policyAuthority = inspectShieldsPolicySnapshotRestoreAuthority(sandboxName); + const policyMutationAllowed = policyAuthority.authority === "nemoclaw-managed"; + if (options.externalVerificationOnly && policyMutationAllowed) { + throw new Error(externalPolicyRecoveryHandoff(sandboxName)); } const ownershipOmissions: ManagedMcpPolicyOmission[] = []; if ( @@ -4321,7 +4321,7 @@ function applyShieldsPolicySnapshot( reason: "Legacy Shields state had no managed MCP ownership manifest at the auto-restore deadline", }); - } else { + } else if (policyMutationAllowed) { assertLegacyMcpPolicyRestoreSafe( fs.readFileSync(snapshotPath, "utf-8"), hasManagedMcpPolicyClaims(sandboxName), @@ -4339,6 +4339,12 @@ function applyShieldsPolicySnapshot( ); rejectFinalShieldsPolicySetResult(result, "restore the Shields policy snapshot"); return result; + } else { + assertLegacyMcpPolicyRestoreSafe( + fs.readFileSync(snapshotPath, "utf-8"), + hasManagedMcpPolicyClaims(sandboxName), + ); + snapshotManagedPolicyKeys = []; } } let managedMcpOmissions: ManagedMcpPolicyOmission[] = []; @@ -4358,7 +4364,9 @@ function applyShieldsPolicySnapshot( } else { const managedMcpPolicies = resolveExactManagedMcpPolicies( sandboxName, - undefined, + policyMutationAllowed + ? undefined + : YAML.stringify(policyAuthority.inspection.effectivePolicy), policyAuthority.gatewayName, ); runtimePolicyPath = buildRuntimeManagedMcpPolicy(snapshotPath, { @@ -4369,6 +4377,23 @@ function applyShieldsPolicySnapshot( } const runtimePolicyIsTemp = runtimePolicyPath !== snapshotPath; try { + if (!policyMutationAllowed) { + const externalRequiredPolicy = readShieldsPolicySnapshot(runtimePolicyPath); + resolveShieldsPolicySnapshotRestoreAuthority( + sandboxName, + externalRequiredPolicy, + policyAuthority, + ); + return { + pid: process.pid, + output: [null, "", ""], + stdout: "", + stderr: "", + status: 0, + signal: null, + externalPolicyVerified: true, + }; + } assertShieldsPolicyMutationAuthority( sandboxName, "restore the Shields policy snapshot", @@ -4554,13 +4579,25 @@ function activateLockdownFromSnapshot( }; } try { - resolveShieldsPolicySnapshotRestoreAuthority(sandboxName, snapshotPath); + if (restoreResult.externalPolicyVerified) { + applyShieldsPolicySnapshot(sandboxName, snapshotPath, { + ...restoreOptions, + externalVerificationOnly: true, + }); + } else { + resolveShieldsPolicySnapshotRestoreAuthority( + sandboxName, + readShieldsPolicySnapshot(snapshotPath), + ); + } } catch (error) { return { ok: false, error: `policy verification after config lock failed: ${ error instanceof Error ? error.message : String(error) }`, + chattrApplied: relock.lastResult.chattrApplied, + fileHashes: relock.lastResult.fileHashes, }; } return { @@ -4639,6 +4676,14 @@ function recoverExpiredAutoRestoreInline( ); const nowIso = new Date().toISOString(); if (!activation.ok) { + const configLocked = + activation.fileHashes !== undefined && typeof activation.chattrApplied === "boolean"; + if (configLocked) { + saveShieldsState(sandboxName, { + chattrApplied: activation.chattrApplied, + fileHashes: activation.fileHashes, + }); + } appendAuditEntry({ action: "shields_up_failed", sandbox: sandboxName, @@ -4648,6 +4693,11 @@ function recoverExpiredAutoRestoreInline( error: `Inline auto-restore failed: ${activation.error ?? "unknown error"}`, }); console.error(" Recovery warning: inline auto-restore failed; shields remain DOWN."); + if (configLocked) { + console.error( + " Recovery warning: configuration remains locked while policy recovery waits.", + ); + } console.error(` Recovery warning: run \`nemoclaw ${sandboxName} shields up\` manually.`); return { attempted: true, restored: false }; } @@ -5939,9 +5989,23 @@ function shieldsUpWithoutHostLock(sandboxName: string, opts: ShieldsUpOpts = {}) protocol, ); if (!activation.ok) { + const configLocked = + activation.fileHashes !== undefined && typeof activation.chattrApplied === "boolean"; + if (configLocked) { + saveShieldsState(sandboxName, { + chattrApplied: activation.chattrApplied, + fileHashes: activation.fileHashes, + }); + } console.error(` ERROR: ${activation.error ?? "unknown restore error"}`); - console.error(" Config remains unlocked — manual intervention required."); - printManualRelockRecoveryHint(sandboxName); + if (configLocked) { + console.error( + " Config remains locked; Shields remain DOWN until policy verification succeeds.", + ); + } else { + console.error(" Config remains unlocked — manual intervention required."); + printManualRelockRecoveryHint(sandboxName); + } return failShieldsCommand(activation.error ?? "unknown restore error", opts.throwOnError); } if (activation.fileHashes && typeof activation.chattrApplied === "boolean") { diff --git a/src/lib/shields/openclaw-transition.test.ts b/src/lib/shields/openclaw-transition.test.ts index 4a08c0759d4..0de9fd2f0a0 100644 --- a/src/lib/shields/openclaw-transition.test.ts +++ b/src/lib/shields/openclaw-transition.test.ts @@ -1426,7 +1426,9 @@ describe("external Shields policy recovery", () => { harness.policyAuthoritySpy.mockReturnValue(mismatchedExternalAuthority); harness.policyRecoveryAuthoritySpy.mockReturnValue(mismatchedExternalAuthority); - expect(() => harness.shieldsUp(sandboxName, { throwOnError: true })).toThrow("must apply"); + expect(() => harness.shieldsUp(sandboxName, { throwOnError: true })).toThrow( + "must make the effective policy", + ); expect(countPolicySets(harness)).toBe(policySetsAfterDown); expect(harness.getOpenClawPosture()).toBe("mutable"); @@ -1435,7 +1437,9 @@ describe("external Shields policy recovery", () => { }) as typeof process.exit); expect(() => harness.shieldsStatus(sandboxName, false)).toThrow("process exit 2"); expect(exitSpy).toHaveBeenCalledWith(2); - expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain("must apply"); + expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain( + "must make the effective policy", + ); const restoredExternalAuthority = externalAuthority( readRestrictivePolicy(harness, sandboxName), @@ -1464,6 +1468,7 @@ describe("external Shields policy recovery", () => { const changedExternalAuthority = externalAuthority({ version: 1, network_policies: {} }); harness.policyAuthoritySpy.mockReturnValue(restoredExternalAuthority); harness.policyRecoveryAuthoritySpy + .mockReturnValueOnce(restoredExternalAuthority) .mockReturnValueOnce(restoredExternalAuthority) .mockReturnValue(changedExternalAuthority); @@ -1472,9 +1477,20 @@ describe("external Shields policy recovery", () => { ); expect(harness.isShieldsDown(sandboxName)).toBe(true); + expect(harness.getOpenClawPosture()).toBe("locked"); expect(countPolicySets(harness)).toBe(policySetsAfterDown); + const errors = harness.errorSpy.mock.calls.flat().join("\n"); + expect(errors).toContain( + "Config remains locked; Shields remain DOWN until policy verification succeeds.", + ); + expect(errors).not.toContain("Config remains unlocked"); expect(harness.auditSpy).not.toHaveBeenCalledWith( expect.objectContaining({ action: "shields_up" }), ); + + harness.policyRecoveryAuthoritySpy.mockReturnValue(restoredExternalAuthority); + harness.shieldsUp(sandboxName, { throwOnError: true }); + expect(harness.isShieldsDown(sandboxName)).toBe(false); + expect(harness.getOpenClawPosture()).toBe("locked"); }); }); diff --git a/src/lib/shields/policy-transition.test.ts b/src/lib/shields/policy-transition.test.ts index e273cebfaef..12c436f11c4 100644 --- a/src/lib/shields/policy-transition.test.ts +++ b/src/lib/shields/policy-transition.test.ts @@ -157,7 +157,7 @@ describe("shields policy transition", () => { }); expect(() => shields.applyShieldsPolicySnapshot(sandboxName, snapshotPath)).toThrow( - "must apply", + "must make the effective policy", ); expect(runSpy).not.toHaveBeenCalled(); }); diff --git a/test/helpers/shields-flow-harness.ts b/test/helpers/shields-flow-harness.ts index 89cc41f1611..3f6d522fd9f 100644 --- a/test/helpers/shields-flow-harness.ts +++ b/test/helpers/shields-flow-harness.ts @@ -18,6 +18,50 @@ export const externalPolicyAuthorityInspection = { effectivePolicy: { version: 1, network_policies: {} }, }; +export function externalPolicyMutationAuthority(effectivePolicy: Record) { + return { + authority: "externally-managed" as const, + authorityRecordedNow: false, + gatewayName: "nemoclaw", + inspection: { authority: "externally-managed" as const, effectivePolicy }, + }; +} + +export function prepareExternalMcpRecoveryFixture(requireDist: NodeRequire, tmpDir: string) { + const alpha = managedMcpPolicy("alpha"); + const beta = managedMcpPolicy("beta"); + const harness = createShieldsFlowHarness(requireDist, tmpDir, { + livePolicyYaml: YAML.stringify({ + version: 1, + network_policies: { restrictive_baseline: {}, [alpha.key]: alpha.networkPolicy }, + }), + sandboxEntry: managedMcpSandbox([alpha]), + }); + harness.shieldsDown("openclaw", { throwOnError: true }); + const snapshotPath = String( + harness.getShieldsPosture("openclaw", false).state.shieldsPolicySnapshotPath, + ); + const savedPolicy = YAML.parse(fs.readFileSync(snapshotPath, "utf-8")); + const registry = requireDist( + "../state/registry.js", + ) as typeof import("../../src/lib/state/registry.js"); + vi.mocked(registry.getSandbox).mockReturnValue({ + ...managedMcpSandbox([beta]), + policyAuthority: "externally-managed", + }); + return { alpha, beta, harness, savedPolicy, snapshotPath }; +} + +export function bindExternalPolicyRecovery( + harness: ShieldsFlowHarness, + effectivePolicy: Record, +): void { + const authority = externalPolicyMutationAuthority(effectivePolicy); + harness.policyAuthoritySpy.mockReturnValue(authority); + harness.policyRecoveryAuthoritySpy.mockReturnValue(authority); + harness.runCaptureSpy.mockReturnValue(YAML.stringify(effectivePolicy)); +} + export const managedPolicyMutationAuthority = { authority: "nemoclaw-managed" as const, authorityRecordedNow: false, From ceae05ec51717b32e781b84deac0fa48842d2d4b Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 17:13:15 -0700 Subject: [PATCH 25/40] fix(shields): retain locked policy recovery Signed-off-by: Apurv Kumaria --- src/lib/policy/README.md | 8 +- src/lib/shields/index.test.ts | 6 + src/lib/shields/index.ts | 237 ++++++++++++++---- src/lib/shields/mutable-config-repair.test.ts | 65 +++++ src/lib/shields/openclaw-transition.test.ts | 12 +- src/lib/shields/policy-transition.test.ts | 23 +- 6 files changed, 294 insertions(+), 57 deletions(-) diff --git a/src/lib/policy/README.md b/src/lib/policy/README.md index d426258eec7..a6001a3ec3f 100644 --- a/src/lib/policy/README.md +++ b/src/lib/policy/README.md @@ -30,9 +30,11 @@ If policy authority becomes external while Shields is down, NemoClaw keeps the saved restrictive policy snapshot and refuses to set policy. The external policy authority must make the effective policy for the named sandbox match the saved restrictive snapshot and current managed MCP entries without changing -policy authority. Then run `nemoclaw shields up`. NemoClaw verifies -the exact effective policy and locks configuration. `shields status` reports -this recovery requirement while the sandbox remains unlocked. +policy authority. `shields status` identifies that required policy by its +canonical JSON SHA-256 digest and network policy keys. Then run +`nemoclaw shields up`. NemoClaw verifies the exact effective policy +and locks configuration. If policy changes during the lock, NemoClaw records +the verified config lock and keeps Shields down until policy recovery succeeds. A legacy sandbox record retains the first qualified `policyAuthority` after a later operation fails. An inspection that cannot determine authority does not change the record. diff --git a/src/lib/shields/index.test.ts b/src/lib/shields/index.test.ts index 927d9cd1d06..e652ca86629 100644 --- a/src/lib/shields/index.test.ts +++ b/src/lib/shields/index.test.ts @@ -406,6 +406,12 @@ describe("shields — unit logic", () => { expect(deriveShieldsMode({}, false)).toBe("mutable_default"); expect(deriveShieldsMode({ shieldsDown: true }, true)).toBe("temporarily_unlocked"); + expect( + deriveShieldsMode( + { shieldsDown: true, policyRecoveryConfigLocked: true }, + true, + ), + ).toBe("locked_recovery"); expect(deriveShieldsMode({ shieldsDown: false }, true)).toBe("locked"); expect(deriveShieldsMode({}, true)).toBe("mutable_default"); }, diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index 45cd5c08ade..661847565bd 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -138,6 +138,7 @@ const { }: typeof import("./hermes-runtime-state-mutation") = require("./hermes-runtime-state-mutation"); type MutableConfigPermsInspection = import("./mutable-config-perms").MutableConfigPermsInspection; type MutableConfigRepairResult = import("./mutable-config-perms").MutableConfigRepairResult; +type MutableConfigPostureMode = import("./mutable-config-perms").MutableConfigPostureMode; type AgentStateLockPlan = import("../agent/definition-types").AgentStateLockPlan; type ManagedMcpPolicyOmission = import("./permissive-runtime").ManagedMcpPolicyOmission; type TimerMarker = import("./timer-control").TimerMarker; @@ -178,14 +179,63 @@ function externalPolicyMatchesShieldsPolicy( return isDeepStrictEqual(authority.inspection.effectivePolicy, requiredPolicy); } -function externalPolicyRecoveryHandoff(sandboxName: string): string { +function canonicalPolicyValue(value: unknown): unknown { + if (Array.isArray(value)) return value.map(canonicalPolicyValue); + if (!isObjectRecord(value)) return value; + return Object.fromEntries( + Object.keys(value) + .sort() + .map((key) => [key, canonicalPolicyValue(value[key])]), + ); +} + +function requiredPolicyReference(requiredPolicy: Record): string { + const digest = createHash("sha256") + .update(JSON.stringify(canonicalPolicyValue(requiredPolicy)), "utf8") + .digest("hex"); + const policyKeys = isObjectRecord(requiredPolicy.network_policies) + ? Object.keys(requiredPolicy.network_policies).sort() + : []; + return `canonical JSON SHA-256 ${digest}; network policy keys: ${ + policyKeys.length > 0 ? policyKeys.join(", ") : "(none)" + }`; +} + +type ExternalPolicyRecoveryReason = "authority-drift" | "policy-mismatch"; + +class ExternalShieldsPolicyRecoveryError extends Error { + constructor(readonly reason: ExternalPolicyRecoveryReason, message: string) { + super(message); + this.name = "ExternalShieldsPolicyRecoveryError"; + } +} + +function externalPolicyRecoveryHandoff( + sandboxName: string, + requiredPolicy: Record, + reason: ExternalPolicyRecoveryReason, +): string { + const cause = + reason === "authority-drift" + ? `Policy authority changed while NemoClaw verified recovery for sandbox '${sandboxName}'.` + : `The effective policy for sandbox '${sandboxName}' does not match the required restrictive policy.`; return ( - `NemoClaw cannot finish the Shields transition for sandbox '${sandboxName}' while its effective policy differs from the required restrictive policy. ` + + `${cause} Required effective policy reference: ${requiredPolicyReference(requiredPolicy)}. ` + "The external policy authority must make the effective policy for this named sandbox match the saved restrictive snapshot and current managed MCP entries without changing policy authority. " + `Then run \`${CLI_NAME} ${sandboxName} shields up\`. NemoClaw will verify the exact effective policy and lock configuration.` ); } +function externalPolicyVerifiedHandoff( + sandboxName: string, + requiredPolicy: Record, +): string { + return ( + `NemoClaw verified the required effective policy for sandbox '${sandboxName}' (${requiredPolicyReference(requiredPolicy)}). ` + + `Run \`${CLI_NAME} ${sandboxName} shields up\` to finish the config lock without changing policy authority.` + ); +} + type ShieldsPolicySnapshotRestoreAuthority = { authority: PolicyMutationAuthority; policyMutationAllowed: boolean; @@ -223,26 +273,47 @@ function resolveShieldsPolicySnapshotRestoreAuthority( requiredPolicy: Record, recorded?: PolicyMutationAuthority, ): ShieldsPolicySnapshotRestoreAuthority { + if ( + recorded?.authority === "externally-managed" && + !externalPolicyMatchesShieldsPolicy(recorded, requiredPolicy) + ) { + throw new ExternalShieldsPolicyRecoveryError( + "policy-mismatch", + externalPolicyRecoveryHandoff(sandboxName, requiredPolicy, "policy-mismatch"), + ); + } const authority = inspectShieldsPolicySnapshotRestoreAuthority(sandboxName, recorded); if (recorded && authority.authority !== recorded.authority) { - throw new Error(externalPolicyRecoveryHandoff(sandboxName)); + throw new ExternalShieldsPolicyRecoveryError( + "authority-drift", + externalPolicyRecoveryHandoff(sandboxName, requiredPolicy, "authority-drift"), + ); } if (authority.authority === "nemoclaw-managed") { return { authority, policyMutationAllowed: true }; } if (!externalPolicyMatchesShieldsPolicy(authority, requiredPolicy)) { - throw new Error(externalPolicyRecoveryHandoff(sandboxName)); + throw new ExternalShieldsPolicyRecoveryError( + "policy-mismatch", + externalPolicyRecoveryHandoff(sandboxName, requiredPolicy, "policy-mismatch"), + ); } const revalidated = inspectPolicyRecoveryAuthority( sandboxName, "finish the externally restored Shields policy snapshot verification", authority.gatewayName, ); - if ( - revalidated.authority !== "externally-managed" || - !externalPolicyMatchesShieldsPolicy(revalidated, requiredPolicy) - ) { - throw new Error(externalPolicyRecoveryHandoff(sandboxName)); + if (revalidated.authority !== "externally-managed") { + throw new ExternalShieldsPolicyRecoveryError( + "authority-drift", + externalPolicyRecoveryHandoff(sandboxName, requiredPolicy, "authority-drift"), + ); + } + if (!externalPolicyMatchesShieldsPolicy(revalidated, requiredPolicy)) { + throw new ExternalShieldsPolicyRecoveryError( + "policy-mismatch", + externalPolicyRecoveryHandoff(sandboxName, requiredPolicy, "policy-mismatch"), + ); } return { authority: revalidated, policyMutationAllowed: false }; } @@ -253,34 +324,40 @@ type ShieldsPolicyRecoveryInspection = | { status: "unavailable"; detail: string }; function inspectShieldsPolicyRecovery(sandboxName: string): ShieldsPolicyRecoveryInspection { + const state = loadShieldsState(sandboxName); + let authority: PolicyMutationAuthority; try { - assertShieldsPolicyMutationAuthority(sandboxName, "inspect Shields policy recovery"); + authority = inspectShieldsPolicySnapshotRestoreAuthority(sandboxName); + } catch (error) { + return { + status: "unavailable", + detail: error instanceof Error ? error.message : String(error), + }; + } + if (authority.authority === "nemoclaw-managed" && !state.policyRecoveryConfigLocked) { return { status: "ready" }; + } + const snapshotPath = state.shieldsPolicySnapshotPath; + if (!snapshotPath || !fs.existsSync(snapshotPath)) { + return { + status: "external", + handoff: `The saved restrictive policy snapshot for sandbox '${sandboxName}' is unavailable. Rebuild the sandbox before finishing the Shields transition.`, + }; + } + try { + const result = applyShieldsPolicySnapshot(sandboxName, snapshotPath, { + externalVerificationOnly: true, + }); + if (!result.externalRequiredPolicy) { + throw new Error("External Shields policy verification did not return its required policy"); + } + return { + status: "external", + handoff: externalPolicyVerifiedHandoff(sandboxName, result.externalRequiredPolicy), + }; } catch (error) { - if (isExternalPolicyAuthorityRefusalError(error)) { - const snapshotPath = loadShieldsState(sandboxName).shieldsPolicySnapshotPath; - if (!snapshotPath || !fs.existsSync(snapshotPath)) { - return { - status: "external", - handoff: `The saved restrictive policy snapshot for sandbox '${sandboxName}' is unavailable. Rebuild the sandbox before finishing the Shields transition.`, - }; - } - try { - inspectPolicyRecoveryAuthority( - sandboxName, - "inspect externally managed Shields policy recovery", - ); - return { - status: "external", - handoff: externalPolicyRecoveryHandoff(sandboxName), - }; - } catch (inspectionError) { - return { - status: "unavailable", - detail: - inspectionError instanceof Error ? inspectionError.message : String(inspectionError), - }; - } + if (error instanceof ExternalShieldsPolicyRecoveryError) { + return { status: "external", handoff: error.message }; } return { status: "unavailable", @@ -1539,11 +1616,12 @@ function stateFilePath(sandboxName: string): string { return path.join(STATE_DIR, `shields-${sandboxName}.json`); } -// Three-state shields model: +// Shields posture model: // "mutable_default" — fresh sandbox, shields never configured (the default) // "locked" — shields up has been run and verified // "temporarily_unlocked" — shields down after a prior shields up -type ShieldsMode = "mutable_default" | "locked" | "temporarily_unlocked"; +// "locked_recovery" — config is locked while policy recovery remains incomplete +type ShieldsMode = "locked" | "locked_recovery" | "mutable_default" | "temporarily_unlocked"; type ShieldsPostureMode = ShieldsMode | "error"; interface ShieldsState { @@ -1555,6 +1633,7 @@ interface ShieldsState { shieldsPolicySnapshotPath?: string | null; /** Exact generated MCP keys owned in the restrictive snapshot. */ shieldsManagedMcpPolicyKeys?: string[]; + policyRecoveryConfigLocked?: boolean; chattrApplied?: boolean; // SHA-256 seal of each locked file, captured by `shields up` after the // lock verification passes. `shields status` re-hashes the same files @@ -1742,6 +1821,9 @@ function completeDeferredShieldsExit(error: unknown, shouldThrow = false): never */ function deriveShieldsMode(state: ShieldsState, hasStateFile: boolean): ShieldsMode { if (!hasStateFile) return "mutable_default"; + if (state.shieldsDown === true && state.policyRecoveryConfigLocked === true) { + return "locked_recovery"; + } if (state.shieldsDown === true) return "temporarily_unlocked"; if (state.shieldsDown === false) return "locked"; // State file exists but shieldsDown is undefined — treat as mutable default @@ -1790,6 +1872,14 @@ function describeShieldsMode(mode: ShieldsPostureMode): Omit privilegedSandboxExecCapture(sandboxName, ["stat", "-c", "%a %U:%G", p]), ); }, @@ -3562,7 +3659,9 @@ function repairMutableConfigPerms(sandboxName: string): MutableConfigRepairResul const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); return repairMutableConfigPermsCore( target, - getShieldsPostureWithoutHostLock(sandboxName, allowInlineRecovery).mode, + mutableConfigPostureMode( + getShieldsPostureWithoutHostLock(sandboxName, allowInlineRecovery).mode, + ), () => normalizeMutableOpenClawConfig(sandboxName, target.configDir), ); }, @@ -4227,6 +4326,7 @@ interface ShieldsPolicySnapshotRestoreOptions { type ShieldsPolicySnapshotRestoreResult = ReturnType & { managedMcpOmissions?: ManagedMcpPolicyOmission[]; externalPolicyVerified?: true; + externalRequiredPolicy?: Record; }; function applyShieldsPolicySnapshot( @@ -4288,9 +4388,6 @@ function applyShieldsPolicySnapshot( const persistedSnapshotMatches = state.shieldsPolicySnapshotPath === snapshotPath; const policyAuthority = inspectShieldsPolicySnapshotRestoreAuthority(sandboxName); const policyMutationAllowed = policyAuthority.authority === "nemoclaw-managed"; - if (options.externalVerificationOnly && policyMutationAllowed) { - throw new Error(externalPolicyRecoveryHandoff(sandboxName)); - } const ownershipOmissions: ManagedMcpPolicyOmission[] = []; if ( transition?.managedMcpPolicyKeys !== undefined && @@ -4321,7 +4418,7 @@ function applyShieldsPolicySnapshot( reason: "Legacy Shields state had no managed MCP ownership manifest at the auto-restore deadline", }); - } else if (policyMutationAllowed) { + } else if (policyMutationAllowed && !options.externalVerificationOnly) { assertLegacyMcpPolicyRestoreSafe( fs.readFileSync(snapshotPath, "utf-8"), hasManagedMcpPolicyClaims(sandboxName), @@ -4364,7 +4461,7 @@ function applyShieldsPolicySnapshot( } else { const managedMcpPolicies = resolveExactManagedMcpPolicies( sandboxName, - policyMutationAllowed + policyMutationAllowed && !options.externalVerificationOnly ? undefined : YAML.stringify(policyAuthority.inspection.effectivePolicy), policyAuthority.gatewayName, @@ -4377,8 +4474,14 @@ function applyShieldsPolicySnapshot( } const runtimePolicyIsTemp = runtimePolicyPath !== snapshotPath; try { + const externalRequiredPolicy = readShieldsPolicySnapshot(runtimePolicyPath); + if (options.externalVerificationOnly && policyMutationAllowed) { + throw new ExternalShieldsPolicyRecoveryError( + "authority-drift", + externalPolicyRecoveryHandoff(sandboxName, externalRequiredPolicy, "authority-drift"), + ); + } if (!policyMutationAllowed) { - const externalRequiredPolicy = readShieldsPolicySnapshot(runtimePolicyPath); resolveShieldsPolicySnapshotRestoreAuthority( sandboxName, externalRequiredPolicy, @@ -4392,6 +4495,7 @@ function applyShieldsPolicySnapshot( status: 0, signal: null, externalPolicyVerified: true, + externalRequiredPolicy: structuredClone(externalRequiredPolicy), }; } assertShieldsPolicyMutationAuthority( @@ -4680,6 +4784,7 @@ function recoverExpiredAutoRestoreInline( activation.fileHashes !== undefined && typeof activation.chattrApplied === "boolean"; if (configLocked) { saveShieldsState(sandboxName, { + policyRecoveryConfigLocked: true, chattrApplied: activation.chattrApplied, fileHashes: activation.fileHashes, }); @@ -4708,6 +4813,7 @@ function recoverExpiredAutoRestoreInline( shieldsDownTimeout: null, shieldsDownReason: null, shieldsDownPolicy: null, + policyRecoveryConfigLocked: false, ...(activation.fileHashes && typeof activation.chattrApplied === "boolean" ? { chattrApplied: activation.chattrApplied, @@ -5247,6 +5353,14 @@ function shieldsDownWithoutHostLock( const reason = opts.reason || null; const policyName = opts.policy || "permissive"; if (state.shieldsDown) { + if (initialMode === "locked_recovery") { + console.error(` Config is locked for ${sandboxName} while policy recovery remains pending.`); + console.error(` Run \`${CLI_NAME} ${sandboxName} shields up\` to complete recovery first.`); + return failShieldsCommand( + `Policy recovery remains pending for ${sandboxName}`, + opts.throwOnError, + ); + } if (isEquivalentShieldsDownRequest(state, timeoutSeconds, reason, policyName)) { if (!hasEquivalentShieldsDownTimerAuthority(sandboxName, state)) { recoverExpiredAutoRestoreInline(sandboxName, state); @@ -5993,6 +6107,7 @@ function shieldsUpWithoutHostLock(sandboxName: string, opts: ShieldsUpOpts = {}) activation.fileHashes !== undefined && typeof activation.chattrApplied === "boolean"; if (configLocked) { saveShieldsState(sandboxName, { + policyRecoveryConfigLocked: true, chattrApplied: activation.chattrApplied, fileHashes: activation.fileHashes, }); @@ -6057,6 +6172,7 @@ function shieldsUpWithoutHostLock(sandboxName: string, opts: ShieldsUpOpts = {}) shieldsDownTimeout: null, shieldsDownReason: null, shieldsDownPolicy: null, + policyRecoveryConfigLocked: false, ...(snapshotLockResult ? { chattrApplied: snapshotLockResult.chattrApplied, @@ -6186,7 +6302,10 @@ function shieldsStatusWithoutHostLock( throw new DeferredShieldsExit("Shields down transition is incomplete", 1); } - const recoveredProviderTarget = recoverActiveHermesRuntimeProviderMutation(sandboxName); + const recoveredProviderTarget = + posture.mode === "locked_recovery" + ? null + : recoverActiveHermesRuntimeProviderMutation(sandboxName); if (recoveredProviderTarget && posture.mode !== "locked") { console.error(" Shields: ERROR (runtime-provider recovery restored lockdown)"); console.error( @@ -6206,7 +6325,9 @@ function shieldsStatusWithoutHostLock( console.log(" Config is mutable. Run `nemoclaw shields up` to opt into lockdown."); return; + case "locked_recovery": case "locked": { + const policyRecoveryLocked = posture.mode === "locked_recovery"; // Cross-check the sandbox filesystem so a host-root tamper that reverts // protected perms back to a sandbox-writable state is surfaced as drift // instead of reported as a clean lockdown. @@ -6216,6 +6337,7 @@ function shieldsStatusWithoutHostLock( const target = recoveredProviderTarget ?? ensureConfigHashSensitiveFile(resolveConfig(sandboxName)); if ( + !policyRecoveryLocked && !recoveredProviderTarget && target.agentName === "hermes" && inspectHermesShieldsProtocol(sandboxName, target) === "provider-state-mutation-v2" @@ -6291,6 +6413,22 @@ function shieldsStatusWithoutHostLock( } throw new DeferredShieldsExit("Locked shields state has filesystem drift", 2); } + if (policyRecoveryLocked) { + const policyRecovery = inspectPolicyRecovery(sandboxName); + console.error(" Shields: DOWN (CONFIG LOCKED — POLICY RECOVERY REQUIRED)"); + console.error(policyLine); + console.error(" Config: locked and verified"); + if (policyRecovery.status === "unavailable") { + console.error(` Policy authority: ${policyRecovery.detail}`); + } else if (policyRecovery.status === "external") { + console.error(` Recovery: ${policyRecovery.handoff}`); + } else { + console.error( + ` Recovery: run \`${CLI_NAME} ${sandboxName} shields up\` to verify policy and complete Shields up.`, + ); + } + throw new DeferredShieldsExit("Locked config is waiting for policy recovery", 2); + } if (!state.fileHashes) { // Legacy state file pre-dates the content seal. Perm-only // verification cannot prove the locked bytes were not already @@ -6388,13 +6526,14 @@ function shieldsStatus( /** * Legacy mutability predicate. Fresh sandboxes and temporarily unlocked - * sandboxes both return true because their config is mutable; user-facing - * callers should use getShieldsPosture() so fresh state is labeled as - * "not configured" instead of "down". + * sandboxes return true because their config is mutable. Locked recovery + * returns false because config remains fail-closed while policy recovery is + * pending. User-facing callers should use getShieldsPosture() so fresh state + * is labeled as "not configured" instead of "down". */ function isShieldsDown(sandboxName: string, allowInlineRecovery = false): boolean { const posture = getShieldsPosture(sandboxName, allowInlineRecovery); - return posture.mode !== "error" && posture.mode !== "locked"; + return posture.mode === "mutable_default" || posture.mode === "temporarily_unlocked"; } /** diff --git a/src/lib/shields/mutable-config-repair.test.ts b/src/lib/shields/mutable-config-repair.test.ts index e1ebcd1a97c..36c0f0077dc 100644 --- a/src/lib/shields/mutable-config-repair.test.ts +++ b/src/lib/shields/mutable-config-repair.test.ts @@ -1,9 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createShieldsFlowHarness } from "../../../test/helpers/shields-flow-harness"; const NORMALIZER = "/usr/local/lib/nemoclaw/normalize_mutable_config_perms.py"; const NORMALIZER_WATCHDOG = ["/usr/bin/timeout", "--signal=TERM", "--kill-after=5s", "15s"]; @@ -152,3 +156,64 @@ describe("mutable OpenClaw config repair", () => { expect(dockerExecFileSync).toHaveBeenCalledTimes(3); }); }); + +describe("locked Shields policy recovery status", () => { + let homeDir: string; + + beforeEach(() => { + homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-locked-policy-recovery-")); + vi.stubEnv("HOME", homeDir); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + fs.rmSync(homeDir, { recursive: true, force: true }); + }); + + it("verifies Hermes locked recovery status without mutating provider state (#9833)", () => { + const sandboxName = "hermes"; + const target = { + agentName: "hermes", + configDir: "/sandbox/.hermes", + configFile: "config.yaml", + configPath: "/sandbox/.hermes/config.yaml", + format: "yaml", + sensitiveFiles: ["/sandbox/.hermes/.env"], + stateLockPlanInImage: true, + }; + const harness = createShieldsFlowHarness(requireSource, homeDir, { + agentConfigTarget: target, + sandboxName, + }); + const stateDir = path.join(homeDir, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync( + path.join(stateDir, `shields-${sandboxName}.json`), + JSON.stringify({ + shieldsDown: true, + policyRecoveryConfigLocked: true, + chattrApplied: true, + fileHashes: { [target.configPath]: "a".repeat(64) }, + }), + ); + const mutationCount = harness.dockerSpawnCalls.length; + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process exit ${String(code)}`); + }) as typeof process.exit); + + expect(() => + harness.shieldsStatus(sandboxName, false, { + inspectPolicyRecovery: () => ({ status: "external", handoff: "policy handoff" }), + resolveConfig: () => target, + verifyLockState: () => ({ ok: true, issues: [] }), + verifyStateLockPlan: () => [], + }), + ).toThrow("process exit 2"); + + expect(harness.dockerSpawnCalls).toHaveLength(mutationCount); + expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain( + "DOWN (CONFIG LOCKED — POLICY RECOVERY REQUIRED)", + ); + }); +}); diff --git a/src/lib/shields/openclaw-transition.test.ts b/src/lib/shields/openclaw-transition.test.ts index 0de9fd2f0a0..2f8c7495e04 100644 --- a/src/lib/shields/openclaw-transition.test.ts +++ b/src/lib/shields/openclaw-transition.test.ts @@ -1432,11 +1432,10 @@ describe("external Shields policy recovery", () => { expect(countPolicySets(harness)).toBe(policySetsAfterDown); expect(harness.getOpenClawPosture()).toBe("mutable"); - const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { throw new Error(`process exit ${String(code)}`); }) as typeof process.exit); expect(() => harness.shieldsStatus(sandboxName, false)).toThrow("process exit 2"); - expect(exitSpy).toHaveBeenCalledWith(2); expect(harness.errorSpy.mock.calls.flat().join("\n")).toContain( "must make the effective policy", ); @@ -1476,7 +1475,6 @@ describe("external Shields policy recovery", () => { "policy verification after config lock failed", ); - expect(harness.isShieldsDown(sandboxName)).toBe(true); expect(harness.getOpenClawPosture()).toBe("locked"); expect(countPolicySets(harness)).toBe(policySetsAfterDown); const errors = harness.errorSpy.mock.calls.flat().join("\n"); @@ -1487,7 +1485,13 @@ describe("external Shields policy recovery", () => { expect(harness.auditSpy).not.toHaveBeenCalledWith( expect.objectContaining({ action: "shields_up" }), ); - + expect(harness.getShieldsPosture(sandboxName, false).mode).toBe("locked_recovery"); + expect(harness.isShieldsDown(sandboxName)).toBe(false); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process exit ${String(code)}`); + }) as typeof process.exit); + expect(() => harness.shieldsStatus(sandboxName, false)).toThrow("process exit 2"); + expect(harness.getOpenClawPosture()).toBe("locked"); harness.policyRecoveryAuthoritySpy.mockReturnValue(restoredExternalAuthority); harness.shieldsUp(sandboxName, { throwOnError: true }); expect(harness.isShieldsDown(sandboxName)).toBe(false); diff --git a/src/lib/shields/policy-transition.test.ts b/src/lib/shields/policy-transition.test.ts index 12c436f11c4..38fae26ce66 100644 --- a/src/lib/shields/policy-transition.test.ts +++ b/src/lib/shields/policy-transition.test.ts @@ -157,9 +157,30 @@ describe("shields policy transition", () => { }); expect(() => shields.applyShieldsPolicySnapshot(sandboxName, snapshotPath)).toThrow( - "must make the effective policy", + /does not match.*canonical JSON SHA-256 [a-f0-9]{64}; network policy keys: test/su, ); expect(runSpy).not.toHaveBeenCalled(); + + const matchingExternalAuthority = { + authority: "externally-managed" as const, + authorityRecordedNow: false, + gatewayName: "nemoclaw", + inspection: { + authority: "externally-managed" as const, + effectivePolicy: { version: 1, network_policies: { test: {} } }, + }, + }; + vi.mocked(policy.inspectPolicyMutationAuthority).mockReturnValue(matchingExternalAuthority); + vi.spyOn(policy, "inspectPolicyRecoveryAuthority") + .mockReturnValueOnce(matchingExternalAuthority) + .mockReturnValue({ + ...matchingExternalAuthority, + authority: "nemoclaw-managed", + inspection: { ...matchingExternalAuthority.inspection, authority: "nemoclaw-managed" }, + }); + expect(() => shields.applyShieldsPolicySnapshot(sandboxName, snapshotPath)).toThrow( + /Policy authority changed.*canonical JSON SHA-256 [a-f0-9]{64}/su, + ); }); it("never relaxes policy or persists mutable state when the base-policy read fails", () => { From c9205ffb4148495b5b5533269a630c26b391d6fd Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 17:35:23 -0700 Subject: [PATCH 26/40] fix(policy): preserve recovery receipts Signed-off-by: Apurv Kumaria --- ci/source-architecture-budget.json | 2 +- .../src/blueprint/runner-identity.test.ts | 1 + .../src/blueprint/runner-mock-fixtures.ts | 6 ++ .../blueprint/runner-name-validation.test.ts | 1 + .../runner-openshell-072-policy.test.ts | 50 ++++++++++- nemoclaw/src/blueprint/runner.test.ts | 13 ++- nemoclaw/src/blueprint/runner.ts | 73 +++++++++-------- src/lib/policy/gateway-state.ts | 4 + src/lib/policy/index.ts | 82 +++++++++++-------- .../policy/policy-mutation-authority.test.ts | 2 +- src/lib/policy/policy-registry.ts | 41 ---------- src/lib/shields/openclaw-transition.test.ts | 22 ++--- 12 files changed, 168 insertions(+), 129 deletions(-) delete mode 100644 src/lib/policy/policy-registry.ts diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index c9b0c1938cb..80a84f46cc2 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -11,7 +11,7 @@ "src/lib/adapters/openshell/runtime.ts": 54, "src/lib/adapters/openshell/timeouts.ts": 38, "src/lib/agent/defs.ts": 33, - "src/lib/cli/branding.ts": 87, + "src/lib/cli/branding.ts": 86, "src/lib/cli/nemoclaw-oclif-command.ts": 106, "src/lib/cli/terminal-style.ts": 43, "src/lib/core/json-types.ts": 37, diff --git a/nemoclaw/src/blueprint/runner-identity.test.ts b/nemoclaw/src/blueprint/runner-identity.test.ts index 0c62a4a0d6b..daf182fbc35 100644 --- a/nemoclaw/src/blueprint/runner-identity.test.ts +++ b/nemoclaw/src/blueprint/runner-identity.test.ts @@ -39,6 +39,7 @@ vi.mock("node:fs", async (importOriginal) => { ...original, mkdirSync: memory.mkdirSync, readFileSync: memory.readFileSync, + renameSync: memory.renameSync, writeFileSync: memory.writeFileSync, readdirSync: memory.readdirSync, realpathSync: memory.realpathSync, diff --git a/nemoclaw/src/blueprint/runner-mock-fixtures.ts b/nemoclaw/src/blueprint/runner-mock-fixtures.ts index ef394e91d0d..3e0d7aec5d9 100644 --- a/nemoclaw/src/blueprint/runner-mock-fixtures.ts +++ b/nemoclaw/src/blueprint/runner-mock-fixtures.ts @@ -69,6 +69,12 @@ export function inMemoryFsMethods(store: Map, options?: I writeFileSync: spy((p: string, data: string) => { store.set(p, { type: "file", content: String(data) }); }), + renameSync: spy((source: string, destination: string) => { + const entry = store.get(source); + if (!entry) return missingEntry(source); + store.set(destination, entry); + store.delete(source); + }), readdirSync: (p: string) => { const prefix = p.endsWith("/") ? p : `${p}/`; const entries = new Set( diff --git a/nemoclaw/src/blueprint/runner-name-validation.test.ts b/nemoclaw/src/blueprint/runner-name-validation.test.ts index c9ce84a4d42..763444c2d4b 100644 --- a/nemoclaw/src/blueprint/runner-name-validation.test.ts +++ b/nemoclaw/src/blueprint/runner-name-validation.test.ts @@ -40,6 +40,7 @@ vi.mock("node:fs", async (importOriginal) => { existsSync: memory.existsSync, mkdirSync: memory.mkdirSync, readFileSync: memory.readFileSync, + renameSync: memory.renameSync, writeFileSync: memory.writeFileSync, readdirSync: memory.readdirSync, }; diff --git a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts index f7f9c705c61..b830961e21a 100644 --- a/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts +++ b/nemoclaw/src/blueprint/runner-openshell-072-policy.test.ts @@ -42,6 +42,7 @@ vi.mock("node:fs", async (importOriginal) => { mkdirSync: memory.mkdirSync, readFileSync: memory.readFileSync, readdirSync: memory.readdirSync, + renameSync: memory.renameSync, writeFileSync: memory.writeFileSync, }; }); @@ -60,6 +61,8 @@ vi.mock("./ssrf.js", async (importOriginal) => { const { actionApply, actionReconcile, actionRollback, actionStatus, main } = await import("./runner.js"); +const { renameSync } = await import("node:fs"); +const mockedRenameSync = vi.mocked(renameSync); const BASE_POLICY = `version: 1 future_policy: @@ -652,7 +655,12 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { stdoutCapture.reset(); actionStatus(runId); - expect(stdoutCapture.jsonOutput()).toEqual({ run_id: runId, status: "unknown" }); + expect(stdoutCapture.jsonOutput()).toMatchObject({ + run_id: runId, + status: "unknown", + run_directory: stateDir, + recovery: expect.stringContaining("Restore a complete plan.json receipt"), + }); await expect(actionReconcile(runId)).rejects.toThrow(/policy transition receipt is invalid/u); await expect(actionRollback(runId)).rejects.toThrow(/policy transition receipt is invalid/u); }); @@ -712,6 +720,46 @@ describe("OpenShell 0.0.72 blueprint policy round-trip", () => { await expect(actionReconcile("missing-reconciliation")).rejects.toThrow(/not found/u); }); + it("preserves the previous receipt when reconciliation replacement is interrupted (#9833)", async () => { + const runId = "interrupted-reconciliation"; + const stateDir = `${FAKE_HOME}/.nemoclaw/state/runs/${runId}`; + const planFile = `${stateDir}/plan.json`; + store.set(stateDir, { type: "dir" }); + store.set(planFile, { + type: "file", + content: JSON.stringify({ ...reconciliationPlan, run_id: runId }), + }); + mockExeca.mockImplementation(async (_cmd: string, args: string[]) => + args.join(" ") === "policy get -g test-gateway --full --output json test-sandbox" + ? sandboxPolicyAuthorityResult( + "test-sandbox", + "nemoclaw-managed", + blueprint().components!.policy!.additions!, + ) + : defaultCommandResult(args), + ); + mockedRenameSync.mockImplementationOnce(() => { + throw new Error("simulated interrupted receipt replacement"); + }); + + await expect(actionReconcile(runId)).rejects.toThrow(/interrupted receipt replacement/u); + expect(JSON.parse(store.get(planFile)?.content ?? "{}")).toMatchObject({ + policy_transition: { status: "incomplete" }, + }); + + stdoutCapture.reset(); + actionStatus(runId); + expect(stdoutCapture.jsonOutput()).toMatchObject({ + policy_transition: { status: "incomplete", reconciliation_required: true }, + }); + await expect(actionRollback(runId)).rejects.toThrow(/is incomplete.*reconcile/u); + + await actionReconcile(runId); + expect(JSON.parse(store.get(planFile)?.content ?? "{}")).toMatchObject({ + policy_transition: { status: "complete" }, + }); + }); + it("treats a complete reconciliation as idempotent and requires a CLI run ID (#9833)", async () => { const runId = "complete-reconciliation"; const stateDir = `${FAKE_HOME}/.nemoclaw/state/runs/${runId}`; diff --git a/nemoclaw/src/blueprint/runner.test.ts b/nemoclaw/src/blueprint/runner.test.ts index 7e76bcda490..bb300c46a2d 100644 --- a/nemoclaw/src/blueprint/runner.test.ts +++ b/nemoclaw/src/blueprint/runner.test.ts @@ -40,6 +40,7 @@ vi.mock("node:fs", async (importOriginal) => { existsSync: memory.existsSync, mkdirSync: memory.mkdirSync, readFileSync: memory.readFileSync, + renameSync: memory.renameSync, writeFileSync: memory.writeFileSync, readdirSync: memory.readdirSync, }; @@ -1283,16 +1284,22 @@ describe("runner", () => { addDir(`${RUNS_DIR}/nc-run-1`); actionStatus("nc-run-1"); - expect(stdoutText()).toContain('"status":"unknown"'); + expect(capturedJsonOutput()).toMatchObject({ run_id: "nc-run-1", status: "unknown" }); }); - it("prints unknown status when plan.json is corrupt", () => { + it("reports recovery details when plan.json is corrupt", () => { addDir(`${RUNS_DIR}/nc-run-1`); addFile(`${RUNS_DIR}/nc-run-1/plan.json`, "{not valid json"); actionStatus("nc-run-1"); - expect(capturedJsonOutput()).toEqual({ run_id: "nc-run-1", status: "unknown" }); + expect(capturedJsonOutput()).toEqual({ + run_id: "nc-run-1", + status: "unknown", + receipt_error: expect.stringContaining("JSON"), + run_directory: `${RUNS_DIR}/nc-run-1`, + recovery: expect.stringContaining("Restore a complete plan.json receipt"), + }); }); // ── Path traversal rejection ────────────────────────────────── diff --git a/nemoclaw/src/blueprint/runner.ts b/nemoclaw/src/blueprint/runner.ts index 13f105fa27b..37ad097e9a4 100644 --- a/nemoclaw/src/blueprint/runner.ts +++ b/nemoclaw/src/blueprint/runner.ts @@ -13,7 +13,7 @@ */ import { randomUUID } from "node:crypto"; -import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join, sep } from "node:path"; @@ -1053,6 +1053,12 @@ function buildPersistedRunPlan(args: { return plan; } +function persistRunReceipt(planFile: string, plan: unknown): void { + const pendingFile = `${planFile}.pending`; + writeFileSync(pendingFile, JSON.stringify(plan, null, 2), { encoding: "utf-8", mode: 0o600 }); + renameSync(pendingFile, planFile); +} + function buildStatusRunPlan(source: unknown, fallbackRunId: string): StatusRunPlan | null { if (!isPlainObject(source)) { return null; @@ -1252,25 +1258,21 @@ export async function actionApply( let sandboxCreatedByApply = false; let inferenceProviderCreatedByApply = false; const persistRunPlan = (): void => { - writeFileSync( + persistRunReceipt( join(stateDir, "plan.json"), - JSON.stringify( - buildPersistedRunPlan({ - runId: rid, - profile, - sandboxName, - sandboxCreatedByApply, - inferenceProviderCreatedByApply, - policyAdditions, - policyAuthorityReceipt, - policyTransition, - inferenceCfg, - runtimeIdentityReceipt, - timestamp: new Date().toISOString(), - }), - null, - 2, - ), + buildPersistedRunPlan({ + runId: rid, + profile, + sandboxName, + sandboxCreatedByApply, + inferenceProviderCreatedByApply, + policyAdditions, + policyAuthorityReceipt, + policyTransition, + inferenceCfg, + runtimeIdentityReceipt, + timestamp: new Date().toISOString(), + }), ); }; const identityDeps = runtimeIdentityDeps((receipt) => { @@ -1720,8 +1722,22 @@ export function actionStatus(rid?: string): void { throw new Error("plan.json must contain a JSON object"); } log(JSON.stringify(safePlan, null, 2)); - } catch { - log(JSON.stringify({ run_id: name, status: "unknown" })); + } catch (error) { + const detail = boundedCommandError(error instanceof Error ? error.message : String(error)); + log( + JSON.stringify( + { + run_id: name, + status: "unknown", + receipt_error: detail, + run_directory: runDir, + recovery: + "Restore a complete plan.json receipt in this run directory before running reconcile or rollback.", + }, + null, + 2, + ), + ); } } @@ -1791,17 +1807,10 @@ export async function actionReconcile(rid: string): Promise { } assertBlueprintPolicyRequirements(observed, additions); - writeFileSync( - planFile, - JSON.stringify( - { - ...plan, - policy_transition: { ...transition, status: "complete" }, - }, - null, - 2, - ), - ); + persistRunReceipt(planFile, { + ...plan, + policy_transition: { ...transition, status: "complete" }, + }); log(`Policy transition for run ${rid} is complete.`); } diff --git a/src/lib/policy/gateway-state.ts b/src/lib/policy/gateway-state.ts index 202d54ffbe5..f8410b65bef 100644 --- a/src/lib/policy/gateway-state.ts +++ b/src/lib/policy/gateway-state.ts @@ -3,6 +3,10 @@ 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/policy/index.ts b/src/lib/policy/index.ts index 8848aa9a865..c9d890d7953 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -8,13 +8,21 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import readline from "node:readline"; -import { isDeepStrictEqual } from "node:util"; import YAML from "yaml"; // Namespace access keeps resolveOpenshell spyable in focused policy tests. +import { + assertExternalPolicyRequirements, + assertRecordedPolicyAuthority, + inspectSandboxPolicyAuthority, + isExternalPolicyAuthorityRefusalError as isExternalAuthorityRefusalError, + isPolicyAuthorityRefusalError as isAuthorityRefusalError, + PolicyAuthorityRefusalError, + type SandboxPolicyAuthority, + type SandboxPolicyAuthorityInspection, +} from "../adapters/openshell/policy-authority"; import * as openshellResolveModule from "../adapters/openshell/resolve"; import { loadAgent, requireAgentPolicyAdditionsPath } from "../agent/defs"; -import { CLI_NAME } from "../cli/branding"; import { getMessagingPolicyKeyAliases, getMessagingPolicyPresetValidationWarnings, @@ -31,7 +39,7 @@ import { OPENSHELL_SANDBOX_HOST_BRIDGE } from "../private-networks"; import { ROOT, run, runCapture, runCaptureEx } from "../runner"; import { diagnosticPreview, isValidName, NAME_ALLOWED_FORMAT } from "../sandbox-name-contract"; import { redact } from "../security/redact"; -import * as registry from "./policy-registry"; +import * as registry from "../state/registry"; import type { BaselineExclusionRuntimeStatus } from "./baseline-exclusion"; import { digestBaselineEntry, @@ -45,7 +53,11 @@ import { buildPolicyGetFullCommand, buildPolicySetCommand, } from "./commands"; -import { inspectGatewayPresetNames, inspectPresetContentGatewayState } from "./gateway-state"; +import { + inspectGatewayPresetNames, + inspectPresetContentGatewayState, + policyValuesEqual, +} from "./gateway-state"; import { parseOpenShellPolicy, stripProviderComposedPolicies, @@ -575,14 +587,14 @@ function policyAuthorityError(error: unknown): string { } export interface PolicyMutationAuthority { - readonly authority: registry.SandboxPolicyAuthority; + readonly authority: SandboxPolicyAuthority; readonly authorityRecordedNow: boolean; readonly gatewayName: string; - readonly inspection: registry.SandboxPolicyAuthorityInspection; + readonly inspection: SandboxPolicyAuthorityInspection; } -export const isPolicyAuthorityRefusalError = registry.isPolicyAuthorityRefusalError; -export const isExternalPolicyAuthorityRefusalError = registry.isExternalPolicyAuthorityRefusalError; +export const isPolicyAuthorityRefusalError = isAuthorityRefusalError; +export const isExternalPolicyAuthorityRefusalError = isExternalAuthorityRefusalError; function inspectLivePolicyAuthority( sandboxName: string, @@ -596,7 +608,7 @@ function inspectLivePolicyAuthority( try { sandbox = registry.getSandbox(sandboxName); } catch { - throw new registry.PolicyAuthorityRefusalError( + throw new PolicyAuthorityRefusalError( `Refusing to ${operation}: sandbox policy authority is unavailable.`, ); } @@ -604,7 +616,7 @@ function inspectLivePolicyAuthority( try { recordedGatewayName = sandbox ? resolveSandboxGatewayName(sandbox) : null; } catch { - throw new registry.PolicyAuthorityRefusalError( + throw new PolicyAuthorityRefusalError( `Refusing to ${operation}: the recorded sandbox gateway is unavailable or invalid.`, ); } @@ -619,11 +631,11 @@ function inspectLivePolicyAuthority( gatewayName = recordedGatewayName ?? requestedGatewayName ?? resolveSandboxGatewayName(undefined); } catch { - throw new registry.PolicyAuthorityRefusalError( + throw new PolicyAuthorityRefusalError( `Refusing to ${operation}: the sandbox gateway is unavailable or invalid.`, ); } - const inspection = registry.inspectSandboxPolicyAuthority({ + const inspection = inspectSandboxPolicyAuthority({ sandboxName, gatewayName, runCaptureEx, @@ -647,7 +659,7 @@ export function inspectPolicyRecoveryAuthority( ): PolicyMutationAuthority { const live = inspectLivePolicyAuthority(sandboxName, operation, requestedGatewayName); if (!live.sandbox) { - throw new registry.PolicyAuthorityRefusalError( + throw new PolicyAuthorityRefusalError( `Refusing to ${operation}: sandbox policy authority is unavailable.`, ); } @@ -666,7 +678,7 @@ export function inspectPolicyMutationAuthority( const { gatewayName, inspection } = live.authority; if (sandbox?.policyAuthority !== undefined) { try { - registry.assertRecordedPolicyAuthority( + assertRecordedPolicyAuthority( sandbox.policyAuthority, inspection.authority, operation, @@ -676,7 +688,7 @@ export function inspectPolicyMutationAuthority( sandbox.policyAuthority === "externally-managed" || inspection.authority === "externally-managed" ) { - throw new registry.PolicyAuthorityRefusalError( + throw new PolicyAuthorityRefusalError( `${policyAuthorityError(error)} The external policy authority must perform the requested policy mutation.`, inspection.authority, ); @@ -726,7 +738,7 @@ export function assertNemoClawManagedPolicy( operation: string, ): void { if (authority.authority === "nemoclaw-managed") return; - throw new registry.PolicyAuthorityRefusalError( + throw new PolicyAuthorityRefusalError( `Refusing to ${operation}: this sandbox policy is externally managed. ` + "The external policy authority must perform the requested policy mutation.", authority.authority, @@ -745,7 +757,7 @@ export function recheckPolicyMutationAuthority( recorded.gatewayName, true, ); - registry.assertRecordedPolicyAuthority(recorded.authority, observed.authority, operation); + assertRecordedPolicyAuthority(recorded.authority, observed.authority, operation); assertNemoClawManagedPolicy(observed, operation); return observed; } @@ -767,7 +779,7 @@ export function rejectFinalPolicySetResult( : (captured.stderr ?? null), }); if (outcome.kind === "rejected") { - throw new registry.PolicyAuthorityRefusalError( + throw new PolicyAuthorityRefusalError( `Refusing to ${operation}: OpenShell rejected the policy change: ${redact(outcome.message)}`, ); } @@ -1046,7 +1058,7 @@ function normalizePersonalOpenInternetPolicy(policyContent: string): string { if ( !isPolicyObject(personalEntry) || !isPolicyObject(reviewedEntry) || - !isDeepStrictEqual(personalEntry, reviewedEntry) + !policyValuesEqual(personalEntry, reviewedEntry) ) { throw new Error( `Cannot compose Personal policy: reserved network policy key '${PERSONAL_OPEN_INTERNET_POLICY_KEY}' does not match the reviewed built-in preset.`, @@ -1115,7 +1127,7 @@ function classifyPresetEntries(currentPolicy: string, presetEntries: string): Pr const presentEntries = expectedEntries.filter(([key]) => Object.hasOwn(current, key)); if (presentEntries.length === 0) return "absent"; return expectedEntries.every( - ([key, value]) => Object.hasOwn(current, key) && isDeepStrictEqual(current[key], value), + ([key, value]) => Object.hasOwn(current, key) && policyValuesEqual(current[key], value), ) ? "match" : "drift"; @@ -1126,7 +1138,7 @@ function classifyPresetEntries(currentPolicy: string, presetEntries: string): Pr function policyDocumentsMatch(left: string, right: string): boolean { try { - return isDeepStrictEqual(YAML.parse(left), YAML.parse(right)); + return policyValuesEqual(YAML.parse(left), YAML.parse(right)); } catch { return false; } @@ -1257,12 +1269,12 @@ function activateOpenClawNpmCompatibility( const reviewed = openClawNpmReviewedEntries(baselinePolicyContent); const compatibilityEntry = npmCompatibilityEntry(reviewed.baseline, reviewed.preset); const currentNpmEntry = networkPolicies[OPENCLAW_NPM_PRESET_KEY]; - if (!isPolicyObject(currentNpmEntry) || !isDeepStrictEqual(currentNpmEntry, reviewed.preset)) { + if (!isPolicyObject(currentNpmEntry) || !policyValuesEqual(currentNpmEntry, reviewed.preset)) { throw new Error( `Cannot compose '${OPENCLAW_NPM_PRESET_KEY}': the resulting entry differs from the reviewed npm preset.`, ); } - if (isDeepStrictEqual(currentBaselineEntry, compatibilityEntry)) { + if (policyValuesEqual(currentBaselineEntry, compatibilityEntry)) { if (!npmWasActive) { throw new Error( `Cannot compose '${OPENCLAW_NPM_PRESET_KEY}': found a compatibility overlay without an active npm preset.`, @@ -1270,7 +1282,7 @@ function activateOpenClawNpmCompatibility( } return { policy: policyContent, widenedBaseline: false }; } - if (!isDeepStrictEqual(currentBaselineEntry, reviewed.baseline)) { + if (!policyValuesEqual(currentBaselineEntry, reviewed.baseline)) { throw new Error( `Cannot compose '${OPENCLAW_NPM_PRESET_KEY}': '${OPENCLAW_NPM_BASELINE_KEY}' differs from the reviewed baseline.`, ); @@ -1302,7 +1314,7 @@ function restoreOpenClawNpmCompatibility( } const reviewed = openClawNpmReviewedEntries(baselinePolicyContent); - if (isDeepStrictEqual(currentBaselineEntry, reviewed.baseline)) return updatedPolicy; + if (policyValuesEqual(currentBaselineEntry, reviewed.baseline)) return updatedPolicy; const currentNpmEntry = current.network_policies[OPENCLAW_NPM_PRESET_KEY]; if (!isPolicyObject(currentNpmEntry)) { @@ -1311,7 +1323,7 @@ function restoreOpenClawNpmCompatibility( ); } const compatibilityEntry = npmCompatibilityEntry(reviewed.baseline, currentNpmEntry); - if (!isDeepStrictEqual(currentBaselineEntry, compatibilityEntry)) { + if (!policyValuesEqual(currentBaselineEntry, compatibilityEntry)) { throw new Error( `Cannot remove '${OPENCLAW_NPM_PRESET_KEY}': '${OPENCLAW_NPM_BASELINE_KEY}' differs from both the reviewed baseline and active compatibility overlay.`, ); @@ -1374,14 +1386,14 @@ function getOpenClawNpmCompatibilityState( if (!isPolicyDocument(parsed) || !isPresetPolicyMap(parsed.network_policies)) return null; const reviewed = openClawNpmReviewedEntries(baselinePolicyContent); const currentNpmEntry = parsed.network_policies[OPENCLAW_NPM_PRESET_KEY]; - if (!isPolicyObject(currentNpmEntry) || !isDeepStrictEqual(currentNpmEntry, reviewed.preset)) { + if (!isPolicyObject(currentNpmEntry) || !policyValuesEqual(currentNpmEntry, reviewed.preset)) { return "drift"; } - if (isDeepStrictEqual(parsed.network_policies[OPENCLAW_NPM_BASELINE_KEY], reviewed.baseline)) { + if (policyValuesEqual(parsed.network_policies[OPENCLAW_NPM_BASELINE_KEY], reviewed.baseline)) { return "repair"; } const compatibilityEntry = npmCompatibilityEntry(reviewed.baseline, currentNpmEntry); - return isDeepStrictEqual(parsed.network_policies[OPENCLAW_NPM_BASELINE_KEY], compatibilityEntry) + return policyValuesEqual(parsed.network_policies[OPENCLAW_NPM_BASELINE_KEY], compatibilityEntry) ? "match" : "drift"; } catch { @@ -1931,7 +1943,7 @@ function reconcileBaselineExclusionTransition( const committed = registry .getBaselineExclusions(sandboxName) .find((entry) => entry.key === transition.exclusion.key); - if (!committed || !isDeepStrictEqual(committed, transition.exclusion)) { + if (!committed || !policyValuesEqual(committed, transition.exclusion)) { console.error( ` The durable exclusion for '${key}' changed during the pending restore. The journal was preserved; inspect registry intent before retrying.`, ); @@ -2020,7 +2032,7 @@ function restoreTransitionCanFinalize( const committed = registry .getBaselineExclusions(sandboxName) .find((entry) => entry.key === transition.exclusion.key); - if (!committed || !isDeepStrictEqual(committed, transition.exclusion)) { + if (!committed || !policyValuesEqual(committed, transition.exclusion)) { console.error( ` The durable exclusion for '${transition.exclusion.key}' no longer matches the pending restore. The journal was preserved; rebuild remains blocked.`, ); @@ -2593,7 +2605,7 @@ function applyPresetContent( try { authority = inspectPolicyAuthority(sandboxName, operation); if (authority.authority === "externally-managed") { - registry.assertExternalPolicyRequirements({ + assertExternalPolicyRequirements({ inspection: authority.inspection, requiredPolicy: { network_policies: requiredNetworkPolicies }, operation, @@ -2872,7 +2884,7 @@ function applyPresets(sandboxName: string, presetNames: string[]): boolean { try { authority = inspectPolicyAuthority(sandboxName, operation); if (authority.authority === "externally-managed") { - registry.assertExternalPolicyRequirements({ + assertExternalPolicyRequirements({ inspection: authority.inspection, requiredPolicy: { network_policies: requiredNetworkPolicies }, operation, @@ -3306,7 +3318,7 @@ async function selectFromList( // path (`policy add `) re-applies edited presets (#7323). process.stderr.write(`\n Preset '${item.name}' is already applied.\n`); process.stderr.write( - ` If its preset file changed, run '${CLI_NAME} policy add ${item.name}' to re-apply it.\n`, + ` If its preset file changed, run 'nemoclaw policy add ${item.name}' to re-apply it.\n`, ); return null; } @@ -3370,7 +3382,7 @@ function applyPermissivePolicy(sandboxName: string): void { recheckPolicyMutationAuthority(sandboxName, operation, authority); setPolicyDocument(sandboxName, materializedPolicy, { gatewayName: authority.gatewayName }); const observed = inspectPolicyAuthority(sandboxName, operation, authority.gatewayName, true); - registry.assertRecordedPolicyAuthority(authority.authority, observed.authority, operation); + assertRecordedPolicyAuthority(authority.authority, observed.authority, operation); assertNemoClawManagedPolicy(observed, operation); console.log(" Applied permissive policy."); } diff --git a/src/lib/policy/policy-mutation-authority.test.ts b/src/lib/policy/policy-mutation-authority.test.ts index ad36acf3990..276d3fe7692 100644 --- a/src/lib/policy/policy-mutation-authority.test.ts +++ b/src/lib/policy/policy-mutation-authority.test.ts @@ -51,7 +51,7 @@ import { removePreset, restoreBaselineEntry, } from "./index"; -import { PolicyAuthorityRefusalError } from "./policy-registry"; +import { PolicyAuthorityRefusalError } from "../adapters/openshell/policy-authority"; const SANDBOX = "authority-9833"; const BASE_POLICY = `version: 1 diff --git a/src/lib/policy/policy-registry.ts b/src/lib/policy/policy-registry.ts deleted file mode 100644 index ee34c18840e..00000000000 --- a/src/lib/policy/policy-registry.ts +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -/** Registry operations owned by policy authority and attribution flows. */ -export { - addBaselineExclusion, - addCustomPolicy, - beginBaselineExclusionTransition, - clearBaselineExclusionTransition, - commitBaselineExclusionTransition, - getBaselineExclusions, - getBaselineExclusionTransition, - getConfiguredMessagingChannelsFromEntry, - getCustomPolicies, - getDisabledMessagingChannelsFromEntry, - getSandbox, - normalizeSandboxPolicyAttribution, - removeBaselineExclusion, - removeCustomPolicyByName, - updateSandbox, -} from "../state/registry"; - -export type { - BaselineExclusionEntry, - BaselineExclusionTransition, - BaselineExclusionTransitionOperation, - SandboxEntry, -} from "../state/registry"; - -export { - assertExternalPolicyRequirements, - assertRecordedPolicyAuthority, - inspectSandboxPolicyAuthority, - isExternalPolicyAuthorityRefusalError, - isPolicyAuthorityRefusalError, - PolicyAuthorityRefusalError, -} from "../adapters/openshell/policy-authority"; -export type { - SandboxPolicyAuthority, - SandboxPolicyAuthorityInspection, -} from "../adapters/openshell/policy-authority"; diff --git a/src/lib/shields/openclaw-transition.test.ts b/src/lib/shields/openclaw-transition.test.ts index 2f8c7495e04..79806790d86 100644 --- a/src/lib/shields/openclaw-transition.test.ts +++ b/src/lib/shields/openclaw-transition.test.ts @@ -17,6 +17,7 @@ import { import { createShieldsFlowHarness, externalPolicyAuthorityInspection, + externalPolicyMutationAuthority, type ShieldsFlowHarness, type ShieldsFlowHarnessOptions, } from "../../../test/helpers/shields-flow-harness"; @@ -1375,18 +1376,6 @@ function countPolicySets(harness: ShieldsFlowHarness): number { ).length; } -function externalAuthority(effectivePolicy: Record) { - return { - authority: "externally-managed" as const, - authorityRecordedNow: false, - gatewayName: "nemoclaw", - inspection: { - authority: "externally-managed" as const, - effectivePolicy, - }, - }; -} - function readRestrictivePolicy(harness: ShieldsFlowHarness, sandboxName: string) { const state = harness.getShieldsPosture(sandboxName, false).state; return YAML.parse(fs.readFileSync(String(state.shieldsPolicySnapshotPath), "utf-8")) as Record< @@ -1440,7 +1429,7 @@ describe("external Shields policy recovery", () => { "must make the effective policy", ); - const restoredExternalAuthority = externalAuthority( + const restoredExternalAuthority = externalPolicyMutationAuthority( readRestrictivePolicy(harness, sandboxName), ); harness.policyAuthoritySpy.mockReturnValue(restoredExternalAuthority); @@ -1461,10 +1450,13 @@ describe("external Shields policy recovery", () => { }); harness.shieldsDown(sandboxName, { throwOnError: true }); const policySetsAfterDown = countPolicySets(harness); - const restoredExternalAuthority = externalAuthority( + const restoredExternalAuthority = externalPolicyMutationAuthority( readRestrictivePolicy(harness, sandboxName), ); - const changedExternalAuthority = externalAuthority({ version: 1, network_policies: {} }); + const changedExternalAuthority = externalPolicyMutationAuthority({ + version: 1, + network_policies: {}, + }); harness.policyAuthoritySpy.mockReturnValue(restoredExternalAuthority); harness.policyRecoveryAuthoritySpy .mockReturnValueOnce(restoredExternalAuthority) From 07346c42863ec539974480f24c7bc8e4eb372e77 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Mon, 24 Aug 2026 17:41:42 -0700 Subject: [PATCH 27/40] fix(policy): import registry owner directly Signed-off-by: Apurv Kumaria --- ci/source-architecture-budget.json | 2 +- src/lib/actions/sandbox/policy-authority/preflight.ts | 2 +- src/lib/actions/sandbox/policy-authority/rebuild.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index a913e9914bd..bb6e047e1af 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -27,7 +27,7 @@ "src/lib/runner.ts": 86, "src/lib/security/redact.ts": 54, "src/lib/state/onboard-session.ts": 36, - "src/lib/state/registry.ts": 101, + "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/policy-authority/preflight.ts b/src/lib/actions/sandbox/policy-authority/preflight.ts index 2d4f008314d..7369dde02dd 100644 --- a/src/lib/actions/sandbox/policy-authority/preflight.ts +++ b/src/lib/actions/sandbox/policy-authority/preflight.ts @@ -13,7 +13,7 @@ import { type SandboxPolicyAuthorityInspection, } from "../../../adapters/openshell/policy-authority"; import { isPresetPolicyMap, parseNetworkPolicies } from "../../../policy/preset-parsing"; -import * as registry from "../../../policy/policy-registry"; +import * as registry from "../../../state/registry"; import { getPersistedSandboxTargetGatewayName } from "../gateway-target"; export { isPolicyAuthorityRefusalError } from "../../../adapters/openshell/policy-authority"; diff --git a/src/lib/actions/sandbox/policy-authority/rebuild.ts b/src/lib/actions/sandbox/policy-authority/rebuild.ts index cf560a6321f..2e98183ee0c 100644 --- a/src/lib/actions/sandbox/policy-authority/rebuild.ts +++ b/src/lib/actions/sandbox/policy-authority/rebuild.ts @@ -17,7 +17,7 @@ import { type SandboxGatewayPresence, } from "../../../onboard/sandbox-recreate-probe"; import * as policies from "../../../policy"; -import * as registry from "../../../policy/policy-registry"; +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"; From 102d167b4844e0246ae1a93c9764c6fa0ffaacce Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Wed, 26 Aug 2026 08:37:28 -0700 Subject: [PATCH 28/40] fix(rebuild): restore authority gate evidence Signed-off-by: Apurv Kumaria --- .../sandbox/policy-authority/preflight.ts | 13 +- .../sandbox/policy-authority/rebuild.test.ts | 99 ++++++ .../rebuild-dcode-pre-delete-drift.test.ts | 8 +- .../sandbox/rebuild-dcode-preflight.test.ts | 5 +- .../sandbox/rebuild-destroy-phase.test.ts | 53 ++++ .../actions/sandbox/rebuild-destroy-phase.ts | 12 +- src/lib/onboard/providers.test.ts | 37 ++- src/lib/onboard/providers.ts | 103 ++++--- src/lib/policy/README.md | 14 +- .../rebuild-credential-preflight.test.ts | 24 +- test/helpers/rebuild-dcode-flow-helpers.ts | 2 + .../gateway-state-reconcile-2276.test.ts | 284 +++++++++--------- ...build-messaging-conflict-preflight.test.ts | 86 +++--- 13 files changed, 495 insertions(+), 245 deletions(-) diff --git a/src/lib/actions/sandbox/policy-authority/preflight.ts b/src/lib/actions/sandbox/policy-authority/preflight.ts index c20d7b5115c..847597bcdfd 100644 --- a/src/lib/actions/sandbox/policy-authority/preflight.ts +++ b/src/lib/actions/sandbox/policy-authority/preflight.ts @@ -6,6 +6,7 @@ import YAML from "yaml"; import { assertExternalPolicyRequirements, + assertObservedPolicyRequirements, assertRecordedPolicyAuthority, inspectActiveGlobalPolicy, inspectOpenShellSandboxIdentityFingerprint, @@ -18,6 +19,7 @@ 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"; @@ -53,10 +55,7 @@ export interface PolicyAuthorityInspectionOptions { export function parseRequiredPolicyDocument(content: string, operation: string): RequiredPolicy { try { - const parsed: unknown = YAML.parse(content); - if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) { - return parsed as RequiredPolicy; - } + return parseOpenShellPolicy(content).policy; } catch { // The common refusal below owns invalid policy document errors. } @@ -139,7 +138,11 @@ function assertPolicyAuthorityRequirements( ): void { for (const inspection of inspections) { for (const requiredPolicy of options.requiredPolicies) { - assertExternalPolicyRequirements({ + const assertRequirements = + inspection.authority === "owner-unknown" + ? assertObservedPolicyRequirements + : assertExternalPolicyRequirements; + assertRequirements({ inspection, requiredPolicy, operation: options.operation, diff --git a/src/lib/actions/sandbox/policy-authority/rebuild.test.ts b/src/lib/actions/sandbox/policy-authority/rebuild.test.ts index 16025b3ef30..efd1da081a9 100644 --- a/src/lib/actions/sandbox/policy-authority/rebuild.test.ts +++ b/src/lib/actions/sandbox/policy-authority/rebuild.test.ts @@ -97,6 +97,105 @@ describe("rebuild policy authority preflight", () => { 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 = { 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 c7bf3ac552d..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,11 +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. + originalEntry, // Destructive-edge receipt qualification. + originalEntry, // Destructive-edge receipt stability read. + originalEntry, // Destructive-edge authority reread. driftedEntry, // Policy-authority reread at the destructive boundary. - driftedEntry, // Exact target 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 d80ae42327b..21d356169c6 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-preflight.test.ts @@ -127,10 +127,7 @@ describe("rebuildSandbox DCode flow: preflight", () => { harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), ).rejects.toThrow("Recorded DCode auto-approval state is invalid"); - expect(harness.registryUpdateSpy).toHaveBeenCalledOnce(); - expect(harness.registryUpdateSpy).toHaveBeenCalledWith("alpha", { - policyAuthority: "nemoclaw-managed", - }); + expect(harness.registryUpdateSpy).not.toHaveBeenCalled(); expect(harness.prepareManagedDcodeRebuildImageSpy).not.toHaveBeenCalled(); expectNoDcodeMutation(harness); }); diff --git a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts index b896021db23..d9ceda0b10b 100644 --- a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts @@ -942,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(); diff --git a/src/lib/actions/sandbox/rebuild-destroy-phase.ts b/src/lib/actions/sandbox/rebuild-destroy-phase.ts index 99330ad145b..8841d996f81 100644 --- a/src/lib/actions/sandbox/rebuild-destroy-phase.ts +++ b/src/lib/actions/sandbox/rebuild-destroy-phase.ts @@ -630,7 +630,17 @@ export async function runRebuildDestroyPhase( }; } if (!validation.ok) { - input.onDeleteStateAmbiguous?.(); + 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; } diff --git a/src/lib/onboard/providers.test.ts b/src/lib/onboard/providers.test.ts index d93bd4fd1c8..7eb1d19f9a5 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", @@ -1044,7 +1045,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) => { @@ -1073,24 +1073,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 94570d9c2bb..5a165fff494 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -46,6 +46,17 @@ function isMessagingProviderBindingConflict(error) { return error instanceof Error && error.code === MESSAGING_PROVIDER_BINDING_CONFLICT; } +function attachMutatedProviderNames(error, names) { + if (names.length === 0) return error; + const failure = error instanceof Error ? error : new Error(String(error)); + const existing = Array.isArray(failure.mutatedProviderNames) ? failure.mutatedProviderNames : []; + failure.mutatedProviderNames = [...new Set([...existing, ...names])]; + const providerNames = failure.mutatedProviderNames.map((name) => JSON.stringify(name)).join(", "); + const diagnostic = `Provider registration changed gateway state for ${providerNames} before the operation stopped. Inspect those providers before retrying.`; + if (!failure.message.includes(diagnostic)) failure.message = `${failure.message} ${diagnostic}`; + return failure; +} + // ── Constants ──────────────────────────────────────────────────── const BUILD_ENDPOINT_URL = "https://integrate.api.nvidia.com/v1"; @@ -616,7 +627,10 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { // channels//provider-profile/.yaml (not a flag inside it); both // bracket steps self-gate when no bridge token def is present. if (options.requireExactBindings && !options.replaceExisting) { - const bindingFailures = preflightMessagingProviderBindings(tokenDefs, runMessagingBridgeOpenshell); + const bindingFailures = preflightMessagingProviderBindings( + tokenDefs, + runMessagingBridgeOpenshell, + ); if (bindingFailures.length > 0) { const message = bindingFailures .map(({ name, message: failure }) => `${name}: ${failure}`) @@ -649,6 +663,7 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { redact, }); const upserted = []; + const mutatedProviderNames = []; const failures = []; for (const { name, envKey, token, providerType } of tokenDefs) { if (!token) continue; @@ -675,33 +690,38 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { knownExists = inspection.kind !== "missing"; } } - result ??= upsertProvider( - name, - providerType || "generic", - envKey, - null, - { [envKey]: token }, - _runOpenshell, - { - replaceExisting: Boolean(options.replaceExisting), - knownExists, - allowedSandboxes: options.allowedSandboxes, - revalidatePolicyRequirements: options.revalidatePolicyRequirements, - requireExactBinding: Boolean(options.requireExactBindings && providerType), - }, - ); - if (result.ok && providerType === MESSAGING_CREDENTIAL_PROVIDER_TYPE) { - const verified = inspectGatewayCredentialOnlyProviderBinding( - { name, type: providerType, credentialKey: envKey }, - runMessagingBridgeOpenshell, + try { + result ??= upsertProvider( + name, + providerType || "generic", + envKey, + null, + { [envKey]: token }, + _runOpenshell, + { + replaceExisting: Boolean(options.replaceExisting), + knownExists, + allowedSandboxes: options.allowedSandboxes, + revalidatePolicyRequirements: options.revalidatePolicyRequirements, + requireExactBinding: Boolean(options.requireExactBindings && providerType), + }, ); - if (verified.kind !== "exact") { - result = { - ok: false, - status: 1, - message: `OpenShell did not confirm messaging provider '${name}' after mutation.`, - }; + if (result.ok) mutatedProviderNames.push(name); + if (result.ok && providerType === MESSAGING_CREDENTIAL_PROVIDER_TYPE) { + const verified = inspectGatewayCredentialOnlyProviderBinding( + { name, type: providerType, credentialKey: envKey }, + runMessagingBridgeOpenshell, + ); + if (verified.kind !== "exact") { + result = { + ok: false, + status: 1, + message: `OpenShell did not confirm messaging provider '${name}' after mutation.`, + }; + } } + } catch (error) { + throw attachMutatedProviderNames(error, mutatedProviderNames); } if (!result.ok) { if (options.bestEffort) { @@ -716,32 +736,39 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { if (failures.length > 0) { const message = failures.map(({ name, message }) => `${name}: ${message}`).join("; "); if (failures.every(({ reason }) => reason === "binding-conflict")) { - throw new MessagingProviderBindingConflictError(message, upserted); + throw new MessagingProviderBindingConflictError(message, mutatedProviderNames); } throw new Error(message); } // Gateway-side token minting is configured AFTER the providers exist (best-effort, // self-gates without a bridge token def). Secret material stays gateway-side — // never written into the sandbox. - const refreshResult = messagingBridgeProvider.configureMessagingBridgeRefreshes(tokenDefs, { - runOpenshell: runMessagingBridgeOpenshell, - redact, - getCredential, - env: process.env, - normalizeCredentialValue, - }); + let refreshResult; + try { + refreshResult = messagingBridgeProvider.configureMessagingBridgeRefreshes(tokenDefs, { + runOpenshell: runMessagingBridgeOpenshell, + redact, + getCredential, + env: process.env, + normalizeCredentialValue, + }); + } catch (error) { + throw attachMutatedProviderNames(error, mutatedProviderNames); + } // Fail-closed: an active bridge channel whose gateway token minting was not // configured can receive webhooks but cannot authenticate outbound replies. // Surface it instead of reporting a fully-configured channel (bestEffort/rollback // paths report residual work by throwing; the normal path exits like a failed // provider upsert above). if (refreshResult && !refreshResult.ok) { + const failure = attachMutatedProviderNames( + new Error("Failed to configure gateway token minting for a messaging bridge."), + mutatedProviderNames, + ); if (options.bestEffort) { - throw new Error("Failed to configure gateway token minting for a messaging bridge."); + throw failure; } - console.error( - "\n ✗ Gateway token minting for a messaging bridge was not configured; aborting.", - ); + console.error(`\n ✗ ${failure.message}`); process.exit(1); } return upserted; diff --git a/src/lib/policy/README.md b/src/lib/policy/README.md index a6001a3ec3f..ee2442ebc6b 100644 --- a/src/lib/policy/README.md +++ b/src/lib/policy/README.md @@ -31,10 +31,16 @@ saved restrictive policy snapshot and refuses to set policy. The external policy authority must make the effective policy for the named sandbox match the saved restrictive snapshot and current managed MCP entries without changing policy authority. `shields status` identifies that required policy by its -canonical JSON SHA-256 digest and network policy keys. Then run -`nemoclaw shields up`. NemoClaw verifies the exact effective policy -and locks configuration. If policy changes during the lock, NemoClaw records -the verified config lock and keeps Shields down until policy recovery succeeds. +canonical JSON SHA-256 digest and network policy keys. The first status can +report no artifact. Run `nemoclaw shields up` once to create and +report the complete recovery artifact. The artifact contains no credential +values. It contains the saved restrictive policy and current managed MCP policy +entries, which may include credential bindings. Apply the artifact as the exact +policy through the external authority; do not reconstruct it from the digest +or key list. Then rerun `nemoclaw shields up`. NemoClaw verifies the +exact effective policy and locks configuration. If policy changes during the +lock, NemoClaw records the verified config lock and keeps Shields down until +policy recovery succeeds. A legacy sandbox record retains the first qualified `policyAuthority` after a later operation fails. An inspection that cannot determine authority does not change the record. diff --git a/test/credentials/rebuild-credential-preflight.test.ts b/test/credentials/rebuild-credential-preflight.test.ts index 10f58095b9b..ce434a47f40 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,7 +112,10 @@ wait();`, dashboardPort: agent === "langchain-deepagents-code" ? 0 : 18789, fromDockerfile: null, policies: [], - policyAuthority: "nemoclaw-managed", + lifecycleGeneration: managedPolicyState.lifecycleGeneration, + lifecycleLiveIdentityFingerprint: managedPolicyState.lifecycleLiveIdentityFingerprint, + policyAuthority: managedPolicyState.policyAuthority, + policyCreationReceipt: managedPolicyState.policyCreationReceipt, agent, ...(agent === "langchain-deepagents-code" ? { @@ -193,17 +205,11 @@ if (a[0] === "sandbox" && a[1] === "get") { 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] === "get" && a.includes("--output") && a.includes("json")) { - process.stdout.write(JSON.stringify({ - scope: "sandbox", - sandbox: "${sandboxName}", - status: "effective", - policy_source: "sandbox", - policy: {}, - }) + "\\n"); + 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/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/runtime/gateway/gateway-state-reconcile-2276.test.ts b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts index a655d5dee49..f0ee5867405 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,7 +87,10 @@ function writeDefaultRegistry(gatewayName: string, gatewayPort: number) { dashboardPort: 28790, fromDockerfile: null, policies: [], - policyAuthority: "nemoclaw-managed", + lifecycleGeneration: managedPolicyState.lifecycleGeneration, + lifecycleLiveIdentityFingerprint: managedPolicyState.lifecycleLiveIdentityFingerprint, + policyAuthority: managedPolicyState.policyAuthority, + policyCreationReceipt: managedPolicyState.policyCreationReceipt, }, }, }), @@ -355,140 +363,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 bf8bae27478..b4a0f9f4f7d 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,21 +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: [], - policyAuthority: "nemoclaw-managed", - 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"), @@ -164,15 +178,15 @@ 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[0]==="sandbox" && a[1]==="get") { process.stdout.write("Name: " + a.at(-1) + "\\nId: sbx-fixture\\nPhase: Ready\\n"); process.exit(0); } +if (a[0]==="sandbox" && a[1]==="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]==="get" && a.includes("--output") && a.includes("json")) { - process.stdout.write(JSON.stringify({scope:"sandbox",sandbox:a.at(-1),status:"effective",policy_source:"sandbox",policy:{}}) + "\\n"); + 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); } @@ -240,22 +254,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 || ""}`; + 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"); + // 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); - }); + // 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); + }, + ); }); From 6e2ad4b343d395bbb7a78e1d490ea8ab650c1ffe Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 27 Aug 2026 15:08:06 -0700 Subject: [PATCH 29/40] test(e2e): bind rebuild fixture policy ownership Signed-off-by: Charan Jagwani --- test/e2e/live/rebuild-openclaw.test.ts | 146 ++++++------------------- 1 file changed, 31 insertions(+), 115 deletions(-) diff --git a/test/e2e/live/rebuild-openclaw.test.ts b/test/e2e/live/rebuild-openclaw.test.ts index 27e4414149f..9e3c76da6f6 100644 --- a/test/e2e/live/rebuild-openclaw.test.ts +++ b/test/e2e/live/rebuild-openclaw.test.ts @@ -11,21 +11,15 @@ 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"; // 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. +// OpenClaw base image, recreate the sandbox from it through NemoClaw, 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. @@ -207,67 +201,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, @@ -512,48 +445,24 @@ test( fs.rmSync(oldBaseBuildContext, { recursive: true, force: true }); } - // Phase 3: create an OpenShell sandbox from the old base image. + // Phase 3: recreate the sandbox through NemoClaw so the old runtime keeps + // an exact policy-creation receipt bound to its new immutable sandbox ID. + // Direct OpenShell creation cannot truthfully establish NemoClaw ownership. 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", + const createOldSandbox = await host.command( + "node", + [CLI_ENTRYPOINT, "onboard", "--non-interactive"], + { + artifactName: "phase-3-onboard-old-openclaw-sandbox", + env: cliEnv(apiKey, { + NEMOCLAW_RECREATE_SANDBOX: "1", + NEMOCLAW_SANDBOX_BASE_IMAGE_REF: OLD_BASE_TAG, + }), + redactionValues: [apiKey], + timeoutMs: ONBOARD_TIMEOUT_MS, + }, ); - 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 }); - } + expectExitZero(createOldSandbox, "nemoclaw onboard old OpenClaw sandbox"); await waitForSandboxReady(sandbox); const oldVersion = await sandbox.exec(SANDBOX_NAME, ["openclaw", "--version"], { @@ -564,9 +473,8 @@ test( expectExitZero(oldVersion, "old openclaw --version"); expect(resultText(oldVersion)).toContain(OLD_OPENCLAW_VERSION); - // 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. + // 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 +535,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: { From f33a64c52ff4b12a0acbbfc6e27c1d9a018f3776 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 27 Aug 2026 16:01:50 -0700 Subject: [PATCH 30/40] fix(e2e): retain PATH for host commands Signed-off-by: Charan Jagwani --- test/e2e/fixtures/shell-probe.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/e2e/fixtures/shell-probe.ts b/test/e2e/fixtures/shell-probe.ts index 0a66f223d35..01caa217084 100644 --- a/test/e2e/fixtures/shell-probe.ts +++ b/test/e2e/fixtures/shell-probe.ts @@ -222,7 +222,10 @@ export class ShellProbe { spawn: { cwd: options.cwd, detached: true, - env: { ...(options.env ?? {}) }, + env: { + PATH: process.env.PATH, + ...(options.env ?? {}), + }, stdio: ["ignore", "pipe", "pipe"], }, }); From b92919736ad9125a26beb12a68f2317d6325690c Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 27 Aug 2026 18:10:31 -0700 Subject: [PATCH 31/40] test(e2e): preserve old runtime during rebuild setup --- .../rebuild-openclaw-old-openshell-wrapper.ts | 122 ++++++++++++++++++ test/e2e/live/rebuild-openclaw.test.ts | 31 +++++ .../rebuild-openclaw-old-base-context.test.ts | 65 ++++++++++ 3 files changed, 218 insertions(+) create mode 100644 test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts diff --git a/test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts b/test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts new file mode 100644 index 00000000000..49d310e2613 --- /dev/null +++ b/test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts @@ -0,0 +1,122 @@ +// 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 { shellQuote } from "../../../src/lib/core/shell-quote"; + +export interface LegacyOpenClawOpenShellWrapper { + directory: string; + executable: string; + logFile: string; +} + +export function createLegacyOpenClawOpenShellWrapper(options: { + root: string; + realOpenShell: string; + baseImage: string; + openClawVersion: string; +}): LegacyOpenClawOpenShellWrapper { + const directory = path.join(options.root, "bin"); + const executable = path.join(directory, "openshell"); + const logFile = path.join(options.root, "sandbox-create-patch.log"); + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + fs.rmSync(logFile, { force: true }); + fs.writeFileSync( + executable, + `#!/usr/bin/env bash +set -euo pipefail +real_openshell=${shellQuote(options.realOpenShell)} +base_image=${shellQuote(options.baseImage)} +openclaw_version=${shellQuote(options.openClawVersion)} +log_file=${shellQuote(logFile)} + +if [ "\${1:-}" != "sandbox" ] || [ "\${2:-}" != "create" ]; then + exec "$real_openshell" "$@" +fi + +dockerfile="" +previous="" +for argument in "$@"; do + if [ "$previous" = "--from" ]; then + dockerfile="$argument" + fi + case "$argument" in + --from=*) dockerfile="\${argument#--from=}" ;; + esac + previous="$argument" +done +if [ -z "$dockerfile" ] || [ ! -f "$dockerfile" ]; then + echo "legacy OpenClaw fixture expected sandbox create --from " >&2 + exit 64 +fi + +blueprint="$(dirname "$dockerfile")/nemoclaw-blueprint/blueprint.yaml" +if [ ! -f "$blueprint" ]; then + echo "legacy OpenClaw fixture expected staged blueprint beside $dockerfile" >&2 + exit 64 +fi + +chmod u+w "$dockerfile" "$blueprint" +python3 - "$dockerfile" "$blueprint" "$base_image" "$openclaw_version" <<'PY' +import pathlib +import re +import sys + +dockerfile = pathlib.Path(sys.argv[1]) +blueprint = pathlib.Path(sys.argv[2]) +base_image = sys.argv[3] +version = sys.argv[4] + + +def replace_one(source: str, pattern: str, replacement: str, label: str) -> str: + updated, count = re.subn(pattern, lambda _match: replacement, source, flags=re.MULTILINE) + if count != 1: + raise SystemExit(f"expected one {label}; found {count}") + return updated + + +dockerfile_source = dockerfile.read_text(encoding="utf-8") +dockerfile_source = replace_one( + dockerfile_source, + r"^ARG BASE_IMAGE=.*$", + f"ARG BASE_IMAGE={base_image}", + "Dockerfile BASE_IMAGE default", +) +dockerfile_source = replace_one( + dockerfile_source, + r"^ARG OPENCLAW_VERSION=.*$", + f"ARG OPENCLAW_VERSION={version}", + "Dockerfile OPENCLAW_VERSION default", +) +dockerfile_source = replace_one( + dockerfile_source, + r"^ARG NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=.*$", + "ARG NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", + "Dockerfile legacy OpenClaw fixture flag", +) +dockerfile.write_text(dockerfile_source, encoding="utf-8") + +blueprint_source = blueprint.read_text(encoding="utf-8") +blueprint_source = replace_one( + blueprint_source, + r"^(\s*)min_openclaw_version:\s*.*$", + f'min_openclaw_version: "{version}"', + "blueprint min_openclaw_version", +) +blueprint.write_text(blueprint_source, encoding="utf-8") +PY +chmod a-w "$dockerfile" "$blueprint" + +printf 'patch sandbox create BASE_IMAGE=%s\n' "$base_image" >>"$log_file" +printf 'patch sandbox create OPENCLAW_VERSION=%s\n' "$openclaw_version" >>"$log_file" +printf 'patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1\n' >>"$log_file" +printf 'patch sandbox create min_openclaw_version=%s\n' "$openclaw_version" >>"$log_file" +exec "$real_openshell" "$@" +`, + { encoding: "utf8", mode: 0o755 }, + ); + fs.chmodSync(executable, 0o755); + return { directory, executable, logFile }; +} diff --git a/test/e2e/live/rebuild-openclaw.test.ts b/test/e2e/live/rebuild-openclaw.test.ts index 9e3c76da6f6..dde38ae751a 100644 --- a/test/e2e/live/rebuild-openclaw.test.ts +++ b/test/e2e/live/rebuild-openclaw.test.ts @@ -15,6 +15,7 @@ import { readJsonFile, readJsonFileOr, restoreFile, snapshotFile } from "../fixt 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 { createLegacyOpenClawOpenShellWrapper } from "./rebuild-openclaw-old-openshell-wrapper.ts"; // The contract stays intentionally local to this live test: build an older // OpenClaw base image, recreate the sandbox from it through NemoClaw, seed @@ -449,6 +450,23 @@ test( // an exact policy-creation receipt bound to its new immutable sandbox ID. // Direct OpenShell creation cannot truthfully establish NemoClaw ownership. progress.phase("create the old OpenClaw sandbox"); + const realOpenShellResult = await host.command("bash", ["-lc", "command -v openshell"], { + artifactName: "phase-3-real-openshell-path", + env: dockerContextEnv(), + timeoutMs: 30_000, + }); + expectExitZero(realOpenShellResult, "resolve real openshell path"); + const realOpenShell = realOpenShellResult.stdout.trim(); + expect( + path.isAbsolute(realOpenShell), + `openshell path must be absolute: ${realOpenShell}`, + ).toBe(true); + const oldOpenShellWrapper = createLegacyOpenClawOpenShellWrapper({ + root: artifacts.pathFor("phase-3-old-openshell-wrapper"), + realOpenShell, + baseImage: OLD_BASE_TAG, + openClawVersion: OLD_OPENCLAW_VERSION, + }); const createOldSandbox = await host.command( "node", [CLI_ENTRYPOINT, "onboard", "--non-interactive"], @@ -457,12 +475,25 @@ test( env: cliEnv(apiKey, { NEMOCLAW_RECREATE_SANDBOX: "1", NEMOCLAW_SANDBOX_BASE_IMAGE_REF: OLD_BASE_TAG, + NEMOCLAW_OPENSHELL_BIN: oldOpenShellWrapper.executable, + PATH: `${oldOpenShellWrapper.directory}:${process.env.PATH ?? "/usr/bin:/bin"}`, }), redactionValues: [apiKey], timeoutMs: ONBOARD_TIMEOUT_MS, }, ); expectExitZero(createOldSandbox, "nemoclaw onboard old OpenClaw sandbox"); + const oldOpenShellWrapperLog = fs.readFileSync(oldOpenShellWrapper.logFile, "utf8"); + expect(oldOpenShellWrapperLog).toContain(`patch sandbox create BASE_IMAGE=${OLD_BASE_TAG}`); + expect(oldOpenShellWrapperLog).toContain( + `patch sandbox create OPENCLAW_VERSION=${OLD_OPENCLAW_VERSION}`, + ); + expect(oldOpenShellWrapperLog).toContain( + "patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", + ); + expect(oldOpenShellWrapperLog).toContain( + `patch sandbox create min_openclaw_version=${OLD_OPENCLAW_VERSION}`, + ); await waitForSandboxReady(sandbox); const oldVersion = await sandbox.exec(SANDBOX_NAME, ["openclaw", "--version"], { diff --git a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts b/test/e2e/support/rebuild-openclaw-old-base-context.test.ts index 7b74f4e63b5..10e8d3f272e 100644 --- a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts +++ b/test/e2e/support/rebuild-openclaw-old-base-context.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { execFileSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -11,6 +12,8 @@ import { directDockerfileBaseCopySources, dockerignoreSecretPatterns, } from "../live/rebuild-openclaw-old-base-context.ts"; +import { createLegacyOpenClawOpenShellWrapper } from "../live/rebuild-openclaw-old-openshell-wrapper.ts"; +import { REPO_ROOT } from "../fixtures/paths.ts"; const copiedContexts: string[] = []; const testFiles: string[] = []; @@ -46,6 +49,68 @@ describe("rebuild-openclaw old-base build context", () => { expect(stagedSources.every((source) => fs.existsSync(source))).toBe(true); }); + it.each([{ fromArgs: ["--from", "DOCKERFILE"] }, { fromArgs: ["--from=DOCKERFILE"] }])( + "patches the generated OpenShell sandbox create context for $fromArgs", + ({ fromArgs }) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-wrapper-")); + testFiles.push(root); + const realOpenShell = path.join(root, "real-openshell"); + const argvLog = path.join(root, "real-openshell-argv.log"); + const buildContext = path.join(root, "context"); + const dockerfile = path.join(buildContext, "Dockerfile"); + const blueprint = path.join(buildContext, "nemoclaw-blueprint", "blueprint.yaml"); + fs.mkdirSync(path.dirname(blueprint), { recursive: true }); + fs.copyFileSync(path.join(REPO_ROOT, "Dockerfile"), dockerfile); + fs.copyFileSync(path.join(REPO_ROOT, "nemoclaw-blueprint", "blueprint.yaml"), blueprint); + fs.chmodSync(dockerfile, 0o444); + fs.chmodSync(blueprint, 0o444); + fs.writeFileSync( + realOpenShell, + `#!/usr/bin/env bash\nprintf '%s\\n' "$@" >"$FAKE_OPENSHELL_ARGV_LOG"\n`, + { mode: 0o755 }, + ); + const wrapper = createLegacyOpenClawOpenShellWrapper({ + root: path.join(root, "wrapper"), + realOpenShell, + baseImage: "nemoclaw-old-base:test", + openClawVersion: "2026.3.11", + }); + + const resolvedFromArgs = fromArgs.map((argument) => + argument.replace("DOCKERFILE", dockerfile), + ); + execFileSync( + wrapper.executable, + ["sandbox", "create", "--name", "fixture", ...resolvedFromArgs], + { env: { ...process.env, FAKE_OPENSHELL_ARGV_LOG: argvLog } }, + ); + + expect(fs.readFileSync(argvLog, "utf8").trim().split("\n")).toEqual([ + "sandbox", + "create", + "--name", + "fixture", + ...resolvedFromArgs, + ]); + const patchedDockerfile = fs.readFileSync(dockerfile, "utf8"); + expect(patchedDockerfile.match(/^ARG BASE_IMAGE=.*$/gm)).toEqual([ + "ARG BASE_IMAGE=nemoclaw-old-base:test", + ]); + 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(blueprint, "utf8")).toMatch( + /^\s*min_openclaw_version: "2026\.3\.11"$/m, + ); + expect(fs.readFileSync(wrapper.logFile, "utf8")).toContain( + "patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", + ); + }, + ); + 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-")), From 3c3f74896e92ecb39722683d2bcc3d0479aa520c Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 27 Aug 2026 18:45:17 -0700 Subject: [PATCH 32/40] test(e2e): scope legacy image patch to Docker build --- ...=> rebuild-openclaw-old-docker-wrapper.ts} | 34 +++++++-------- test/e2e/live/rebuild-openclaw.test.ts | 42 +++++++++---------- .../rebuild-openclaw-old-base-context.test.ts | 38 ++++++++--------- 3 files changed, 56 insertions(+), 58 deletions(-) rename test/e2e/live/{rebuild-openclaw-old-openshell-wrapper.ts => rebuild-openclaw-old-docker-wrapper.ts} (74%) diff --git a/test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts b/test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts similarity index 74% rename from test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts rename to test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts index 49d310e2613..d89bc064eb8 100644 --- a/test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts +++ b/test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts @@ -6,49 +6,49 @@ import path from "node:path"; import { shellQuote } from "../../../src/lib/core/shell-quote"; -export interface LegacyOpenClawOpenShellWrapper { +export interface LegacyOpenClawDockerWrapper { directory: string; executable: string; logFile: string; } -export function createLegacyOpenClawOpenShellWrapper(options: { +export function createLegacyOpenClawDockerWrapper(options: { root: string; - realOpenShell: string; + realDocker: string; baseImage: string; openClawVersion: string; -}): LegacyOpenClawOpenShellWrapper { +}): LegacyOpenClawDockerWrapper { const directory = path.join(options.root, "bin"); - const executable = path.join(directory, "openshell"); - const logFile = path.join(options.root, "sandbox-create-patch.log"); + const executable = path.join(directory, "docker"); + const logFile = path.join(options.root, "docker-build-patch.log"); fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); fs.rmSync(logFile, { force: true }); fs.writeFileSync( executable, `#!/usr/bin/env bash set -euo pipefail -real_openshell=${shellQuote(options.realOpenShell)} +real_docker=${shellQuote(options.realDocker)} base_image=${shellQuote(options.baseImage)} openclaw_version=${shellQuote(options.openClawVersion)} log_file=${shellQuote(logFile)} -if [ "\${1:-}" != "sandbox" ] || [ "\${2:-}" != "create" ]; then - exec "$real_openshell" "$@" +if [ "\${1:-}" != "build" ]; then + exec "$real_docker" "$@" fi dockerfile="" previous="" for argument in "$@"; do - if [ "$previous" = "--from" ]; then + if [ "$previous" = "-f" ] || [ "$previous" = "--file" ]; then dockerfile="$argument" fi case "$argument" in - --from=*) dockerfile="\${argument#--from=}" ;; + --file=*) dockerfile="\${argument#--file=}" ;; esac previous="$argument" done if [ -z "$dockerfile" ] || [ ! -f "$dockerfile" ]; then - echo "legacy OpenClaw fixture expected sandbox create --from " >&2 + echo "legacy OpenClaw fixture expected docker build -f " >&2 exit 64 fi @@ -109,11 +109,11 @@ blueprint.write_text(blueprint_source, encoding="utf-8") PY chmod a-w "$dockerfile" "$blueprint" -printf 'patch sandbox create BASE_IMAGE=%s\n' "$base_image" >>"$log_file" -printf 'patch sandbox create OPENCLAW_VERSION=%s\n' "$openclaw_version" >>"$log_file" -printf 'patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1\n' >>"$log_file" -printf 'patch sandbox create min_openclaw_version=%s\n' "$openclaw_version" >>"$log_file" -exec "$real_openshell" "$@" +printf 'patch docker build BASE_IMAGE=%s\n' "$base_image" >>"$log_file" +printf 'patch docker build OPENCLAW_VERSION=%s\n' "$openclaw_version" >>"$log_file" +printf 'patch docker build NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1\n' >>"$log_file" +printf 'patch docker build min_openclaw_version=%s\n' "$openclaw_version" >>"$log_file" +exec "$real_docker" "$@" `, { encoding: "utf8", mode: 0o755 }, ); diff --git a/test/e2e/live/rebuild-openclaw.test.ts b/test/e2e/live/rebuild-openclaw.test.ts index dde38ae751a..5f9bc629569 100644 --- a/test/e2e/live/rebuild-openclaw.test.ts +++ b/test/e2e/live/rebuild-openclaw.test.ts @@ -15,7 +15,7 @@ import { readJsonFile, readJsonFileOr, restoreFile, snapshotFile } from "../fixt 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 { createLegacyOpenClawOpenShellWrapper } from "./rebuild-openclaw-old-openshell-wrapper.ts"; +import { createLegacyOpenClawDockerWrapper } from "./rebuild-openclaw-old-docker-wrapper.ts"; // The contract stays intentionally local to this live test: build an older // OpenClaw base image, recreate the sandbox from it through NemoClaw, seed @@ -315,6 +315,8 @@ test( oldBaseTag: OLD_BASE_TAG, preservedBoundaries: [ "docker build Dockerfile.base with old OPENCLAW_VERSION", + "test-only Docker wrapper patches only the generated sandbox build context", + "real OpenShell binary remains authoritative for preflight and sandbox creation", "openshell sandbox create/exec/policy", "real nemoclaw onboard and rebuild CLI", "workspace marker, registry/session files, backup manifest, config hash", @@ -450,20 +452,17 @@ test( // an exact policy-creation receipt bound to its new immutable sandbox ID. // Direct OpenShell creation cannot truthfully establish NemoClaw ownership. progress.phase("create the old OpenClaw sandbox"); - const realOpenShellResult = await host.command("bash", ["-lc", "command -v openshell"], { - artifactName: "phase-3-real-openshell-path", + const realDockerResult = await host.command("bash", ["-lc", "command -v docker"], { + artifactName: "phase-3-real-docker-path", env: dockerContextEnv(), timeoutMs: 30_000, }); - expectExitZero(realOpenShellResult, "resolve real openshell path"); - const realOpenShell = realOpenShellResult.stdout.trim(); - expect( - path.isAbsolute(realOpenShell), - `openshell path must be absolute: ${realOpenShell}`, - ).toBe(true); - const oldOpenShellWrapper = createLegacyOpenClawOpenShellWrapper({ - root: artifacts.pathFor("phase-3-old-openshell-wrapper"), - realOpenShell, + expectExitZero(realDockerResult, "resolve real docker path"); + const realDocker = realDockerResult.stdout.trim(); + expect(path.isAbsolute(realDocker), `docker path must be absolute: ${realDocker}`).toBe(true); + const oldDockerWrapper = createLegacyOpenClawDockerWrapper({ + root: artifacts.pathFor("phase-3-old-docker-wrapper"), + realDocker, baseImage: OLD_BASE_TAG, openClawVersion: OLD_OPENCLAW_VERSION, }); @@ -475,24 +474,23 @@ test( env: cliEnv(apiKey, { NEMOCLAW_RECREATE_SANDBOX: "1", NEMOCLAW_SANDBOX_BASE_IMAGE_REF: OLD_BASE_TAG, - NEMOCLAW_OPENSHELL_BIN: oldOpenShellWrapper.executable, - PATH: `${oldOpenShellWrapper.directory}:${process.env.PATH ?? "/usr/bin:/bin"}`, + PATH: `${oldDockerWrapper.directory}:${process.env.PATH ?? "/usr/bin:/bin"}`, }), redactionValues: [apiKey], timeoutMs: ONBOARD_TIMEOUT_MS, }, ); expectExitZero(createOldSandbox, "nemoclaw onboard old OpenClaw sandbox"); - const oldOpenShellWrapperLog = fs.readFileSync(oldOpenShellWrapper.logFile, "utf8"); - expect(oldOpenShellWrapperLog).toContain(`patch sandbox create BASE_IMAGE=${OLD_BASE_TAG}`); - expect(oldOpenShellWrapperLog).toContain( - `patch sandbox create OPENCLAW_VERSION=${OLD_OPENCLAW_VERSION}`, + const oldDockerWrapperLog = fs.readFileSync(oldDockerWrapper.logFile, "utf8"); + expect(oldDockerWrapperLog).toContain(`patch docker build BASE_IMAGE=${OLD_BASE_TAG}`); + expect(oldDockerWrapperLog).toContain( + `patch docker build OPENCLAW_VERSION=${OLD_OPENCLAW_VERSION}`, ); - expect(oldOpenShellWrapperLog).toContain( - "patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", + expect(oldDockerWrapperLog).toContain( + "patch docker build NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", ); - expect(oldOpenShellWrapperLog).toContain( - `patch sandbox create min_openclaw_version=${OLD_OPENCLAW_VERSION}`, + expect(oldDockerWrapperLog).toContain( + `patch docker build min_openclaw_version=${OLD_OPENCLAW_VERSION}`, ); await waitForSandboxReady(sandbox); diff --git a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts b/test/e2e/support/rebuild-openclaw-old-base-context.test.ts index 10e8d3f272e..16fca1e1ed3 100644 --- a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts +++ b/test/e2e/support/rebuild-openclaw-old-base-context.test.ts @@ -12,7 +12,7 @@ import { directDockerfileBaseCopySources, dockerignoreSecretPatterns, } from "../live/rebuild-openclaw-old-base-context.ts"; -import { createLegacyOpenClawOpenShellWrapper } from "../live/rebuild-openclaw-old-openshell-wrapper.ts"; +import { createLegacyOpenClawDockerWrapper } from "../live/rebuild-openclaw-old-docker-wrapper.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; const copiedContexts: string[] = []; @@ -49,13 +49,13 @@ describe("rebuild-openclaw old-base build context", () => { expect(stagedSources.every((source) => fs.existsSync(source))).toBe(true); }); - it.each([{ fromArgs: ["--from", "DOCKERFILE"] }, { fromArgs: ["--from=DOCKERFILE"] }])( - "patches the generated OpenShell sandbox create context for $fromArgs", - ({ fromArgs }) => { + it.each([{ fileArgs: ["-f", "DOCKERFILE"] }, { fileArgs: ["--file=DOCKERFILE"] }])( + "patches the generated Docker build context for $fileArgs", + ({ fileArgs }) => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-wrapper-")); testFiles.push(root); - const realOpenShell = path.join(root, "real-openshell"); - const argvLog = path.join(root, "real-openshell-argv.log"); + const realDocker = path.join(root, "real-docker"); + const argvLog = path.join(root, "real-docker-argv.log"); const buildContext = path.join(root, "context"); const dockerfile = path.join(buildContext, "Dockerfile"); const blueprint = path.join(buildContext, "nemoclaw-blueprint", "blueprint.yaml"); @@ -65,32 +65,32 @@ describe("rebuild-openclaw old-base build context", () => { fs.chmodSync(dockerfile, 0o444); fs.chmodSync(blueprint, 0o444); fs.writeFileSync( - realOpenShell, - `#!/usr/bin/env bash\nprintf '%s\\n' "$@" >"$FAKE_OPENSHELL_ARGV_LOG"\n`, + realDocker, + `#!/usr/bin/env bash\nprintf '%s\\n' "$@" >"$FAKE_DOCKER_ARGV_LOG"\n`, { mode: 0o755 }, ); - const wrapper = createLegacyOpenClawOpenShellWrapper({ + const wrapper = createLegacyOpenClawDockerWrapper({ root: path.join(root, "wrapper"), - realOpenShell, + realDocker, baseImage: "nemoclaw-old-base:test", openClawVersion: "2026.3.11", }); - const resolvedFromArgs = fromArgs.map((argument) => + const resolvedFileArgs = fileArgs.map((argument) => argument.replace("DOCKERFILE", dockerfile), ); execFileSync( wrapper.executable, - ["sandbox", "create", "--name", "fixture", ...resolvedFromArgs], - { env: { ...process.env, FAKE_OPENSHELL_ARGV_LOG: argvLog } }, + ["build", "--tag", "fixture:old", ...resolvedFileArgs, buildContext], + { env: { ...process.env, FAKE_DOCKER_ARGV_LOG: argvLog } }, ); expect(fs.readFileSync(argvLog, "utf8").trim().split("\n")).toEqual([ - "sandbox", - "create", - "--name", - "fixture", - ...resolvedFromArgs, + "build", + "--tag", + "fixture:old", + ...resolvedFileArgs, + buildContext, ]); const patchedDockerfile = fs.readFileSync(dockerfile, "utf8"); expect(patchedDockerfile.match(/^ARG BASE_IMAGE=.*$/gm)).toEqual([ @@ -106,7 +106,7 @@ describe("rebuild-openclaw old-base build context", () => { /^\s*min_openclaw_version: "2026\.3\.11"$/m, ); expect(fs.readFileSync(wrapper.logFile, "utf8")).toContain( - "patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", + "patch docker build NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", ); }, ); From a4411d306d27ca1bfc109f6aff49427eff55897c Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 27 Aug 2026 19:12:51 -0700 Subject: [PATCH 33/40] test(e2e): enable legacy image prebuild --- test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts | 2 +- test/e2e/live/rebuild-openclaw.test.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts b/test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts index d89bc064eb8..b74158ae863 100644 --- a/test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts +++ b/test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts @@ -101,7 +101,7 @@ dockerfile.write_text(dockerfile_source, encoding="utf-8") blueprint_source = blueprint.read_text(encoding="utf-8") blueprint_source = replace_one( blueprint_source, - r"^(\s*)min_openclaw_version:\s*.*$", + r"^min_openclaw_version:.*$", f'min_openclaw_version: "{version}"', "blueprint min_openclaw_version", ) diff --git a/test/e2e/live/rebuild-openclaw.test.ts b/test/e2e/live/rebuild-openclaw.test.ts index 5f9bc629569..200271e867a 100644 --- a/test/e2e/live/rebuild-openclaw.test.ts +++ b/test/e2e/live/rebuild-openclaw.test.ts @@ -474,6 +474,7 @@ test( env: cliEnv(apiKey, { NEMOCLAW_RECREATE_SANDBOX: "1", NEMOCLAW_SANDBOX_BASE_IMAGE_REF: OLD_BASE_TAG, + NEMOCLAW_SANDBOX_PREBUILD: "1", PATH: `${oldDockerWrapper.directory}:${process.env.PATH ?? "/usr/bin:/bin"}`, }), redactionValues: [apiKey], From cb15ad3f36e246b9e0ee4e1b9fe77070e89c9800 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 27 Aug 2026 19:56:41 -0700 Subject: [PATCH 34/40] test(e2e): preserve OpenShell companion identity --- ...rebuild-openclaw-old-openshell-wrapper.ts} | 34 ++++----- test/e2e/live/rebuild-openclaw.test.ts | 72 ++++++++++++------- .../rebuild-openclaw-old-base-context.test.ts | 60 +++++++++++----- 3 files changed, 106 insertions(+), 60 deletions(-) rename test/e2e/live/{rebuild-openclaw-old-docker-wrapper.ts => rebuild-openclaw-old-openshell-wrapper.ts} (74%) diff --git a/test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts b/test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts similarity index 74% rename from test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts rename to test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts index b74158ae863..78a7d046168 100644 --- a/test/e2e/live/rebuild-openclaw-old-docker-wrapper.ts +++ b/test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts @@ -6,49 +6,49 @@ import path from "node:path"; import { shellQuote } from "../../../src/lib/core/shell-quote"; -export interface LegacyOpenClawDockerWrapper { +export interface LegacyOpenClawOpenShellWrapper { directory: string; executable: string; logFile: string; } -export function createLegacyOpenClawDockerWrapper(options: { +export function createLegacyOpenClawOpenShellWrapper(options: { root: string; - realDocker: string; + realOpenShell: string; baseImage: string; openClawVersion: string; -}): LegacyOpenClawDockerWrapper { +}): LegacyOpenClawOpenShellWrapper { const directory = path.join(options.root, "bin"); - const executable = path.join(directory, "docker"); - const logFile = path.join(options.root, "docker-build-patch.log"); + const executable = path.join(directory, "openshell"); + const logFile = path.join(options.root, "sandbox-create-patch.log"); fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); fs.rmSync(logFile, { force: true }); fs.writeFileSync( executable, `#!/usr/bin/env bash set -euo pipefail -real_docker=${shellQuote(options.realDocker)} +real_openshell=${shellQuote(options.realOpenShell)} base_image=${shellQuote(options.baseImage)} openclaw_version=${shellQuote(options.openClawVersion)} log_file=${shellQuote(logFile)} -if [ "\${1:-}" != "build" ]; then - exec "$real_docker" "$@" +if [ "\${1:-}" != "sandbox" ] || [ "\${2:-}" != "create" ]; then + exec "$real_openshell" "$@" fi dockerfile="" previous="" for argument in "$@"; do - if [ "$previous" = "-f" ] || [ "$previous" = "--file" ]; then + if [ "$previous" = "--from" ]; then dockerfile="$argument" fi case "$argument" in - --file=*) dockerfile="\${argument#--file=}" ;; + --from=*) dockerfile="\${argument#--from=}" ;; esac previous="$argument" done if [ -z "$dockerfile" ] || [ ! -f "$dockerfile" ]; then - echo "legacy OpenClaw fixture expected docker build -f " >&2 + echo "legacy OpenClaw fixture expected sandbox create --from " >&2 exit 64 fi @@ -109,11 +109,11 @@ blueprint.write_text(blueprint_source, encoding="utf-8") PY chmod a-w "$dockerfile" "$blueprint" -printf 'patch docker build BASE_IMAGE=%s\n' "$base_image" >>"$log_file" -printf 'patch docker build OPENCLAW_VERSION=%s\n' "$openclaw_version" >>"$log_file" -printf 'patch docker build NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1\n' >>"$log_file" -printf 'patch docker build min_openclaw_version=%s\n' "$openclaw_version" >>"$log_file" -exec "$real_docker" "$@" +printf 'patch sandbox create BASE_IMAGE=%s\n' "$base_image" >>"$log_file" +printf 'patch sandbox create OPENCLAW_VERSION=%s\n' "$openclaw_version" >>"$log_file" +printf 'patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1\n' >>"$log_file" +printf 'patch sandbox create min_openclaw_version=%s\n' "$openclaw_version" >>"$log_file" +exec "$real_openshell" "$@" `, { encoding: "utf8", mode: 0o755 }, ); diff --git a/test/e2e/live/rebuild-openclaw.test.ts b/test/e2e/live/rebuild-openclaw.test.ts index 200271e867a..32593531b58 100644 --- a/test/e2e/live/rebuild-openclaw.test.ts +++ b/test/e2e/live/rebuild-openclaw.test.ts @@ -15,7 +15,7 @@ import { readJsonFile, readJsonFileOr, restoreFile, snapshotFile } from "../fixt 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 { createLegacyOpenClawDockerWrapper } from "./rebuild-openclaw-old-docker-wrapper.ts"; +import { createLegacyOpenClawOpenShellWrapper } from "./rebuild-openclaw-old-openshell-wrapper.ts"; // The contract stays intentionally local to this live test: build an older // OpenClaw base image, recreate the sandbox from it through NemoClaw, seed @@ -315,8 +315,8 @@ test( oldBaseTag: OLD_BASE_TAG, preservedBoundaries: [ "docker build Dockerfile.base with old OPENCLAW_VERSION", - "test-only Docker wrapper patches only the generated sandbox build context", - "real OpenShell binary remains authoritative for preflight and sandbox creation", + "test-only OpenShell wrapper patches only the generated sandbox create context", + "real OpenShell CLI and driver binaries remain authoritative", "openshell sandbox create/exec/policy", "real nemoclaw onboard and rebuild CLI", "workspace marker, registry/session files, backup manifest, config hash", @@ -452,17 +452,40 @@ test( // an exact policy-creation receipt bound to its new immutable sandbox ID. // Direct OpenShell creation cannot truthfully establish NemoClaw ownership. progress.phase("create the old OpenClaw sandbox"); - const realDockerResult = await host.command("bash", ["-lc", "command -v docker"], { - artifactName: "phase-3-real-docker-path", - env: dockerContextEnv(), - timeoutMs: 30_000, - }); - expectExitZero(realDockerResult, "resolve real docker path"); - const realDocker = realDockerResult.stdout.trim(); - expect(path.isAbsolute(realDocker), `docker path must be absolute: ${realDocker}`).toBe(true); - const oldDockerWrapper = createLegacyOpenClawDockerWrapper({ - root: artifacts.pathFor("phase-3-old-docker-wrapper"), - realDocker, + const realOpenShellComponentsResult = await host.command( + "bash", + [ + "-lc", + 'for name in openshell openshell-gateway openshell-sandbox; do command -v "$name"; done', + ], + { + artifactName: "phase-3-real-openshell-components", + env: dockerContextEnv(), + timeoutMs: 30_000, + }, + ); + expectExitZero(realOpenShellComponentsResult, "resolve real OpenShell component paths"); + const realOpenShellComponents = realOpenShellComponentsResult.stdout + .split(/\r?\n/) + .map((value) => value.trim()) + .filter(Boolean); + expect(realOpenShellComponents).toHaveLength(3); + const [realOpenShell, realOpenShellGateway, realOpenShellSandbox] = realOpenShellComponents; + expect( + path.isAbsolute(realOpenShell), + `OpenShell CLI path must be absolute: ${realOpenShell}`, + ).toBe(true); + expect( + path.isAbsolute(realOpenShellGateway), + `OpenShell gateway path must be absolute: ${realOpenShellGateway}`, + ).toBe(true); + expect( + path.isAbsolute(realOpenShellSandbox), + `OpenShell sandbox path must be absolute: ${realOpenShellSandbox}`, + ).toBe(true); + const oldOpenShellWrapper = createLegacyOpenClawOpenShellWrapper({ + root: artifacts.pathFor("phase-3-old-openshell-wrapper"), + realOpenShell, baseImage: OLD_BASE_TAG, openClawVersion: OLD_OPENCLAW_VERSION, }); @@ -474,24 +497,25 @@ test( env: cliEnv(apiKey, { NEMOCLAW_RECREATE_SANDBOX: "1", NEMOCLAW_SANDBOX_BASE_IMAGE_REF: OLD_BASE_TAG, - NEMOCLAW_SANDBOX_PREBUILD: "1", - PATH: `${oldDockerWrapper.directory}:${process.env.PATH ?? "/usr/bin:/bin"}`, + NEMOCLAW_OPENSHELL_GATEWAY_BIN: realOpenShellGateway, + NEMOCLAW_OPENSHELL_SANDBOX_BIN: realOpenShellSandbox, + PATH: `${oldOpenShellWrapper.directory}:${process.env.PATH ?? "/usr/bin:/bin"}`, }), redactionValues: [apiKey], timeoutMs: ONBOARD_TIMEOUT_MS, }, ); expectExitZero(createOldSandbox, "nemoclaw onboard old OpenClaw sandbox"); - const oldDockerWrapperLog = fs.readFileSync(oldDockerWrapper.logFile, "utf8"); - expect(oldDockerWrapperLog).toContain(`patch docker build BASE_IMAGE=${OLD_BASE_TAG}`); - expect(oldDockerWrapperLog).toContain( - `patch docker build OPENCLAW_VERSION=${OLD_OPENCLAW_VERSION}`, + const oldOpenShellWrapperLog = fs.readFileSync(oldOpenShellWrapper.logFile, "utf8"); + expect(oldOpenShellWrapperLog).toContain(`patch sandbox create BASE_IMAGE=${OLD_BASE_TAG}`); + expect(oldOpenShellWrapperLog).toContain( + `patch sandbox create OPENCLAW_VERSION=${OLD_OPENCLAW_VERSION}`, ); - expect(oldDockerWrapperLog).toContain( - "patch docker build NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", + expect(oldOpenShellWrapperLog).toContain( + "patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", ); - expect(oldDockerWrapperLog).toContain( - `patch docker build min_openclaw_version=${OLD_OPENCLAW_VERSION}`, + expect(oldOpenShellWrapperLog).toContain( + `patch sandbox create min_openclaw_version=${OLD_OPENCLAW_VERSION}`, ); await waitForSandboxReady(sandbox); diff --git a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts b/test/e2e/support/rebuild-openclaw-old-base-context.test.ts index 16fca1e1ed3..6f6e42e3874 100644 --- a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts +++ b/test/e2e/support/rebuild-openclaw-old-base-context.test.ts @@ -12,7 +12,7 @@ import { directDockerfileBaseCopySources, dockerignoreSecretPatterns, } from "../live/rebuild-openclaw-old-base-context.ts"; -import { createLegacyOpenClawDockerWrapper } from "../live/rebuild-openclaw-old-docker-wrapper.ts"; +import { createLegacyOpenClawOpenShellWrapper } from "../live/rebuild-openclaw-old-openshell-wrapper.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; const copiedContexts: string[] = []; @@ -49,13 +49,13 @@ describe("rebuild-openclaw old-base build context", () => { expect(stagedSources.every((source) => fs.existsSync(source))).toBe(true); }); - it.each([{ fileArgs: ["-f", "DOCKERFILE"] }, { fileArgs: ["--file=DOCKERFILE"] }])( - "patches the generated Docker build context for $fileArgs", - ({ fileArgs }) => { + it.each([{ fromArgs: ["--from", "DOCKERFILE"] }, { fromArgs: ["--from=DOCKERFILE"] }])( + "patches the generated sandbox create context for $fromArgs", + ({ fromArgs }) => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-wrapper-")); testFiles.push(root); - const realDocker = path.join(root, "real-docker"); - const argvLog = path.join(root, "real-docker-argv.log"); + const realOpenShell = path.join(root, "real-openshell"); + const argvLog = path.join(root, "real-openshell-argv.log"); const buildContext = path.join(root, "context"); const dockerfile = path.join(buildContext, "Dockerfile"); const blueprint = path.join(buildContext, "nemoclaw-blueprint", "blueprint.yaml"); @@ -65,32 +65,34 @@ describe("rebuild-openclaw old-base build context", () => { fs.chmodSync(dockerfile, 0o444); fs.chmodSync(blueprint, 0o444); fs.writeFileSync( - realDocker, - `#!/usr/bin/env bash\nprintf '%s\\n' "$@" >"$FAKE_DOCKER_ARGV_LOG"\n`, + realOpenShell, + `#!/usr/bin/env bash\nprintf '%s\\n' "$@" >"$FAKE_OPENSHELL_ARGV_LOG"\n`, { mode: 0o755 }, ); - const wrapper = createLegacyOpenClawDockerWrapper({ + const wrapper = createLegacyOpenClawOpenShellWrapper({ root: path.join(root, "wrapper"), - realDocker, + realOpenShell, baseImage: "nemoclaw-old-base:test", openClawVersion: "2026.3.11", }); - const resolvedFileArgs = fileArgs.map((argument) => + const resolvedFromArgs = fromArgs.map((argument) => argument.replace("DOCKERFILE", dockerfile), ); execFileSync( wrapper.executable, - ["build", "--tag", "fixture:old", ...resolvedFileArgs, buildContext], - { env: { ...process.env, FAKE_DOCKER_ARGV_LOG: argvLog } }, + ["sandbox", "create", "--name", "fixture", ...resolvedFromArgs, "--", "nemoclaw-start"], + { env: { ...process.env, FAKE_OPENSHELL_ARGV_LOG: argvLog } }, ); expect(fs.readFileSync(argvLog, "utf8").trim().split("\n")).toEqual([ - "build", - "--tag", - "fixture:old", - ...resolvedFileArgs, - buildContext, + "sandbox", + "create", + "--name", + "fixture", + ...resolvedFromArgs, + "--", + "nemoclaw-start", ]); const patchedDockerfile = fs.readFileSync(dockerfile, "utf8"); expect(patchedDockerfile.match(/^ARG BASE_IMAGE=.*$/gm)).toEqual([ @@ -106,11 +108,31 @@ describe("rebuild-openclaw old-base build context", () => { /^\s*min_openclaw_version: "2026\.3\.11"$/m, ); expect(fs.readFileSync(wrapper.logFile, "utf8")).toContain( - "patch docker build NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", + "patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", ); }, ); + it("passes OpenShell preflight commands through without patching", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-wrapper-")); + testFiles.push(root); + const realOpenShell = path.join(root, "real-openshell"); + fs.writeFileSync(realOpenShell, "#!/usr/bin/env bash\nprintf 'openshell 0.0.106\\n'\n", { + mode: 0o755, + }); + const wrapper = createLegacyOpenClawOpenShellWrapper({ + root: path.join(root, "wrapper"), + realOpenShell, + baseImage: "nemoclaw-old-base:test", + openClawVersion: "2026.3.11", + }); + + const output = execFileSync(wrapper.executable, ["--version"], { encoding: "utf8" }); + + expect(output).toBe("openshell 0.0.106\n"); + expect(fs.existsSync(wrapper.logFile)).toBe(false); + }); + 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-")), From 4749b5c5db8d1d681ee36cd3de2bf4c4fb6175bd Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 27 Aug 2026 21:00:51 -0700 Subject: [PATCH 35/40] test(e2e): use explicit legacy rebuild context --- .../live/rebuild-openclaw-legacy-context.ts | 98 ++++++++++++++ .../rebuild-openclaw-old-openshell-wrapper.ts | 122 ------------------ test/e2e/live/rebuild-openclaw.test.ts | 67 +++------- .../rebuild-openclaw-old-base-context.test.ts | 116 ++++++----------- 4 files changed, 150 insertions(+), 253 deletions(-) create mode 100644 test/e2e/live/rebuild-openclaw-legacy-context.ts delete mode 100644 test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts 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..e2db18ac934 --- /dev/null +++ b/test/e2e/live/rebuild-openclaw-legacy-context.ts @@ -0,0 +1,98 @@ +// 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 inputs needed to create the historical sandbox exercised by this E2E. + * The caller restores the current trusted recipe before invoking rebuild. + */ +export function createLegacyOpenClawSandboxContext(options: { + rootDir: string; + baseImage: 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 BASE_IMAGE=.*$/gm, + `ARG BASE_IMAGE=${options.baseImage}`, + "Dockerfile BASE_IMAGE default", + ); + legacyDockerfile = replaceExactlyOne( + legacyDockerfile, + /^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-openshell-wrapper.ts b/test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts deleted file mode 100644 index 78a7d046168..00000000000 --- a/test/e2e/live/rebuild-openclaw-old-openshell-wrapper.ts +++ /dev/null @@ -1,122 +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 path from "node:path"; - -import { shellQuote } from "../../../src/lib/core/shell-quote"; - -export interface LegacyOpenClawOpenShellWrapper { - directory: string; - executable: string; - logFile: string; -} - -export function createLegacyOpenClawOpenShellWrapper(options: { - root: string; - realOpenShell: string; - baseImage: string; - openClawVersion: string; -}): LegacyOpenClawOpenShellWrapper { - const directory = path.join(options.root, "bin"); - const executable = path.join(directory, "openshell"); - const logFile = path.join(options.root, "sandbox-create-patch.log"); - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - fs.rmSync(logFile, { force: true }); - fs.writeFileSync( - executable, - `#!/usr/bin/env bash -set -euo pipefail -real_openshell=${shellQuote(options.realOpenShell)} -base_image=${shellQuote(options.baseImage)} -openclaw_version=${shellQuote(options.openClawVersion)} -log_file=${shellQuote(logFile)} - -if [ "\${1:-}" != "sandbox" ] || [ "\${2:-}" != "create" ]; then - exec "$real_openshell" "$@" -fi - -dockerfile="" -previous="" -for argument in "$@"; do - if [ "$previous" = "--from" ]; then - dockerfile="$argument" - fi - case "$argument" in - --from=*) dockerfile="\${argument#--from=}" ;; - esac - previous="$argument" -done -if [ -z "$dockerfile" ] || [ ! -f "$dockerfile" ]; then - echo "legacy OpenClaw fixture expected sandbox create --from " >&2 - exit 64 -fi - -blueprint="$(dirname "$dockerfile")/nemoclaw-blueprint/blueprint.yaml" -if [ ! -f "$blueprint" ]; then - echo "legacy OpenClaw fixture expected staged blueprint beside $dockerfile" >&2 - exit 64 -fi - -chmod u+w "$dockerfile" "$blueprint" -python3 - "$dockerfile" "$blueprint" "$base_image" "$openclaw_version" <<'PY' -import pathlib -import re -import sys - -dockerfile = pathlib.Path(sys.argv[1]) -blueprint = pathlib.Path(sys.argv[2]) -base_image = sys.argv[3] -version = sys.argv[4] - - -def replace_one(source: str, pattern: str, replacement: str, label: str) -> str: - updated, count = re.subn(pattern, lambda _match: replacement, source, flags=re.MULTILINE) - if count != 1: - raise SystemExit(f"expected one {label}; found {count}") - return updated - - -dockerfile_source = dockerfile.read_text(encoding="utf-8") -dockerfile_source = replace_one( - dockerfile_source, - r"^ARG BASE_IMAGE=.*$", - f"ARG BASE_IMAGE={base_image}", - "Dockerfile BASE_IMAGE default", -) -dockerfile_source = replace_one( - dockerfile_source, - r"^ARG OPENCLAW_VERSION=.*$", - f"ARG OPENCLAW_VERSION={version}", - "Dockerfile OPENCLAW_VERSION default", -) -dockerfile_source = replace_one( - dockerfile_source, - r"^ARG NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=.*$", - "ARG NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", - "Dockerfile legacy OpenClaw fixture flag", -) -dockerfile.write_text(dockerfile_source, encoding="utf-8") - -blueprint_source = blueprint.read_text(encoding="utf-8") -blueprint_source = replace_one( - blueprint_source, - r"^min_openclaw_version:.*$", - f'min_openclaw_version: "{version}"', - "blueprint min_openclaw_version", -) -blueprint.write_text(blueprint_source, encoding="utf-8") -PY -chmod a-w "$dockerfile" "$blueprint" - -printf 'patch sandbox create BASE_IMAGE=%s\n' "$base_image" >>"$log_file" -printf 'patch sandbox create OPENCLAW_VERSION=%s\n' "$openclaw_version" >>"$log_file" -printf 'patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1\n' >>"$log_file" -printf 'patch sandbox create min_openclaw_version=%s\n' "$openclaw_version" >>"$log_file" -exec "$real_openshell" "$@" -`, - { encoding: "utf8", mode: 0o755 }, - ); - fs.chmodSync(executable, 0o755); - return { directory, executable, logFile }; -} diff --git a/test/e2e/live/rebuild-openclaw.test.ts b/test/e2e/live/rebuild-openclaw.test.ts index 32593531b58..0079867ccb3 100644 --- a/test/e2e/live/rebuild-openclaw.test.ts +++ b/test/e2e/live/rebuild-openclaw.test.ts @@ -15,7 +15,7 @@ import { readJsonFile, readJsonFileOr, restoreFile, snapshotFile } from "../fixt 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 { createLegacyOpenClawOpenShellWrapper } from "./rebuild-openclaw-old-openshell-wrapper.ts"; +import { createLegacyOpenClawSandboxContext } from "./rebuild-openclaw-legacy-context.ts"; // The contract stays intentionally local to this live test: build an older // OpenClaw base image, recreate the sandbox from it through NemoClaw, seed @@ -315,8 +315,8 @@ test( oldBaseTag: OLD_BASE_TAG, preservedBoundaries: [ "docker build Dockerfile.base with old OPENCLAW_VERSION", - "test-only OpenShell wrapper patches only the generated sandbox create context", - "real OpenShell CLI and driver binaries remain authoritative", + "test-only --from context starts with the old recipe 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", @@ -452,71 +452,28 @@ test( // an exact policy-creation receipt bound to its new immutable sandbox ID. // Direct OpenShell creation cannot truthfully establish NemoClaw ownership. progress.phase("create the old OpenClaw sandbox"); - const realOpenShellComponentsResult = await host.command( - "bash", - [ - "-lc", - 'for name in openshell openshell-gateway openshell-sandbox; do command -v "$name"; done', - ], - { - artifactName: "phase-3-real-openshell-components", - env: dockerContextEnv(), - timeoutMs: 30_000, - }, - ); - expectExitZero(realOpenShellComponentsResult, "resolve real OpenShell component paths"); - const realOpenShellComponents = realOpenShellComponentsResult.stdout - .split(/\r?\n/) - .map((value) => value.trim()) - .filter(Boolean); - expect(realOpenShellComponents).toHaveLength(3); - const [realOpenShell, realOpenShellGateway, realOpenShellSandbox] = realOpenShellComponents; - expect( - path.isAbsolute(realOpenShell), - `OpenShell CLI path must be absolute: ${realOpenShell}`, - ).toBe(true); - expect( - path.isAbsolute(realOpenShellGateway), - `OpenShell gateway path must be absolute: ${realOpenShellGateway}`, - ).toBe(true); - expect( - path.isAbsolute(realOpenShellSandbox), - `OpenShell sandbox path must be absolute: ${realOpenShellSandbox}`, - ).toBe(true); - const oldOpenShellWrapper = createLegacyOpenClawOpenShellWrapper({ - root: artifacts.pathFor("phase-3-old-openshell-wrapper"), - realOpenShell, + const legacyContext = createLegacyOpenClawSandboxContext({ + rootDir: REPO_ROOT, baseImage: OLD_BASE_TAG, openClawVersion: OLD_OPENCLAW_VERSION, }); + cleanup.trackDisposable("remove legacy OpenClaw sandbox context", () => + legacyContext.cleanup(), + ); const createOldSandbox = await host.command( "node", - [CLI_ENTRYPOINT, "onboard", "--non-interactive"], + [CLI_ENTRYPOINT, "onboard", "--non-interactive", "--from", legacyContext.dockerfile], { artifactName: "phase-3-onboard-old-openclaw-sandbox", env: cliEnv(apiKey, { NEMOCLAW_RECREATE_SANDBOX: "1", NEMOCLAW_SANDBOX_BASE_IMAGE_REF: OLD_BASE_TAG, - NEMOCLAW_OPENSHELL_GATEWAY_BIN: realOpenShellGateway, - NEMOCLAW_OPENSHELL_SANDBOX_BIN: realOpenShellSandbox, - PATH: `${oldOpenShellWrapper.directory}:${process.env.PATH ?? "/usr/bin:/bin"}`, }), redactionValues: [apiKey], timeoutMs: ONBOARD_TIMEOUT_MS, }, ); expectExitZero(createOldSandbox, "nemoclaw onboard old OpenClaw sandbox"); - const oldOpenShellWrapperLog = fs.readFileSync(oldOpenShellWrapper.logFile, "utf8"); - expect(oldOpenShellWrapperLog).toContain(`patch sandbox create BASE_IMAGE=${OLD_BASE_TAG}`); - expect(oldOpenShellWrapperLog).toContain( - `patch sandbox create OPENCLAW_VERSION=${OLD_OPENCLAW_VERSION}`, - ); - expect(oldOpenShellWrapperLog).toContain( - "patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", - ); - expect(oldOpenShellWrapperLog).toContain( - `patch sandbox create min_openclaw_version=${OLD_OPENCLAW_VERSION}`, - ); await waitForSandboxReady(sandbox); const oldVersion = await sandbox.exec(SANDBOX_NAME, ["openclaw", "--version"], { @@ -526,6 +483,12 @@ test( }); expectExitZero(oldVersion, "old openclaw --version"); expect(resultText(oldVersion)).toContain(OLD_OPENCLAW_VERSION); + expect(registrySandbox().fromDockerfile).toBe(legacyContext.dockerfile); + + // 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. diff --git a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts b/test/e2e/support/rebuild-openclaw-old-base-context.test.ts index 6f6e42e3874..a79b1bf2920 100644 --- a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts +++ b/test/e2e/support/rebuild-openclaw-old-base-context.test.ts @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { execFileSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -12,7 +11,7 @@ import { directDockerfileBaseCopySources, dockerignoreSecretPatterns, } from "../live/rebuild-openclaw-old-base-context.ts"; -import { createLegacyOpenClawOpenShellWrapper } from "../live/rebuild-openclaw-old-openshell-wrapper.ts"; +import { createLegacyOpenClawSandboxContext } from "../live/rebuild-openclaw-legacy-context.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; const copiedContexts: string[] = []; @@ -49,88 +48,47 @@ describe("rebuild-openclaw old-base build context", () => { expect(stagedSources.every((source) => fs.existsSync(source))).toBe(true); }); - it.each([{ fromArgs: ["--from", "DOCKERFILE"] }, { fromArgs: ["--from=DOCKERFILE"] }])( - "patches the generated sandbox create context for $fromArgs", - ({ fromArgs }) => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-wrapper-")); - testFiles.push(root); - const realOpenShell = path.join(root, "real-openshell"); - const argvLog = path.join(root, "real-openshell-argv.log"); - const buildContext = path.join(root, "context"); - const dockerfile = path.join(buildContext, "Dockerfile"); - const blueprint = path.join(buildContext, "nemoclaw-blueprint", "blueprint.yaml"); - fs.mkdirSync(path.dirname(blueprint), { recursive: true }); - fs.copyFileSync(path.join(REPO_ROOT, "Dockerfile"), dockerfile); - fs.copyFileSync(path.join(REPO_ROOT, "nemoclaw-blueprint", "blueprint.yaml"), blueprint); - fs.chmodSync(dockerfile, 0o444); - fs.chmodSync(blueprint, 0o444); - fs.writeFileSync( - realOpenShell, - `#!/usr/bin/env bash\nprintf '%s\\n' "$@" >"$FAKE_OPENSHELL_ARGV_LOG"\n`, - { mode: 0o755 }, - ); - const wrapper = createLegacyOpenClawOpenShellWrapper({ - root: path.join(root, "wrapper"), - realOpenShell, - baseImage: "nemoclaw-old-base:test", - openClawVersion: "2026.3.11", - }); - - const resolvedFromArgs = fromArgs.map((argument) => - argument.replace("DOCKERFILE", dockerfile), - ); - execFileSync( - wrapper.executable, - ["sandbox", "create", "--name", "fixture", ...resolvedFromArgs, "--", "nemoclaw-start"], - { env: { ...process.env, FAKE_OPENSHELL_ARGV_LOG: argvLog } }, - ); - - expect(fs.readFileSync(argvLog, "utf8").trim().split("\n")).toEqual([ - "sandbox", - "create", - "--name", - "fixture", - ...resolvedFromArgs, - "--", - "nemoclaw-start", - ]); - const patchedDockerfile = fs.readFileSync(dockerfile, "utf8"); - expect(patchedDockerfile.match(/^ARG BASE_IMAGE=.*$/gm)).toEqual([ - "ARG BASE_IMAGE=nemoclaw-old-base:test", - ]); - 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(blueprint, "utf8")).toMatch( - /^\s*min_openclaw_version: "2026\.3\.11"$/m, - ); - expect(fs.readFileSync(wrapper.logFile, "utf8")).toContain( - "patch sandbox create NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1", - ); - }, - ); - - it("passes OpenShell preflight commands through without patching", () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-rebuild-openclaw-wrapper-")); - testFiles.push(root); - const realOpenShell = path.join(root, "real-openshell"); - fs.writeFileSync(realOpenShell, "#!/usr/bin/env bash\nprintf 'openshell 0.0.106\\n'\n", { - mode: 0o755, - }); - const wrapper = createLegacyOpenClawOpenShellWrapper({ - root: path.join(root, "wrapper"), - realOpenShell, + it("stages an old complete sandbox context 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 legacyContext = createLegacyOpenClawSandboxContext({ + rootDir: REPO_ROOT, baseImage: "nemoclaw-old-base:test", openClawVersion: "2026.3.11", }); + copiedContexts.push(legacyContext.buildCtx); + + const patchedDockerfile = fs.readFileSync(legacyContext.dockerfile, "utf8"); + expect(patchedDockerfile.match(/^ARG BASE_IMAGE=.*$/gm)).toEqual([ + "ARG BASE_IMAGE=nemoclaw-old-base:test", + ]); + 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); - const output = execFileSync(wrapper.executable, ["--version"], { encoding: "utf8" }); + legacyContext.restoreCurrent(); - expect(output).toBe("openshell 0.0.106\n"); - expect(fs.existsSync(wrapper.logFile)).toBe(false); + 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); }); it("parses direct Dockerfile.base COPY syntax without silently ignoring variants", () => { From 5714c426f14c1ad4c66779868035c6f086cb7703 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Thu, 27 Aug 2026 21:47:01 -0700 Subject: [PATCH 36/40] test: cover MCP rebuild refusal compensation Signed-off-by: Carlos Villela --- ...cp-bridge-rebuild-policy-authority.test.ts | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) 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 index a9dd296f2ed..4203f830675 100644 --- a/src/lib/actions/sandbox/mcp-bridge-rebuild-policy-authority.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-rebuild-policy-authority.test.ts @@ -150,7 +150,28 @@ describe("MCP rebuild policy authority", () => { expect(mocks.detachProvider).not.toHaveBeenCalled(); }); - it("compensates completed provider and adapter teardown without mutating policy (#9833)", async () => { + 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", From 71885380f5a75002d5250175410ead0a91c37e1b Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 27 Aug 2026 23:02:32 -0700 Subject: [PATCH 37/40] test(e2e): keep rebuild fixture on current base --- test/e2e/README.md | 2 +- .../live/rebuild-openclaw-legacy-context.ts | 12 +- .../live/rebuild-openclaw-old-base-context.ts | 118 ------- test/e2e/live/rebuild-openclaw.test.ts | 112 +------ .../rebuild-openclaw-legacy-context.test.ts | 61 ++++ .../rebuild-openclaw-old-base-context.test.ts | 293 ------------------ tools/e2e/target-catalogue.mts | 2 +- 7 files changed, 82 insertions(+), 518 deletions(-) delete mode 100644 test/e2e/live/rebuild-openclaw-old-base-context.ts create mode 100644 test/e2e/support/rebuild-openclaw-legacy-context.test.ts delete mode 100644 test/e2e/support/rebuild-openclaw-old-base-context.test.ts diff --git a/test/e2e/README.md b/test/e2e/README.md index 3025c97917d..dcc175312ca 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 index e2db18ac934..0dc669c00db 100644 --- a/test/e2e/live/rebuild-openclaw-legacy-context.ts +++ b/test/e2e/live/rebuild-openclaw-legacy-context.ts @@ -35,12 +35,12 @@ function writePreservingMode(filePath: string, contents: string, mode: number): /** * Stage the complete trusted OpenClaw Docker build context, then lower only - * the inputs needed to create the historical sandbox exercised by this E2E. - * The caller restores the current trusted recipe before invoking rebuild. + * 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; - baseImage: string; openClawVersion: string; }): LegacyOpenClawSandboxContext { const staged = stageOptimizedSandboxBuildContext(options.rootDir); @@ -54,12 +54,6 @@ export function createLegacyOpenClawSandboxContext(options: { try { let legacyDockerfile = replaceExactlyOne( currentDockerfile, - /^ARG BASE_IMAGE=.*$/gm, - `ARG BASE_IMAGE=${options.baseImage}`, - "Dockerfile BASE_IMAGE default", - ); - legacyDockerfile = replaceExactlyOne( - legacyDockerfile, /^ARG OPENCLAW_VERSION=.*$/gm, `ARG OPENCLAW_VERSION=${options.openClawVersion}`, "Dockerfile OPENCLAW_VERSION default", 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 0079867ccb3..fe054967653 100644 --- a/test/e2e/live/rebuild-openclaw.test.ts +++ b/test/e2e/live/rebuild-openclaw.test.ts @@ -14,13 +14,13 @@ import { expect, test } from "../fixtures/e2e-test.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, recreate the sandbox from it through NemoClaw, 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. @@ -48,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; @@ -142,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]; } @@ -273,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", ], @@ -312,10 +295,9 @@ test( oldOpenClawVersion: OLD_OPENCLAW_VERSION, sandboxName: SANDBOX_NAME, markerFile: MARKER_FILE, - oldBaseTag: OLD_BASE_TAG, preservedBoundaries: [ - "docker build Dockerfile.base with old OPENCLAW_VERSION", - "test-only --from context starts with the old recipe and is restored before rebuild", + "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", @@ -343,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); @@ -357,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(), @@ -417,44 +391,13 @@ 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: recreate the sandbox through NemoClaw so the old runtime keeps - // an exact policy-creation receipt bound to its new immutable sandbox ID. - // Direct OpenShell creation cannot truthfully establish NemoClaw ownership. - progress.phase("create the old OpenClaw sandbox"); + // 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, - baseImage: OLD_BASE_TAG, openClawVersion: OLD_OPENCLAW_VERSION, }); cleanup.trackDisposable("remove legacy OpenClaw sandbox context", () => @@ -465,10 +408,7 @@ test( [CLI_ENTRYPOINT, "onboard", "--non-interactive", "--from", legacyContext.dockerfile], { artifactName: "phase-3-onboard-old-openclaw-sandbox", - env: cliEnv(apiKey, { - NEMOCLAW_RECREATE_SANDBOX: "1", - NEMOCLAW_SANDBOX_BASE_IMAGE_REF: OLD_BASE_TAG, - }), + env: cliEnv(apiKey, { NEMOCLAW_RECREATE_SANDBOX: "1" }), redactionValues: [apiKey], timeoutMs: ONBOARD_TIMEOUT_MS, }, @@ -626,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 a79b1bf2920..00000000000 --- a/test/e2e/support/rebuild-openclaw-old-base-context.test.ts +++ /dev/null @@ -1,293 +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"; -import { createLegacyOpenClawSandboxContext } from "../live/rebuild-openclaw-legacy-context.ts"; -import { REPO_ROOT } from "../fixtures/paths.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("stages an old complete sandbox context 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 legacyContext = createLegacyOpenClawSandboxContext({ - rootDir: REPO_ROOT, - baseImage: "nemoclaw-old-base:test", - openClawVersion: "2026.3.11", - }); - copiedContexts.push(legacyContext.buildCtx); - - const patchedDockerfile = fs.readFileSync(legacyContext.dockerfile, "utf8"); - expect(patchedDockerfile.match(/^ARG BASE_IMAGE=.*$/gm)).toEqual([ - "ARG BASE_IMAGE=nemoclaw-old-base:test", - ]); - 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); - }); - - 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/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, From 8ddd9e8b692cd33a4d0698d98bbc057817eb0f77 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Thu, 27 Aug 2026 23:28:26 -0700 Subject: [PATCH 38/40] fix: preserve rebuild policy authority failures Signed-off-by: Carlos Villela --- src/lib/onboard/providers.ts | 5 ++++- test/credentials/rebuild-credential-preflight.test.ts | 6 +++++- test/runtime/gateway/gateway-state-reconcile-2276.test.ts | 7 ++++++- .../messaging/rebuild-messaging-conflict-preflight.test.ts | 6 +++++- 4 files changed, 20 insertions(+), 4 deletions(-) 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/test/credentials/rebuild-credential-preflight.test.ts b/test/credentials/rebuild-credential-preflight.test.ts index ce434a47f40..43c2534ded1 100644 --- a/test/credentials/rebuild-credential-preflight.test.ts +++ b/test/credentials/rebuild-credential-preflight.test.ts @@ -200,7 +200,7 @@ 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); @@ -208,6 +208,10 @@ if (a[0] === "sandbox" && a[1] === "get") { 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); diff --git a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts index f0ee5867405..af17df60837 100644 --- a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts +++ b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts @@ -164,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); diff --git a/test/runtime/messaging/rebuild-messaging-conflict-preflight.test.ts b/test/runtime/messaging/rebuild-messaging-conflict-preflight.test.ts index b4a0f9f4f7d..5fd287377be 100644 --- a/test/runtime/messaging/rebuild-messaging-conflict-preflight.test.ts +++ b/test/runtime/messaging/rebuild-messaging-conflict-preflight.test.ts @@ -178,8 +178,12 @@ 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[0]==="sandbox" && a[1]==="get") { process.stdout.write("Name: " + a.at(-1) + "\\nId: ${SANDBOX_ID}\\nPhase: Ready\\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); From 8015468454df22182201c71fcb40df2dd4f8460f Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 28 Aug 2026 00:16:40 -0700 Subject: [PATCH 39/40] ci: retrigger PR review advisor Signed-off-by: Carlos Villela From 450887fa4b7ac7e9c41da34130bda249531fba73 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 28 Aug 2026 00:20:40 -0700 Subject: [PATCH 40/40] ci: retrigger PR review advisor Signed-off-by: Carlos Villela