diff --git a/docs/reference/configure-runtime-identity.mdx b/docs/reference/configure-runtime-identity.mdx index 1335af9c298..66a3c125053 100644 --- a/docs/reference/configure-runtime-identity.mdx +++ b/docs/reference/configure-runtime-identity.mdx @@ -223,13 +223,23 @@ The runner validates an existing provider's non-secret binding to report a preci It never reuses that provider because OpenShell does not expose a secret-safe snapshot that rollback could restore. Only an absent provider proceeds to profile import. -When the profile is already registered, the runner first requires an export match. -It then creates the provider, configures gateway-managed OAuth refresh, and performs the initial token rotation. +After a fresh import or an already-registered result, the runner exports the gateway profile and compares it with the validated local profile. +An export failure, timeout, or mismatch stops apply before provider creation. +The runner preserves a mismatched gateway profile because another gateway client may own it. +Ask the gateway operator to inspect the profile before retrying. +After a match, the runner creates the provider. +After provider creation, the runner tries to export the profile before it configures credential refresh. +After attachment, it tries another export. +If either export succeeds with a different definition, the runner warns that the gateway catalog changed. +NemoClaw cannot confirm which definition OpenShell used at bind time. +If either export fails or times out, the runner warns that verification did not complete and asks the gateway operator to inspect the profile. +These warnings contain no credential values and do not roll back setup. Before attachment, the runner creates or reuses the configured inference provider. For a reused sandbox and provider, it preserves the live route only when the provider, model, and requested timeout match the blueprint. An absent or different route must pass `openshell inference set`. The runner attaches the runtime identity and applies policy additions only after OpenShell confirms the route. +It performs the initial token rotation after attachment. Each successful apply creates and owns the runtime identity provider whose refresh state it mutates. The persisted plan records ownership of the runtime identity provider, sandbox attachment, inference provider, and sandbox. diff --git a/nemoclaw/src/blueprint/runner-identity.test.ts b/nemoclaw/src/blueprint/runner-identity.test.ts index 880c5f4a48e..3cfd5c018ba 100644 --- a/nemoclaw/src/blueprint/runner-identity.test.ts +++ b/nemoclaw/src/blueprint/runner-identity.test.ts @@ -76,6 +76,7 @@ const { actionApply, actionPlan, actionRollback, actionStatus, loadBlueprint } = const matchingProvider = MATCHING_RUNTIME_PROVIDER_LISTING; const matchingInferenceProvider = MATCHING_INFERENCE_PROVIDER_LISTING; const matchingInferenceRoute = MATCHING_INFERENCE_ROUTE_LISTING; +const runtimeIdentityProfilePath = "/blueprint/provider-profiles/okta-runtime-v1.yaml"; const success = successResult(); const providersV2Enabled = providersV2EnabledResult(); @@ -86,8 +87,16 @@ const identityPolicyAdditions = { }, }; +function runtimeIdentityProfileExport(args: readonly string[]) { + return args.join(" ") === "provider profile export okta-runtime-v1 --output yaml" + ? { exitCode: 0, stdout: store.get(runtimeIdentityProfilePath)?.content ?? "", stderr: "" } + : null; +} + function responseQueue( - overrides: Array<[string, Array<{ exitCode?: number; stdout: string; stderr: string }>]>, + overrides: Array< + [string, Array<{ exitCode?: number; stdout: string; stderr: string; timedOut?: boolean }>] + >, ) { const responses = new Map([ ["sandbox get test-sandbox", [failureResult("sandbox not found")]], @@ -105,7 +114,11 @@ function responseQueue( ]); mockExeca.mockImplementation(async (_command: string, args: string[]) => { const command = args.join(" "); - const fallback = responses.get(command)?.shift() ?? fallbacks.get(command) ?? success; + const fallback = + responses.get(command)?.shift() ?? + fallbacks.get(command) ?? + runtimeIdentityProfileExport(args) ?? + success; return fallback.exitCode === undefined ? fallback : resultWithBlueprintPolicy(args, { @@ -155,8 +168,9 @@ function installPolicyIdentityResponses(policyWriteFailure?: string): void { runtimeProviderListing: matchingProvider, policyWriteFailure, }); - mockExeca.mockImplementation(async (_command: string, args: string[]) => - identityPolicyResult(args), + mockExeca.mockImplementation( + async (_command: string, args: string[]) => + runtimeIdentityProfileExport(args) ?? identityPolicyResult(args), ); } @@ -170,12 +184,13 @@ describe("blueprint identity wrapper", () => { mockExeca.mockImplementation(async (_command: string, args: string[]) => resultWithBlueprintPolicy( args, - args.join(" ") === "settings get --global --json" ? providersV2Enabled : success, + runtimeIdentityProfileExport(args) ?? + (args.join(" ") === "settings get --global --json" ? providersV2Enabled : success), ), ); process.env.NEMOCLAW_BLUEPRINT_PATH = "/blueprint"; store.set("/blueprint", { type: "dir" }); - store.set("/blueprint/provider-profiles/okta-runtime-v1.yaml", { + store.set(runtimeIdentityProfilePath, { type: "file", content: [ "id: okta-runtime-v1", @@ -350,6 +365,31 @@ describe("blueprint identity wrapper", () => { ); }); + it("bounds a timed-out profile export before runtime provider creation", async () => { + process.env.OKTA_CLIENT_ID = "client-id"; + process.env.OKTA_REFRESH_TOKEN = "refresh-secret"; + process.env.OKTA_CLIENT_SECRET = "client-secret"; + responseQueue([ + ["provider get acme-okta-runtime", [failureResult("provider not found")]], + [ + "provider profile export okta-runtime-v1 --output yaml", + [{ stdout: "", stderr: "", timedOut: true }], + ], + ]); + + await expect(actionApply("default", blueprint({ identity: oktaIdentity() }))).rejects.toThrow( + /profile 'okta-runtime-v1'.*OpenShell command timed out after 30 seconds/, + ); + expect(mockExeca).toHaveBeenCalledWith( + "openshell", + ["provider", "profile", "export", "okta-runtime-v1", "--output", "yaml"], + expect.objectContaining({ timeout: 30_000, reject: false }), + ); + expect(mockExeca.mock.calls.map(([, args]) => (args ?? []).join(" "))).not.toContain( + "provider create --name acme-okta-runtime --type okta-runtime-v1 --runtime-credentials", + ); + }); + it("applies policy before inference and runtime credential mutations", async () => { process.env.OKTA_CLIENT_ID = "client-id"; process.env.OKTA_REFRESH_TOKEN = "refresh-secret"; @@ -1108,6 +1148,71 @@ describe("blueprint identity wrapper", () => { expect(store.get(`/fakehome/.nemoclaw/state/runs/${plan.run_id}/rolled_back`)).toBeUndefined(); }); + it.each([true, false])( + "records attachment ownership before the advisory profile export when created: %s", + async (created) => { + process.env.OKTA_CLIENT_ID = "client-id"; + process.env.OKTA_REFRESH_TOKEN = "refresh-secret"; + process.env.OKTA_CLIENT_SECRET = "client-secret"; + responseQueue([ + [ + "provider get acme-okta-runtime", + [ + failureResult("provider not found"), + ...Array.from({ length: 5 }, () => ({ + exitCode: 0, + stdout: matchingProvider, + stderr: "", + })), + ], + ], + [ + "sandbox provider attach test-sandbox acme-okta-runtime", + [created ? success : failureResult("already attached")], + ], + ]); + const originalRun = mockExeca.getMockImplementation()!; + let attachmentSeen = false; + let signalExport!: () => void; + let releaseExport!: () => void; + const exportStarted = new Promise((resolve) => { + signalExport = resolve; + }); + const exportReleased = new Promise((resolve) => { + releaseExport = resolve; + }); + const pauseExport = () => { + signalExport(); + return exportReleased; + }; + mockExeca.mockImplementation(async (command: string, args: string[]) => { + const commandText = args.join(" "); + attachmentSeen ||= commandText === "sandbox provider attach test-sandbox acme-okta-runtime"; + await (attachmentSeen && + commandText === "provider profile export okta-runtime-v1 --output yaml" + ? pauseExport() + : Promise.resolve()); + return originalRun(command, args); + }); + + const apply = actionApply("default", blueprint({ identity: oktaIdentity() })); + try { + await exportStarted; + const planEntry = [...store.entries()].find(([path]) => path.endsWith("/plan.json"))?.[1]; + expect(planEntry?.content).toBeDefined(); + expect(JSON.parse(planEntry!.content!).identity.attachment_created).toBe(created); + expect( + mockExeca.mock.calls.some(([, args]) => + (args as string[]).join(" ").startsWith("provider refresh rotate "), + ), + ).toBe(false); + } finally { + releaseExport(); + } + await apply; + }, + ); + it.each([true, false])( "preserves runtime identity when other resources are owned: %s (#9833)", async (ownsOtherResources) => { diff --git a/nemoclaw/src/blueprint/runner.ts b/nemoclaw/src/blueprint/runner.ts index c7286d459dc..d3683b9dd0a 100644 --- a/nemoclaw/src/blueprint/runner.ts +++ b/nemoclaw/src/blueprint/runner.ts @@ -1216,11 +1216,14 @@ async function runRuntimeIdentityCommand( stderr: "pipe", env: buildBlueprintOpenShellEnv(gateway, options?.env), extendEnv: false, + ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}), }); return { exitCode: result.exitCode ?? 1, stdout: result.stdout, - stderr: result.stderr, + stderr: result.timedOut + ? `OpenShell command timed out after ${(options?.timeoutMs ?? 0) / 1_000} seconds` + : result.stderr, }; } @@ -1228,6 +1231,7 @@ function runtimeIdentityCommandDeps(gateway: string): RuntimeIdentityCommandDeps return { run: (args, options) => runRuntimeIdentityCommand(args, options, gateway), formatError: boundedCommandError, + warn: (message) => log(`Warning: ${message}`), }; } @@ -2014,20 +2018,7 @@ export async function actionApply( } if (runtimeIdentityReceipt) { - const attachmentCreated = await attachRuntimeIdentity( - runtimeIdentityReceipt, - sandboxName, - identityDeps, - ); - runtimeIdentityReceipt = { - ...runtimeIdentityReceipt, - attachment_created: attachmentCreated, - }; - try { - persistRunPlan(); - } catch (error) { - throw error; - } + await attachRuntimeIdentity(runtimeIdentityReceipt, sandboxName, identityDeps); await mintRuntimeIdentityCredential(runtimeIdentityReceipt, identityDeps); } diff --git a/nemoclaw/src/blueprint/runtime-identity.test.ts b/nemoclaw/src/blueprint/runtime-identity.test.ts index 87c42b7975a..ea7d00e18f4 100644 --- a/nemoclaw/src/blueprint/runtime-identity.test.ts +++ b/nemoclaw/src/blueprint/runtime-identity.test.ts @@ -116,6 +116,16 @@ const profileDocument = [ "inference_capable: false", "", ].join("\n"); +const gatewayExportDocument = profileDocument + .replace( + "id: okta-runtime-v1", + "id: okta-runtime-v1\nresource_version: 1\nsource: user\nscope: workspace", + ) + .replace(" header_name: authorization", " header_name: authorization\n query_param: ''") + .replace( + " - name: client_id\n required: true", + " - name: client_id\n required: true\n secret: false", + ); const entraProfileDocument = readFileSync( new URL("../../../nemoclaw-blueprint/provider-profiles/entra-runtime-v1.yaml", import.meta.url), "utf8", @@ -158,7 +168,7 @@ function commandKey(args: string[]): string { describe("runtime identity contract", () => { let root: string; let profilePath: string; - let calls: Array<{ args: string[]; env?: Record }>; + let calls: Array<{ args: string[]; env?: Record; timeoutMs?: number }>; let responses: Map; let environment: NodeJS.ProcessEnv; let deps: RuntimeIdentityDeps; @@ -166,6 +176,7 @@ describe("runtime identity contract", () => { let persistedReceipts: RuntimeIdentityReceipt[]; let importedProfilePaths: string[]; let importedProfileSources: string[]; + let warnings: string[]; beforeEach(() => { root = mkdtempSync(join(tmpdir(), "nemoclaw-runtime-identity-")); @@ -180,6 +191,7 @@ describe("runtime identity contract", () => { persistedReceipts = []; importedProfilePaths = []; importedProfileSources = []; + warnings = []; environment = { OKTA_CLIENT_ID: "client-id", OKTA_REFRESH_TOKEN: "refresh-secret", @@ -187,7 +199,7 @@ describe("runtime identity contract", () => { }; deps = { run: async (args, options) => { - calls.push({ args, env: options?.env }); + calls.push({ args, env: options?.env, timeoutMs: options?.timeoutMs }); const captureCommand: Partial void>> = { "provider profile import --file": () => { importedProfilePaths.push(args[5]); @@ -195,13 +207,19 @@ describe("runtime identity contract", () => { }, }; captureCommand[commandKey(args)]?.(); - return responses.get(commandKey(args))?.shift() ?? success; + return ( + responses.get(commandKey(args))?.shift() ?? + (commandKey(args).startsWith("provider profile export ") + ? { exitCode: 0, stdout: importedProfileSources.at(-1) ?? profileDocument, stderr: "" } + : success) + ); }, formatError: (output, secretValues = []) => secretValues.reduce( (redacted, secret) => redacted.replaceAll(secret, secret.length > 0 ? "" : ""), output, ), + warn: (message) => warnings.push(message), validateEndpointUrl: async (url) => { validatedDestinations.push(url); return { dnsResolved: false }; @@ -326,13 +344,15 @@ describe("runtime identity contract", () => { it("creates and configures a new provider without putting secrets in argv", async () => { responses.set("provider get acme-okta-runtime", [missingProvider]); - await expect(prepareRuntimeIdentity(config, deps)).resolves.toEqual(createdReceipt); + await expect(prepareRuntimeIdentity(config, deps)).resolves.toMatchObject(createdReceipt); expect(calls.map(({ args }) => commandKey(args))).toEqual([ "settings get --global --json", "provider get acme-okta-runtime", "provider profile import --file", + "provider profile export okta-runtime-v1 --output yaml", "provider create --name acme-okta-runtime --type okta-runtime-v1 --runtime-credentials", + "provider profile export okta-runtime-v1 --output yaml", "provider refresh configure acme-okta-runtime --credential-key OKTA_ACCESS_TOKEN --strategy oauth2-refresh-token --material client_id=client-id --secret-material-env refresh_token=OKTA_REFRESH_TOKEN --secret-material-env client_secret=OKTA_CLIENT_SECRET", ]); expect(calls.flatMap(({ args }) => args)).not.toContain("refresh-secret"); @@ -392,7 +412,163 @@ describe("runtime identity contract", () => { { exitCode: 0, stdout: profileDocument, stderr: "" }, ]); - await expect(prepareRuntimeIdentity(config, deps)).resolves.toEqual(createdReceipt); + await expect(prepareRuntimeIdentity(config, deps)).resolves.toMatchObject(createdReceipt); + }); + + it("accepts OpenShell's catalog metadata and explicit default fields without a false post-mutation warning", async () => { + responses.set("provider get acme-okta-runtime", [missingProvider]); + responses.set("provider profile export okta-runtime-v1 --output yaml", [ + { exitCode: 0, stdout: gatewayExportDocument, stderr: "" }, + { exitCode: 0, stdout: gatewayExportDocument, stderr: "" }, + ]); + + await expect(prepareRuntimeIdentity(config, deps)).resolves.toMatchObject(createdReceipt); + expect(warnings).toEqual([]); + expect(persistedReceipts).toHaveLength(1); + }); + + it.each([ + gatewayExportDocument.replace("source: user", "source: builtin"), + gatewayExportDocument.replace("scope: workspace", "scope: platform"), + gatewayExportDocument.replace("query_param: ''", "query_param: credential"), + gatewayExportDocument.replace("secret: false", "secret: true"), + gatewayExportDocument.replace("resource_version: 1", "resource_version: 0"), + ])("rejects incompatible gateway export metadata or credential fields", async (exported) => { + responses.set("provider get acme-okta-runtime", [missingProvider]); + responses.set("provider profile export okta-runtime-v1 --output yaml", [ + { exitCode: 0, stdout: exported, stderr: "" }, + ]); + + await expect(prepareRuntimeIdentity(config, deps)).rejects.toThrow(/incompatible binding/); + expect(calls.map(({ args }) => commandKey(args))).not.toContain( + "provider create --name acme-okta-runtime --type okta-runtime-v1 --runtime-credentials", + ); + expect(persistedReceipts).toEqual([]); + }); + + it("warns after provider creation if the profile changed without changing the result", async () => { + responses.set("provider get acme-okta-runtime", [missingProvider]); + responses.set("provider profile export okta-runtime-v1 --output yaml", [ + { exitCode: 0, stdout: profileDocument, stderr: "" }, + { + exitCode: 0, + stdout: profileDocument.replace("Okta Runtime Credentials v1", "Changed profile"), + stderr: "", + }, + ]); + + await expect(prepareRuntimeIdentity(config, deps)).resolves.toMatchObject(createdReceipt); + expect(warnings).toEqual([ + expect.stringContaining("cannot confirm which definition was used at bind time"), + ]); + expect(warnings[0]).not.toMatch(/refresh-secret|client-secret|client-id|atomic/iu); + expect(persistedReceipts).toHaveLength(1); + expect(calls.map(({ args }) => commandKey(args))).not.toContain( + "provider delete acme-okta-runtime", + ); + }); + + it.each([ + ["fails", "export denied refresh-secret"], + ["times out", "OpenShell command timed out after 30 seconds refresh-secret"], + ])("warns and continues provider setup if the post-creation export %s", async (_case, error) => { + responses.set("provider get acme-okta-runtime", [missingProvider]); + responses.set("provider profile export okta-runtime-v1 --output yaml", [ + { exitCode: 0, stdout: profileDocument, stderr: "" }, + { exitCode: 1, stdout: "", stderr: error }, + ]); + + await expect(prepareRuntimeIdentity(config, deps)).resolves.toMatchObject(createdReceipt); + expect(warnings).toEqual([ + expect.stringContaining( + "profile 'okta-runtime-v1' could not be verified after a provider change", + ), + ]); + expect(warnings[0]).toContain("Ask the gateway operator to inspect the profile"); + expect(warnings[0]).not.toMatch( + /refresh-secret|client-secret|client-id|export denied|atomic/iu, + ); + }); + + it("warns and continues provider setup if the post-creation export throws", async () => { + responses.set("provider get acme-okta-runtime", [missingProvider]); + const run = deps.run; + let exportCount = 0; + deps.run = (args, options) => + commandKey(args) === "provider profile export okta-runtime-v1 --output yaml" && + ++exportCount === 2 + ? Promise.reject(new Error("refresh-secret")) + : run(args, options); + + await expect(prepareRuntimeIdentity(config, deps)).resolves.toMatchObject(createdReceipt); + expect(warnings).toEqual([ + expect.stringContaining( + "profile 'okta-runtime-v1' could not be verified after a provider change", + ), + ]); + expect(warnings[0]).not.toContain("refresh-secret"); + }); + + it("rejects a fresh import that exports a different profile before provider creation", async () => { + responses.set("provider get acme-okta-runtime", [missingProvider]); + responses.set("provider profile export okta-runtime-v1 --output yaml", [ + { + exitCode: 0, + stdout: profileDocument.replace("OKTA_ACCESS_TOKEN", "DIFFERENT_TOKEN"), + stderr: "", + }, + ]); + + await expect(prepareRuntimeIdentity(config, deps)).rejects.toThrow( + /profile 'okta-runtime-v1' has an incompatible binding/, + ); + expect(calls.map(({ args }) => commandKey(args))).toEqual([ + "settings get --global --json", + "provider get acme-okta-runtime", + "provider profile import --file", + "provider profile export okta-runtime-v1 --output yaml", + ]); + expect(persistedReceipts).toEqual([]); + }); + + it("stops before provider creation when a fresh import cannot be verified", async () => { + responses.set("provider get acme-okta-runtime", [missingProvider]); + responses.set("provider profile export okta-runtime-v1 --output yaml", [ + { + exitCode: 1, + stdout: "export denied for client-id", + stderr: "refresh-secret client-secret", + }, + ]); + + const error = await prepareRuntimeIdentity(config, deps).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain("export denied for "); + expect((error as Error).message).not.toMatch(/client-id|refresh-secret|client-secret/u); + expect(calls.map(({ args }) => commandKey(args))).not.toContain( + "provider create --name acme-okta-runtime --type okta-runtime-v1 --runtime-credentials", + ); + expect(persistedReceipts).toEqual([]); + }); + + it("bounds profile export and stops before provider creation when it times out", async () => { + responses.set("provider get acme-okta-runtime", [missingProvider]); + responses.set("provider profile export okta-runtime-v1 --output yaml", [ + { exitCode: 1, stdout: "", stderr: "OpenShell command timed out after 30 seconds" }, + ]); + + await expect(prepareRuntimeIdentity(config, deps)).rejects.toThrow( + /profile 'okta-runtime-v1':\s+OpenShell command timed out after 30 seconds/, + ); + expect( + calls.find( + ({ args }) => commandKey(args) === "provider profile export okta-runtime-v1 --output yaml", + )?.timeoutMs, + ).toBe(30_000); + expect(calls.map(({ args }) => commandKey(args))).not.toContain( + "provider create --name acme-okta-runtime --type okta-runtime-v1 --runtime-credentials", + ); + expect(persistedReceipts).toEqual([]); }); it("rejects an incompatible existing profile", async () => { @@ -409,9 +585,13 @@ describe("runtime identity contract", () => { ]); await expect(prepareRuntimeIdentity(config, deps)).rejects.toThrow( - /profile 'okta-runtime-v1' exists with an incompatible binding/, + /profile 'okta-runtime-v1' has an incompatible binding/, ); expect(calls.map(({ args }) => commandKey(args))).toContain("provider get acme-okta-runtime"); + expect(calls.map(({ args }) => commandKey(args))).not.toContain( + "provider create --name acme-okta-runtime --type okta-runtime-v1 --runtime-credentials", + ); + expect(persistedReceipts).toEqual([]); }); it("reports a failure to export an existing profile", async () => { @@ -424,6 +604,10 @@ describe("runtime identity contract", () => { ]); await expect(prepareRuntimeIdentity(config, deps)).rejects.toThrow(/export denied/); + expect(calls.map(({ args }) => commandKey(args))).not.toContain( + "provider create --name acme-okta-runtime --type okta-runtime-v1 --runtime-credentials", + ); + expect(persistedReceipts).toEqual([]); }); it.each([ @@ -491,7 +675,7 @@ describe("runtime identity contract", () => { return { dnsResolved: true }; }; - await expect(prepareRuntimeIdentity(config, deps)).resolves.toEqual(createdReceipt); + await expect(prepareRuntimeIdentity(config, deps)).resolves.toMatchObject(createdReceipt); expect(validatedDestinations).toEqual([ "https://example.okta.com/oauth2/default/v1/token", "https://api.example.okta.com/", @@ -748,7 +932,7 @@ describe("runtime identity contract", () => { const configWithoutSecret = { ...config, client_secret_env: undefined }; responses.set("provider get acme-okta-runtime", [missingProvider]); - await expect(prepareRuntimeIdentity(configWithoutSecret, deps)).resolves.toEqual( + await expect(prepareRuntimeIdentity(configWithoutSecret, deps)).resolves.toMatchObject( createdReceipt, ); expect(calls.at(-1)?.env).toEqual({ OKTA_REFRESH_TOKEN: "refresh-secret" }); @@ -765,7 +949,7 @@ describe("runtime identity contract", () => { return { dnsResolved: false }; }; - await expect(prepareRuntimeIdentity(config, deps)).resolves.toEqual(createdReceipt); + await expect(prepareRuntimeIdentity(config, deps)).resolves.toMatchObject(createdReceipt); expect(readFileSync(profilePath, "utf8")).toBe(replacement); expect(importedProfileSources).toEqual([profileDocument]); @@ -915,7 +1099,7 @@ describe("runtime identity contract", () => { await expect(prepareRuntimeIdentity(config, deps)).rejects.toThrow( /configure failed[\s\S]*cleanup failed[\s\S]*delete failed/, ); - expect(persistedReceipts).toEqual([createdReceipt]); + expect(persistedReceipts).toEqual([expect.objectContaining(createdReceipt)]); }); it("does not delete a newly created provider when its binding changes before compensation", async () => { @@ -972,6 +1156,46 @@ describe("runtime identity contract", () => { ]); }); + it("warns after attachment if the verified profile changed without changing the attach result", async () => { + responses.set("settings get --global --json", [providersV2Enabled, providersV2Enabled]); + responses.set("provider get acme-okta-runtime", [missingProvider, matchingProviderResult]); + responses.set("provider profile export okta-runtime-v1 --output yaml", [ + { exitCode: 0, stdout: profileDocument, stderr: "" }, + { exitCode: 0, stdout: profileDocument, stderr: "" }, + { + exitCode: 0, + stdout: profileDocument.replace("Okta Runtime Credentials v1", "Changed profile"), + stderr: "", + }, + ]); + + const receipt = await prepareRuntimeIdentity(config, deps); + await expect(attachRuntimeIdentity(receipt, "sandbox", deps)).resolves.toBe(true); + expect(warnings).toEqual([ + expect.stringContaining("cannot confirm which definition was used at bind time"), + ]); + expect(warnings[0]).not.toMatch(/refresh-secret|client-secret|client-id|atomic/iu); + }); + + it("warns after attachment if the profile export fails without changing the attach result", async () => { + responses.set("settings get --global --json", [providersV2Enabled, providersV2Enabled]); + responses.set("provider get acme-okta-runtime", [missingProvider, matchingProviderResult]); + responses.set("provider profile export okta-runtime-v1 --output yaml", [ + { exitCode: 0, stdout: profileDocument, stderr: "" }, + { exitCode: 0, stdout: profileDocument, stderr: "" }, + { exitCode: 1, stdout: "", stderr: "export denied refresh-secret" }, + ]); + + const receipt = await prepareRuntimeIdentity(config, deps); + await expect(attachRuntimeIdentity(receipt, "sandbox", deps)).resolves.toBe(true); + expect(warnings).toEqual([ + expect.stringContaining( + "profile 'okta-runtime-v1' could not be verified after a provider change", + ), + ]); + expect(warnings[0]).not.toContain("refresh-secret"); + }); + it("attaches a provider whose refresh is configured before its first mint", async () => { responses.set("provider get acme-okta-runtime", [configuredProviderResult]); responses.set("provider refresh status acme-okta-runtime --credential-key OKTA_ACCESS_TOKEN", [ diff --git a/nemoclaw/src/blueprint/runtime-identity.ts b/nemoclaw/src/blueprint/runtime-identity.ts index 9c5ebb6c9df..6b2c625977b 100644 --- a/nemoclaw/src/blueprint/runtime-identity.ts +++ b/nemoclaw/src/blueprint/runtime-identity.ts @@ -10,6 +10,7 @@ import { statSync, writeFileSync, } from "node:fs"; +import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { isAbsolute, join, relative, resolve, sep } from "node:path"; import { isDeepStrictEqual } from "node:util"; @@ -100,6 +101,7 @@ export interface RuntimeIdentityPlan { export interface RuntimeIdentityReceipt extends RuntimeIdentityPlan { provider_created: boolean; attachment_created: boolean; + verified_profile_sha256?: string; } export interface RuntimeIdentityCommandResult { @@ -110,6 +112,7 @@ export interface RuntimeIdentityCommandResult { export interface RuntimeIdentityCommandOptions { env?: Record; + timeoutMs?: number; } export interface RuntimeIdentityCommandDeps { @@ -118,6 +121,7 @@ export interface RuntimeIdentityCommandDeps { options?: RuntimeIdentityCommandOptions, ): Promise; formatError(output: string, secretValues?: readonly string[]): string; + warn(message: string): void; blueprintPath?: string; env?: NodeJS.ProcessEnv; } @@ -392,9 +396,10 @@ function parseRuntimeIdentityEndpoint( function parseRuntimeIdentityProfile( content: string, - config: RuntimeIdentityConfig, + config: Pick, policy: RuntimeIdentityProfilePolicy, label: string, + gatewayExport = false, ): ParsedRuntimeIdentityProfile { if (Buffer.byteLength(content, "utf8") > MAX_PROFILE_BYTES) { throw new Error(`${label} exceeds the ${MAX_PROFILE_BYTES}-byte limit`); @@ -408,6 +413,42 @@ function parseRuntimeIdentityProfile( if (!isPlainObject(parsed) || parsed.id !== config.provider_type) { throw new Error(`${label} must declare id '${config.provider_type}'`); } + if (gatewayExport) { + // OpenShell's export includes catalog provenance and explicit empty/default + // credential fields. Check those values before comparing the binding. + const hasCatalogMetadata = ["resource_version", "source", "scope"].some((key) => key in parsed); + if (hasCatalogMetadata) { + if ( + !Number.isSafeInteger(parsed.resource_version) || + (parsed.resource_version as number) < 1 || + parsed.source !== "user" || + parsed.scope !== "workspace" + ) { + throw new Error(`${label} has an unsupported catalog origin`); + } + delete parsed.resource_version; + delete parsed.source; + delete parsed.scope; + } + if (Array.isArray(parsed.credentials)) { + for (const credential of parsed.credentials) { + if (!isPlainObject(credential)) continue; + if (credential.query_param === "") delete credential.query_param; + if (!isPlainObject(credential.refresh) || !Array.isArray(credential.refresh.material)) { + continue; + } + for (const material of credential.refresh.material) { + if ( + isPlainObject(material) && + material.name === "client_id" && + material.secret === false + ) { + delete material.secret; + } + } + } + } + } if (!hasOnlyKeys(parsed, RUNTIME_IDENTITY_PROFILE_KEYS)) { throw new Error(`${label} contains unsupported top-level fields`); } @@ -630,6 +671,7 @@ export function isRuntimeIdentityReceipt(value: unknown): value is RuntimeIdenti "credential_key", "provider_created", "attachment_created", + "verified_profile_sha256", ]) && typeof value.provider_type === "string" && PROVIDER_TYPE_PATTERN.test(value.provider_type) && @@ -638,7 +680,10 @@ export function isRuntimeIdentityReceipt(value: unknown): value is RuntimeIdenti typeof value.credential_key === "string" && ENV_NAME_PATTERN.test(value.credential_key) && typeof value.provider_created === "boolean" && - typeof value.attachment_created === "boolean" + typeof value.attachment_created === "boolean" && + (value.verified_profile_sha256 === undefined || + (typeof value.verified_profile_sha256 === "string" && + /^[a-f0-9]{64}$/u.test(value.verified_profile_sha256))) ); } @@ -650,6 +695,63 @@ export function buildRuntimeIdentityPlan(config: RuntimeIdentityConfig): Runtime }; } +function profileDigest(document: Record): string { + return createHash("sha256").update(JSON.stringify(document)).digest("hex"); +} + +function warnWithoutChangingResult(deps: RuntimeIdentityCommandDeps, message: string): void { + try { + deps.warn(message); + } catch { + // A warning callback must not change the result of a completed mutation. + } +} + +async function warnIfProfileChanged( + receipt: RuntimeIdentityReceipt, + policy: RuntimeIdentityProfilePolicy, + deps: RuntimeIdentityCommandDeps, +): Promise { + if (!receipt.verified_profile_sha256) return; + let result: RuntimeIdentityCommandResult | undefined; + try { + result = await deps.run( + ["openshell", "provider", "profile", "export", receipt.provider_type, "--output", "yaml"], + { timeoutMs: 30_000 }, + ); + } catch { + // The export may throw, including on timeout. Report only the outcome, never command output. + } + if (result?.exitCode !== 0) { + warnWithoutChangingResult( + deps, + `Runtime identity provider profile '${receipt.provider_type}' could not be verified after a provider change. ` + + "Ask the gateway operator to inspect the profile. NemoClaw continues setup without post-change verification.", + ); + return; + } + let matches = false; + try { + const profile = parseRuntimeIdentityProfile( + result.stdout, + receipt, + policy, + "Gateway profile", + true, + ); + matches = profileDigest(profile.document) === receipt.verified_profile_sha256; + } catch { + // A readable but incompatible profile also differs from the verified definition. + } + if (!matches) { + warnWithoutChangingResult( + deps, + `Runtime identity provider profile '${receipt.provider_type}' changed in the gateway catalog. ` + + "NemoClaw cannot confirm which definition was used at bind time. Ask the gateway operator to inspect the profile.", + ); + } +} + function commandOutput(result: RuntimeIdentityCommandResult): string { return `${result.stdout}\n${result.stderr}`; } @@ -923,50 +1025,47 @@ export async function prepareRuntimeIdentity( } const profileImport = await importValidatedProfile(profileSource, deps); - if (profileImport.exitCode !== 0) { - if (!/already exists/i.test(commandOutput(profileImport))) { - throw new Error( - `Failed to import runtime identity provider profile: ${deps.formatError(commandOutput(profileImport))}`, - ); - } - const profileExport = await deps.run([ - "openshell", - "provider", - "profile", - "export", - config.provider_type, - "--output", - "yaml", - ]); - if (profileExport.exitCode !== 0) { - throw new Error( - `Failed to inspect existing runtime identity provider profile: ${deps.formatError(commandOutput(profileExport))}`, - ); - } - let existingProfile: ParsedRuntimeIdentityProfile; - try { - existingProfile = parseRuntimeIdentityProfile( - profileExport.stdout, - config, - profilePolicy, - "Existing runtime identity provider profile", - ); - } catch { - throw new Error( - `Runtime identity provider profile '${config.provider_type}' exists with an incompatible binding`, - ); - } - if (!isDeepStrictEqual(existingProfile.document, requestedProfile.document)) { - throw new Error( - `Runtime identity provider profile '${config.provider_type}' exists with an incompatible binding`, - ); - } + if (profileImport.exitCode !== 0 && !/already exists/i.test(commandOutput(profileImport))) { + throw new Error( + `Failed to import runtime identity provider profile: ${deps.formatError(commandOutput(profileImport))}`, + ); + } + const profileExport = await deps.run( + ["openshell", "provider", "profile", "export", config.provider_type, "--output", "yaml"], + { timeoutMs: 30_000 }, + ); + if (profileExport.exitCode !== 0) { + throw new Error( + `Failed to inspect runtime identity provider profile '${config.provider_type}': ${deps.formatError(commandOutput(profileExport), [clientId, refreshToken, clientSecret ?? ""])}`, + ); + } + let importedProfile: ParsedRuntimeIdentityProfile; + try { + importedProfile = parseRuntimeIdentityProfile( + profileExport.stdout, + config, + profilePolicy, + "Imported runtime identity provider profile", + true, + ); + } catch { + throw new Error( + `Runtime identity provider profile '${config.provider_type}' has an incompatible binding; ask the gateway operator to inspect the profile before retrying`, + ); + } + if (!isDeepStrictEqual(importedProfile.document, requestedProfile.document)) { + // Import success does not prove exclusive ownership of this mutable catalog ID. + // Preserve a mismatched profile because another gateway client may have replaced it. + throw new Error( + `Runtime identity provider profile '${config.provider_type}' has an incompatible binding; ask the gateway operator to inspect the profile before retrying`, + ); } const receipt: RuntimeIdentityReceipt = { ...plan, provider_created: true, attachment_created: false, + verified_profile_sha256: profileDigest(requestedProfile.document), }; let providerAcquired = false; try { @@ -990,6 +1089,7 @@ export async function prepareRuntimeIdentity( // persistence fails, preserve the provider instead of deleting a resource // that the next process cannot prove this run created. providerAcquired = true; + await warnIfProfileChanged(receipt, profilePolicy, deps); const refreshArgs = [ "openshell", @@ -1052,7 +1152,7 @@ export async function mintRuntimeIdentityCredential( export async function attachRuntimeIdentity( receipt: RuntimeIdentityReceipt, sandboxName: string, - deps: RuntimeIdentityCommandDeps, + deps: RuntimeIdentityDeps, ): Promise { await requireProviderDerivedPolicy(deps); const state = await inspectProvider(receipt, deps, true); @@ -1069,8 +1169,15 @@ export async function attachRuntimeIdentity( sandboxName, receipt.provider_name, ]); - if (attach.exitCode === 0) return true; - if (/already attached/i.test(commandOutput(attach))) return false; + if (attach.exitCode === 0 || /already attached/i.test(commandOutput(attach))) { + const attachmentCreated = attach.exitCode === 0; + if (attachmentCreated) { + deps.persistReceipt({ ...receipt, attachment_created: true }); + } + const policy = deps.profilePolicy ?? RUNTIME_IDENTITY_PROFILE_POLICIES[receipt.provider_type]; + if (policy) await warnIfProfileChanged(receipt, policy, deps); + return attachmentCreated; + } throw new Error( `Failed to attach runtime identity provider '${receipt.provider_name}': ${deps.formatError(commandOutput(attach))}`, ); diff --git a/test/onboarding/blueprint-runtime-identity-lifecycle.test.ts b/test/onboarding/blueprint-runtime-identity-lifecycle.test.ts index b03d7c16de3..24fed76a2d1 100644 --- a/test/onboarding/blueprint-runtime-identity-lifecycle.test.ts +++ b/test/onboarding/blueprint-runtime-identity-lifecycle.test.ts @@ -28,6 +28,7 @@ interface FakeOpenShellCall { interface FakeOpenShellState { attachments: Record; calls: FakeOpenShellCall[]; + profileSource: string | null; profiles: string[]; providers: Record< string, @@ -53,6 +54,7 @@ const CONFIG = { const INITIAL_STATE: FakeOpenShellState = { attachments: {}, calls: [], + profileSource: null, profiles: [], providers: {}, }; @@ -108,10 +110,16 @@ if (args[0] === "provider" && args[1] === "get") { } if (args.join(" ").startsWith("provider profile import --file ")) { + state.profileSource = fs.readFileSync(args[args.indexOf("--file") + 1], "utf8"); state.profiles.push("okta-runtime-v1"); save(0); } +if (args.join(" ") === "provider profile export okta-runtime-v1 --output yaml") { + if (!state.profileSource) save(1, "", "provider profile not found"); + save(0, state.profileSource); +} + if (args[0] === "provider" && args[1] === "create") { const name = args[args.indexOf("--name") + 1]; const type = args[args.indexOf("--type") + 1]; @@ -193,6 +201,7 @@ describe("blueprint runtime identity lifecycle integration", () => { OKTA_CLIENT_SECRET: "integration-client-secret", }; const persistedReceipts: RuntimeIdentityReceipt[] = []; + const warnings: string[] = []; const run = async ( args: string[], options?: RuntimeIdentityCommandOptions, @@ -217,6 +226,7 @@ describe("blueprint runtime identity lifecycle integration", () => { formatError: (output, secrets = []) => secrets.reduce((redacted, secret) => redacted.replaceAll(secret, ""), output), persistReceipt: (receipt) => persistedReceipts.push({ ...receipt }), + warn: (message) => warnings.push(message), run, // This test intentionally bypasses DNS validation and uses a fake OpenShell to isolate lifecycle orchestration. // TC-INF-12 separately proves the successful path through a real @@ -233,14 +243,18 @@ describe("blueprint runtime identity lifecycle integration", () => { await mintRuntimeIdentityCredential(receipt, deps); let state = await readState(fakeOpenShell); - expect(receipt).toEqual({ + expect(receipt).toMatchObject({ provider_type: "okta-runtime-v1", provider_name: "e2e-okta-runtime", credential_key: "OKTA_ACCESS_TOKEN", provider_created: true, attachment_created: true, }); - expect(persistedReceipts).toEqual([{ ...receipt, attachment_created: false }]); + expect(persistedReceipts).toEqual([ + { ...receipt, attachment_created: false }, + { ...receipt, attachment_created: true }, + ]); + expect(warnings).toEqual([]); expect(state.profiles).toEqual(["okta-runtime-v1"]); expect(state.providers["e2e-okta-runtime"]).toMatchObject({ configured: true,