Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions docs/reference/configure-runtime-identity.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
117 changes: 111 additions & 6 deletions nemoclaw/src/blueprint/runner-identity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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")]],
Expand All @@ -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, {
Expand Down Expand Up @@ -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),
);
}

Expand All @@ -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",
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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<void>((resolve) => {
signalExport = resolve;
});
const exportReleased = new Promise<void>((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) => {
Expand Down
21 changes: 6 additions & 15 deletions nemoclaw/src/blueprint/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1216,18 +1216,22 @@ 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,
};
}

function runtimeIdentityCommandDeps(gateway: string): RuntimeIdentityCommandDeps {
return {
run: (args, options) => runRuntimeIdentityCommand(args, options, gateway),
formatError: boundedCommandError,
warn: (message) => log(`Warning: ${message}`),
};
}

Expand Down Expand Up @@ -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);
}

Expand Down
Loading