From 1a7f0b3156f41e17c7d7af37c0617fd4b25147dc Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Tue, 25 Aug 2026 17:02:32 -0700 Subject: [PATCH 01/11] fix(policy): resolve review advisor findings Signed-off-by: Apurv Kumaria --- ci/source-architecture-budget.json | 4 +- .../checks/openshell-policy-mutation-read.mts | 3 +- src/lib/actions/sandbox/destroy.ts | 100 +++--------- .../openshell/policy-authority.test.ts | 116 +++++++------ .../adapters/openshell/policy-authority.ts | 58 +++---- src/lib/adapters/openshell/runtime.test.ts | 21 +++ src/lib/adapters/openshell/runtime.ts | 9 +- src/lib/policy/README.md | 5 +- src/lib/policy/commands.ts | 11 +- src/lib/policy/index.ts | 3 +- src/lib/shields/destroy-cleanup.ts | 152 ++++++++++++++++++ test/platform/images/image-cleanup.test.ts | 69 ++++++++ .../policy-mutation-read-discovery.test.ts | 24 +-- 13 files changed, 384 insertions(+), 191 deletions(-) create mode 100644 src/lib/shields/destroy-cleanup.ts diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index f7f3a472189..df91c6eb039 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": 20, "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": 39, "src/lib/agent/defs.ts": 33, "src/lib/cli/branding.ts": 87, @@ -38,7 +38,7 @@ "maxByFile": { "src/lib/actions/inference-set.ts": 32, "src/lib/actions/sandbox/connect.ts": 43, - "src/lib/actions/sandbox/destroy.ts": 29, + "src/lib/actions/sandbox/destroy.ts": 28, "src/lib/actions/sandbox/doctor.ts": 29, "src/lib/actions/sandbox/gateway-state.ts": 21, "src/lib/actions/sandbox/status-snapshot.ts": 19, diff --git a/scripts/checks/openshell-policy-mutation-read.mts b/scripts/checks/openshell-policy-mutation-read.mts index 8a9d3bc3337..b2fe5a8e165 100644 --- a/scripts/checks/openshell-policy-mutation-read.mts +++ b/scripts/checks/openshell-policy-mutation-read.mts @@ -124,7 +124,7 @@ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ view: "full", failureHandling: "unclassified", }, - unclassifiedFull("buildPolicyGetFullJsonCommand"), + unclassifiedFull("buildPolicyGetFullJsonArgs"), ], }, ] as const; @@ -138,6 +138,7 @@ export interface DiscoveredPolicyReadSite { const POLICY_GET_BUILDERS = new Map([ ["buildPolicyGetCommand", "base"], ["buildPolicyGetFullCommand", "full"], + ["buildPolicyGetFullJsonArgs", "full"], ["buildPolicyGetFullJsonCommand", "full"], ]); diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 0748dea7987..83512a2c5de 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -35,10 +35,14 @@ import { SANDBOX_PROVIDER_SUFFIXES, } from "../../onboard/sandbox-provider-cleanup"; import { validateName } from "../../runner"; -import { killTimer as defaultKillShieldsTimer } from "../../shields/timer-control"; +import { + cleanupShieldsDestroyArtifacts as cleanupShieldsDestroyArtifactsOwned, + type CleanupShieldsDestroyArtifactsDeps, + removeShieldsState as removeShieldsStateOwned, + type RemoveShieldsStateDeps, +} from "../../shields/destroy-cleanup"; import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock"; import * as onboardSession from "../../state/onboard-session"; -import { resolveNemoclawStateDir } from "../../state/paths"; import * as registry from "../../state/registry"; import { assertSandboxDestroyCommandAvailable, @@ -118,22 +122,6 @@ export type CleanupSandboxServicesDeps = { googlechatWebhookTunnelPidDir?: (servicePidDir: string) => string; }; -type ShieldsTimerNeutralizeResult = { - warnings?: string[]; -}; - -type CleanupShieldsDestroyArtifactsDeps = { - killShieldsTimer?: (sandboxName: string) => ShieldsTimerNeutralizeResult | void; - rmSync?: typeof fs.rmSync; - stateDir?: string; - warn?: (message: string) => void; -}; - -type RemoveShieldsStateDeps = { - rmSync?: typeof fs.rmSync; - warn?: (message: string) => void; -}; - async function resolveCleanupGatewayDecision(options: DestroySandboxOptions): Promise { const decision = resolveDestroyGatewayCleanupDecision(options, { nonInteractive: isNonInteractiveEnv(), @@ -276,52 +264,15 @@ export function cleanupSandboxServices( } } -/** - * Remove host-side Shields state and recovery artifacts for a sandbox. - * - * Without this cleanup, stale state or an external policy handoff from a - * previous sandbox can survive destroy → re-onboard under the same name. - * - * See: https://github.com/NVIDIA/NemoClaw/issues/3114 - */ export function removeShieldsState( sandboxName: string, - stateDir = resolveNemoclawStateDir(), + stateDir?: string, deps: RemoveShieldsStateDeps = {}, ): void { - const rmSync = deps.rmSync ?? fs.rmSync; - const warn = deps.warn ?? ((message: string) => console.warn(` ${YW}⚠${R} ${message}`)); - const resolvedStateDir = path.resolve(stateDir); - const recoveryArtifactName = `shields-external-policy-${sandboxName}.yaml`; - const artifactNames = [ - recoveryArtifactName, - `shields-${sandboxName}.json`, - `shields-timer-${sandboxName}.json`, - ]; - for (const artifactName of artifactNames) { - const filePath = path.resolve(resolvedStateDir, artifactName); - if (!filePath.startsWith(`${resolvedStateDir}${path.sep}`)) { - // Defense-in-depth: sandbox names are validated to [a-z0-9-] at - // all entry points, but reject traversal attempts just in case. - continue; - } - try { - rmSync(filePath, { force: true }); - } catch (error) { - // force: true already suppresses ENOENT. A recovery handoff must not - // become unbound under a reusable sandbox name, so preserve Shields - // state and stop cleanup when that artifact cannot be removed. - if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; - const message = error instanceof Error ? error.message : String(error); - if (artifactName === recoveryArtifactName) { - throw new Error( - `Could not remove external Shields policy recovery artifact '${filePath}': ${message}. Shields state was preserved for retry.`, - { cause: error }, - ); - } - warn(`Failed to remove Shields cleanup artifact '${filePath}': ${message}`); - } - } + removeShieldsStateOwned(sandboxName, stateDir, { + ...deps, + warn: deps.warn ?? defaultDestroyWarn, + }); } /** @@ -415,6 +366,16 @@ function defaultDestroyWarn(message: string): void { console.warn(` ${YW}⚠${R} ${message}`); } +export function cleanupShieldsDestroyArtifacts( + sandboxName: string, + deps: CleanupShieldsDestroyArtifactsDeps = {}, +): void { + cleanupShieldsDestroyArtifactsOwned(sandboxName, { + ...deps, + warn: deps.warn ?? defaultDestroyWarn, + }); +} + export async function revokeDestroyedSandboxHttpsPinRoute( gatewayName: string, routeId: string, @@ -451,25 +412,6 @@ export async function revokeDestroyedSandboxHttpsPinRoute( } } -export function cleanupShieldsDestroyArtifacts( - sandboxName: string, - deps: CleanupShieldsDestroyArtifactsDeps = {}, -): void { - const killShieldsTimer = deps.killShieldsTimer ?? defaultKillShieldsTimer; - const stateDir = deps.stateDir ?? resolveNemoclawStateDir(); - const warn = deps.warn ?? defaultDestroyWarn; - - const timerResult = killShieldsTimer(sandboxName); - for (const warning of timerResult?.warnings ?? []) { - warn(warning); - } - - removeShieldsState(sandboxName, stateDir, { - rmSync: deps.rmSync ?? fs.rmSync, - warn, - }); -} - export type { WipeSandboxStateDeps }; // Re-export so existing callers (tests, downstream code) keep working after // the wipe was extracted out of the destroy monolith (#5455 PRA-2). diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts index 6b7bc59b9db..1a2a15c9601 100644 --- a/src/lib/adapters/openshell/policy-authority.test.ts +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -3,13 +3,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import * as openshellResolveModule from "./resolve"; +import * as openshellRuntimeModule from "./runtime"; import { assertExternalPolicyRequirements, assertRecordedPolicyAuthority, inspectSandboxPolicyAuthority, isExternalPolicyAuthorityRefusalError, - type PolicyAuthorityCapture, policyAuthorityInternals, type SandboxPolicyAuthorityInspection, } from "./policy-authority"; @@ -18,18 +17,23 @@ function captureResult( stdout: string, overrides: Partial<{ stderr: string; - exitCode: number | null; - timedOut: boolean; + status: number | null; + error: Error; }> = {}, ) { return { + status: overrides.status === undefined ? 0 : overrides.status, + output: stdout, stdout, stderr: overrides.stderr ?? "", - exitCode: overrides.exitCode ?? 0, - timedOut: overrides.timedOut ?? false, + ...(overrides.error ? { error: overrides.error } : {}), }; } +function captureError(code: string, message: string): Error { + return Object.assign(new Error(message), { code }); +} + function sandboxMetadata(overrides: Record = {}): Record { return { scope: "sandbox", @@ -54,49 +58,57 @@ function errorFrom(action: () => unknown): Error { describe("OpenShell policy authority inspection", () => { beforeEach(() => { vi.restoreAllMocks(); - vi.spyOn(openshellResolveModule, "resolveOpenshell").mockReturnValue(null); }); afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); }); it("recognizes a sandbox-scoped effective policy as NemoClaw-managed (#9833)", () => { - const runCaptureEx = vi.fn(() => - captureResult(JSON.stringify(sandboxMetadata())), - ); + vi.stubEnv("HOME", "/tmp/policy-authority-home"); + vi.stubEnv("NEMOCLAW_POLICY_CAPTURE_SECRET", "must-not-reach-openshell"); + const captureOpenshell = vi + .spyOn(openshellRuntimeModule, "captureResolvedOpenshell") + .mockReturnValue(captureResult(JSON.stringify(sandboxMetadata()))); - expect(inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx })).toEqual({ + expect(inspectSandboxPolicyAuthority({ sandboxName: "alpha" })).toEqual({ authority: "nemoclaw-managed", effectivePolicy: { version: 1, network_policies: { baseline: { endpoints: ["base.test"] } }, }, }); - expect(runCaptureEx).toHaveBeenCalledWith( - ["openshell", "policy", "get", "--full", "--output", "json", "alpha"], - { + expect(captureOpenshell).toHaveBeenCalledWith( + ["policy", "get", "--full", "--output", "json", "alpha"], + expect.objectContaining({ + ignoreError: true, + includeStreams: true, maxBuffer: policyAuthorityInternals.captureMaxBytes, + replaceEnv: true, timeout: policyAuthorityInternals.captureTimeoutMs, - }, + }), ); + const captureOptions = captureOpenshell.mock.calls[0]?.[1]; + expect(captureOptions?.env).toMatchObject({ HOME: "/tmp/policy-authority-home" }); + expect(captureOptions?.env).not.toHaveProperty("NEMOCLAW_POLICY_CAPTURE_SECRET"); }); 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 }))), - ); + const captureOpenshell = vi + .spyOn(openshellRuntimeModule, "captureResolvedOpenshell") + .mockReturnValue( + 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", + expect(captureOpenshell.mock.calls[0]?.[0]).toEqual([ "policy", "get", "-g", @@ -109,24 +121,23 @@ describe("OpenShell policy authority inspection", () => { }); it("rejects invalid sandbox and gateway identities before querying policy (#9833)", () => { - const runCaptureEx = vi.fn(() => - captureResult(JSON.stringify(sandboxMetadata())), - ); + const captureOpenshell = vi + .spyOn(openshellRuntimeModule, "captureResolvedOpenshell") + .mockReturnValue(captureResult(JSON.stringify(sandboxMetadata()))); - expect(() => inspectSandboxPolicyAuthority({ sandboxName: "--global", runCaptureEx })).toThrow( + expect(() => inspectSandboxPolicyAuthority({ sandboxName: "--global" })).toThrow( /Invalid sandbox name/, ); expect(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha", gatewayName: "invalid gateway", - runCaptureEx, }), ).toThrow(/Invalid gateway name/); - expect(() => - inspectSandboxPolicyAuthority({ sandboxName: "alpha", gatewayName: "", runCaptureEx }), - ).toThrow(/gateway name is required/); - expect(runCaptureEx).not.toHaveBeenCalled(); + expect(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha", gatewayName: "" })).toThrow( + /gateway name is required/, + ); + expect(captureOpenshell).not.toHaveBeenCalled(); }); it.each([ @@ -135,65 +146,66 @@ describe("OpenShell policy authority inspection", () => { ["an unknown source", sandboxMetadata({ policy_source: "unknown" })], ])("rejects sandbox metadata with %s (#9833)", (_caseName, metadata) => { const secret = "captured-policy-secret"; - const runCaptureEx = vi.fn(() => + vi.spyOn(openshellRuntimeModule, "captureResolvedOpenshell").mockReturnValue( captureResult(JSON.stringify({ ...metadata, diagnostic: secret })), ); - const error = errorFrom(() => - inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx }), - ); + const error = errorFrom(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha" })); expect(error.message).toContain("inspection failed"); expect(error.message).not.toContain(secret); }); it.each(["", " \n\t"])("fails closed when sandbox policy output is empty (%j) (#9833)", (raw) => { - const runCaptureEx = vi.fn(() => captureResult(raw)); + vi.spyOn(openshellRuntimeModule, "captureResolvedOpenshell").mockReturnValue( + captureResult(raw), + ); - expect(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx })).toThrow( + expect(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha" })).toThrow( /empty sandbox policy authority metadata/u, ); }); it.each([ - ["a nonzero exit", { exitCode: 7 }], - ["a timeout", { timedOut: true }], + ["a nonzero exit", { status: 7 }], + ["a timeout", { status: null, error: captureError("ETIMEDOUT", "timeout secret") }], + ["a capture error", { status: null, error: captureError("EACCES", "capture secret") }], ["malformed JSON", {}], ])("fails closed without exposing output after %s (#9833)", (_caseName, overrides) => { - const runCaptureEx = vi.fn(() => + vi.spyOn(openshellRuntimeModule, "captureResolvedOpenshell").mockReturnValue( captureResult('{"secret":"captured-stdout-secret"', { ...overrides, stderr: "captured-stderr-secret", }), ); - const error = errorFrom(() => - inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx }), - ); + const error = errorFrom(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha" })); expect(error.message).not.toContain("captured-stdout-secret"); expect(error.message).not.toContain("captured-stderr-secret"); + expect(error.message).not.toMatch(/timeout secret|capture secret/u); }); it("replaces a thrown capture diagnostic instead of exposing command output (#9833)", () => { - const runCaptureEx = vi.fn(() => { + vi.spyOn(openshellRuntimeModule, "captureResolvedOpenshell").mockImplementation(() => { throw new Error("captured-policy-secret"); }); - const error = errorFrom(() => - inspectSandboxPolicyAuthority({ sandboxName: "alpha", runCaptureEx }), - ); + const error = errorFrom(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha" })); 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 }), + const secret = "captured-oversized-secret"; + vi.spyOn(openshellRuntimeModule, "captureResolvedOpenshell").mockReturnValue( + captureResult(secret, { + status: null, + error: captureError("ENOBUFS", secret), + }), ); + + const error = errorFrom(() => inspectSandboxPolicyAuthority({ sandboxName: "alpha" })); expect(error.message).toContain("capture limit"); - expect(error.message).not.toContain(oversized.slice(0, 32)); + expect(error.message).not.toContain(secret); }); }); diff --git a/src/lib/adapters/openshell/policy-authority.ts b/src/lib/adapters/openshell/policy-authority.ts index 0793d4693db..14c8371113f 100644 --- a/src/lib/adapters/openshell/policy-authority.ts +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -7,7 +7,7 @@ import { NAME_ALLOWED_FORMAT, NAME_MAX_LENGTH, } from "../../sandbox-name-contract"; -import { buildPolicyGetFullJsonCommand } from "../../policy/commands"; +import { buildPolicyGetFullJsonArgs } from "../../policy/commands"; import { assertExternalPolicyRequirementContainment, assertMatchingPolicyAuthority, @@ -15,6 +15,7 @@ import { parseSandboxPolicyAuthorityMetadata, type SandboxPolicyAuthorityInspection as CanonicalSandboxPolicyAuthorityInspection, } from "../../policy/merge"; +import * as openshellRuntime from "./runtime"; const POLICY_AUTHORITY_CAPTURE_MAX_BYTES = 1024 * 1024; const POLICY_AUTHORITY_CAPTURE_TIMEOUT_MS = 30_000; @@ -54,22 +55,9 @@ export function isExternalPolicyAuthorityRefusalError(error: unknown): boolean { ); } -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 SandboxPolicyAuthorityInspectionOptions { readonly sandboxName: string; readonly gatewayName?: string; - readonly runCaptureEx: PolicyAuthorityCapture; } function validatePolicyAuthorityName(name: string, label: string): string { @@ -100,58 +88,52 @@ function failInspection(subject: "sandbox" | "global", reason: string): never { } function capturePolicyQuery( - command: readonly string[], - capture: PolicyAuthorityCapture, + args: string[], subject: "sandbox" | "global", queryKind: "machine-readable policy" | "policy history", -): { readonly stdout: string; readonly stderr: string } { - let result: PolicyAuthorityCaptureResult; +): string { + let result: ReturnType; try { - result = capture(command, { + result = openshellRuntime.captureResolvedOpenshell(args, { + env: openshellRuntime.buildOpenShellSubprocessEnv(), + ignoreError: true, + includeStreams: true, maxBuffer: POLICY_AUTHORITY_CAPTURE_MAX_BYTES, + replaceEnv: true, 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 - ) { + const errorCode = (result.error as NodeJS.ErrnoException | undefined)?.code; + if (errorCode === "ENOBUFS") { failInspection(subject, `the ${queryKind} response exceeded the capture limit`); } - if (result.timedOut === true) { + if (errorCode === "ETIMEDOUT") { failInspection(subject, `the ${queryKind} query timed out`); } - if (result.timedOut !== false || result.exitCode !== 0) { + if (result.error) { + failInspection(subject, `the ${queryKind} query could not run`); + } + if (result.status !== 0) { failInspection(subject, `the ${queryKind} query did not complete successfully`); } - return { stdout: result.stdout, stderr }; + return result.stdout ?? ""; } /** 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, + const raw = capturePolicyQuery( + buildPolicyGetFullJsonArgs(validatedSandboxName, validatedGatewayName), "sandbox", "machine-readable policy", ); diff --git a/src/lib/adapters/openshell/runtime.test.ts b/src/lib/adapters/openshell/runtime.test.ts index ad40ae62628..33132abf5c8 100644 --- a/src/lib/adapters/openshell/runtime.test.ts +++ b/src/lib/adapters/openshell/runtime.test.ts @@ -41,6 +41,7 @@ function largeOutputExecutable(name: string): string { } afterEach(() => { + vi.restoreAllMocks(); vi.unstubAllEnvs(); for (const directory of directories.splice(0)) { fs.rmSync(directory, { recursive: true, force: true }); @@ -93,4 +94,24 @@ describe("captureResolvedOpenshell", () => { expect(result.status).toBe(0); expect(result.output).toBe("snapshot"); }); + + it("keeps ignored spawn failures nonfatal and redacted (#9833)", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-runtime-test-")); + directories.push(directory); + const unavailable = path.join(directory, "openshell"); + fs.writeFileSync(unavailable, "not executable", { mode: 0o600 }); + const exit = vi.spyOn(process, "exit").mockImplementation((code) => { + throw new Error(`unexpected exit ${String(code)}`); + }); + const errorLine = vi.spyOn(console, "error").mockImplementation(() => undefined); + + expect(() => + captureResolvedOpenshell([], { + ignoreError: true, + openshellBinary: unavailable, + }), + ).toThrow("OpenShell capture could not run"); + expect(exit).not.toHaveBeenCalled(); + expect(errorLine).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index c6dc0435afb..f8d302b5a7b 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -94,6 +94,7 @@ export function captureResolvedOpenshell(args: CommandArgs, opts: RunnerOptions const openshell = opts.openshellBinary ?? resolveOpenshellBinaryOrNull(); if (!openshell) throw new Error("OpenShell is unavailable"); if (!path.isAbsolute(openshell)) throw new Error("OpenShell executable must be absolute"); + const keepCaptureNonfatal = opts.ignoreError === true; return captureOpenshellCommand(openshell, args, { cwd: ROOT, env: opts.env, @@ -105,8 +106,12 @@ export function captureResolvedOpenshell(args: CommandArgs, opts: RunnerOptions killSignal: opts.killSignal, killProcessTreeOnTimeout: opts.killProcessTreeOnTimeout, maxBuffer: opts.maxBuffer, - errorLine: console.error, - exit: (code: number) => process.exit(code), + errorLine: keepCaptureNonfatal ? () => undefined : console.error, + exit: keepCaptureNonfatal + ? () => { + throw new Error("OpenShell capture could not run"); + } + : (code: number) => process.exit(code), }); } diff --git a/src/lib/policy/README.md b/src/lib/policy/README.md index ee2442ebc6b..11d59a6c951 100644 --- a/src/lib/policy/README.md +++ b/src/lib/policy/README.md @@ -11,9 +11,12 @@ 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. +For a policy-mutation flow, NemoClaw records the first qualified authority before another policy +read or set. NemoClaw refuses the operation when it cannot write that record. +Shields recovery can read live authority without changing the durable recorded authority. + Immediately before each policy set, NemoClaw reads authority again and compares it with the record. NemoClaw refuses the policy set when: diff --git a/src/lib/policy/commands.ts b/src/lib/policy/commands.ts index a042bbecb24..6a260fc4444 100644 --- a/src/lib/policy/commands.ts +++ b/src/lib/policy/commands.ts @@ -46,8 +46,8 @@ function policyGatewayArgs(gatewayName?: string): string[] { } /** Read effective sandbox policy and its authority metadata as JSON. */ -export function buildPolicyGetFullJsonCommand(sandboxName: string, gatewayName?: string): string[] { - return buildOpenshellCommand([ +export function buildPolicyGetFullJsonArgs(sandboxName: string, gatewayName?: string): string[] { + return [ "policy", "get", ...policyGatewayArgs(gatewayName), @@ -55,5 +55,10 @@ export function buildPolicyGetFullJsonCommand(sandboxName: string, gatewayName?: "--output", "json", sandboxName, - ]); + ]; +} + +/** Read effective sandbox policy and its authority metadata as JSON. */ +export function buildPolicyGetFullJsonCommand(sandboxName: string, gatewayName?: string): string[] { + return buildOpenshellCommand(buildPolicyGetFullJsonArgs(sandboxName, gatewayName)); } diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index 7e6165cea31..c25faef6ee7 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -38,7 +38,7 @@ 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, runCaptureEx } from "../runner"; +import { ROOT, run, runCapture } from "../runner"; import { diagnosticPreview, isValidName, NAME_ALLOWED_FORMAT } from "../sandbox-name-contract"; import { redact } from "../security/redact"; import * as registry from "../state/registry"; @@ -636,7 +636,6 @@ function inspectLivePolicyAuthority( const inspection = inspectSandboxPolicyAuthority({ sandboxName, gatewayName, - runCaptureEx, }); return { sandbox, diff --git a/src/lib/shields/destroy-cleanup.ts b/src/lib/shields/destroy-cleanup.ts new file mode 100644 index 00000000000..50c17a0f97d --- /dev/null +++ b/src/lib/shields/destroy-cleanup.ts @@ -0,0 +1,152 @@ +// 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 { openRegularFileNoFollow } from "../adapters/fs/regular-file"; +import { resolveNemoclawStateDir } from "../state/paths"; +import { killTimer, type KillTimerResult } from "./timer-control"; + +export type RemoveShieldsStateDeps = { + rmSync?: typeof fs.rmSync; + warn?: (message: string) => void; +}; + +export type CleanupShieldsDestroyArtifactsDeps = RemoveShieldsStateDeps & { + killShieldsTimer?: ( + sandboxName: string, + ) => Pick; + stateDir?: string; +}; + +function defaultCleanupWarn(message: string): void { + console.warn(` ⚠ ${message}`); +} + +// Match the maximum size accepted by the owning Shields policy-artifact boundary. +const MAX_SHIELDS_CLEANUP_SNAPSHOT_BYTES = 16 * 1024 * 1024; + +function readShieldsCleanupSnapshot(filePath: string): Buffer | undefined { + let artifact: ReturnType | undefined; + try { + artifact = openRegularFileNoFollow(filePath); + return artifact.readBytes(MAX_SHIELDS_CLEANUP_SNAPSHOT_BYTES); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + const message = error instanceof Error ? error.message : String(error); + throw new Error( + `Could not read Shields cleanup artifact '${filePath}' before removal: ${message}. Shields state was preserved for retry.`, + { cause: error }, + ); + } finally { + artifact?.close(); + } +} + +function restoreShieldsCleanupSnapshot(filePath: string, snapshot: Buffer | undefined): void { + if (snapshot === undefined) return; + fs.writeFileSync(filePath, snapshot, { flag: "wx", mode: 0o600 }); +} + +function removeShieldsRecoveryStatePair( + recoveryArtifactPath: string, + stateRecordPath: string, + rmSync: typeof fs.rmSync, +): void { + const recoverySnapshot = readShieldsCleanupSnapshot(recoveryArtifactPath); + try { + rmSync(recoveryArtifactPath, { force: true }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error( + `Could not remove external Shields policy recovery artifact '${recoveryArtifactPath}': ${message}. Shields state was preserved for retry.`, + { cause: error }, + ); + } + + try { + rmSync(stateRecordPath, { force: true }); + } catch (error) { + let rollbackError: unknown; + try { + restoreShieldsCleanupSnapshot(recoveryArtifactPath, recoverySnapshot); + } catch (error) { + rollbackError = error; + } + const message = error instanceof Error ? error.message : String(error); + const rollbackStatus = + rollbackError === undefined + ? "Shields cleanup artifacts were restored or retained for retry." + : `Shields cleanup rollback was incomplete: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}.`; + throw new Error( + `Could not remove Shields state record '${stateRecordPath}': ${message}. ${rollbackStatus}`, + { cause: error }, + ); + } +} + +/** + * Remove host-side Shields state and recovery artifacts for a sandbox. + * + * Without this cleanup, stale state or an external policy handoff from a + * previous sandbox can survive destroy → re-onboard under the same name. + * + * See: https://github.com/NVIDIA/NemoClaw/issues/3114 + */ +export function removeShieldsState( + sandboxName: string, + stateDir = resolveNemoclawStateDir(), + deps: RemoveShieldsStateDeps = {}, +): void { + const rmSync = deps.rmSync ?? fs.rmSync; + const warn = deps.warn ?? defaultCleanupWarn; + const resolvedStateDir = path.resolve(stateDir); + const filePaths = [ + `shields-external-policy-${sandboxName}.yaml`, + `shields-${sandboxName}.json`, + `shields-timer-${sandboxName}.json`, + ].map((artifactName) => path.resolve(resolvedStateDir, artifactName)); + if (filePaths.some((filePath) => !filePath.startsWith(`${resolvedStateDir}${path.sep}`))) { + // Defense-in-depth: sandbox names are validated to [a-z0-9-] at all + // entry points, but reject traversal attempts just in case. + return; + } + const [recoveryArtifactPath, stateRecordPath, timerMarkerPath] = filePaths as [ + string, + string, + string, + ]; + removeShieldsRecoveryStatePair(recoveryArtifactPath, stateRecordPath, rmSync); + try { + rmSync(timerMarkerPath, { force: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + const message = error instanceof Error ? error.message : String(error); + warn(`Failed to remove Shields cleanup artifact '${timerMarkerPath}': ${message}`); + } +} + +/** Revoke timer authority before retiring Shields destroy-cleanup state. */ +export function cleanupShieldsDestroyArtifacts( + sandboxName: string, + deps: CleanupShieldsDestroyArtifactsDeps = {}, +): void { + const killShieldsTimer = deps.killShieldsTimer ?? killTimer; + const warn = deps.warn ?? defaultCleanupWarn; + + const timerResult = killShieldsTimer(sandboxName); + for (const warning of timerResult.warnings) { + warn(warning); + } + if (!timerResult.authorityRevoked) { + throw new Error( + `Could not revoke Shields timer authority for sandbox '${sandboxName}'. Shields cleanup artifacts were preserved for retry.`, + ); + } + + removeShieldsState(sandboxName, deps.stateDir ?? resolveNemoclawStateDir(), { + rmSync: deps.rmSync ?? fs.rmSync, + warn, + }); +} diff --git a/test/platform/images/image-cleanup.test.ts b/test/platform/images/image-cleanup.test.ts index aa64651e8a9..79cfd59330b 100644 --- a/test/platform/images/image-cleanup.test.ts +++ b/test/platform/images/image-cleanup.test.ts @@ -318,6 +318,7 @@ describe("image cleanup: sandbox destroy removes Docker image (#2086)", () => { killShieldsTimer: (sandboxName) => { killCalls.push(sandboxName); return { + authorityRevoked: true, warnings: [], }; }, @@ -334,6 +335,73 @@ describe("image cleanup: sandbox destroy removes Docker image (#2086)", () => { fs.rmSync(stateDir, { recursive: true, force: true }); }); + it("destroy preserves all Shields artifacts when timer authority revocation fails (#9833)", () => { + const warnings: string[] = []; + const rmSync = vi.fn(); + + expect(() => + cleanupShieldsDestroyArtifacts("alpha", { + stateDir: "/tmp/nonexistent-state-dir", + rmSync: rmSync as unknown as typeof fs.rmSync, + killShieldsTimer: () => ({ + authorityRevoked: false, + warnings: ["Failed to remove the Shields timer marker"], + }), + warn: (message) => warnings.push(message), + }), + ).toThrow( + "Could not revoke Shields timer authority for sandbox 'alpha'. Shields cleanup artifacts were preserved for retry.", + ); + + expect(warnings).toEqual(["Failed to remove the Shields timer marker"]); + expect(rmSync).not.toHaveBeenCalled(); + }); + + it("destroy restores the recovery artifact when Shields state removal fails (#9833)", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "destroy-shields-rollback-")); + const recoveryPath = path.join(stateDir, "shields-external-policy-alpha.yaml"); + const statePath = path.join(stateDir, "shields-alpha.json"); + const timerPath = path.join(stateDir, "shields-timer-alpha.json"); + const recoveryContent = "version: 1\nnetwork_policies: {}\n"; + const stateContent = '{"shieldsDown":true}'; + fs.writeFileSync(recoveryPath, recoveryContent, { mode: 0o600 }); + fs.writeFileSync(statePath, stateContent, { mode: 0o600 }); + fs.writeFileSync(timerPath, '{"pid":9999}', { mode: 0o600 }); + const rmSync = vi.fn((...args: Parameters) => { + const [artifactPath] = args; + switch (path.basename(String(artifactPath))) { + case "shields-alpha.json": { + const error = new Error("permission denied") as NodeJS.ErrnoException; + error.code = "EACCES"; + throw error; + } + default: + fs.rmSync(...args); + } + }); + + try { + expect(() => + cleanupShieldsDestroyArtifacts("alpha", { + stateDir, + rmSync: rmSync as unknown as typeof fs.rmSync, + killShieldsTimer: () => ({ authorityRevoked: true, warnings: [] }), + }), + ).toThrow( + `Could not remove Shields state record '${statePath}': permission denied. Shields cleanup artifacts were restored or retained for retry.`, + ); + + expect(fs.readFileSync(recoveryPath, "utf8")).toBe(recoveryContent); + expect(fs.readFileSync(statePath, "utf8")).toBe(stateContent); + expect(fs.existsSync(timerPath)).toBe(true); + expect( + rmSync.mock.calls.map(([artifactPath]) => path.basename(String(artifactPath))), + ).toEqual(["shields-external-policy-alpha.yaml", "shields-alpha.json"]); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } + }); + it("destroy preserves Shields state when external recovery cleanup fails (#9833)", () => { const warnings: string[] = []; const rmSync = vi.fn((artifactPath: string) => { @@ -349,6 +417,7 @@ describe("image cleanup: sandbox destroy removes Docker image (#2086)", () => { stateDir: "/tmp/nonexistent-state-dir", rmSync: rmSync as unknown as typeof fs.rmSync, killShieldsTimer: () => ({ + authorityRevoked: true, warnings: ["Failed to terminate Shields timer PID 4242"], }), warn: (message) => warnings.push(message), diff --git a/test/runtime/policy/policy-mutation-read-discovery.test.ts b/test/runtime/policy/policy-mutation-read-discovery.test.ts index d09cd1ec54a..f4f95959830 100644 --- a/test/runtime/policy/policy-mutation-read-discovery.test.ts +++ b/test/runtime/policy/policy-mutation-read-discovery.test.ts @@ -51,7 +51,7 @@ function shieldsAuditSource( describe("OpenShell policy mutation read discovery (#6921)", () => { it("counts canonical builder bindings and direct argv reads", () => { const source = [ - 'import { buildPolicyGetCommand as buildBase } from "./policy/commands";', + 'import { buildPolicyGetCommand as buildBase, buildPolicyGetFullJsonArgs as buildFullJsonArgs } from "./policy/commands";', 'import * as policyBuilders from "./policy/index";', 'const { buildPolicyGetFullCommand: buildFull } = require("./policy");', 'const requiredPolicyBuilders = require("./policy");', @@ -62,13 +62,14 @@ describe("OpenShell policy mutation read discovery (#6921)", () => { 'policyBuilders["buildPolicyGetFullCommand"](sandboxName);', "buildFull(sandboxName);", "requiredPolicyBuilders.buildPolicyGetCommand(sandboxName);", + "buildFullJsonArgs(sandboxName);", '["openshell", "policy", "get", "--base", sandboxName];', '["policy", "get", "--full", sandboxName];', 'const arrayDecoy = `["policy", "get", "--base", sandboxName]`;', '["not-openshell", "policy", "get", "--base", sandboxName];', ].join("\n"); - expect(countPolicyReadCalls(source, "/repo/src/lib/fixture.ts", "/repo")).toBe(7); + expect(countPolicyReadCalls(source, "/repo/src/lib/fixture.ts", "/repo")).toBe(8); }); it("classifies gateway-pinned direct policy reads", () => { @@ -81,15 +82,16 @@ describe("OpenShell policy mutation read discovery (#6921)", () => { "}", ].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", - }, - ]); + 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("ignores direct policy reads with ambiguous view flags (#9833)", () => { From 55a2b1b0127f3a9d0b6a5d6d6194c3beb03826e8 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Tue, 25 Aug 2026 18:18:36 -0700 Subject: [PATCH 02/11] fix(policy): complete review advisor follow-up Signed-off-by: Apurv Kumaria --- ci/source-architecture-budget.json | 2 +- src/lib/actions/sandbox/destroy.ts | 31 +-- .../snapshot-auto-create-failure.test.ts | 8 +- .../sandbox/snapshot-restore-test-fixture.ts | 5 +- src/lib/actions/sandbox/snapshot.ts | 2 +- .../policy/policy-mutation-authority.test.ts | 70 ++++++ src/lib/shields/destroy-cleanup.test.ts | 220 ++++++++++++++++++ test/helpers/destroy-flow-test-harness.ts | 2 +- test/platform/images/image-cleanup.test.ts | 211 ----------------- 9 files changed, 307 insertions(+), 244 deletions(-) create mode 100644 src/lib/shields/destroy-cleanup.test.ts diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index df91c6eb039..7396f913772 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -45,7 +45,7 @@ "src/lib/actions/sandbox/policy-channel.ts": 30, "src/lib/actions/sandbox/process-recovery.ts": 21, "src/lib/actions/sandbox/rebuild-pipeline.ts": 29, - "src/lib/actions/sandbox/snapshot.ts": 40, + "src/lib/actions/sandbox/snapshot.ts": 41, "src/lib/actions/uninstall/run-plan.ts": 25, "src/lib/inference/local.ts": 22, "src/lib/inference/onboard-probes.ts": 21, diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 83512a2c5de..df7f0374e8a 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -35,12 +35,7 @@ import { SANDBOX_PROVIDER_SUFFIXES, } from "../../onboard/sandbox-provider-cleanup"; import { validateName } from "../../runner"; -import { - cleanupShieldsDestroyArtifacts as cleanupShieldsDestroyArtifactsOwned, - type CleanupShieldsDestroyArtifactsDeps, - removeShieldsState as removeShieldsStateOwned, - type RemoveShieldsStateDeps, -} from "../../shields/destroy-cleanup"; +import { cleanupShieldsDestroyArtifacts } from "../../shields/destroy-cleanup"; import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock"; import * as onboardSession from "../../state/onboard-session"; import * as registry from "../../state/registry"; @@ -264,17 +259,6 @@ export function cleanupSandboxServices( } } -export function removeShieldsState( - sandboxName: string, - stateDir?: string, - deps: RemoveShieldsStateDeps = {}, -): void { - removeShieldsStateOwned(sandboxName, stateDir, { - ...deps, - warn: deps.warn ?? defaultDestroyWarn, - }); -} - /** * Remove only a provider-owned per-sandbox workload image. Shared managed * cohorts and ambiguous ownership are never deleted. @@ -366,16 +350,6 @@ function defaultDestroyWarn(message: string): void { console.warn(` ${YW}⚠${R} ${message}`); } -export function cleanupShieldsDestroyArtifacts( - sandboxName: string, - deps: CleanupShieldsDestroyArtifactsDeps = {}, -): void { - cleanupShieldsDestroyArtifactsOwned(sandboxName, { - ...deps, - warn: deps.warn ?? defaultDestroyWarn, - }); -} - export async function revokeDestroyedSandboxHttpsPinRoute( gatewayName: string, routeId: string, @@ -568,7 +542,8 @@ async function destroySandboxUnlocked( let destructiveResult: Awaited>; try { destructiveResult = await executeSandboxDestroy({ - cleanupShieldsArtifacts: cleanupShieldsDestroyArtifacts, + cleanupShieldsArtifacts: (name) => + cleanupShieldsDestroyArtifacts(name, { warn: defaultDestroyWarn }), force: normalized.force === true, getSandbox: registry.getSandbox, listSandboxes: registry.listSandboxes, diff --git a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts index cedcf0fb240..002d7c8cc1b 100644 --- a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts +++ b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts @@ -57,6 +57,7 @@ const reserveSandboxInferenceRouteMock = vi.fn((name: string, route: Record(async () => ({ status: 7, output: "create failed before registry write", @@ -241,8 +242,10 @@ vi.mock("../../state/sandbox", () => ({ listBackups: vi.fn(() => []), restoreSandboxState: restoreSandboxStateMock, })); +vi.mock("../../shields/destroy-cleanup", () => ({ + cleanupShieldsDestroyArtifacts: cleanupShieldsDestroyArtifactsMock, +})); vi.mock("./destroy", () => ({ - cleanupShieldsDestroyArtifacts: vi.fn(), removeSandboxRegistryEntryOutcome: removeSandboxRegistryEntryOutcomeMock, requireSandboxDestructiveCleanupAuthority: vi.fn(() => ({ provider: runtimeProvider })), })); @@ -418,6 +421,9 @@ describe("snapshot restore auto-create failures", () => { expect(nimRuntime.stopNimContainer).not.toHaveBeenCalled(); expect(nimRuntime.stopNimContainerByName).not.toHaveBeenCalled(); expect(removeSandboxRegistryEntryOutcomeMock).toHaveBeenCalledWith("beta"); + expect(cleanupShieldsDestroyArtifactsMock.mock.invocationCallOrder[0]).toBeLessThan( + removeSandboxRegistryEntryOutcomeMock.mock.invocationCallOrder[0]!, + ); expect(getSandboxMock("beta")).toBeNull(); expect(consoleError.mock.calls.flat().join("\n")).toContain("injected live route failure"); expect(restoreSandboxStateMock).not.toHaveBeenCalled(); diff --git a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts index afa5c6cb4ca..4903d733bed 100644 --- a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts +++ b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts @@ -351,12 +351,15 @@ vi.mock("../../state/sandbox", () => ({ restoreSandboxState: restoreSandboxStateMock, })); +vi.mock("../../shields/destroy-cleanup", () => ({ + cleanupShieldsDestroyArtifacts: lifecycleMock.cleanupShieldsDestroyArtifactsMock, +})); + vi.mock("./destroy", async () => { const runtimeProviders = await vi.importActual< typeof import("../../onboard/runtime-provider/access") >("../../onboard/runtime-provider/access"); return { - cleanupShieldsDestroyArtifacts: lifecycleMock.cleanupShieldsDestroyArtifactsMock, removeSandboxRegistryEntry: vi.fn(() => true), removeSandboxRegistryEntryOutcome: removeSandboxRegistryEntryOutcomeMock, requireSandboxDestructiveCleanupAuthority: (sandboxName: string, sandbox: SandboxRecord) => diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 4f780f920ef..35fd77c6089 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -52,6 +52,7 @@ import { ROOT, run, shellQuote, validateName } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; import { streamSandboxCreate } from "../../sandbox/create-stream"; import * as shields from "../../shields"; +import { cleanupShieldsDestroyArtifacts } from "../../shields/destroy-cleanup"; import { withTimerBoundShieldsMutationLock } from "../../shields/timer-bound-lock"; import { readTimerMarker } from "../../shields/timer-control"; import { isSandboxReady } from "../../state/gateway"; @@ -67,7 +68,6 @@ import { parseDcodeProbeState, } from "./dcode-activity-probe"; import { - cleanupShieldsDestroyArtifacts, removeSandboxRegistryEntryOutcome, requireSandboxDestructiveCleanupAuthority, } from "./destroy"; diff --git a/src/lib/policy/policy-mutation-authority.test.ts b/src/lib/policy/policy-mutation-authority.test.ts index 276d3fe7692..2d0eb8fae7c 100644 --- a/src/lib/policy/policy-mutation-authority.test.ts +++ b/src/lib/policy/policy-mutation-authority.test.ts @@ -46,8 +46,10 @@ vi.mock("../state/registry", async (importOriginal) => ({ import { applyPermissivePolicy, applyPresetContent, + applyPresets, excludeBaselineEntry, inspectPolicyRecoveryAuthority, + loadPresetForSandbox, removePreset, restoreBaselineEntry, } from "./index"; @@ -77,6 +79,12 @@ network_policies: `; const WEATHER_POLICY = YAML.parse(WEATHER_PRESET).network_policies.weather; +function loadBuiltInWeatherPolicy(): Record { + const preset = loadPresetForSandbox(SANDBOX, "weather"); + expect(preset).not.toBeNull(); + return YAML.parse(preset!).network_policies.weather as Record; +} + function reportedErrors(): string { return vi .mocked(console.error) @@ -135,6 +143,68 @@ describe("PolicyMutationAuthority", () => { }); }); + it("accepts complete external requirements through applyPresets without local mutation or attribution (#9833)", () => { + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { network_policies: { weather: loadBuiltInWeatherPolicy() } }, + }); + + expect(applyPresets(SANDBOX, ["weather"])).toBe(true); + + expect(mocks.runCapture).not.toHaveBeenCalled(); + expect(mocks.run).not.toHaveBeenCalled(); + expect(mocks.updateSandbox).toHaveBeenCalledOnce(); + expect(mocks.updateSandbox).toHaveBeenCalledWith(SANDBOX, { + policyAuthority: "externally-managed", + }); + expect(sandbox).toEqual( + expect.objectContaining({ policyAuthority: "externally-managed", policies: [] }), + ); + expect(console.log).not.toHaveBeenCalledWith(" Applied preset: weather"); + }); + + it.each([ + { + caseName: "missing", + expectedDiagnostic: 'missing entries "weather"', + networkPolicies: {}, + }, + { + caseName: "changed", + expectedDiagnostic: 'drifted entries "weather"', + networkPolicies: null, + }, + ])( + "refuses $caseName external requirements through applyPresets without local mutation or attribution (#9833)", + ({ expectedDiagnostic, networkPolicies }) => { + const effectiveNetworkPolicies = + networkPolicies ?? { + weather: { ...loadBuiltInWeatherPolicy(), name: "changed-weather" }, + }; + mocks.inspectSandboxPolicyAuthority.mockReturnValue({ + authority: "externally-managed", + effectivePolicy: { network_policies: effectiveNetworkPolicies }, + }); + + expect(applyPresets(SANDBOX, ["weather"])).toBe(false); + + expect(reportedErrors()).toContain("external policy authority"); + expect(reportedErrors()).toContain(expectedDiagnostic); + 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(mocks.updateSandbox).toHaveBeenCalledWith(SANDBOX, { + policyAuthority: "externally-managed", + }); + expect(sandbox).toEqual( + expect.objectContaining({ policyAuthority: "externally-managed", policies: [] }), + ); + expect(console.log).not.toHaveBeenCalledWith(" Applied preset: weather"); + }, + ); + it("records external authority before refusing a missing preset requirement (#9833)", () => { mocks.inspectSandboxPolicyAuthority.mockReturnValue({ authority: "externally-managed", diff --git a/src/lib/shields/destroy-cleanup.test.ts b/src/lib/shields/destroy-cleanup.test.ts new file mode 100644 index 00000000000..c899c22e2e6 --- /dev/null +++ b/src/lib/shields/destroy-cleanup.test.ts @@ -0,0 +1,220 @@ +// 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, vi } from "vitest"; + +import { resolveNemoclawStateDir } from "../state/paths"; +import { cleanupShieldsDestroyArtifacts, removeShieldsState } from "./destroy-cleanup"; + +describe("Shields destroy cleanup", () => { + it("destroy neutralizes active shields timer and only deletes target sandbox files", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "destroy-shields-")); + const alphaRecovery = path.join(stateDir, "shields-external-policy-alpha.yaml"); + const alphaState = path.join(stateDir, "shields-alpha.json"); + const alphaTimer = path.join(stateDir, "shields-timer-alpha.json"); + const betaRecovery = path.join(stateDir, "shields-external-policy-beta.yaml"); + const betaState = path.join(stateDir, "shields-beta.json"); + const betaTimer = path.join(stateDir, "shields-timer-beta.json"); + + fs.writeFileSync(alphaRecovery, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync(alphaState, '{"shieldsDown":true}'); + fs.writeFileSync(alphaTimer, '{"pid":9999}'); + fs.writeFileSync(betaRecovery, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync(betaState, '{"shieldsDown":true}'); + fs.writeFileSync(betaTimer, '{"pid":9999}'); + + const killCalls: string[] = []; + cleanupShieldsDestroyArtifacts("alpha", { + stateDir, + killShieldsTimer: (sandboxName) => { + killCalls.push(sandboxName); + return { + authorityRevoked: true, + warnings: [], + }; + }, + }); + + expect(killCalls).toEqual(["alpha"]); + expect(fs.existsSync(alphaRecovery)).toBe(false); + expect(fs.existsSync(alphaState)).toBe(false); + expect(fs.existsSync(alphaTimer)).toBe(false); + expect(fs.existsSync(betaRecovery)).toBe(true); + expect(fs.existsSync(betaState)).toBe(true); + expect(fs.existsSync(betaTimer)).toBe(true); + + fs.rmSync(stateDir, { recursive: true, force: true }); + }); + + it("destroy preserves all Shields artifacts when timer authority revocation fails (#9833)", () => { + const warnings: string[] = []; + const rmSync = vi.fn(); + + expect(() => + cleanupShieldsDestroyArtifacts("alpha", { + stateDir: "/tmp/nonexistent-state-dir", + rmSync: rmSync as unknown as typeof fs.rmSync, + killShieldsTimer: () => ({ + authorityRevoked: false, + warnings: ["Failed to remove the Shields timer marker"], + }), + warn: (message) => warnings.push(message), + }), + ).toThrow( + "Could not revoke Shields timer authority for sandbox 'alpha'. Shields cleanup artifacts were preserved for retry.", + ); + + expect(warnings).toEqual(["Failed to remove the Shields timer marker"]); + expect(rmSync).not.toHaveBeenCalled(); + }); + + it("destroy restores the recovery artifact when Shields state removal fails (#9833)", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "destroy-shields-rollback-")); + const recoveryPath = path.join(stateDir, "shields-external-policy-alpha.yaml"); + const statePath = path.join(stateDir, "shields-alpha.json"); + const timerPath = path.join(stateDir, "shields-timer-alpha.json"); + const recoveryContent = "version: 1\nnetwork_policies: {}\n"; + const stateContent = '{"shieldsDown":true}'; + fs.writeFileSync(recoveryPath, recoveryContent, { mode: 0o600 }); + fs.writeFileSync(statePath, stateContent, { mode: 0o600 }); + fs.writeFileSync(timerPath, '{"pid":9999}', { mode: 0o600 }); + const rmSync = vi.fn((...args: Parameters) => { + const [artifactPath] = args; + switch (path.basename(String(artifactPath))) { + case "shields-alpha.json": { + const error = new Error("permission denied") as NodeJS.ErrnoException; + error.code = "EACCES"; + throw error; + } + default: + fs.rmSync(...args); + } + }); + + try { + expect(() => + cleanupShieldsDestroyArtifacts("alpha", { + stateDir, + rmSync: rmSync as unknown as typeof fs.rmSync, + killShieldsTimer: () => ({ authorityRevoked: true, warnings: [] }), + }), + ).toThrow( + `Could not remove Shields state record '${statePath}': permission denied. Shields cleanup artifacts were restored or retained for retry.`, + ); + + expect(fs.readFileSync(recoveryPath, "utf8")).toBe(recoveryContent); + expect(fs.readFileSync(statePath, "utf8")).toBe(stateContent); + expect(fs.existsSync(timerPath)).toBe(true); + expect( + rmSync.mock.calls.map(([artifactPath]) => path.basename(String(artifactPath))), + ).toEqual(["shields-external-policy-alpha.yaml", "shields-alpha.json"]); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } + }); + + it("destroy preserves Shields state when external recovery cleanup fails (#9833)", () => { + const warnings: string[] = []; + const rmSync = vi.fn((artifactPath: string) => { + switch (path.basename(artifactPath)) { + case "shields-external-policy-alpha.yaml": { + const error = new Error("permission denied") as NodeJS.ErrnoException; + error.code = "EACCES"; + throw error; + } + } + }); + + expect(() => + cleanupShieldsDestroyArtifacts("alpha", { + stateDir: "/tmp/nonexistent-state-dir", + rmSync: rmSync as unknown as typeof fs.rmSync, + killShieldsTimer: () => ({ + authorityRevoked: true, + warnings: ["Failed to terminate Shields timer PID 4242"], + }), + warn: (message) => warnings.push(message), + }), + ).toThrow( + "Could not remove external Shields policy recovery artifact '/tmp/nonexistent-state-dir/shields-external-policy-alpha.yaml': permission denied. Shields state was preserved for retry.", + ); + + expect(warnings).toEqual(["Failed to terminate Shields timer PID 4242"]); + expect(rmSync).toHaveBeenCalledOnce(); + expect(rmSync.mock.calls[0][0]).toContain("shields-external-policy-alpha.yaml"); + }); + + it("state-dir helper resolves ~/.nemoclaw/state from a single shared helper", () => { + const resolved = resolveNemoclawStateDir("/tmp/example-home"); + expect(resolved).toBe(path.join("/tmp/example-home", ".nemoclaw", "state")); + }); +}); + +describe("shields state cleanup on destroy (#3114)", () => { + it("removes Shields state, timer, and external recovery files for the sandbox", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); + try { + const shieldsFile = path.join(tmpDir, "shields-alpha.json"); + const timerFile = path.join(tmpDir, "shields-timer-alpha.json"); + const recoveryFile = path.join(tmpDir, "shields-external-policy-alpha.yaml"); + fs.writeFileSync(shieldsFile, JSON.stringify({ shieldsDown: false })); + fs.writeFileSync(timerFile, JSON.stringify({ pid: 12345 })); + fs.writeFileSync(recoveryFile, "version: 1\nnetwork_policies: {}\n"); + + removeShieldsState("alpha", tmpDir); + + expect(fs.existsSync(shieldsFile)).toBe(false); + expect(fs.existsSync(timerFile)).toBe(false); + expect(fs.existsSync(recoveryFile)).toBe(false); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("is a no-op when no shields state files exist", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); + try { + // Must not throw + removeShieldsState("nonexistent", tmpDir); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("does not remove state files for other sandboxes", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); + try { + const otherFile = path.join(tmpDir, "shields-bravo.json"); + const otherRecoveryFile = path.join(tmpDir, "shields-external-policy-bravo.yaml"); + fs.writeFileSync(otherFile, JSON.stringify({ shieldsDown: false })); + fs.writeFileSync(otherRecoveryFile, "version: 1\nnetwork_policies: {}\n"); + + removeShieldsState("alpha", tmpDir); + + expect(fs.existsSync(otherFile)).toBe(true); + expect(fs.existsSync(otherRecoveryFile)).toBe(true); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("rejects path traversal in sandbox name", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); + const escapedFile = path.join(tmpDir, "..", "shields-traversal.json"); + try { + fs.writeFileSync(escapedFile, "should survive"); + + // A name containing ../ should not delete files outside stateDir + removeShieldsState("../../../../shields-traversal", tmpDir); + + expect(fs.existsSync(escapedFile)).toBe(true); + } finally { + fs.rmSync(escapedFile, { force: true }); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); +}); diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index ec7a3676a5f..ce586afd78d 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -549,7 +549,7 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr }); const killTimerSpy = vi.spyOn(timerControl, "killTimer").mockImplementation(() => { events.push("timer-cleanup"); - return { warnings: [] }; + return { authorityRevoked: true, warnings: [] }; }); const preparedServers = options.mcpAddState === "prepared" ? [] : (options.mcpServers ?? []); const mcpPreparation = { diff --git a/test/platform/images/image-cleanup.test.ts b/test/platform/images/image-cleanup.test.ts index 79cfd59330b..b38f376e063 100644 --- a/test/platform/images/image-cleanup.test.ts +++ b/test/platform/images/image-cleanup.test.ts @@ -4,18 +4,13 @@ // Verify that sandbox lifecycle operations clean up host-side Docker images. // See: https://github.com/NVIDIA/NemoClaw/issues/2086 -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import { help as renderRootHelp } from "../../../src/lib/actions/root-help"; import { - cleanupShieldsDestroyArtifacts, removeSandboxImage, removeSandboxRegistryEntry, removeSandboxRegistryEntryOutcome, removeSandboxRegistryEntryWithReceipt, - removeShieldsState, requireSandboxDestructiveCleanupAuthority, } from "../../../src/lib/actions/sandbox/destroy"; import { requireSnapshotDestinationRegistryRemoval } from "../../../src/lib/actions/sandbox/snapshot"; @@ -25,7 +20,6 @@ import { normalizeGarbageCollectImagesOptions } from "../../../src/lib/domain/li import { getSandboxDeleteOutcome } from "../../../src/lib/domain/sandbox/destroy"; import { createDockerRuntimeProviderBundle } from "../../../src/lib/onboard/runtime-provider/docker"; import { createRuntimeProviderBundleRegistry } from "../../../src/lib/onboard/runtime-provider/registry"; -import { resolveNemoclawStateDir } from "../../../src/lib/state/paths"; describe("image cleanup: sandbox destroy removes Docker image (#2086)", () => { it("removes sandbox images before deleting the registry entry", () => { @@ -295,211 +289,6 @@ describe("image cleanup: sandbox destroy removes Docker image (#2086)", () => { gatewayUnreachable: false, }); }); - - it("destroy neutralizes active shields timer and only deletes target sandbox files", () => { - const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "destroy-shields-")); - const alphaRecovery = path.join(stateDir, "shields-external-policy-alpha.yaml"); - const alphaState = path.join(stateDir, "shields-alpha.json"); - const alphaTimer = path.join(stateDir, "shields-timer-alpha.json"); - const betaRecovery = path.join(stateDir, "shields-external-policy-beta.yaml"); - const betaState = path.join(stateDir, "shields-beta.json"); - const betaTimer = path.join(stateDir, "shields-timer-beta.json"); - - fs.writeFileSync(alphaRecovery, "version: 1\nnetwork_policies: {}\n"); - fs.writeFileSync(alphaState, '{"shieldsDown":true}'); - fs.writeFileSync(alphaTimer, '{"pid":9999}'); - fs.writeFileSync(betaRecovery, "version: 1\nnetwork_policies: {}\n"); - fs.writeFileSync(betaState, '{"shieldsDown":true}'); - fs.writeFileSync(betaTimer, '{"pid":9999}'); - - const killCalls: string[] = []; - cleanupShieldsDestroyArtifacts("alpha", { - stateDir, - killShieldsTimer: (sandboxName) => { - killCalls.push(sandboxName); - return { - authorityRevoked: true, - warnings: [], - }; - }, - }); - - expect(killCalls).toEqual(["alpha"]); - expect(fs.existsSync(alphaRecovery)).toBe(false); - expect(fs.existsSync(alphaState)).toBe(false); - expect(fs.existsSync(alphaTimer)).toBe(false); - expect(fs.existsSync(betaRecovery)).toBe(true); - expect(fs.existsSync(betaState)).toBe(true); - expect(fs.existsSync(betaTimer)).toBe(true); - - fs.rmSync(stateDir, { recursive: true, force: true }); - }); - - it("destroy preserves all Shields artifacts when timer authority revocation fails (#9833)", () => { - const warnings: string[] = []; - const rmSync = vi.fn(); - - expect(() => - cleanupShieldsDestroyArtifacts("alpha", { - stateDir: "/tmp/nonexistent-state-dir", - rmSync: rmSync as unknown as typeof fs.rmSync, - killShieldsTimer: () => ({ - authorityRevoked: false, - warnings: ["Failed to remove the Shields timer marker"], - }), - warn: (message) => warnings.push(message), - }), - ).toThrow( - "Could not revoke Shields timer authority for sandbox 'alpha'. Shields cleanup artifacts were preserved for retry.", - ); - - expect(warnings).toEqual(["Failed to remove the Shields timer marker"]); - expect(rmSync).not.toHaveBeenCalled(); - }); - - it("destroy restores the recovery artifact when Shields state removal fails (#9833)", () => { - const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "destroy-shields-rollback-")); - const recoveryPath = path.join(stateDir, "shields-external-policy-alpha.yaml"); - const statePath = path.join(stateDir, "shields-alpha.json"); - const timerPath = path.join(stateDir, "shields-timer-alpha.json"); - const recoveryContent = "version: 1\nnetwork_policies: {}\n"; - const stateContent = '{"shieldsDown":true}'; - fs.writeFileSync(recoveryPath, recoveryContent, { mode: 0o600 }); - fs.writeFileSync(statePath, stateContent, { mode: 0o600 }); - fs.writeFileSync(timerPath, '{"pid":9999}', { mode: 0o600 }); - const rmSync = vi.fn((...args: Parameters) => { - const [artifactPath] = args; - switch (path.basename(String(artifactPath))) { - case "shields-alpha.json": { - const error = new Error("permission denied") as NodeJS.ErrnoException; - error.code = "EACCES"; - throw error; - } - default: - fs.rmSync(...args); - } - }); - - try { - expect(() => - cleanupShieldsDestroyArtifacts("alpha", { - stateDir, - rmSync: rmSync as unknown as typeof fs.rmSync, - killShieldsTimer: () => ({ authorityRevoked: true, warnings: [] }), - }), - ).toThrow( - `Could not remove Shields state record '${statePath}': permission denied. Shields cleanup artifacts were restored or retained for retry.`, - ); - - expect(fs.readFileSync(recoveryPath, "utf8")).toBe(recoveryContent); - expect(fs.readFileSync(statePath, "utf8")).toBe(stateContent); - expect(fs.existsSync(timerPath)).toBe(true); - expect( - rmSync.mock.calls.map(([artifactPath]) => path.basename(String(artifactPath))), - ).toEqual(["shields-external-policy-alpha.yaml", "shields-alpha.json"]); - } finally { - fs.rmSync(stateDir, { recursive: true, force: true }); - } - }); - - it("destroy preserves Shields state when external recovery cleanup fails (#9833)", () => { - const warnings: string[] = []; - const rmSync = vi.fn((artifactPath: string) => { - if (artifactPath.endsWith("shields-external-policy-alpha.yaml")) { - const error = new Error("permission denied") as NodeJS.ErrnoException; - error.code = "EACCES"; - throw error; - } - }); - - expect(() => - cleanupShieldsDestroyArtifacts("alpha", { - stateDir: "/tmp/nonexistent-state-dir", - rmSync: rmSync as unknown as typeof fs.rmSync, - killShieldsTimer: () => ({ - authorityRevoked: true, - warnings: ["Failed to terminate Shields timer PID 4242"], - }), - warn: (message) => warnings.push(message), - }), - ).toThrow( - "Could not remove external Shields policy recovery artifact '/tmp/nonexistent-state-dir/shields-external-policy-alpha.yaml': permission denied. Shields state was preserved for retry.", - ); - - expect(warnings).toEqual(["Failed to terminate Shields timer PID 4242"]); - expect(rmSync).toHaveBeenCalledOnce(); - expect(rmSync.mock.calls[0][0]).toContain("shields-external-policy-alpha.yaml"); - }); - - it("state-dir helper resolves ~/.nemoclaw/state from a single shared helper", () => { - const resolved = resolveNemoclawStateDir("/tmp/example-home"); - expect(resolved).toBe(path.join("/tmp/example-home", ".nemoclaw", "state")); - }); -}); - -describe("shields state cleanup on destroy (#3114)", () => { - it("removes Shields state, timer, and external recovery files for the sandbox", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - try { - const shieldsFile = path.join(tmpDir, "shields-alpha.json"); - const timerFile = path.join(tmpDir, "shields-timer-alpha.json"); - const recoveryFile = path.join(tmpDir, "shields-external-policy-alpha.yaml"); - fs.writeFileSync(shieldsFile, JSON.stringify({ shieldsDown: false })); - fs.writeFileSync(timerFile, JSON.stringify({ pid: 12345 })); - fs.writeFileSync(recoveryFile, "version: 1\nnetwork_policies: {}\n"); - - removeShieldsState("alpha", tmpDir); - - expect(fs.existsSync(shieldsFile)).toBe(false); - expect(fs.existsSync(timerFile)).toBe(false); - expect(fs.existsSync(recoveryFile)).toBe(false); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - - it("is a no-op when no shields state files exist", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - try { - // Must not throw - removeShieldsState("nonexistent", tmpDir); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - - it("does not remove state files for other sandboxes", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - try { - const otherFile = path.join(tmpDir, "shields-bravo.json"); - const otherRecoveryFile = path.join(tmpDir, "shields-external-policy-bravo.yaml"); - fs.writeFileSync(otherFile, JSON.stringify({ shieldsDown: false })); - fs.writeFileSync(otherRecoveryFile, "version: 1\nnetwork_policies: {}\n"); - - removeShieldsState("alpha", tmpDir); - - expect(fs.existsSync(otherFile)).toBe(true); - expect(fs.existsSync(otherRecoveryFile)).toBe(true); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - - it("rejects path traversal in sandbox name", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - const escapedFile = path.join(tmpDir, "..", "shields-traversal.json"); - try { - fs.writeFileSync(escapedFile, "should survive"); - - // A name containing ../ should not delete files outside stateDir - removeShieldsState("../../../../shields-traversal", tmpDir); - - expect(fs.existsSync(escapedFile)).toBe(true); - } finally { - fs.rmSync(escapedFile, { force: true }); - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); }); describe("image cleanup: gc command exists (#2086)", () => { From 403cb657f2c8c2fc2487c3a3df56d1b38bef9ecb Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Tue, 25 Aug 2026 18:47:14 -0700 Subject: [PATCH 03/11] fix(shields): keep cleanup behind lifecycle gate Signed-off-by: Apurv Kumaria --- src/lib/shields/destroy-cleanup.test.ts | 51 ++++++++++++++++++++----- src/lib/shields/destroy-cleanup.ts | 4 +- 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/src/lib/shields/destroy-cleanup.test.ts b/src/lib/shields/destroy-cleanup.test.ts index c899c22e2e6..2aa3d88f2f5 100644 --- a/src/lib/shields/destroy-cleanup.test.ts +++ b/src/lib/shields/destroy-cleanup.test.ts @@ -8,7 +8,7 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import { resolveNemoclawStateDir } from "../state/paths"; -import { cleanupShieldsDestroyArtifacts, removeShieldsState } from "./destroy-cleanup"; +import { cleanupShieldsDestroyArtifacts } from "./destroy-cleanup"; describe("Shields destroy cleanup", () => { it("destroy neutralizes active shields timer and only deletes target sandbox files", () => { @@ -27,19 +27,28 @@ describe("Shields destroy cleanup", () => { fs.writeFileSync(betaState, '{"shieldsDown":true}'); fs.writeFileSync(betaTimer, '{"pid":9999}'); - const killCalls: string[] = []; + const cleanupCalls: string[] = []; cleanupShieldsDestroyArtifacts("alpha", { stateDir, killShieldsTimer: (sandboxName) => { - killCalls.push(sandboxName); + cleanupCalls.push(`revoke:${sandboxName}`); return { authorityRevoked: true, warnings: [], }; }, + rmSync: ((...args: Parameters) => { + cleanupCalls.push(`remove:${path.basename(String(args[0]))}`); + fs.rmSync(...args); + }) as typeof fs.rmSync, }); - expect(killCalls).toEqual(["alpha"]); + expect(cleanupCalls).toEqual([ + "revoke:alpha", + "remove:shields-external-policy-alpha.yaml", + "remove:shields-alpha.json", + "remove:shields-timer-alpha.json", + ]); expect(fs.existsSync(alphaRecovery)).toBe(false); expect(fs.existsSync(alphaState)).toBe(false); expect(fs.existsSync(alphaTimer)).toBe(false); @@ -165,7 +174,10 @@ describe("shields state cleanup on destroy (#3114)", () => { fs.writeFileSync(timerFile, JSON.stringify({ pid: 12345 })); fs.writeFileSync(recoveryFile, "version: 1\nnetwork_policies: {}\n"); - removeShieldsState("alpha", tmpDir); + cleanupShieldsDestroyArtifacts("alpha", { + stateDir: tmpDir, + killShieldsTimer: () => ({ authorityRevoked: true, warnings: [] }), + }); expect(fs.existsSync(shieldsFile)).toBe(false); expect(fs.existsSync(timerFile)).toBe(false); @@ -175,11 +187,19 @@ describe("shields state cleanup on destroy (#3114)", () => { } }); - it("is a no-op when no shields state files exist", () => { + it("tolerates missing Shields artifacts after revoking timer authority", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); try { - // Must not throw - removeShieldsState("nonexistent", tmpDir); + const killShieldsTimer = vi.fn(() => ({ authorityRevoked: true, warnings: [] })); + + expect(() => + cleanupShieldsDestroyArtifacts("nonexistent", { + stateDir: tmpDir, + killShieldsTimer, + }), + ).not.toThrow(); + + expect(killShieldsTimer).toHaveBeenCalledWith("nonexistent"); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); } @@ -193,7 +213,10 @@ describe("shields state cleanup on destroy (#3114)", () => { fs.writeFileSync(otherFile, JSON.stringify({ shieldsDown: false })); fs.writeFileSync(otherRecoveryFile, "version: 1\nnetwork_policies: {}\n"); - removeShieldsState("alpha", tmpDir); + cleanupShieldsDestroyArtifacts("alpha", { + stateDir: tmpDir, + killShieldsTimer: () => ({ authorityRevoked: true, warnings: [] }), + }); expect(fs.existsSync(otherFile)).toBe(true); expect(fs.existsSync(otherRecoveryFile)).toBe(true); @@ -205,12 +228,20 @@ describe("shields state cleanup on destroy (#3114)", () => { it("rejects path traversal in sandbox name", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); const escapedFile = path.join(tmpDir, "..", "shields-traversal.json"); + const killShieldsTimer = vi.fn(() => ({ authorityRevoked: true, warnings: [] })); + const rmSync = vi.fn(); try { fs.writeFileSync(escapedFile, "should survive"); // A name containing ../ should not delete files outside stateDir - removeShieldsState("../../../../shields-traversal", tmpDir); + cleanupShieldsDestroyArtifacts("../../../../shields-traversal", { + stateDir: tmpDir, + killShieldsTimer, + rmSync: rmSync as unknown as typeof fs.rmSync, + }); + expect(killShieldsTimer).toHaveBeenCalledWith("../../../../shields-traversal"); + expect(rmSync).not.toHaveBeenCalled(); expect(fs.existsSync(escapedFile)).toBe(true); } finally { fs.rmSync(escapedFile, { force: true }); diff --git a/src/lib/shields/destroy-cleanup.ts b/src/lib/shields/destroy-cleanup.ts index 50c17a0f97d..9fadfc31017 100644 --- a/src/lib/shields/destroy-cleanup.ts +++ b/src/lib/shields/destroy-cleanup.ts @@ -8,7 +8,7 @@ import { openRegularFileNoFollow } from "../adapters/fs/regular-file"; import { resolveNemoclawStateDir } from "../state/paths"; import { killTimer, type KillTimerResult } from "./timer-control"; -export type RemoveShieldsStateDeps = { +type RemoveShieldsStateDeps = { rmSync?: typeof fs.rmSync; warn?: (message: string) => void; }; @@ -94,7 +94,7 @@ function removeShieldsRecoveryStatePair( * * See: https://github.com/NVIDIA/NemoClaw/issues/3114 */ -export function removeShieldsState( +function removeShieldsState( sandboxName: string, stateDir = resolveNemoclawStateDir(), deps: RemoveShieldsStateDeps = {}, From 9981455dd82276935fe3604a2fd290c4e1f9e8f8 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Tue, 25 Aug 2026 19:26:58 -0700 Subject: [PATCH 04/11] fix(policy): enforce advisor ownership boundaries Signed-off-by: Apurv Kumaria --- scripts/checks/layer-import-boundaries.mts | 13 ++ .../checks/openshell-policy-mutation-read.mts | 1 - .../openshell/policy-authority.test.ts | 97 --------------- .../adapters/openshell/policy-authority.ts | 65 ++-------- src/lib/policy/commands.ts | 18 --- src/lib/policy/index.ts | 21 ++-- src/lib/policy/policy-authority.test.ts | 114 ++++++++++++++++++ src/lib/policy/policy-authority.ts | 72 +++++++++++ src/lib/shields/destroy-cleanup.test.ts | 43 ------- .../layer-import-boundaries.test.ts | 17 +++ 10 files changed, 236 insertions(+), 225 deletions(-) create mode 100644 src/lib/policy/policy-authority.test.ts create mode 100644 src/lib/policy/policy-authority.ts diff --git a/scripts/checks/layer-import-boundaries.mts b/scripts/checks/layer-import-boundaries.mts index b1d65379d65..25dabb9c9a3 100644 --- a/scripts/checks/layer-import-boundaries.mts +++ b/scripts/checks/layer-import-boundaries.mts @@ -254,6 +254,19 @@ function checkActionFile(absPath: string, repoPath: string, violations: Violatio function checkAdapterFile(absPath: string, repoPath: string, violations: Violation[]): void { for (const ref of collectImportRefs(absPath)) { + if (repoPath.startsWith("src/lib/adapters/openshell/")) { + const policyTarget = importTargetsForbiddenLayer(absPath, ref, ["src/lib/policy/"]); + if (policyTarget) { + addViolation( + violations, + repoPath, + ref.line, + ref.column, + "openshell-adapters-no-policy", + `OpenShell adapters must not import policy module ${policyTarget}`, + ); + } + } const target = importTargetsForbiddenLayer(absPath, ref, ["src/commands/"], true); if (target) { addViolation( diff --git a/scripts/checks/openshell-policy-mutation-read.mts b/scripts/checks/openshell-policy-mutation-read.mts index b2fe5a8e165..6e983662188 100644 --- a/scripts/checks/openshell-policy-mutation-read.mts +++ b/scripts/checks/openshell-policy-mutation-read.mts @@ -124,7 +124,6 @@ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ view: "full", failureHandling: "unclassified", }, - unclassifiedFull("buildPolicyGetFullJsonArgs"), ], }, ] as const; diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts index 1a2a15c9601..17b815a9a1a 100644 --- a/src/lib/adapters/openshell/policy-authority.test.ts +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -5,12 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as openshellRuntimeModule from "./runtime"; import { - assertExternalPolicyRequirements, - assertRecordedPolicyAuthority, inspectSandboxPolicyAuthority, - isExternalPolicyAuthorityRefusalError, policyAuthorityInternals, - type SandboxPolicyAuthorityInspection, } from "./policy-authority"; function captureResult( @@ -208,96 +204,3 @@ describe("OpenShell policy authority inspection", () => { expect(error.message).not.toContain(secret); }); }); - -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/); - }); - - 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", () => { - 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 index 14c8371113f..75f43f5068a 100644 --- a/src/lib/adapters/openshell/policy-authority.ts +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -7,14 +7,11 @@ import { NAME_ALLOWED_FORMAT, NAME_MAX_LENGTH, } from "../../sandbox-name-contract"; -import { buildPolicyGetFullJsonArgs } from "../../policy/commands"; import { - assertExternalPolicyRequirementContainment, - assertMatchingPolicyAuthority, type OpenShellPolicyAuthority, parseSandboxPolicyAuthorityMetadata, type SandboxPolicyAuthorityInspection as CanonicalSandboxPolicyAuthorityInspection, -} from "../../policy/merge"; +} from "../../../../nemoclaw/dist/shared/openshell-policy-boundary.cjs"; import * as openshellRuntime from "./runtime"; const POLICY_AUTHORITY_CAPTURE_MAX_BYTES = 1024 * 1024; const POLICY_AUTHORITY_CAPTURE_TIMEOUT_MS = 30_000; @@ -133,7 +130,15 @@ export function inspectSandboxPolicyAuthority({ ? undefined : validatePolicyAuthorityName(gatewayName, "gateway name"); const raw = capturePolicyQuery( - buildPolicyGetFullJsonArgs(validatedSandboxName, validatedGatewayName), + [ + "policy", + "get", + ...(validatedGatewayName ? ["-g", validatedGatewayName] : []), + "--full", + "--output", + "json", + validatedSandboxName, + ], "sandbox", "machine-readable policy", ); @@ -147,56 +152,6 @@ export function inspectSandboxPolicyAuthority({ } } -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); - try { - assertMatchingPolicyAuthority(recorded, observed); - } catch (error) { - const detail = error instanceof Error ? error.message : "policy authority is invalid"; - const observedAuthority = - observed === "nemoclaw-managed" || observed === "externally-managed" ? observed : undefined; - throw new PolicyAuthorityRefusalError(`Refusing to ${label}: ${detail}.`, observedAuthority); - } -} - -/** - * 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, - operation, - sandboxName, -}: { - readonly inspection: SandboxPolicyAuthorityInspection; - readonly requiredPolicy: JsonObject; - readonly operation: string; - readonly sandboxName?: string; -}): void { - const label = operationLabel(operation); - 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}${target}: ${detail}. 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/commands.ts b/src/lib/policy/commands.ts index 6a260fc4444..876131381dd 100644 --- a/src/lib/policy/commands.ts +++ b/src/lib/policy/commands.ts @@ -44,21 +44,3 @@ export function buildPolicyGetFullCommand(sandboxName: string, gatewayName?: str function policyGatewayArgs(gatewayName?: string): string[] { return gatewayName ? ["-g", gatewayName] : []; } - -/** Read effective sandbox policy and its authority metadata as JSON. */ -export function buildPolicyGetFullJsonArgs(sandboxName: string, gatewayName?: string): string[] { - return [ - "policy", - "get", - ...policyGatewayArgs(gatewayName), - "--full", - "--output", - "json", - sandboxName, - ]; -} - -/** Read effective sandbox policy and its authority metadata as JSON. */ -export function buildPolicyGetFullJsonCommand(sandboxName: string, gatewayName?: string): string[] { - return buildOpenshellCommand(buildPolicyGetFullJsonArgs(sandboxName, gatewayName)); -} diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index c25faef6ee7..fdbe78d6b92 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -11,17 +11,6 @@ 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"; @@ -76,6 +65,16 @@ import { type PolicyValue, parseNetworkPolicies, } from "./preset-parsing"; +import { + assertExternalPolicyRequirements, + assertRecordedPolicyAuthority, + inspectSandboxPolicyAuthority, + isExternalPolicyAuthorityRefusalError as isExternalAuthorityRefusalError, + isPolicyAuthorityRefusalError as isAuthorityRefusalError, + PolicyAuthorityRefusalError, + type SandboxPolicyAuthority, + type SandboxPolicyAuthorityInspection, +} from "./policy-authority"; import { escapeTerminalText, logPresetScope, renderPresetScope } from "./preset-scope-render"; import { parseAndValidateSandboxPolicy } from "./sandbox-policy-validation"; import { splitSemanticFindings, validatePolicySemantics } from "./semantic-validation"; diff --git a/src/lib/policy/policy-authority.test.ts b/src/lib/policy/policy-authority.test.ts new file mode 100644 index 00000000000..b211bc485c7 --- /dev/null +++ b/src/lib/policy/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 } from "vitest"; + +import { + assertExternalPolicyRequirements, + assertRecordedPolicyAuthority, + isExternalPolicyAuthorityRefusalError, + type SandboxPolicyAuthorityInspection, +} from "./policy-authority"; + +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("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/); + }); + + 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", () => { + 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/policy/policy-authority.ts b/src/lib/policy/policy-authority.ts new file mode 100644 index 00000000000..31534ba105d --- /dev/null +++ b/src/lib/policy/policy-authority.ts @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + inspectSandboxPolicyAuthority, + isExternalPolicyAuthorityRefusalError, + isPolicyAuthorityRefusalError, + PolicyAuthorityRefusalError, + type SandboxPolicyAuthority, + type SandboxPolicyAuthorityInspection, +} from "../adapters/openshell/policy-authority"; +import { assertExternalPolicyRequirementContainment, assertMatchingPolicyAuthority } from "./merge"; + +type JsonObject = Record; + +export { + inspectSandboxPolicyAuthority, + isExternalPolicyAuthorityRefusalError, + isPolicyAuthorityRefusalError, + PolicyAuthorityRefusalError, +}; +export type { SandboxPolicyAuthority, SandboxPolicyAuthorityInspection }; + +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); + try { + assertMatchingPolicyAuthority(recorded, observed); + } catch (error) { + const detail = error instanceof Error ? error.message : "policy authority is invalid"; + const observedAuthority = + observed === "nemoclaw-managed" || observed === "externally-managed" ? observed : undefined; + throw new PolicyAuthorityRefusalError(`Refusing to ${label}: ${detail}.`, observedAuthority); + } +} + +/** + * 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, + operation, + sandboxName, +}: { + readonly inspection: SandboxPolicyAuthorityInspection; + readonly requiredPolicy: JsonObject; + readonly operation: string; + readonly sandboxName?: string; +}): void { + const label = operationLabel(operation); + 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}${target}: ${detail}. Ask the external policy authority to supply the exact required entries.`, + ); + } +} diff --git a/src/lib/shields/destroy-cleanup.test.ts b/src/lib/shields/destroy-cleanup.test.ts index 2aa3d88f2f5..33c8fa8f935 100644 --- a/src/lib/shields/destroy-cleanup.test.ts +++ b/src/lib/shields/destroy-cleanup.test.ts @@ -164,29 +164,6 @@ describe("Shields destroy cleanup", () => { }); describe("shields state cleanup on destroy (#3114)", () => { - it("removes Shields state, timer, and external recovery files for the sandbox", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - try { - const shieldsFile = path.join(tmpDir, "shields-alpha.json"); - const timerFile = path.join(tmpDir, "shields-timer-alpha.json"); - const recoveryFile = path.join(tmpDir, "shields-external-policy-alpha.yaml"); - fs.writeFileSync(shieldsFile, JSON.stringify({ shieldsDown: false })); - fs.writeFileSync(timerFile, JSON.stringify({ pid: 12345 })); - fs.writeFileSync(recoveryFile, "version: 1\nnetwork_policies: {}\n"); - - cleanupShieldsDestroyArtifacts("alpha", { - stateDir: tmpDir, - killShieldsTimer: () => ({ authorityRevoked: true, warnings: [] }), - }); - - expect(fs.existsSync(shieldsFile)).toBe(false); - expect(fs.existsSync(timerFile)).toBe(false); - expect(fs.existsSync(recoveryFile)).toBe(false); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - it("tolerates missing Shields artifacts after revoking timer authority", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); try { @@ -205,26 +182,6 @@ describe("shields state cleanup on destroy (#3114)", () => { } }); - it("does not remove state files for other sandboxes", () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); - try { - const otherFile = path.join(tmpDir, "shields-bravo.json"); - const otherRecoveryFile = path.join(tmpDir, "shields-external-policy-bravo.yaml"); - fs.writeFileSync(otherFile, JSON.stringify({ shieldsDown: false })); - fs.writeFileSync(otherRecoveryFile, "version: 1\nnetwork_policies: {}\n"); - - cleanupShieldsDestroyArtifacts("alpha", { - stateDir: tmpDir, - killShieldsTimer: () => ({ authorityRevoked: true, warnings: [] }), - }); - - expect(fs.existsSync(otherFile)).toBe(true); - expect(fs.existsSync(otherRecoveryFile)).toBe(true); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - it("rejects path traversal in sandbox name", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-cleanup-")); const escapedFile = path.join(tmpDir, "..", "shields-traversal.json"); diff --git a/test/repository/layer-import-boundaries.test.ts b/test/repository/layer-import-boundaries.test.ts index 81ef79800d9..ec552b95408 100644 --- a/test/repository/layer-import-boundaries.test.ts +++ b/test/repository/layer-import-boundaries.test.ts @@ -73,6 +73,23 @@ describe("CLI layer import boundaries (#6245)", () => { ); }); + it("keeps OpenShell adapters independent from policy modules (#9833)", () => { + const violations = scanFixture( + fixturePath("src/lib/adapters/openshell", "policy"), + 'import { buildPolicyGetCommand } from "../../policy/commands";\nexport { buildPolicyGetCommand };\n', + ); + + expect(violations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + detail: + "OpenShell adapters must not import policy module src/lib/policy/commands.ts", + rule: "openshell-adapters-no-policy", + }), + ]), + ); + }); + it("blocks bare fs imports in messaging manifests (#6245)", () => { const violations = scanFixture( fixturePath("src/lib/messaging/manifest", "bare-fs"), From 863527cffd86d26b089fb858309aa62cafe9dde3 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Tue, 25 Aug 2026 21:08:20 -0700 Subject: [PATCH 05/11] test(onboard): repair canonical authority fixtures Signed-off-by: Apurv Kumaria --- test/helpers/managed-image-buildless-e2e.ts | 17 ----------------- test/helpers/onboard-script-mocks.cjs | 17 ++++++++++++++++- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/test/helpers/managed-image-buildless-e2e.ts b/test/helpers/managed-image-buildless-e2e.ts index 8f570c35025..372aee323fd 100644 --- a/test/helpers/managed-image-buildless-e2e.ts +++ b/test/helpers/managed-image-buildless-e2e.ts @@ -479,23 +479,6 @@ runner.runCapture = (command) => { .mockOnboardRunCapture(command); return mocked === null ? "" : mocked; }; -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 ? { name: sandboxName, diff --git a/test/helpers/onboard-script-mocks.cjs b/test/helpers/onboard-script-mocks.cjs index a725fa666fa..06e571c9054 100644 --- a/test/helpers/onboard-script-mocks.cjs +++ b/test/helpers/onboard-script-mocks.cjs @@ -344,13 +344,28 @@ function mockStructuredOpenShellCaptureFromRunner() { path.resolve(__dirname, "../../src/lib/adapters/openshell/client.ts"), ); client.captureOpenshellCommand = (binary, args, options = {}) => { - const stdout = String( + let stdout = String( runner.runCapture([binary, ...args], { ...options, ignoreError: true, includeStderr: false, }) || "", ); + if ( + args[0] === "policy" && + args[1] === "get" && + !args.includes("--global") && + stdout.trim().length === 0 + ) { + const sandboxName = String(args.at(-1) || "unknown"); + stdout = JSON.stringify({ + scope: "sandbox", + sandbox: sandboxName, + status: "effective", + policy_source: "sandbox", + policy: {}, + }); + } const isSandboxGet = args[0] === "sandbox" && args[1] === "get"; if (isSandboxGet && stdout.trim().length === 0) { const sandboxName = String(args.at(-1) || "unknown"); From b6d6d4e8cfe3e862b41cee14f5772c971a31b639 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Wed, 26 Aug 2026 04:40:22 -0700 Subject: [PATCH 06/11] fix(snapshot): preserve service cleanup state on restore Signed-off-by: Apurv Kumaria --- ci/source-architecture-budget.json | 4 +- .../snapshot-auto-create-failure.test.ts | 49 ++++++++++++++++++- .../sandbox/snapshot-restore-test-fixture.ts | 5 ++ src/lib/actions/sandbox/snapshot.ts | 38 +++----------- .../destroy-cleanup-sandbox-services.test.ts | 2 +- 5 files changed, 63 insertions(+), 35 deletions(-) diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 2399df877d1..4aa70a88257 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -22,7 +22,7 @@ "src/lib/credentials/store.ts": 46, "src/lib/inference/config.ts": 30, "src/lib/inference/web-search.ts": 21, - "src/lib/messaging/channels/index.ts": 25, + "src/lib/messaging/channels/index.ts": 24, "src/lib/onboard/gateway-binding.ts": 52, "src/lib/runner.ts": 86, "src/lib/security/redact.ts": 54, @@ -45,7 +45,7 @@ "src/lib/actions/sandbox/policy-channel.ts": 30, "src/lib/actions/sandbox/process-recovery.ts": 21, "src/lib/actions/sandbox/rebuild-pipeline.ts": 29, - "src/lib/actions/sandbox/snapshot.ts": 41, + "src/lib/actions/sandbox/snapshot.ts": 40, "src/lib/actions/uninstall/run-plan.ts": 25, "src/lib/inference/local.ts": 22, "src/lib/inference/onboard-probes.ts": 21, diff --git a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts index 002d7c8cc1b..55678cdf9bd 100644 --- a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts +++ b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts @@ -26,6 +26,7 @@ const captureOpenshellMock = vi.fn(() => ({ status: 0, output: "alpha Ready\nbeta Ready\nId: beta-runtime-id\n", })); +const parseLiveSandboxNamesMock = vi.fn(() => new Set(["alpha"])); const getSandboxMock = vi.fn((name?: string) => harness.entries.get(name ?? "") ?? null); const registerSandboxMock = vi.fn( ( @@ -57,6 +58,7 @@ const reserveSandboxInferenceRouteMock = vi.fn((name: string, route: Record(async () => ({ status: 7, @@ -191,7 +193,7 @@ vi.mock("../../runner", () => ({ validateName: vi.fn((value: string) => value), })); vi.mock("../../runtime-recovery", () => ({ - parseLiveSandboxNames: vi.fn(() => new Set(["alpha"])), + parseLiveSandboxNames: parseLiveSandboxNamesMock, })); vi.mock("../../sandbox/create-stream", () => ({ streamSandboxCreate: streamSandboxCreateMock })); vi.mock("../../shields", () => ({ @@ -246,6 +248,7 @@ vi.mock("../../shields/destroy-cleanup", () => ({ cleanupShieldsDestroyArtifacts: cleanupShieldsDestroyArtifactsMock, })); vi.mock("./destroy", () => ({ + cleanupSandboxServices: cleanupSandboxServicesMock, removeSandboxRegistryEntryOutcome: removeSandboxRegistryEntryOutcomeMock, requireSandboxDestructiveCleanupAuthority: vi.fn(() => ({ provider: runtimeProvider })), })); @@ -268,6 +271,8 @@ describe("snapshot restore auto-create failures", () => { vi.clearAllMocks(); harness.entries.clear(); harness.entries.set("alpha", sourceEntry()); + cleanupSandboxServicesMock.mockImplementation(() => undefined); + parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha"])); streamSandboxCreateMock.mockResolvedValue({ status: 7, output: "create failed before registry write", @@ -420,7 +425,11 @@ describe("snapshot restore auto-create failures", () => { const nimRuntime = await import("../../inference/nim"); expect(nimRuntime.stopNimContainer).not.toHaveBeenCalled(); expect(nimRuntime.stopNimContainerByName).not.toHaveBeenCalled(); + expect(cleanupSandboxServicesMock).toHaveBeenCalledWith("beta"); expect(removeSandboxRegistryEntryOutcomeMock).toHaveBeenCalledWith("beta"); + expect(cleanupSandboxServicesMock.mock.invocationCallOrder[0]).toBeLessThan( + cleanupShieldsDestroyArtifactsMock.mock.invocationCallOrder[0]!, + ); expect(cleanupShieldsDestroyArtifactsMock.mock.invocationCallOrder[0]).toBeLessThan( removeSandboxRegistryEntryOutcomeMock.mock.invocationCallOrder[0]!, ); @@ -428,4 +437,42 @@ describe("snapshot restore auto-create failures", () => { expect(consoleError.mock.calls.flat().join("\n")).toContain("injected live route failure"); expect(restoreSandboxStateMock).not.toHaveBeenCalled(); }); + + it("preserves cleanup state when the Google Chat tunnel cannot stop (#9833)", async () => { + const destination = { + name: "beta", + openshellDriver: "docker", + provider: "vllm-local", + model: "model-b", + endpointUrl: "https://inference.local/v1", + lifecycleGeneration: "beta-generation-1", + }; + harness.entries.set("beta", destination); + parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha", "beta"])); + cleanupSandboxServicesMock.mockImplementationOnce(() => { + throw new Error("Refusing to finish sandbox cleanup while its Google Chat tunnel remains"); + }); + vi.spyOn(console, "log").mockImplementation(() => {}); + const { getLatestBackup } = await import("../../state/sandbox"); + vi.mocked(getLatestBackup).mockReturnValue({ + timestamp: "2026-06-15T00:00:00.000Z", + backupPath: "/tmp/backup-alpha", + } as ReturnType); + const { runSandboxSnapshot } = await import("./snapshot"); + + await expect( + runSandboxSnapshot("alpha", { + kind: "restore", + to: "beta", + force: true, + yes: true, + }), + ).rejects.toThrow("Refusing to finish sandbox cleanup"); + + expect(cleanupSandboxServicesMock).toHaveBeenCalledWith("beta"); + expect(cleanupShieldsDestroyArtifactsMock).not.toHaveBeenCalled(); + expect(removeSandboxRegistryEntryOutcomeMock).not.toHaveBeenCalled(); + expect(harness.entries.get("beta")).toBe(destination); + expect(streamSandboxCreateMock).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts index f9fd53a2f1d..aa7be19cc30 100644 --- a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts +++ b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts @@ -141,6 +141,7 @@ const lifecycleMock = vi.hoisted(() => { const events: string[] = []; return { events, + cleanupSandboxServicesMock: vi.fn(() => events.push("cleanup-services")), cleanupShieldsDestroyArtifactsMock: vi.fn(() => events.push("cleanup-shields")), readTimerMarkerMock: vi.fn(() => null as Record | null), withTimerBoundMock: vi.fn( @@ -362,6 +363,7 @@ vi.mock("./destroy", async () => { typeof import("../../onboard/runtime-provider/access") >("../../onboard/runtime-provider/access"); return { + cleanupSandboxServices: lifecycleMock.cleanupSandboxServicesMock, removeSandboxRegistryEntry: vi.fn(() => true), removeSandboxRegistryEntryOutcome: removeSandboxRegistryEntryOutcomeMock, requireSandboxDestructiveCleanupAuthority: (sandboxName: string, sandbox: SandboxRecord) => @@ -390,6 +392,9 @@ export function resetSnapshotRestoreMocks(): void { shieldsMock.isShieldsDownMock.mockReturnValue(true); shieldsMock.shieldsUpMock.mockImplementation(() => lifecycleMock.events.push("harden")); lifecycleMock.events.length = 0; + lifecycleMock.cleanupSandboxServicesMock + .mockReset() + .mockImplementation(() => lifecycleMock.events.push("cleanup-services")); lifecycleMock.readTimerMarkerMock.mockReturnValue(null); captureOpenshellMock.mockImplementation((args) => defaultOpenshellResponses(args)); dockerInspectMock.mockReturnValue({ status: 0, stdout: "true\n" }); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 06c57df9d18..aab83491093 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -27,7 +27,6 @@ import { } from "../../inference/gateway-route-compatibility"; import { withGatewayRouteMutationLock } from "../../inference/gateway-route-mutation-lock"; import * as nim from "../../inference/nim"; -import { listMessagingProviderSuffixes } from "../../messaging/channels"; import { findAvailableDashboardPort, getRegistryOccupiedDashboardPorts, @@ -68,6 +67,7 @@ import { parseDcodeProbeState, } from "./dcode-activity-probe"; import { + cleanupSandboxServices, removeSandboxRegistryEntryOutcome, requireSandboxDestructiveCleanupAuthority, } from "./destroy"; @@ -654,16 +654,11 @@ async function autoCreateSandboxFromSource( // Delete an existing destination sandbox so `snapshot restore --to --force` // can recreate it from the source's image. Stops the destination's NIM // container, runs `openshell sandbox delete`, performs the destination-only -// cleanups that `sandboxDestroy` does (PID dir, per-sandbox messaging -// providers, shields state), then drops the NemoClaw registry entry. Throws -// SnapshotCommandError on failure so the caller does not proceed into a -// partially-deleted target. -// -// Host-shared cleanups that destroy.ts performs \u2014 Ollama auth proxy -// (`killStaleProxy`), host services (`cleanupSandboxServices` with -// `stopHostServices`), Ollama model unload, gateway teardown \u2014 are -// deliberately skipped here because they can also affect the source sandbox -// we are about to clone from. +// per-sandbox service, provider, and Shields cleanup that `sandboxDestroy` +// owns, then drops the NemoClaw registry entry. Shared host services and +// gateway teardown stay running because they can also serve the source sandbox +// we are about to clone from. Throws SnapshotCommandError on failure so the +// caller does not proceed into a partially-deleted target. function deleteSandboxForRestore(name: string): void { withTimerBoundShieldsMutationLock(name, "delete snapshot restore destination", () => { const sbMeta = registry.getSandbox(name); @@ -737,26 +732,7 @@ function deleteSandboxForRestore(name: string): void { snapshotExit(1); } } - // Destination-only cleanup so the recreated sandbox does not inherit stale - // host-side state or hit provider-name conflicts (Codex #3796 P2): - // - /tmp/nemoclaw-services-: PID dir for this sandbox's services - // - OpenShell per-sandbox messaging bridge providers declared by channel - // manifests. - // - shields-.json + shields timer: per-sandbox shields artifacts - try { - fs.rmSync(`/tmp/nemoclaw-services-${name}`, { - recursive: true, - force: true, - }); - } catch { - // PID dir may not exist \u2014 ignore. - } - for (const suffix of listMessagingProviderSuffixes()) { - runOpenshell(["provider", "delete", `${name}${suffix}`], { - ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], - }); - } + cleanupSandboxServices(name); cleanupShieldsDestroyArtifacts(name); requireSnapshotDestinationRegistryRemoval(name, removeSandboxRegistryEntryOutcome(name)); }); diff --git a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts index 2bdb5ab6e5c..7997d1b6c7a 100644 --- a/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts +++ b/test/runtime/sandbox/destroy-cleanup-sandbox-services.test.ts @@ -112,7 +112,7 @@ describe("cleanupSandboxServices Ollama unload (#2717)", () => { ); }); - it("fails closed before other cleanup when the Google Chat tunnel cannot stop", () => { + it("retains service PID directories and fails closed when the Google Chat tunnel cannot stop", () => { const harness = buildDeps({ provider: "ollama-local" }); vi.mocked(harness.deps.stopGooglechatWebhookTunnel).mockImplementation(() => { throw new Error("cloudflared refused to stop"); From a01ebc955c507a2236a067e3547f0eb9d085cc5b Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Wed, 26 Aug 2026 07:06:21 -0700 Subject: [PATCH 07/11] fix(onboard): persist retained APF recovery Signed-off-by: Apurv Kumaria --- .dsh/tools/analyze_pr_value_stream/index.ts | 303 +++++++++--------- .../sandbox-gpu-create-identity-gate.test.ts | 107 +++++++ .../onboard/sandbox-gpu-create-run-attempt.ts | 2 + 3 files changed, 261 insertions(+), 151 deletions(-) diff --git a/.dsh/tools/analyze_pr_value_stream/index.ts b/.dsh/tools/analyze_pr_value_stream/index.ts index 94350c42504..768e976fba4 100644 --- a/.dsh/tools/analyze_pr_value_stream/index.ts +++ b/.dsh/tools/analyze_pr_value_stream/index.ts @@ -410,160 +410,162 @@ export default async function analyze_pr_value_stream(input: { for (let index = 0; index < waterfallRuns.length; index += 4) { const batch = await Promise.all( waterfallRuns.slice(index, index + 4).map(async (run: any) => { - const runResult = await tools.run_github_cli({ - workdir: input.workdir, - args: [ - "api", - "repos/" + repository + "/actions/runs/" + run.id, - "--jq", - "{id,name,event,run_attempt,head_sha,status,conclusion,created_at,run_started_at,updated_at,html_url}", - ], - }); - const runDetails = JSON.parse(runResult.stdout); - if ( - runDetails?.id !== run.id || - runDetails?.head_sha !== pull.headRefOid || - !Number.isSafeInteger(runDetails?.run_attempt) - ) - throw new Error("workflow run did not match the exact-head waterfall contract"); - const jobsResult = await tools.run_github_cli({ - workdir: input.workdir, - args: [ - "api", - "repos/" + repository + "/actions/runs/" + run.id + "/jobs?filter=latest&per_page=100", - "--jq", - "{total_count,jobs:[.jobs[] | {id,name,status,conclusion,created_at,started_at,completed_at,runner_name,runner_group_name,labels,html_url,steps}]}", - ], - }); - const jobsPayload = JSON.parse(jobsResult.stdout); - if ( - !Number.isSafeInteger(jobsPayload?.total_count) || - !Array.isArray(jobsPayload?.jobs) || - jobsPayload.total_count > 100 || - jobsPayload.jobs.length !== jobsPayload.total_count - ) - throw new Error("workflow job list exceeded the complete bounded waterfall contract"); - const runCreated = parseTime(run.created_at, "workflow createdAt"); - const shardJobs = jobsPayload.jobs.filter((job: any) => shardJobName.test(job?.name)); - let artifactsByName = new Map(); - if (shardJobs.length > 0 && maxTestArtifacts > 0) { - try { - const artifactsResult = await tools.run_github_cli({ - workdir: input.workdir, - args: [ - "api", - "repos/" + repository + "/actions/runs/" + run.id + "/artifacts?per_page=100", - "--jq", - "{total_count,artifacts:[.artifacts[] | {id,name,size_in_bytes,expired,workflow_run_id:.workflow_run.id,workflow_run_head_sha:.workflow_run.head_sha}]}", - ], - }); - const payload = JSON.parse(artifactsResult.stdout); - if ( - Number.isSafeInteger(payload?.total_count) && - payload.total_count <= 100 && - Array.isArray(payload?.artifacts) && - payload.artifacts.length === payload.total_count - ) { - const counts = new Map(); - for (const artifact of payload.artifacts) - counts.set(artifact?.name, (counts.get(artifact?.name) ?? 0) + 1); - artifactsByName = new Map( - payload.artifacts - .filter((artifact: any) => counts.get(artifact?.name) === 1) - .map((artifact: any) => [artifact.name, artifact]), - ); + const runResult = await tools.run_github_cli({ + workdir: input.workdir, + args: [ + "api", + "repos/" + repository + "/actions/runs/" + run.id, + "--jq", + "{id,name,event,run_attempt,head_sha,status,conclusion,created_at,run_started_at,updated_at,html_url}", + ], + }); + const runDetails = JSON.parse(runResult.stdout); + if ( + runDetails?.id !== run.id || + runDetails?.head_sha !== pull.headRefOid || + !Number.isSafeInteger(runDetails?.run_attempt) + ) + throw new Error("workflow run did not match the exact-head waterfall contract"); + const jobsResult = await tools.run_github_cli({ + workdir: input.workdir, + args: [ + "api", + "repos/" + repository + "/actions/runs/" + run.id + "/jobs?filter=latest&per_page=100", + "--jq", + "{total_count,jobs:[.jobs[] | {id,name,status,conclusion,created_at,started_at,completed_at,runner_name,runner_group_name,labels,html_url,steps}]}", + ], + }); + const jobsPayload = JSON.parse(jobsResult.stdout); + if ( + !Number.isSafeInteger(jobsPayload?.total_count) || + !Array.isArray(jobsPayload?.jobs) || + jobsPayload.total_count > 100 || + jobsPayload.jobs.length !== jobsPayload.total_count + ) + throw new Error("workflow job list exceeded the complete bounded waterfall contract"); + const runCreated = parseTime(run.created_at, "workflow createdAt"); + const shardJobs = jobsPayload.jobs.filter((job: any) => shardJobName.test(job?.name)); + let artifactsByName = new Map(); + if (shardJobs.length > 0 && maxTestArtifacts > 0) { + try { + const artifactsResult = await tools.run_github_cli({ + workdir: input.workdir, + args: [ + "api", + "repos/" + repository + "/actions/runs/" + run.id + "/artifacts?per_page=100", + "--jq", + "{total_count,artifacts:[.artifacts[] | {id,name,size_in_bytes,expired,workflow_run_id:.workflow_run.id,workflow_run_head_sha:.workflow_run.head_sha}]}", + ], + }); + const payload = JSON.parse(artifactsResult.stdout); + if ( + Number.isSafeInteger(payload?.total_count) && + payload.total_count <= 100 && + Array.isArray(payload?.artifacts) && + payload.artifacts.length === payload.total_count + ) { + const counts = new Map(); + for (const artifact of payload.artifacts) + counts.set(artifact?.name, (counts.get(artifact?.name) ?? 0) + 1); + artifactsByName = new Map( + payload.artifacts + .filter((artifact: any) => counts.get(artifact?.name) === 1) + .map((artifact: any) => [artifact.name, artifact]), + ); + } + } catch { + artifactsByName = new Map(); } - } catch { - artifactsByName = new Map(); } - } - const jobs = []; - for (const job of jobsPayload.jobs) { - if (!Number.isSafeInteger(job?.id) || !Array.isArray(job?.steps)) - throw new Error("workflow job did not match the waterfall contract"); - const jobCreated = parseTime(job.created_at, "job createdAt"); - const jobStarted = parseTime(job.started_at, "job startedAt"); - const jobCompleted = - job.completed_at === null ? null : parseTime(job.completed_at, "job completedAt"); - let testRun = null; - const match = shardJobName.exec(job.name); - if (match !== null && testArtifactsRead < maxTestArtifacts) { - const artifact = artifactsByName.get("cli-blob-report-" + match[1]); - if (artifact !== undefined) { - testArtifactsRead += 1; - testRun = await readTestRun(run.id, pull.headRefOid, Number(match[1]), artifact); + const jobs = []; + for (const job of jobsPayload.jobs) { + if (!Number.isSafeInteger(job?.id) || !Array.isArray(job?.steps)) + throw new Error("workflow job did not match the waterfall contract"); + const jobCreated = parseTime(job.created_at, "job createdAt"); + const jobStarted = parseTime(job.started_at, "job startedAt"); + const jobCompleted = + job.completed_at === null ? null : parseTime(job.completed_at, "job completedAt"); + let testRun = null; + const match = shardJobName.exec(job.name); + if (match !== null && testArtifactsRead < maxTestArtifacts) { + const artifact = artifactsByName.get("cli-blob-report-" + match[1]); + if (artifact !== undefined) { + testArtifactsRead += 1; + testRun = await readTestRun(run.id, pull.headRefOid, Number(match[1]), artifact); + } } - } - const steps = job.steps.map((step: any) => { - if (!Number.isSafeInteger(step?.number)) - throw new Error("workflow step did not match the waterfall contract"); - const stepStarted = parseTime(step.started_at, "step startedAt"); - const stepCompleted = - step.completed_at === null ? null : parseTime(step.completed_at, "step completedAt"); - return { - number: step.number, - name: String(step.name ?? "").slice(0, 200), - status: String(step.status ?? "").slice(0, 40), - conclusion: - step.conclusion === null ? null : String(step.conclusion ?? "").slice(0, 40), - startedAt: iso(stepStarted), - completedAt: stepCompleted === null ? null : iso(stepCompleted), - offsetSeconds: offsetSeconds(headObserved, stepStarted), - durationSeconds: stepCompleted === null ? null : seconds(stepStarted, stepCompleted), + const steps = job.steps.map((step: any) => { + if (!Number.isSafeInteger(step?.number)) + throw new Error("workflow step did not match the waterfall contract"); + const stepStarted = parseTime(step.started_at, "step startedAt"); + const stepCompleted = + step.completed_at === null ? null : parseTime(step.completed_at, "step completedAt"); + return { + number: step.number, + name: String(step.name ?? "").slice(0, 200), + status: String(step.status ?? "").slice(0, 40), + conclusion: + step.conclusion === null ? null : String(step.conclusion ?? "").slice(0, 40), + startedAt: iso(stepStarted), + completedAt: stepCompleted === null ? null : iso(stepCompleted), + offsetSeconds: offsetSeconds(headObserved, stepStarted), + durationSeconds: stepCompleted === null ? null : seconds(stepStarted, stepCompleted), + }; + }); + const normalizedJob = { + id: job.id, + name: String(job.name ?? "").slice(0, 200), + status: String(job.status ?? "").slice(0, 40), + conclusion: job.conclusion === null ? null : String(job.conclusion ?? "").slice(0, 40), + url: String(job.html_url ?? "").slice(0, 500), + runner: job.runner_name === null ? null : String(job.runner_name ?? "").slice(0, 200), + runnerGroup: + job.runner_group_name === null + ? null + : String(job.runner_group_name ?? "").slice(0, 200), + labels: job.labels.slice(0, 20).map((label: any) => String(label).slice(0, 100)), + createdAt: iso(jobCreated), + startedAt: iso(jobStarted), + completedAt: jobCompleted === null ? null : iso(jobCompleted), + offsetSeconds: offsetSeconds(headObserved, jobStarted), + queueSeconds: jobCreated <= jobStarted ? seconds(jobCreated, jobStarted) : null, + durationSeconds: jobCompleted === null ? null : seconds(jobStarted, jobCompleted), + testRun, + steps, }; - }); - const normalizedJob = { - id: job.id, - name: String(job.name ?? "").slice(0, 200), - status: String(job.status ?? "").slice(0, 40), - conclusion: job.conclusion === null ? null : String(job.conclusion ?? "").slice(0, 40), - url: String(job.html_url ?? "").slice(0, 500), - runner: job.runner_name === null ? null : String(job.runner_name ?? "").slice(0, 200), - runnerGroup: - job.runner_group_name === null + jobs.push(normalizedJob); + } + const earliestJobStart = + jobs.length > 0 + ? Math.min( + ...jobs.map((job: any) => parseTime(job.startedAt, "normalized job startedAt")), + ) + : parseTime(runDetails.run_started_at, "workflow startedAt"); + const runStarted = Math.min( + parseTime(runDetails.run_started_at, "workflow startedAt"), + earliestJobStart, + ); + const runCompleted = + runDetails.status === "completed" + ? parseTime(runDetails.updated_at, "workflow completedAt") + : null; + return { + id: runDetails.id, + name: String(runDetails.name ?? "").slice(0, 200), + event: String(runDetails.event ?? "").slice(0, 60), + attempt: runDetails.run_attempt, + status: String(runDetails.status ?? "").slice(0, 40), + conclusion: + runDetails.conclusion === null ? null - : String(job.runner_group_name ?? "").slice(0, 200), - labels: job.labels.slice(0, 20).map((label: any) => String(label).slice(0, 100)), - createdAt: iso(jobCreated), - startedAt: iso(jobStarted), - completedAt: jobCompleted === null ? null : iso(jobCompleted), - offsetSeconds: offsetSeconds(headObserved, jobStarted), - queueSeconds: jobCreated <= jobStarted ? seconds(jobCreated, jobStarted) : null, - durationSeconds: jobCompleted === null ? null : seconds(jobStarted, jobCompleted), - testRun, - steps, - }; - jobs.push(normalizedJob); - } - const earliestJobStart = - jobs.length > 0 - ? Math.min( - ...jobs.map((job: any) => parseTime(job.startedAt, "normalized job startedAt")), - ) - : parseTime(runDetails.run_started_at, "workflow startedAt"); - const runStarted = Math.min( - parseTime(runDetails.run_started_at, "workflow startedAt"), - earliestJobStart, - ); - const runCompleted = - runDetails.status === "completed" - ? parseTime(runDetails.updated_at, "workflow completedAt") - : null; - return { - id: runDetails.id, - name: String(runDetails.name ?? "").slice(0, 200), - event: String(runDetails.event ?? "").slice(0, 60), - attempt: runDetails.run_attempt, - status: String(runDetails.status ?? "").slice(0, 40), - conclusion: - runDetails.conclusion === null ? null : String(runDetails.conclusion ?? "").slice(0, 40), - url: String(runDetails.html_url ?? "").slice(0, 500), - createdAt: iso(runCreated), - startedAt: iso(runStarted), - completedAt: runCompleted === null ? null : iso(runCompleted), - offsetSeconds: offsetSeconds(headObserved, runCreated), - queueSeconds: seconds(runCreated, runStarted), - durationSeconds: runCompleted === null ? null : seconds(runStarted, runCompleted), + : String(runDetails.conclusion ?? "").slice(0, 40), + url: String(runDetails.html_url ?? "").slice(0, 500), + createdAt: iso(runCreated), + startedAt: iso(runStarted), + completedAt: runCompleted === null ? null : iso(runCompleted), + offsetSeconds: offsetSeconds(headObserved, runCreated), + queueSeconds: seconds(runCreated, runStarted), + durationSeconds: runCompleted === null ? null : seconds(runStarted, runCompleted), jobs, }; }), @@ -686,8 +688,7 @@ export default async function analyze_pr_value_stream(input: { .flatMap((run: any) => run.jobs) .filter((job: any) => job.queueSeconds !== null) .sort( - (a: any, b: any) => - b.queueSeconds - a.queueSeconds || a.name.localeCompare(b.name), + (a: any, b: any) => b.queueSeconds - a.queueSeconds || a.name.localeCompare(b.name), )[0] ?? null; const longestChecks = checkRows .slice() diff --git a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts index 3e78600b617..510cfb760c3 100644 --- a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts +++ b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts @@ -233,6 +233,57 @@ describe("created sandbox identity gate", () => { expect(mocks.waitForCreatedSandboxReadyWithTrace).not.toHaveBeenCalled(); }); + it("persists unresolved APF recovery before rejecting a missing post-create identity (#9833)", async () => { + let nonce = ""; + const input = noGpuInput(); + input.requirePolicylessCreate = true; + input.verifyCreatedSandboxBeforeEffects = vi.fn(); + input.revalidateVerifiedSandboxBeforeEffect = vi.fn(); + const persistRetainedApfSandboxRecovery = vi.fn(() => true); + input.persistRetainedApfSandboxRecovery = persistRetainedApfSandboxRecovery; + const patch = createGpuPatchFixture(); + mocks.createDockerGpuSandboxCreatePatch.mockReturnValue(patch); + mocks.streamSandboxCreate.mockImplementation(async (_command, args) => { + nonce = createAttemptNonce(args); + return { status: 0, output: "Created sandbox: alpha", sawProgress: true }; + }); + const deps = createGpuFlowDeps(); + vi.mocked(deps.runCaptureOpenshell).mockReturnValue("[]"); + const exit = vi.spyOn(process, "exit").mockImplementation((code) => { + throw new Error(`process.exit:${code}`); + }); + + const error = await runSandboxGpuCreateFlow(input, deps).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(Error); + expect(String(error)).toContain( + "did not return one exact durable sandbox identity before post-create effects", + ); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + createAttemptNonce: nonce, + liveIdentityFingerprint: null, + message: formatRetainedApfSandboxRecoveryReceipt({ + createAttemptNonce: nonce, + liveIdentityFingerprint: null, + }), + }); + expect(exit).not.toHaveBeenCalled(); + const output = vi.mocked(console.error).mock.calls.flat().join("\n"); + expect(output).toContain(`${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}`); + expect(output).toContain("Recovery is blocked"); + expect(output).toContain("onboard --fresh --apf-interceptor --name "); + expect(output).not.toContain("onboard --resume"); + expect(input.verifyCreatedSandboxBeforeEffects).not.toHaveBeenCalled(); + expect(patch.ensureApplied).not.toHaveBeenCalled(); + expect(mocks.waitForCreatedSandboxReadyWithTrace).not.toHaveBeenCalled(); + expect(deps.runOpenshell).not.toHaveBeenCalledWith( + ["sandbox", "delete", "alpha"], + expect.anything(), + ); + }); + it("requires checkpoint revalidation before the first post-create effect (#9833)", async () => { let nonce = ""; const input = noGpuInput(); @@ -503,6 +554,62 @@ describe("created sandbox identity gate", () => { expect(output).not.toContain("onboard --resume"); }); + it("persists identifiable APF recovery before a terminal readiness exit (#9833)", async () => { + let nonce = ""; + const input = noGpuInput(); + input.requirePolicylessCreate = true; + input.verifyCreatedSandboxBeforeEffects = vi.fn(); + input.revalidateVerifiedSandboxBeforeEffect = vi.fn(); + const persistRetainedApfSandboxRecovery = vi.fn(() => true); + input.persistRetainedApfSandboxRecovery = persistRetainedApfSandboxRecovery; + const patch = createGpuPatchFixture(); + mocks.createDockerGpuSandboxCreatePatch.mockReturnValue(patch); + mocks.streamSandboxCreate.mockImplementation(async (_command, args) => { + nonce = createAttemptNonce(args); + return { status: 0, output: "Created sandbox: alpha", sawProgress: true }; + }); + mocks.waitForCreatedSandboxReadyWithTrace.mockReturnValue({ + ready: false, + reason: "terminal_failure_phase", + failurePhase: "Error", + }); + const deps = createGpuFlowDeps(); + vi.mocked(deps.runCaptureOpenshell).mockImplementation(() => + sandboxListJson("alpha-sandbox-id", { [NEMOCLAW_CREATE_ATTEMPT_LABEL]: nonce }), + ); + const exit = vi.spyOn(process, "exit").mockImplementation((code) => { + throw new Error(`process.exit:${code}`); + }); + + await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow("process.exit:1"); + + const fingerprint = fingerprintSandboxRecreateValue("alpha-sandbox-id"); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + createAttemptNonce: nonce, + liveIdentityFingerprint: fingerprint, + message: formatRetainedApfSandboxRecoveryReceipt({ + createAttemptNonce: nonce, + liveIdentityFingerprint: fingerprint, + }), + }); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledBefore( + patch.rollbackManagedStartupAfterCreateFailure, + ); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledBefore(exit); + const output = vi.mocked(console.error).mock.calls.flat().join("\n"); + expect(output).toContain(`${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}`); + expect(output).toContain(`Durable sandbox identity fingerprint: ${fingerprint}`); + expect(output).toContain("onboard --fresh --apf-interceptor --name "); + expect(output).not.toContain("onboard --resume"); + expect(output).not.toContain("alpha-sandbox-id"); + expect(deps.runOpenshell).not.toHaveBeenCalledWith( + ["sandbox", "delete", "alpha"], + expect.anything(), + ); + }); + it.each([ ["returns false", () => false], [ diff --git a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts index 1e6a8ebbf23..ce199e5ff60 100644 --- a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts +++ b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts @@ -770,6 +770,7 @@ export function createSandboxGpuCreateAttemptRunner( runCaptureOpenshell: deps.runCaptureOpenshell, }); } catch (error) { + persistApfCreateFailureRecovery(input, captureRetainedSandboxRecovery); throw new Error( `Sandbox '${input.sandboxName}' was created, but OpenShell did not return one exact durable sandbox identity before post-create effects.`, { cause: error }, @@ -866,6 +867,7 @@ export function createSandboxGpuCreateAttemptRunner( ...captureRetainedSandboxRecovery(), } as const; } + persistApfCreateFailureRecovery(input, captureRetainedSandboxRecovery); await runtimePatch.rollbackManagedStartupAfterCreateFailure(); printCreateFailureDiagnostics(input.sandboxName, { backupPath: input.restoreBackupPath, From 71972bf6ee14038cc806bf2f1408e19b42fd1917 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Wed, 26 Aug 2026 07:41:28 -0700 Subject: [PATCH 08/11] fix(onboard): persist APF recovery before terminal exits Signed-off-by: Apurv Kumaria --- ...ocker-gpu-sandbox-create-lifecycle.test.ts | 9 ++- src/lib/onboard/docker-gpu-sandbox-create.ts | 8 ++- .../managed-bootstrap/docker-runtime.test.ts | 8 ++- .../managed-bootstrap/docker-runtime.ts | 1 + .../managed-bootstrap/runtime-create.ts | 2 + .../sandbox-gpu-create-identity-gate.test.ts | 58 +++++++++++++++++++ .../onboard/sandbox-gpu-create-run-attempt.ts | 45 +++++++++++++- 7 files changed, 124 insertions(+), 7 deletions(-) diff --git a/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts b/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts index fde42865d83..16793ba8e60 100644 --- a/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts +++ b/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts @@ -441,20 +441,23 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { expect(onPatchFailureExit).not.toHaveBeenCalled(); }); - it("records patchError when recreate throws and exitOnPatchError reports it via printDockerGpuPatchFailureAndExit", async () => { + it("invokes retained-sandbox recovery once before reporting a deferred patch failure (#9833)", async () => { + const events: string[] = []; const deps = makeDeps(); const recreatePatch = vi.fn(() => { throw new Error("docker rename failed"); }); const waitForSupervisor = vi.fn(); const finalizeBackup = vi.fn(); - const onPatchFailureExit = vi.fn(); + const beforeFailureExit = vi.fn(() => events.push("before-failure-exit")); + const onPatchFailureExit = vi.fn(() => events.push("failure-exit")); const findContainerIds = vi.fn(() => ["existing-container"]); const patch = createDockerGpuSandboxCreatePatch({ route: "compatibility", sandboxName: "alpha", timeoutSecs: 60, + beforeFailureExit, deps, overrides: { findContainerIds, @@ -468,7 +471,9 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { patch.maybeApplyDuringCreate(); expect(patch.createFailureMessage()).toMatch(/Docker GPU patch failed/); await patch.exitOnPatchError(); + expect(beforeFailureExit).toHaveBeenCalledOnce(); expect(onPatchFailureExit).toHaveBeenCalledTimes(1); + expect(events).toEqual(["before-failure-exit", "failure-exit"]); // Supervisor wait must be skipped because needsSupervisorWait stayed false. patch.waitForSupervisorReconnectIfNeeded(); expect(waitForSupervisor).not.toHaveBeenCalled(); diff --git a/src/lib/onboard/docker-gpu-sandbox-create.ts b/src/lib/onboard/docker-gpu-sandbox-create.ts index e4ed566917b..8750fa02623 100644 --- a/src/lib/onboard/docker-gpu-sandbox-create.ts +++ b/src/lib/onboard/docker-gpu-sandbox-create.ts @@ -87,6 +87,8 @@ type DockerGpuSandboxCreatePatchOptions = { requiredUlimits?: Parameters[0]["requiredUlimits"]; timeoutSecs: number; backend?: DockerGpuPatchBackend; + /** Persist caller-owned recovery evidence immediately before a terminal failure report. */ + beforeFailureExit?: () => void; /** * Whether the host is Docker Desktop WSL. Defaults to the cached * `isDockerDesktopWslRuntime()` probe. When true, the GPU patch skips the CDI @@ -177,8 +179,12 @@ export function createDockerGpuSandboxCreatePatch( const finalizeBackup = options.overrides?.finalizeBackup ?? finalizeDockerGpuPatchBackup; const captureFailedClone = options.overrides?.capturePreRollbackDiagnostics ?? captureDockerGpuPreRollbackDiagnostics; - const onPatchFailureExit = + const reportPatchFailureAndExit = options.overrides?.onPatchFailureExit ?? printDockerGpuPatchFailureAndExit; + const onPatchFailureExit: PatchFailureExitFn = (sandboxName, error, deps) => { + options.beforeFailureExit?.(); + reportPatchFailureAndExit(sandboxName, error, deps); + }; const failureDiagnosticDeps = { runCaptureOpenshell: options.deps.runCaptureOpenshell, dockerCapture: options.deps.dockerCapture, diff --git a/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts b/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts index bf32ef8da1c..47742e28361 100644 --- a/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-runtime.test.ts @@ -499,7 +499,8 @@ describe("Docker managed-bootstrap lifecycle composition", () => { } }); - it("does not finalize rollback after a claimed commit loses acknowledgement", async () => { + it("persists recovery before a managed commit loses acknowledgement (#9833)", async () => { + const events: string[] = []; const stateRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-runtime-")); const seed = authority("openclaw"); const prepared = Object.freeze({}) as ManagedBootstrapPreparedTransaction; @@ -516,7 +517,9 @@ describe("Docker managed-bootstrap lifecycle composition", () => { }); adapterMocks.activate.mockResolvedValue(activated); adapterMocks.finalize.mockRejectedValue(new Error("commit acknowledgement lost")); + const beforeFailureExit = vi.fn(() => events.push("before-failure-exit")); const onPatchFailure = vi.fn((error: unknown): never => { + events.push("failure-exit"); throw error; }); const lifecycle = createDockerManagedBootstrapSurface().createLifecycle({ @@ -546,6 +549,7 @@ describe("Docker managed-bootstrap lifecycle composition", () => { }, requiredLimits: [], timeoutSecs: 30, + beforeFailureExit, onPatchFailure, network: { inferenceProvider: "openai", @@ -572,7 +576,9 @@ describe("Docker managed-bootstrap lifecycle composition", () => { expect.anything(), expect.objectContaining({ outcome: "commit", transaction: activated }), ); + expect(beforeFailureExit).toHaveBeenCalledOnce(); expect(onPatchFailure).toHaveBeenCalledOnce(); + expect(events).toEqual(["before-failure-exit", "failure-exit"]); await expect(lifecycle.recoverUnfinished()).resolves.toEqual({ receipts: [], failures: [] }); fs.rmSync(stateRoot, { recursive: true, force: true }); }); diff --git a/src/lib/onboard/managed-bootstrap/docker-runtime.ts b/src/lib/onboard/managed-bootstrap/docker-runtime.ts index cb4dc77f848..3739b39c3cd 100644 --- a/src/lib/onboard/managed-bootstrap/docker-runtime.ts +++ b/src/lib/onboard/managed-bootstrap/docker-runtime.ts @@ -179,6 +179,7 @@ function createDockerLifecycle( timeoutSecs: input.timeoutSecs, backend, dockerDesktopWsl, + beforeFailureExit: input.beforeFailureExit, deps: input.dependencies, ...(input.onPatchFailure ? { diff --git a/src/lib/onboard/managed-bootstrap/runtime-create.ts b/src/lib/onboard/managed-bootstrap/runtime-create.ts index 872d3a66d0e..e981611a9fc 100644 --- a/src/lib/onboard/managed-bootstrap/runtime-create.ts +++ b/src/lib/onboard/managed-bootstrap/runtime-create.ts @@ -113,6 +113,8 @@ export interface ManagedBootstrapRuntimeCreateLifecycleInput { readonly sandboxGpuConfig: SandboxGpuConfig; readonly requiredLimits: readonly ManagedBootstrapRuntimeLimit[]; readonly timeoutSecs: number; + /** Persist caller-owned recovery evidence before canonical patch termination. */ + readonly beforeFailureExit?: () => void; readonly onPatchFailure?: (error: unknown) => never; readonly network: { readonly inferenceProvider: string; diff --git a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts index 510cfb760c3..d530688c69d 100644 --- a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts +++ b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts @@ -654,6 +654,64 @@ describe("created sandbox identity gate", () => { }, ); + it("persists APF recovery once when post-create revalidation fails (#9833)", async () => { + const events: string[] = []; + let nonce = ""; + const revalidationFailure = new Error("checkpoint changed"); + const input = noGpuInput(); + input.requirePolicylessCreate = true; + input.verifyCreatedSandboxBeforeEffects = vi.fn(async () => { + events.push("verify"); + }); + input.revalidateVerifiedSandboxBeforeEffect = vi.fn(() => { + events.push("revalidate"); + throw revalidationFailure; + }); + const persistRetainedApfSandboxRecovery = vi.fn(() => { + events.push("persist"); + return false; + }); + input.persistRetainedApfSandboxRecovery = persistRetainedApfSandboxRecovery; + const patch = createGpuPatchFixture(); + mocks.createDockerGpuSandboxCreatePatch.mockReturnValue(patch); + mocks.streamSandboxCreate.mockImplementation(async (_command, args) => { + nonce = createAttemptNonce(args); + return { status: 0, output: "Created sandbox: alpha", sawProgress: true }; + }); + const deps = createGpuFlowDeps(); + vi.mocked(deps.runCaptureOpenshell).mockImplementation(() => + sandboxListJson("alpha-sandbox-id", { [NEMOCLAW_CREATE_ATTEMPT_LABEL]: nonce }), + ); + + const error = await runSandboxGpuCreateFlow(input, deps).catch((caught: unknown) => caught); + + expect(error).toBe(revalidationFailure); + const fingerprint = fingerprintSandboxRecreateValue("alpha-sandbox-id"); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + createAttemptNonce: nonce, + liveIdentityFingerprint: fingerprint, + message: formatRetainedApfSandboxRecoveryReceipt({ + createAttemptNonce: nonce, + liveIdentityFingerprint: fingerprint, + }), + }); + expect(events).toEqual(["verify", "revalidate", "persist"]); + const output = vi.mocked(console.error).mock.calls.flat().join("\n"); + expect(output).toContain( + "APF recovery is blocked because NemoClaw could not save this create-attempt evidence", + ); + expect(output).not.toContain("onboard --resume"); + expect(patch.exitOnPatchError).not.toHaveBeenCalled(); + expect(patch.ensureApplied).not.toHaveBeenCalled(); + expect(mocks.waitForCreatedSandboxReadyWithTrace).not.toHaveBeenCalled(); + expect(deps.runOpenshell).not.toHaveBeenCalledWith( + ["sandbox", "delete", "alpha"], + expect.anything(), + ); + }); + it("stops before a runtime patch when the durable checkpoint drifts (#9833)", async () => { let nonce = ""; const input = noGpuInput(); diff --git a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts index ce199e5ff60..c4f5775a877 100644 --- a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts +++ b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts @@ -497,7 +497,11 @@ export function createSandboxGpuCreateAttemptRunner( const nativeFallbackHasCleanBaseline = managedRouting?.nativeFallbackHasCleanBaseline ?? (nativeFallbackBaseline?.ok === true && nativeFallbackBaseline.ids.length === 0); - const runAttempt = async (route: SelectedDockerGpuRoute) => { + const runAttemptCore = async ( + route: SelectedDockerGpuRoute, + armApfPostCreateRecovery: (persist: () => void) => void, + persistApfPostCreateRecoveryOnce: () => void, + ) => { const deferPostCreateEffects = input.verifyCreatedSandboxBeforeEffects !== undefined; const compatibility = route === "compatibility"; if (compatibility && input.initialGpuRoute === "native") { @@ -517,6 +521,12 @@ export function createSandboxGpuCreateAttemptRunner( : null; const captureRetainedSandboxRecovery = () => captureRetainedApfSandboxRecovery(input, deps, createAttemptNonce); + const armRetainedApfSandboxRecovery = (): void => { + if (!input.requirePolicylessCreate) return; + armApfPostCreateRecovery(() => + persistApfCreateFailureRecovery(input, captureRetainedSandboxRecovery), + ); + }; const attemptArgv = createAttemptNonce ? addCreateAttemptIdentityLabel(unboundAttemptArgv, createAttemptNonce) : unboundAttemptArgv; @@ -546,6 +556,7 @@ export function createSandboxGpuCreateAttemptRunner( sandboxGpuConfig: input.sandboxGpuConfig, requiredLimits: input.requiredUlimits ?? [], timeoutSecs: input.sandboxReadyTimeoutSecs, + beforeFailureExit: persistApfPostCreateRecoveryOnce, network: { inferenceProvider: input.provider, gatewayUsesContainerBridge: input.dockerDriverGateway, @@ -586,6 +597,7 @@ export function createSandboxGpuCreateAttemptRunner( requiredUlimits: input.requiredUlimits, timeoutSecs: input.sandboxReadyTimeoutSecs, backend: input.sandboxGpuConfig.hostGpuPlatform === "jetson" ? "jetson" : "generic", + beforeFailureExit: persistApfPostCreateRecoveryOnce, deps, })); const inspectNativeRuntime = (): NativeRuntimeSnapshot | null => { @@ -659,6 +671,7 @@ export function createSandboxGpuCreateAttemptRunner( if (result.status !== 0 && createFailure?.kind !== "sandbox_create_incomplete") { throw new ManagedBootstrapCreateStreamFailure(result); } + armRetainedApfSandboxRecovery(); if (createFailure?.kind === "sandbox_create_incomplete") { const readiness = sandboxReadinessTracing.waitForCreatedSandboxReadyWithTrace({ sandboxName: input.sandboxName, @@ -757,6 +770,7 @@ export function createSandboxGpuCreateAttemptRunner( }); if (failureResult) return failureResult; } + armRetainedApfSandboxRecovery(); if (!createdSandboxVerified && deferPostCreateEffects) { if (!createAttemptNonce) { throw new Error("Sandbox create-attempt identity was not generated."); @@ -770,7 +784,6 @@ export function createSandboxGpuCreateAttemptRunner( runCaptureOpenshell: deps.runCaptureOpenshell, }); } catch (error) { - persistApfCreateFailureRecovery(input, captureRetainedSandboxRecovery); throw new Error( `Sandbox '${input.sandboxName}' was created, but OpenShell did not return one exact durable sandbox identity before post-create effects.`, { cause: error }, @@ -789,6 +802,7 @@ export function createSandboxGpuCreateAttemptRunner( const expectedRecreatedSandboxId = preRecreateIdentity?.state === "identified" ? preRecreateIdentity.sandboxId : null; if (deferRestartSafeCutover && !expectedRecreatedSandboxId) { + persistApfPostCreateRecoveryOnce(); console.error(""); console.error( ` Sandbox '${input.sandboxName}' reached Ready, but OpenShell did not return one exact durable sandbox ID before runtime recreation.`, @@ -867,7 +881,7 @@ export function createSandboxGpuCreateAttemptRunner( ...captureRetainedSandboxRecovery(), } as const; } - persistApfCreateFailureRecovery(input, captureRetainedSandboxRecovery); + persistApfPostCreateRecoveryOnce(); await runtimePatch.rollbackManagedStartupAfterCreateFailure(); printCreateFailureDiagnostics(input.sandboxName, { backupPath: input.restoreBackupPath, @@ -912,6 +926,7 @@ export function createSandboxGpuCreateAttemptRunner( }, ); } catch (error) { + persistApfPostCreateRecoveryOnce(); await runtimePatch.rollbackManagedStartupAfterCreateFailure(); throw error; } @@ -937,6 +952,7 @@ export function createSandboxGpuCreateAttemptRunner( } as const; } } + persistApfPostCreateRecoveryOnce(); await runtimePatch.rollbackManagedStartupAfterCreateFailure(); console.error(""); console.error(" Native sandbox GPU proof failed."); @@ -949,6 +965,7 @@ export function createSandboxGpuCreateAttemptRunner( process.exit(1); } if (proof.status === "failed") { + persistApfPostCreateRecoveryOnce(); await runtimePatch.rollbackManagedStartupAfterCreateFailure(); throw new Error("Sandbox GPU proof returned failed status."); } @@ -971,5 +988,27 @@ export function createSandboxGpuCreateAttemptRunner( } as const; }; + const runAttempt = async (route: SelectedDockerGpuRoute) => { + let persistApfPostCreateRecovery: (() => void) | null = null; + let apfPostCreateRecoveryPersisted = false; + const persistApfPostCreateRecoveryOnce = (): void => { + if (apfPostCreateRecoveryPersisted || !persistApfPostCreateRecovery) return; + apfPostCreateRecoveryPersisted = true; + persistApfPostCreateRecovery(); + }; + try { + return await runAttemptCore( + route, + (persist) => { + persistApfPostCreateRecovery ??= persist; + }, + persistApfPostCreateRecoveryOnce, + ); + } catch (error) { + persistApfPostCreateRecoveryOnce(); + throw error; + } + }; + return { state, managedRouting, runAttempt }; } From 48345b8b5358699beece7aba4fbf96cd703e7587 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 27 Aug 2026 11:29:15 -0700 Subject: [PATCH 09/11] fix(policy): restore review repair boundaries Signed-off-by: Apurv Kumaria --- .../checks/openshell-policy-mutation-read.mts | 5 +- .../openshell/policy-authority.test.ts | 102 ------------- .../adapters/openshell/policy-authority.ts | 138 +++++------------- .../sandbox-create/policy-creation-receipt.ts | 6 +- .../sandbox-gpu-create-identity-gate.test.ts | 49 ++++--- .../onboard/sandbox-gpu-create-run-attempt.ts | 3 +- 6 files changed, 76 insertions(+), 227 deletions(-) diff --git a/scripts/checks/openshell-policy-mutation-read.mts b/scripts/checks/openshell-policy-mutation-read.mts index 767c189e5ef..d0ac8b5513a 100644 --- a/scripts/checks/openshell-policy-mutation-read.mts +++ b/scripts/checks/openshell-policy-mutation-read.mts @@ -118,8 +118,10 @@ const NON_MUTATION_POLICY_READS: readonly AuditedPolicyReadFile[] = [ { relativePath: "src/lib/policy/commands.ts", expectedReads: [ - unclassifiedBase("buildPolicyGetCommand"), + unclassifiedFull("buildGlobalPolicyGetFullJsonArgs"), + unclassifiedBase("buildPolicyGetArgs"), unclassifiedFull("buildPolicyGetFullCommand"), + unclassifiedFull("buildPolicyGetFullJsonArgs"), ], }, ] as const; @@ -131,6 +133,7 @@ export interface DiscoveredPolicyReadSite { } const POLICY_GET_BUILDERS = new Map([ + ["buildGlobalPolicyGetFullJsonArgs", "full"], ["buildPolicyGetCommand", "base"], ["buildPolicyGetArgs", "base"], ["buildPolicyGetFullCommand", "full"], diff --git a/src/lib/adapters/openshell/policy-authority.test.ts b/src/lib/adapters/openshell/policy-authority.test.ts index c11d5859119..fb5a5e7afce 100644 --- a/src/lib/adapters/openshell/policy-authority.test.ts +++ b/src/lib/adapters/openshell/policy-authority.test.ts @@ -7,17 +7,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as openshellRuntimeModule from "./runtime"; import { - assertExternalPolicyRequirements, assertOpenShellGatewayPortBinding, - assertRecordedPolicyAuthority, captureSandboxBasePolicy, inspectActiveGlobalPolicy, inspectOpenShellSandboxPolicyReadiness, inspectOpenShellSandboxIdentityFingerprint, inspectSandboxPolicyAuthority, - isExternalPolicyAuthorityRefusalError, policyAuthorityInternals, - type SandboxPolicyAuthorityInspection, } from "./policy-authority"; function captureResult( @@ -489,101 +485,3 @@ describe("OpenShell policy authority inspection", () => { expect(error.message).not.toContain("captured-stderr-secret"); }); }); - -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/); - }); - - 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", () => { - 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", - policyIdentity: { hash: "policy-alpha", activeVersion: 7 }, - 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: {}, - policyIdentity: { hash: "policy-alpha", activeVersion: 7 }, - }, - 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 index 99302e2974e..c87c5badd2d 100644 --- a/src/lib/adapters/openshell/policy-authority.ts +++ b/src/lib/adapters/openshell/policy-authority.ts @@ -8,22 +8,13 @@ import { NAME_MAX_LENGTH, } from "../../sandbox-name-contract"; import { - buildGlobalPolicyGetFullJsonArgs, - buildGlobalPolicyListArgs, - buildPolicyGetArgs, - buildPolicyGetFullJsonArgs, -} from "../../policy/commands"; -import { - assertExternalPolicyRequirementContainment, - assertMatchingPolicyAuthority, - assertPolicyRequirementContainment, classifyOpenShellGlobalPolicyHistory, parseActiveGlobalPolicyAuthorityMetadata, type ActiveGlobalPolicyInspection, type OpenShellPolicyAuthority, parseSandboxPolicyAuthorityMetadata, type SandboxPolicyAuthorityInspection as CanonicalSandboxPolicyAuthorityInspection, -} from "../../policy/merge"; +} from "../../../../nemoclaw/dist/shared/openshell-policy-boundary.cjs"; import * as openshellRuntime from "./runtime"; import { fingerprintOpenShellSandboxId, @@ -37,7 +28,7 @@ type JsonObject = Record; export type SandboxPolicyAuthority = OpenShellPolicyAuthority; export type SandboxPolicyAuthorityInspection = CanonicalSandboxPolicyAuthorityInspection; -export type { ActiveGlobalPolicyInspection } from "../../policy/merge"; +export type { ActiveGlobalPolicyInspection }; export type OpenShellSandboxPolicyReadiness = | { readonly state: "ready" } @@ -148,14 +139,6 @@ function captureAuthorityRead( runtimeSelection?: { readonly gatewayName?: string }, ): { readonly output: string; readonly stdout: string; readonly stderr: string } { const result = captureBoundedOpenShell(args, subject, runtimeSelection); - if ( - !isObject(result) || - typeof result.output !== "string" || - typeof result.stdout !== "string" || - typeof result.stderr !== "string" - ) { - failInspection(subject, "the policy query returned an invalid result"); - } const errorCode = (result.error as NodeJS.ErrnoException | undefined)?.code; if (errorCode === "ETIMEDOUT") { failInspection(subject, "the policy query timed out"); @@ -169,7 +152,7 @@ function captureAuthorityRead( if (result.status !== 0) { failInspection(subject, "the policy query did not complete successfully"); } - return { output: result.output, stdout: result.stdout, stderr: result.stderr }; + return { output: result.output, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; } function capturePolicyRead( @@ -191,7 +174,15 @@ export function inspectSandboxPolicyAuthority({ ? undefined : validatePolicyAuthorityName(gatewayName, "gateway name"); const raw = capturePolicyRead( - buildPolicyGetFullJsonArgs(validatedSandboxName, validatedGatewayName), + [ + "policy", + "get", + ...(validatedGatewayName ? ["-g", validatedGatewayName] : []), + "--full", + "--output", + "json", + validatedSandboxName, + ], "sandbox", { gatewayName: validatedGatewayName }, ); @@ -256,16 +247,33 @@ export function inspectActiveGlobalPolicy({ gatewayName === undefined ? undefined : validatePolicyAuthorityName(gatewayName, "gateway name"); - const history = captureAuthorityRead(buildGlobalPolicyListArgs(validatedGatewayName), "global", { - gatewayName: validatedGatewayName, - }); + const history = captureAuthorityRead( + [ + "policy", + "list", + ...(validatedGatewayName ? ["-g", validatedGatewayName] : []), + "--global", + "--limit", + "1", + ], + "global", + { gatewayName: validatedGatewayName }, + ); const historyState = classifyOpenShellGlobalPolicyHistory(history.stdout, history.stderr); if (historyState === "absent") return { state: "absent" }; if (historyState === "invalid") { failInspection("global", "OpenShell returned invalid global policy history"); } const raw = captureAuthorityRead( - buildGlobalPolicyGetFullJsonArgs(validatedGatewayName), + [ + "policy", + "get", + ...(validatedGatewayName ? ["-g", validatedGatewayName] : []), + "--global", + "--full", + "--output", + "json", + ], "global", { gatewayName: validatedGatewayName }, ).stdout; @@ -281,12 +289,10 @@ export function inspectActiveGlobalPolicy({ /** Read one sandbox base policy through the same bounded OpenShell adapter. */ export function captureSandboxBasePolicy(sandboxName: string, gatewayName: string): string { + const validatedSandboxName = validatePolicyAuthorityName(sandboxName, "sandbox name"); const validatedGatewayName = validatePolicyAuthorityName(gatewayName, "gateway name"); return capturePolicyRead( - buildPolicyGetArgs( - validatePolicyAuthorityName(sandboxName, "sandbox name"), - validatedGatewayName, - ), + ["policy", "get", "-g", validatedGatewayName, "--base", validatedSandboxName], "sandbox", { gatewayName: validatedGatewayName }, ); @@ -348,80 +354,6 @@ export function assertOpenShellGatewayPortBinding(options: { } } -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); - try { - assertMatchingPolicyAuthority(recorded, observed); - } catch (error) { - const detail = error instanceof Error ? error.message : "policy authority is invalid"; - const observedAuthority = - observed === "nemoclaw-managed" || observed === "externally-managed" ? observed : undefined; - throw new PolicyAuthorityRefusalError(`Refusing to ${label}: ${detail}.`, observedAuthority); - } -} - -/** - * 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, - operation, - sandboxName, -}: { - readonly inspection: SandboxPolicyAuthorityInspection; - readonly requiredPolicy: JsonObject; - readonly operation: string; - readonly sandboxName?: string; -}): void { - const label = operationLabel(operation); - 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}${target}: ${detail}. Ask the external policy authority to supply the exact required entries.`, - ); - } -} - -/** Verify required entries without assigning ownership to a sandbox-scoped policy. */ -export function assertObservedPolicyRequirements({ - inspection, - requiredPolicy, - operation, - sandboxName, -}: { - readonly inspection: SandboxPolicyAuthorityInspection; - readonly requiredPolicy: JsonObject; - readonly operation: string; - readonly sandboxName?: string; -}): void { - const label = operationLabel(operation); - const target = sandboxName ? ` for sandbox ${JSON.stringify(sandboxName)}` : ""; - try { - assertPolicyRequirementContainment(inspection, requiredPolicy); - } catch (error) { - const detail = error instanceof Error ? error.message : "the policy requirement is invalid"; - throw new PolicyAuthorityRefusalError( - `Refusing to ${label}${target}: ${detail}. The verified policy must 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/onboard/sandbox-create/policy-creation-receipt.ts b/src/lib/onboard/sandbox-create/policy-creation-receipt.ts index a21103ea95d..d8da8df96b4 100644 --- a/src/lib/onboard/sandbox-create/policy-creation-receipt.ts +++ b/src/lib/onboard/sandbox-create/policy-creation-receipt.ts @@ -5,8 +5,6 @@ import fs from "node:fs"; import { isDeepStrictEqual } from "node:util"; import { - assertExternalPolicyRequirements, - assertObservedPolicyRequirements, assertOpenShellGatewayPortBinding, captureSandboxBasePolicy, inspectOpenShellSandboxPolicyReadiness, @@ -14,6 +12,10 @@ import { PolicyAuthorityRefusalError, type SandboxPolicyAuthority, } from "../../adapters/openshell/policy-authority"; +import { + assertExternalPolicyRequirements, + assertObservedPolicyRequirements, +} from "../../policy/policy-authority"; import { waitUntil } from "../../core/wait"; import type { NemoClawPolicyCreationReceipt } from "../../policy/merge"; import { normalizePendingSandboxPolicyVerification } from "../../state/registry-normalization"; diff --git a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts index 09ff21e980f..920e6d83ed4 100644 --- a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts +++ b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts @@ -63,11 +63,13 @@ import { resetGpuFlowMocks, setupGpuFlowMocks, } from "./__test-helpers__/sandbox-gpu-create-flow"; +import { formatRetainedApfSandboxRecoveryReceipt } from "./created-sandbox-failure"; import { createHermesPortableReadyCapture, createHermesPortableReadyRunner, } from "./experimental/hermes-portable-onboarding"; import { runSandboxGpuCreateFlow } from "./sandbox-gpu-create-flow"; +import { resetOnboardResumeHintForTests } from "./resume-hint"; import { fingerprintSandboxRecreateValue } from "./sandbox-recreate-transaction"; function sandboxListJson( @@ -118,7 +120,10 @@ function refuseEffectStartingWith(prefix: string): (operation: string) => void { } beforeEach(() => setupGpuFlowMocks(mocks)); -afterEach(resetGpuFlowMocks); +afterEach(() => { + resetGpuFlowMocks(); + resetOnboardResumeHintForTests(); +}); describe("created sandbox identity gate", () => { it("resumes the exact verified sandbox without issuing another create (#9833)", async () => { @@ -768,6 +773,8 @@ describe("created sandbox identity gate", () => { input.verifyCreatedSandboxBeforeEffects = vi.fn(); input.revalidateVerifiedSandboxBeforeEffect = vi.fn(); input.persistRetainedSandboxRecovery = vi.fn(() => true); + const persistRetainedApfSandboxRecovery = vi.fn(() => true); + input.persistRetainedApfSandboxRecovery = persistRetainedApfSandboxRecovery; mocks.streamSandboxCreate.mockImplementationOnce(async (_command, args) => { nonce = createAttemptNonce(args); return { @@ -799,15 +806,17 @@ describe("created sandbox identity gate", () => { await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow("process.exit:1"); const fingerprint = fingerprintSandboxRecreateValue("alpha-sandbox-id"); - expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( - expect.stringMatching( - new RegExp( - `^Create-attempt label: ${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}\\. Durable sandbox identity fingerprint: ${fingerprint}\\.`, - "u", - ), - ), - ); - expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledBefore(exit); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + createAttemptNonce: nonce, + liveIdentityFingerprint: fingerprint, + message: formatRetainedApfSandboxRecoveryReceipt({ + createAttemptNonce: nonce, + liveIdentityFingerprint: fingerprint, + }), + }); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledBefore(exit); const output = vi.mocked(console.error).mock.calls.flat().join("\n"); expect(output).toContain(`${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}`); expect(output).toContain(`Durable sandbox identity fingerprint: ${fingerprint}`); @@ -826,6 +835,8 @@ describe("created sandbox identity gate", () => { input.verifyCreatedSandboxBeforeEffects = vi.fn(); input.revalidateVerifiedSandboxBeforeEffect = vi.fn(); input.persistRetainedSandboxRecovery = vi.fn(() => true); + const persistRetainedApfSandboxRecovery = vi.fn(() => true); + input.persistRetainedApfSandboxRecovery = persistRetainedApfSandboxRecovery; mocks.streamSandboxCreate.mockImplementationOnce(async (_command, args) => { nonce = createAttemptNonce(args); return { @@ -854,14 +865,16 @@ describe("created sandbox identity gate", () => { await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow("process.exit:1"); - expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( - expect.stringMatching( - new RegExp( - `^Create-attempt label: ${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}\\..*Recovery is blocked until an OpenShell administrator resolves the create-attempt label`, - "u", - ), - ), - ); + expect(persistRetainedApfSandboxRecovery).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + createAttemptNonce: nonce, + liveIdentityFingerprint: null, + message: formatRetainedApfSandboxRecoveryReceipt({ + createAttemptNonce: nonce, + liveIdentityFingerprint: null, + }), + }); const output = vi.mocked(console.error).mock.calls.flat().join("\n"); expect(output).toContain(`${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}`); expect(output).toContain("Recovery is blocked"); diff --git a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts index 0c1c8234a73..9baa6d1701b 100644 --- a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts +++ b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts @@ -9,6 +9,7 @@ import { parseOpenShellSandboxId, resolveCreatedOpenShellSandboxId, resolveOpenShellSandboxId, + settleCreatedOpenShellSandboxId, } from "../adapters/openshell/sandbox-identity"; import { printSandboxCreateRecoveryHints } from "../build-context"; import { streamSandboxCreate } from "../sandbox/create-stream"; @@ -1007,7 +1008,7 @@ export function createSandboxGpuCreateAttemptRunner( ); console.error(" Verify the sandbox identity before manual cleanup."); } - process.exit(createResult.status === 0 ? 1 : createResult.status); + process.exit(createResult?.status === 0 ? 1 : (createResult?.status ?? 1)); } if (input.sandboxGpuConfig.sandboxGpuEnabled) { revalidatePostCreateEffect(`verify GPU access for sandbox '${input.sandboxName}'`); From 6a049372f697cab24ac416e225d31f12f8075233 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Thu, 27 Aug 2026 11:48:47 -0700 Subject: [PATCH 10/11] test(policy): preserve structured capture failures Signed-off-by: Apurv Kumaria --- test/helpers/onboard-script-mocks.cjs | 35 ++++++++++++++++--- .../onboard-fresh-create-identity.test.ts | 12 +++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/test/helpers/onboard-script-mocks.cjs b/test/helpers/onboard-script-mocks.cjs index 400acef1ae7..458aad54dbd 100644 --- a/test/helpers/onboard-script-mocks.cjs +++ b/test/helpers/onboard-script-mocks.cjs @@ -756,13 +756,38 @@ function mockStructuredOpenShellCaptureFromRunner() { ...(options.includeStreams === true ? { stdout: "", stderr } : {}), }; } + const isStructuredPolicyRead = + args[0] === "policy" && (args[1] === "get" || args[1] === "list"); + const structuredPolicyRead = isStructuredPolicyRead + ? runner.runCaptureEx([binary, ...args], { + ...options, + ignoreError: true, + includeStderr: false, + }) + : null; const stdout = String( - runner.runCapture([binary, ...args], { - ...options, - ignoreError: true, - includeStderr: false, - }) || "", + structuredPolicyRead?.stdout ?? + runner.runCapture([binary, ...args], { + ...options, + ignoreError: true, + includeStderr: false, + }) ?? + "", ); + const stderr = String(structuredPolicyRead?.stderr ?? ""); + if (structuredPolicyRead) { + const error = structuredPolicyRead.timedOut + ? Object.assign(new Error("OpenShell fixture capture timed out"), { code: "ETIMEDOUT" }) + : undefined; + if (error || structuredPolicyRead.exitCode !== 0 || stdout.trim().length > 0) { + return { + status: structuredPolicyRead.exitCode, + output: options.includeStderr === true ? `${stdout}${stderr}`.trim() : stdout.trim(), + ...(options.includeStreams === true ? { stdout, stderr } : {}), + ...(error ? { error } : {}), + }; + } + } if (isCreatedSandboxPolicyRead && stdout.trim().length === 0) { const fallback = JSON.stringify({ scope: "sandbox", diff --git a/test/onboarding/onboard-fresh-create-identity.test.ts b/test/onboarding/onboard-fresh-create-identity.test.ts index d1006a9fab0..c26868a06b6 100644 --- a/test/onboarding/onboard-fresh-create-identity.test.ts +++ b/test/onboarding/onboard-fresh-create-identity.test.ts @@ -131,6 +131,18 @@ runner.run = (command, opts = {}) => { } if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; return ""; +}; +runner.runCaptureEx = (command) => { + const cmd = _n(command); + if (cmd.endsWith("policy get -g nemoclaw --full --output json my-assistant")) { + return { + stdout: JSON.stringify({ scope: "sandbox", sandbox: "my-assistant", status: "effective", policy_source: "sandbox", hash: "fixture-policy", active_version: 1, policy: effectivePolicy }), + stderr: "", + exitCode: 0, + timedOut: false, + }; + } + return { stdout: "", stderr: "", exitCode: 0, timedOut: false }; }; const session = onboardSession.createSession({ sessionId: "session-owner", From 546519369f7974927d991969426030400e4c8c78 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 27 Aug 2026 12:31:54 -0700 Subject: [PATCH 11/11] test(policy): cover allowed adapter imports Signed-off-by: Charan Jagwani --- test/repository/layer-import-boundaries.test.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/test/repository/layer-import-boundaries.test.ts b/test/repository/layer-import-boundaries.test.ts index ec552b95408..eaf727319b7 100644 --- a/test/repository/layer-import-boundaries.test.ts +++ b/test/repository/layer-import-boundaries.test.ts @@ -82,14 +82,24 @@ describe("CLI layer import boundaries (#6245)", () => { expect(violations).toEqual( expect.arrayContaining([ expect.objectContaining({ - detail: - "OpenShell adapters must not import policy module src/lib/policy/commands.ts", + detail: "OpenShell adapters must not import policy module src/lib/policy/commands.ts", rule: "openshell-adapters-no-policy", }), ]), ); }); + it("allows OpenShell adapters to import neighboring adapter modules (#9833)", () => { + const violations = scanFixture( + fixturePath("src/lib/adapters/openshell", "runtime"), + 'import { captureResolvedOpenshell } from "./runtime";\nexport { captureResolvedOpenshell };\n', + ); + + expect(violations).not.toEqual( + expect.arrayContaining([expect.objectContaining({ rule: "openshell-adapters-no-policy" })]), + ); + }); + it("blocks bare fs imports in messaging manifests (#6245)", () => { const violations = scanFixture( fixturePath("src/lib/messaging/manifest", "bare-fs"),