From d91e7f78505b8f9a59316ea3a79f24e965427526 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:35:47 -0700 Subject: [PATCH 01/11] test(e2e): use mock baseline for native NVIDIA switch Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/live/openclaw-inference-switch.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 27f910e2528..c5ad738c965 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -1156,7 +1156,8 @@ test( }); const useMockBaseline = - SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1"; + SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER || + (SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1"); // OpenShell reaches this fixture from its gateway network namespace, where // the runner's loopback address is not routable. const baselineProvider: FakeOpenAiCompatibleServer | undefined = useMockBaseline From 1ffa09326ac560b9c455dbdbdd40cd082385cc50 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:48:53 -0700 Subject: [PATCH 02/11] test(e2e): protect native switch baseline credentials Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ...openclaw-inference-switch-baseline.test.ts | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 test/e2e/support/openclaw-inference-switch-baseline.test.ts diff --git a/test/e2e/support/openclaw-inference-switch-baseline.test.ts b/test/e2e/support/openclaw-inference-switch-baseline.test.ts new file mode 100644 index 00000000000..bcc4a9eaa53 --- /dev/null +++ b/test/e2e/support/openclaw-inference-switch-baseline.test.ts @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; + +import { afterEach, expect, it, vi } from "vitest"; + +const captured = vi.hoisted(() => ({ test: vi.fn() })); +vi.mock("../fixtures/e2e-test.ts", async () => ({ + expect: (await import("vitest")).expect, + test: captured.test, +})); +vi.mock("../fixtures/managed-image-receipt.ts", () => ({ + selectedE2eManagedImageReference: () => "example.invalid/openclaw@sha256:" + "a".repeat(64), +})); + +const disposables: Array<() => unknown> = []; +afterEach(async () => { + for (const dispose of disposables.splice(0).reverse()) await dispose(); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +it("keeps the public NVIDIA key out of the native switch baseline", async () => { + vi.resetModules(); + captured.test.mockClear(); + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "nvidia-prod"); + vi.stubEnv("NEMOCLAW_SWITCH_MOCK_ANTHROPIC", "0"); + const exists = fs.existsSync; + vi.spyOn(fs, "existsSync").mockImplementation((file) => + String(file).endsWith("bin/nemoclaw.js") ? true : exists(file), + ); + const result = { exitCode: 0, stdout: "", stderr: "" }; + const stop = new Error("onboarding captured"); + const nemoclaw = vi.fn( + async (_args: string[], _options: { env: NodeJS.ProcessEnv; redactionValues: string[] }) => { + throw stop; + }, + ); + await import("../live/openclaw-inference-switch.test.ts"); + const { startTestProgress } = await import("../fixtures/progress.ts"); + const progress = startTestProgress( + "native switch baseline", + captured.test.mock.calls[0]![1].meta.e2ePhases, + { logLine: () => undefined }, + ); + disposables.push(() => progress.stop()); + const run = captured.test.mock.calls[0]![2] as (input: object) => Promise; + const required = vi.fn((name: string) => { + expect(name).toBe("NVIDIA_API_KEY"); + return "nvapi-public-fixture-key"; + }); + await expect( + run({ + artifacts: { target: { declare: vi.fn() } }, + cleanup: { + trackDisposable: (_name: string, dispose: () => unknown) => disposables.push(dispose), + trackGateway: vi.fn(), + trackSandbox: vi.fn(), + }, + host: { nemoclaw, command: vi.fn(async () => result) }, + progress, + runtimeProvider: { requireAvailable: vi.fn() }, + sandbox: { openshell: vi.fn(async () => result), cleanupSandbox: vi.fn() }, + secrets: { required }, + }), + ).rejects.toBe(stop); + expect(required).toHaveBeenCalledExactlyOnceWith("NVIDIA_API_KEY"); + const options = nemoclaw.mock.calls[0]![1]; + const environment = options.env; + expect(environment.NEMOCLAW_PROVIDER).toBe("custom"); + expect(environment.NEMOCLAW_ENDPOINT_URL).toMatch(/^http:\/\/host\.openshell\.internal:\d+\/v1$/); + expect(environment.NEMOCLAW_MODEL).toBe("openclaw-switch-baseline-model"); + expect(environment.COMPATIBLE_API_KEY).toBe("openclaw-switch-baseline-credential"); + expect(environment.NVIDIA_INFERENCE_API_KEY).toBeUndefined(); + expect(environment.NVIDIA_API_KEY).toBeUndefined(); + expect(options.redactionValues).toContain("nvapi-public-fixture-key"); + expect(options.redactionValues).toContain("openclaw-switch-baseline-credential"); +}); From 2bd54be82e15dcbc17eb8e2c1f4c50b0a60b9ce4 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:22:55 -0700 Subject: [PATCH 03/11] test(e2e): map native switch baseline fast test Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/mock-parity.json | 1 + 1 file changed, 1 insertion(+) diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index d0b2034e536..0f2dfd1ff40 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -839,6 +839,7 @@ "test/e2e/support/e2e-clients.test.ts", "test/e2e/support/inference-switch-workflow-boundary.test.ts", "test/e2e/support/managed-image-receipt.test.ts", + "test/e2e/support/openclaw-inference-switch-baseline.test.ts", "test/e2e/support/openclaw-inference-switch-helpers.test.ts", "test/e2e/support/public-nvidia-switch-provider.test.ts", "test/security/admin-approval-helper.test.ts", From ecd9835a95b7309411f26f94f354cbd9fc88518f Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:09:03 -0700 Subject: [PATCH 04/11] test(e2e): register switch baseline cleanup before credentials Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../live/openclaw-inference-switch.test.ts | 6 +- ...openclaw-inference-switch-baseline.test.ts | 57 ++++++++++++++++--- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index c5ad738c965..25053b0925d 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -1163,6 +1163,9 @@ test( const baselineProvider: FakeOpenAiCompatibleServer | undefined = useMockBaseline ? await startMockOpenClawBaselineProvider(progress) : undefined; + cleanup.trackDisposable("close baseline inference provider", async () => { + await baselineProvider?.close(); + }); const publicApiKey = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER ? requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")) @@ -1188,9 +1191,6 @@ test( cleanup.trackDisposable("close switched Anthropic provider", async () => { await mockProvider?.close(); }); - cleanup.trackDisposable("close baseline inference provider", async () => { - await baselineProvider?.close(); - }); const customDockerfile = writeCustomOpenClawDockerfile(home); cleanup.trackGateway(host, "nemoclaw", { artifactName: "cleanup-openshell-gateway-destroy-openclaw-inference-switch", diff --git a/test/e2e/support/openclaw-inference-switch-baseline.test.ts b/test/e2e/support/openclaw-inference-switch-baseline.test.ts index bcc4a9eaa53..6f68c12102e 100644 --- a/test/e2e/support/openclaw-inference-switch-baseline.test.ts +++ b/test/e2e/support/openclaw-inference-switch-baseline.test.ts @@ -17,11 +17,12 @@ vi.mock("../fixtures/managed-image-receipt.ts", () => ({ const disposables: Array<() => unknown> = []; afterEach(async () => { for (const dispose of disposables.splice(0).reverse()) await dispose(); + vi.doUnmock("../live/openclaw-inference-switch-helpers.ts"); vi.restoreAllMocks(); vi.unstubAllEnvs(); }); -it("keeps the public NVIDIA key out of the native switch baseline", async () => { +async function loadNativeSwitchRun() { vi.resetModules(); captured.test.mockClear(); vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "nvidia-prod"); @@ -30,13 +31,6 @@ it("keeps the public NVIDIA key out of the native switch baseline", async () => vi.spyOn(fs, "existsSync").mockImplementation((file) => String(file).endsWith("bin/nemoclaw.js") ? true : exists(file), ); - const result = { exitCode: 0, stdout: "", stderr: "" }; - const stop = new Error("onboarding captured"); - const nemoclaw = vi.fn( - async (_args: string[], _options: { env: NodeJS.ProcessEnv; redactionValues: string[] }) => { - throw stop; - }, - ); await import("../live/openclaw-inference-switch.test.ts"); const { startTestProgress } = await import("../fixtures/progress.ts"); const progress = startTestProgress( @@ -46,6 +40,18 @@ it("keeps the public NVIDIA key out of the native switch baseline", async () => ); disposables.push(() => progress.stop()); const run = captured.test.mock.calls[0]![2] as (input: object) => Promise; + return { progress, run }; +} + +it("keeps the public NVIDIA key out of the native switch baseline", async () => { + const { progress, run } = await loadNativeSwitchRun(); + const result = { exitCode: 0, stdout: "", stderr: "" }; + const stop = new Error("onboarding captured"); + const nemoclaw = vi.fn( + async (_args: string[], _options: { env: NodeJS.ProcessEnv; redactionValues: string[] }) => { + throw stop; + }, + ); const required = vi.fn((name: string) => { expect(name).toBe("NVIDIA_API_KEY"); return "nvapi-public-fixture-key"; @@ -77,3 +83,38 @@ it("keeps the public NVIDIA key out of the native switch baseline", async () => expect(options.redactionValues).toContain("nvapi-public-fixture-key"); expect(options.redactionValues).toContain("openclaw-switch-baseline-credential"); }); + +it("closes the mock baseline when public key retrieval fails", async () => { + const close = vi.fn(async () => undefined); + vi.doMock("../live/openclaw-inference-switch-helpers.ts", async (importOriginal) => ({ + ...(await importOriginal()), + startMockOpenClawBaselineProvider: async () => ({ close }), + })); + const { progress, run } = await loadNativeSwitchRun(); + const missingKey = new Error("NVIDIA_API_KEY unavailable"); + const registered = new Map unknown>(); + await expect( + run({ + artifacts: { target: { declare: vi.fn() } }, + cleanup: { + trackDisposable: (name: string, dispose: () => unknown) => registered.set(name, dispose), + trackGateway: vi.fn(), + trackSandbox: vi.fn(), + }, + host: { command: vi.fn() }, + progress, + runtimeProvider: { requireAvailable: vi.fn() }, + sandbox: { openshell: vi.fn() }, + secrets: { + required: vi.fn(() => { + throw missingKey; + }), + }, + }), + ).rejects.toBe(missingKey); + const dispose = registered.get("close baseline inference provider"); + expect(dispose).toBeDefined(); + expect(close).not.toHaveBeenCalled(); + await dispose?.(); + expect(close).toHaveBeenCalledOnce(); +}); From 2c483fc404166b5622089de064b6cbb991eac1fe Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:09:05 -0700 Subject: [PATCH 05/11] test(e2e): assert switched route from JSON output --- test/e2e/live/openclaw-inference-switch.test.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 25053b0925d..84540dedb48 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -227,10 +227,6 @@ async function proveSelectedMockBaselineAuthentication( ).toContainEqual(expectedRequest); } -function stripAnsi(value: string): string { - return value.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, ""); -} - function parsePortEnv(name: string, fallback: number): number { const raw = process.env[name]; if (!raw) return fallback; @@ -534,7 +530,7 @@ async function openclawGatewayPid(sandbox: SandboxClient, home: string): Promise } async function getRouteOutput(host: HostCliClient, home: string): Promise { - return runNemoclaw(host, home, ["inference", "get"], { + return runNemoclaw(host, home, ["inference", "get", "--json"], { artifactName: "nemoclaw-inference-get-after-switch", timeoutMs: COMMAND_TIMEOUT_MS, }); @@ -1322,9 +1318,9 @@ test( progress.phase("inspect route configuration and recorded state"); const route = await getRouteOutput(host, home); expect(route.exitCode, resultText(route)).toBe(0); - const plainRoute = stripAnsi(resultText(route)); - expect(plainRoute).toContain(`Provider: ${SWITCH_PROVIDER}`); - expect(plainRoute).toContain(`Model: ${SWITCH_MODEL}`); + const routeState = JSON.parse(route.stdout) as { provider?: unknown; model?: unknown }; + expect(routeState.provider).toBe(SWITCH_PROVIDER); + expect(routeState.model).toBe(SWITCH_MODEL); await assertOpenClawConfig(sandbox, home, { model: SWITCH_MODEL, inferenceApi: SWITCH_INFERENCE_API, From ed6364867048bd20ad095dae8b78762bcfa94948 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:12:13 -0700 Subject: [PATCH 06/11] test: verify native inference credential in sandbox --- .../live/openclaw-inference-switch.test.ts | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 84540dedb48..cfddd1d4e36 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -17,6 +17,7 @@ import os from "node:os"; import path from "node:path"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; +import { NVIDIA_INFERENCE_PLACEHOLDER } from "../../../src/lib/inference-credential.ts"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-nvidia/contract.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import type { ArtifactSink } from "../fixtures/artifacts.ts"; @@ -618,7 +619,22 @@ async function readAndAssertOpenClawConfig( ): Promise { const configResult = await sandbox.exec( SANDBOX_NAME, - ["cat", "/sandbox/.openclaw/openclaw.json"], + expected.nativeNvidia + ? [ + "node", + "-e", + [ + 'const fs = require("node:fs");', + 'const config = JSON.parse(fs.readFileSync("/sandbox/.openclaw/openclaw.json", "utf8"));', + "const provider = config.models?.providers?.inference;", + // Keep this comparison inside the sandbox: ShellProbe redacts + // credential-shaped JSON fields before returning stdout. + `require("node:assert/strict").ok(provider?.apiKey === ${JSON.stringify(NVIDIA_INFERENCE_PLACEHOLDER)}, "native credential reference mismatch");`, + "delete provider.apiKey;", + "process.stdout.write(JSON.stringify(config));", + ].join(" "), + ] + : ["cat", "/sandbox/.openclaw/openclaw.json"], { artifactName: expected.artifactName, env: commandEnv(home), @@ -641,7 +657,7 @@ async function readAndAssertOpenClawConfig( ? "https://inference.local" : "https://inference.local/v1", ); - expect(provider?.apiKey).toBe(expected.nativeNvidia ? "${NVIDIA_INFERENCE_API_KEY}" : "unused"); + expect(provider?.apiKey).toBe(expected.nativeNvidia ? undefined : "unused"); expect(provider?.api).toBe(expected.inferenceApi); expect(selectedModel?.name).toBe(expectedPrimary); return selectedModel; From d9ce09f1b3fac31b2812b13fd78bd7524a38fb46 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:01:06 -0700 Subject: [PATCH 07/11] fix(inference): carry scoped provider handle into OpenClaw gateway config Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/inference-credential.ts | 8 +- .../compose-sandbox-config-body.test.ts | 168 ++++++++++++++++++ src/lib/sandbox/config.ts | 112 ++++++++++-- .../live/openclaw-inference-switch.test.ts | 9 +- 4 files changed, 276 insertions(+), 21 deletions(-) diff --git a/src/lib/inference-credential.ts b/src/lib/inference-credential.ts index 3348d9706e5..c0f173031ab 100644 --- a/src/lib/inference-credential.ts +++ b/src/lib/inference-credential.ts @@ -1,9 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -// Both agents expand this reference from the supervisor-issued, scoped -// OpenShell handle at config load. A static resolver alias has no provider -// identity and is rejected by the endpoint-bound native provider. +// The initial agent config expands this reference from the supervisor-issued, +// scoped OpenShell handle. An OpenClaw inference switch materializes that handle +// in its fresh sandbox exec before restarting the older gateway process. A +// static resolver alias has no provider identity and is rejected by the +// endpoint-bound native provider. export const NVIDIA_INFERENCE_PLACEHOLDER = "${NVIDIA_INFERENCE_API_KEY}"; export function managedInferenceApiKey( diff --git a/src/lib/sandbox/compose-sandbox-config-body.test.ts b/src/lib/sandbox/compose-sandbox-config-body.test.ts index 4978e9ceba0..58e7dfbdac6 100644 --- a/src/lib/sandbox/compose-sandbox-config-body.test.ts +++ b/src/lib/sandbox/compose-sandbox-config-body.test.ts @@ -2,7 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; import type { OpenShellRuntimeSelection } from "../adapters/openshell/runtime-selection"; +import { NVIDIA_INFERENCE_PLACEHOLDER } from "../inference-credential"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../inference/native-nvidia/contract"; import YAML from "yaml"; const { @@ -10,6 +16,7 @@ const { buildOpenClawNativeConfigSetInvocation, composeSandboxConfigBody, hermesConfigAllowsPrivateUrls, + runOpenClawNativeConfigBatchUntilHandleReady, writeSandboxConfig, } = require("./config") as { buildOpenClawNativeConfigBatchInvocation: ( @@ -34,6 +41,12 @@ const { }, ) => string; hermesConfigAllowsPrivateUrls: (config: Record) => boolean; + runOpenClawNativeConfigBatchUntilHandleReady: ( + nativeNvidiaUpdate: boolean, + run: () => { status: number; stderr: string; error?: Error; signal?: string }, + wait?: (ms: number) => void, + warn?: (message: string) => void, + ) => void; writeSandboxConfig: ( sandboxName: string, target: typeof OPENCLAW_TARGET, @@ -144,6 +157,161 @@ describe("composeSandboxConfigBody", () => { ]); }); + it("gives a newly attached native NVIDIA handle to OpenClaw without exposing the raw key", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-config-")); + try { + const executable = path.join(directory, "openclaw"); + fs.writeFileSync(executable, '#!/bin/sh\ncat "$4"\n', { mode: 0o700 }); + const invocation = buildOpenClawNativeConfigBatchInvocation("alpha", [ + { dotpath: "agents.defaults.model.primary", value: "inference/nvidia/model-a" }, + { + dotpath: "models.providers.inference", + value: { + baseUrl: "https://integrate.api.nvidia.com/v1", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", + api: "openai-completions", + models: [{ id: "nvidia/model-a" }], + }, + }, + ]); + const command = invocation.args.slice(invocation.args.indexOf("--") + 1); + const handle = "openshell:resolve:env:v42_NVIDIA_INFERENCE_API_KEY"; + const run = (value: string | undefined) => + spawnSync(command[0]!, command.slice(1), { + input: invocation.input, + encoding: "utf8", + timeout: 5_000, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH ?? ""}`, + ...(value === undefined + ? { NVIDIA_INFERENCE_API_KEY: undefined } + : { NVIDIA_INFERENCE_API_KEY: value }), + }, + }); + + const success = run(handle); + expect(success.status, `${success.error?.message ?? ""} ${success.stderr}`).toBe(0); + const batch = JSON.parse(success.stdout) as Array<{ path: string; value: unknown }>; + expect(batch).toEqual([ + { path: "agents.defaults.model.primary", value: "inference/nvidia/model-a" }, + { + path: "models.providers.inference", + value: { + baseUrl: "https://integrate.api.nvidia.com/v1", + apiKey: handle, + api: "openai-completions", + models: [{ id: "nvidia/model-a" }], + }, + }, + ]); + expect(invocation.input).not.toContain(handle); + expect(invocation.args.join(" ")).not.toContain(handle); + expect(invocation.input).toContain(NVIDIA_INFERENCE_PLACEHOLDER); + expect(invocation.input).toContain(NVIDIA_HOSTED_NATIVE_ENDPOINT); + + const wrongEndpoint = buildOpenClawNativeConfigBatchInvocation("alpha", [ + { + dotpath: "models.providers.inference", + value: { + baseUrl: "https://other.example/v1", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", + }, + }, + ]); + const wrongCommand = wrongEndpoint.args.slice(wrongEndpoint.args.indexOf("--") + 1); + const refused = spawnSync(wrongCommand[0]!, wrongCommand.slice(1), { + input: wrongEndpoint.input, + encoding: "utf8", + timeout: 5_000, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH ?? ""}`, + NVIDIA_INFERENCE_API_KEY: handle, + }, + }); + expect(refused.status).not.toBe(0); + expect(refused.stdout).toBe(""); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); + + it.each([ + { value: undefined, expectedStatus: 75 }, + { value: "nvapi-do-not-write", expectedStatus: 1 }, + { value: "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", expectedStatus: 1 }, + ])( + "refuses invalid native NVIDIA handle $value before config mutation", + ({ value, expectedStatus }) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-config-")); + try { + fs.writeFileSync(path.join(directory, "openclaw"), '#!/bin/sh\ncat "$4"\n', { + mode: 0o700, + }); + const invocation = buildOpenClawNativeConfigBatchInvocation("alpha", [ + { + dotpath: "models.providers.inference", + value: { baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, apiKey: NVIDIA_INFERENCE_PLACEHOLDER }, + }, + ]); + const command = invocation.args.slice(invocation.args.indexOf("--") + 1); + const failed = spawnSync(command[0]!, command.slice(1), { + input: invocation.input, + encoding: "utf8", + timeout: 5_000, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH ?? ""}`, + NVIDIA_INFERENCE_API_KEY: value, + }, + }); + expect(failed.status).toBe(expectedStatus); + expect(failed.stdout).toBe(""); + expect(failed.stderr).not.toContain("nvapi-do-not-write"); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + + it("retries only a missing newly attached handle before OpenClaw mutates config", () => { + const pending = { status: 75, stderr: "NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\n" }; + const succeeded = { status: 0, stderr: "" }; + const run = vi.fn().mockReturnValueOnce(pending).mockReturnValueOnce(succeeded); + const wait = vi.fn(); + const warn = vi.fn(); + + runOpenClawNativeConfigBatchUntilHandleReady(true, run, wait, warn); + expect(run).toHaveBeenCalledTimes(2); + expect(wait).toHaveBeenCalledExactlyOnceWith(2_000); + expect(warn).toHaveBeenCalledExactlyOnceWith( + "Native NVIDIA provider handle pending; config attempt 1/10", + ); + + const exhaustedRun = vi.fn().mockReturnValue(pending); + const exhaustedWait = vi.fn(); + expect(() => + runOpenClawNativeConfigBatchUntilHandleReady(true, exhaustedRun, exhaustedWait, vi.fn()), + ).toThrow("Native OpenClaw config command failed after 10 attempt(s)"); + expect(exhaustedRun).toHaveBeenCalledTimes(10); + expect(exhaustedWait).toHaveBeenCalledTimes(9); + }); + + it.each([ + { status: 75, stderr: "unrelated failure" }, + { status: 1, stderr: "NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING" }, + { status: 1, stderr: "Native NVIDIA provider handle is unavailable or invalid" }, + ])("does not retry other native config failures: $status $stderr", (result) => { + const failedRun = vi.fn().mockReturnValue(result); + const wait = vi.fn(); + expect(() => + runOpenClawNativeConfigBatchUntilHandleReady(true, failedRun, wait, vi.fn()), + ).toThrow("Native OpenClaw config command failed after 1 attempt(s)"); + expect(failedRun).toHaveBeenCalledOnce(); + expect(wait).not.toHaveBeenCalled(); + }); + it("pins native writes to the supplied gateway instead of the ambient selection (#11764)", () => { vi.stubEnv("OPENSHELL_GATEWAY", "other-gateway"); const invocation = buildOpenClawNativeConfigSetInvocation( diff --git a/src/lib/sandbox/config.ts b/src/lib/sandbox/config.ts index 556857e076a..4764aa53593 100644 --- a/src/lib/sandbox/config.ts +++ b/src/lib/sandbox/config.ts @@ -664,12 +664,62 @@ export interface OpenClawConfigUpdate { value: ConfigValue; } +// A provider attached after sandbox creation appears in fresh OpenShell exec +// processes, but not in the existing OpenClaw gateway's environment. The +// gateway restart replaces that process image with its old environment. Pin +// the supervisor-issued handle in the native config batch before restarting; +// the actual credential remains outside the sandbox and endpoint-bound. +const materializeNativeNvidiaHandle = [ + "import json, os, re, sys", + 'handle = os.environ.get("NVIDIA_INFERENCE_API_KEY", "")', + "if not handle:", + ' sys.stderr.write("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\\n")', + " raise SystemExit(75)", + 'if not re.fullmatch(r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY", handle):', + ' raise SystemExit("Native NVIDIA provider handle is unavailable or invalid")', + 'with open(sys.argv[1], "r+", encoding="utf-8") as stream:', + " updates = json.load(stream)", + " if not isinstance(updates, list):", + ' raise SystemExit("Invalid OpenClaw config batch")', + " matched = 0", + " for update in updates:", + ' if not isinstance(update, dict) or update.get("path") != "models.providers.inference":', + " continue", + ' provider = update.get("value")', + ' if not isinstance(provider, dict) or provider.get("apiKey") != sys.argv[3]:', + " continue", + ' if provider.get("baseUrl") != sys.argv[2]:', + ' raise SystemExit("Native NVIDIA provider endpoint does not match")', + ' provider["apiKey"] = handle', + " matched += 1", + " if matched != 1:", + ' raise SystemExit("Expected one native NVIDIA provider config update")', + " stream.seek(0)", + ' json.dump(updates, stream, separators=(",", ":"))', + " stream.truncate()", +].join("\n"); +// Keep these literals alongside the sandbox command. The focused test checks +// them against the canonical inference constants without adding dependencies +// to this already saturated config module. +const nativeNvidiaPlaceholder = "${NVIDIA_INFERENCE_API_KEY}"; +const nativeNvidiaEndpoint = "https://integrate.api.nvidia.com/v1"; + function buildOpenClawNativeConfigBatchInvocation( sandboxName: string, updates: readonly OpenClawConfigUpdate[], gateway?: string | OpenShellRuntimeSelection, ) { + const nativeNvidiaUpdate = updates.some( + ({ dotpath, value }) => + dotpath === "models.providers.inference" && + isConfigObject(value) && + value.apiKey === nativeNvidiaPlaceholder, + ); + const materializeCommand = nativeNvidiaUpdate + ? `python3 -c ${shellQuote(materializeNativeNvidiaHandle)} "$file" ${shellQuote(nativeNvidiaEndpoint)} ${shellQuote(nativeNvidiaPlaceholder)} || exit $?; ` + : ""; return { + nativeNvidiaUpdate, ...(!gateway || typeof gateway === "string" ? {} : { @@ -687,7 +737,7 @@ function buildOpenClawNativeConfigBatchInvocation( "--", "sh", "-c", - 'umask 077; file=$(mktemp /tmp/nemoclaw-openclaw-config.XXXXXX) || exit $?; trap \'rm -f "$file"\' EXIT; cat >"$file" || exit $?; openclaw config set --batch-file "$file"', + `umask 077; file=$(mktemp /tmp/nemoclaw-openclaw-config.XXXXXX) || exit $?; trap 'rm -f "$file"' EXIT; cat >"$file" || exit $?; ${materializeCommand}openclaw config set --batch-file "$file"`, "nemoclaw-openclaw-config-set-batch", ], input: JSON.stringify(updates.map(({ dotpath, value }) => ({ path: dotpath, value }))), @@ -738,20 +788,53 @@ function setOpenClawConfigValues( } } const invocation = buildOpenClawNativeConfigBatchInvocation(sandboxName, updates, gateway); - const result = runOpenshellCommand(getOpenshellBinary(), invocation.args, { - env: invocation.env, - replaceEnv: invocation.replaceEnv, - ignoreError: true, - input: invocation.input, - maxBuffer: CONFIG_CAPTURE_MAX_BUFFER, - stdio: ["pipe", "pipe", "pipe"], - timeout: OPENSHELL_OPERATION_TIMEOUT_MS, - }); - if (!result.error && !result.signal && result.status === 0) return; - const detail = redactFull( - result.error?.message || String(result.stderr ?? "").trim() || "command failed", + runOpenClawNativeConfigBatchUntilHandleReady(invocation.nativeNvidiaUpdate, () => + runOpenshellCommand(getOpenshellBinary(), invocation.args, { + env: invocation.env, + replaceEnv: invocation.replaceEnv, + ignoreError: true, + input: invocation.input, + maxBuffer: CONFIG_CAPTURE_MAX_BUFFER, + stdio: ["pipe", "pipe", "pipe"], + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }), ); - throw new Error(`Native OpenClaw config command failed: ${detail}`); +} + +type NativeConfigBatchResult = Pick< + ReturnType, + "error" | "signal" | "status" | "stderr" +>; + +function runOpenClawNativeConfigBatchUntilHandleReady( + nativeNvidiaUpdate: boolean, + run: () => NativeConfigBatchResult, + wait: (ms: number) => void = (ms) => + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms), + warn: (message: string) => void = console.warn, +): void { + // OpenShell 0.0.116 attach can confirm desired state before a fresh process + // receives the new environment. This retry is owned by native inference and + // applies only when the materializer exited before OpenClaw changed config. + const maxAttempts = nativeNvidiaUpdate ? 10 : 1; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + const result = run(); + if (!result.error && !result.signal && result.status === 0) return; + const handlePending = + !result.error && + !result.signal && + result.status === 75 && + String(result.stderr ?? "").includes("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING"); + if (handlePending && attempt < maxAttempts) { + warn(`Native NVIDIA provider handle pending; config attempt ${attempt}/${maxAttempts}`); + wait(2_000); + continue; + } + const detail = redactFull( + result.error?.message || String(result.stderr ?? "").trim() || "command failed", + ); + throw new Error(`Native OpenClaw config command failed after ${attempt} attempt(s): ${detail}`); + } } function unsetOpenClawConfigValue( @@ -1361,6 +1444,7 @@ export { resolveAgentConfig, restartSandboxAgentAfterConfigSet, rewriteConfigUrlsWithDnsPinning, + runOpenClawNativeConfigBatchUntilHandleReady, setOpenClawConfigValue, setOpenClawConfigValues, setDotpath, diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index cfddd1d4e36..906ab828665 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -17,7 +17,6 @@ import os from "node:os"; import path from "node:path"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; -import { NVIDIA_INFERENCE_PLACEHOLDER } from "../../../src/lib/inference-credential.ts"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-nvidia/contract.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import type { ArtifactSink } from "../fixtures/artifacts.ts"; @@ -627,9 +626,11 @@ async function readAndAssertOpenClawConfig( 'const fs = require("node:fs");', 'const config = JSON.parse(fs.readFileSync("/sandbox/.openclaw/openclaw.json", "utf8"));', "const provider = config.models?.providers?.inference;", - // Keep this comparison inside the sandbox: ShellProbe redacts - // credential-shaped JSON fields before returning stdout. - `require("node:assert/strict").ok(provider?.apiKey === ${JSON.stringify(NVIDIA_INFERENCE_PLACEHOLDER)}, "native credential reference mismatch");`, + // A fresh exec receives the newly attached provider handle. Keep + // both values inside the sandbox because ShellProbe redacts the + // credential-shaped config field before returning stdout. + "const handle = process.env.NVIDIA_INFERENCE_API_KEY;", + 'require("node:assert/strict").ok(/^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY$/.test(handle ?? "") && provider?.apiKey === handle, "native credential reference mismatch");', "delete provider.apiKey;", "process.stdout.write(JSON.stringify(config));", ].join(" "), From c17428248c1b1d24c65e90fce6ce395009fd2910 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:58:30 -0700 Subject: [PATCH 08/11] refactor(inference): use canonical native route contract Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/source-architecture-budget.json | 6 +- .../compose-sandbox-config-body.test.ts | 8 +- src/lib/sandbox/config.ts | 240 +++--------------- src/lib/sandbox/openclaw-native-config.ts | 235 +++++++++++++++++ 4 files changed, 276 insertions(+), 213 deletions(-) create mode 100644 src/lib/sandbox/openclaw-native-config.ts diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index f9a7d548779..d25d6e5282b 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -6,7 +6,7 @@ "src/lib/actions/sandbox/mcp-bridge-contracts.ts": 24, "src/lib/actions/sandbox/process-recovery.ts": 12, "src/lib/adapters/docker/index.ts": 40, - "src/lib/adapters/openshell/client.ts": 17, + "src/lib/adapters/openshell/client.ts": 18, "src/lib/adapters/openshell/command-argv.ts": 17, "src/lib/adapters/openshell/resolve.ts": 22, "src/lib/adapters/openshell/runtime.ts": 41, @@ -19,7 +19,7 @@ "src/lib/cli/terminal-style.ts": 37, "src/lib/core/json-types.ts": 32, "src/lib/core/ports.ts": 87, - "src/lib/core/shell-quote.ts": 20, + "src/lib/core/shell-quote.ts": 21, "src/lib/core/url-utils.ts": 22, "src/lib/core/wait.ts": 30, "src/lib/credentials/store.ts": 44, @@ -57,7 +57,7 @@ "src/lib/onboard/sandbox-gpu-create-run-attempt.ts": 18, "src/lib/onboard/machine/handlers/sandbox.ts": 21, "src/lib/policy/index.ts": 22, - "src/lib/sandbox/config.ts": 18, + "src/lib/sandbox/config.ts": 17, "scripts/checks/run-managed-image-openshell-e2e.ts": 18 } }, diff --git a/src/lib/sandbox/compose-sandbox-config-body.test.ts b/src/lib/sandbox/compose-sandbox-config-body.test.ts index 58e7dfbdac6..fa843358c3f 100644 --- a/src/lib/sandbox/compose-sandbox-config-body.test.ts +++ b/src/lib/sandbox/compose-sandbox-config-body.test.ts @@ -167,8 +167,8 @@ describe("composeSandboxConfigBody", () => { { dotpath: "models.providers.inference", value: { - baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "${NVIDIA_INFERENCE_API_KEY}", + baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + apiKey: NVIDIA_INFERENCE_PLACEHOLDER, api: "openai-completions", models: [{ id: "nvidia/model-a" }], }, @@ -198,7 +198,7 @@ describe("composeSandboxConfigBody", () => { { path: "models.providers.inference", value: { - baseUrl: "https://integrate.api.nvidia.com/v1", + baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, apiKey: handle, api: "openai-completions", models: [{ id: "nvidia/model-a" }], @@ -215,7 +215,7 @@ describe("composeSandboxConfigBody", () => { dotpath: "models.providers.inference", value: { baseUrl: "https://other.example/v1", - apiKey: "${NVIDIA_INFERENCE_API_KEY}", + apiKey: NVIDIA_INFERENCE_PLACEHOLDER, }, }, ]); diff --git a/src/lib/sandbox/config.ts b/src/lib/sandbox/config.ts index 4764aa53593..da969ee5684 100644 --- a/src/lib/sandbox/config.ts +++ b/src/lib/sandbox/config.ts @@ -57,9 +57,13 @@ const { serializeConfig, }: typeof import("./config-format") = require("./config-format"); const { - OPENSHELL_OPERATION_TIMEOUT_MS, -}: typeof import("../adapters/openshell/timeouts") = require("../adapters/openshell/timeouts"); -const { redactFull }: typeof import("../security/redact") = require("../security/redact"); + buildOpenClawNativeConfigBatchInvocation, + buildOpenClawNativeConfigSetInvocation, + executeOpenClawNativeConfigBatch, + executeOpenClawNativeConfigSet, + runOpenClawNativeConfigBatchUntilHandleReady, + runOpenClawNativeConfigCommand, +}: typeof import("./openclaw-native-config") = require("./openclaw-native-config"); const { loadSandboxCredentialRoute, loadRotateTokenSession, @@ -69,6 +73,8 @@ const { type ConfigObject = import("../security/credential-filter").ConfigObject; type ConfigValue = import("../security/credential-filter").ConfigValue; +import type { OpenClawConfigUpdate } from "./openclaw-native-config"; +export type { OpenClawConfigUpdate } from "./openclaw-native-config"; const { runOpenshellCommand, captureOpenshellCommand } = require("../adapters/openshell/client"); function parseJson(text: string): T { @@ -611,139 +617,6 @@ function recomputeSandboxConfigHash(sandboxName: string, target: AgentConfigTarg privilegedSandboxExec(sandboxName, ["sh", "-c", script]); } -function runOpenClawNativeConfigCommand( - sandboxName: string, - args: string[], - gateway?: string | OpenShellRuntimeSelection, -): void { - validateName(sandboxName, "sandbox name"); - const result = captureOpenshellCommand( - getOpenshellBinary(), - [ - ...(gateway ? ["-g", typeof gateway === "string" ? gateway : gateway.gatewayName] : []), - "sandbox", - "exec", - "--name", - sandboxName, - "--env", - "HOME=/sandbox", - "--", - "openclaw", - "config", - ...args, - ], - { - ...(!gateway || typeof gateway === "string" - ? {} - : { - env: buildSelectedOpenShellSubprocessEnv(gateway), - replaceEnv: true, - }), - ignoreError: true, - includeStreams: true, - maxBuffer: CONFIG_CAPTURE_MAX_BUFFER, - timeout: OPENSHELL_OPERATION_TIMEOUT_MS, - }, - ); - if (!result.error && !result.signal && result.status === 0) return; - const detail = redactFull(result.error?.message || result.stderr?.trim() || "command failed"); - throw new Error(`Native OpenClaw config command failed: ${detail}`); -} - -function buildOpenClawNativeConfigSetInvocation( - sandboxName: string, - dotpath: string, - value: ConfigValue, - gateway?: string | OpenShellRuntimeSelection, -) { - return buildOpenClawNativeConfigBatchInvocation(sandboxName, [{ dotpath, value }], gateway); -} - -export interface OpenClawConfigUpdate { - dotpath: string; - value: ConfigValue; -} - -// A provider attached after sandbox creation appears in fresh OpenShell exec -// processes, but not in the existing OpenClaw gateway's environment. The -// gateway restart replaces that process image with its old environment. Pin -// the supervisor-issued handle in the native config batch before restarting; -// the actual credential remains outside the sandbox and endpoint-bound. -const materializeNativeNvidiaHandle = [ - "import json, os, re, sys", - 'handle = os.environ.get("NVIDIA_INFERENCE_API_KEY", "")', - "if not handle:", - ' sys.stderr.write("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\\n")', - " raise SystemExit(75)", - 'if not re.fullmatch(r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY", handle):', - ' raise SystemExit("Native NVIDIA provider handle is unavailable or invalid")', - 'with open(sys.argv[1], "r+", encoding="utf-8") as stream:', - " updates = json.load(stream)", - " if not isinstance(updates, list):", - ' raise SystemExit("Invalid OpenClaw config batch")', - " matched = 0", - " for update in updates:", - ' if not isinstance(update, dict) or update.get("path") != "models.providers.inference":', - " continue", - ' provider = update.get("value")', - ' if not isinstance(provider, dict) or provider.get("apiKey") != sys.argv[3]:', - " continue", - ' if provider.get("baseUrl") != sys.argv[2]:', - ' raise SystemExit("Native NVIDIA provider endpoint does not match")', - ' provider["apiKey"] = handle', - " matched += 1", - " if matched != 1:", - ' raise SystemExit("Expected one native NVIDIA provider config update")', - " stream.seek(0)", - ' json.dump(updates, stream, separators=(",", ":"))', - " stream.truncate()", -].join("\n"); -// Keep these literals alongside the sandbox command. The focused test checks -// them against the canonical inference constants without adding dependencies -// to this already saturated config module. -const nativeNvidiaPlaceholder = "${NVIDIA_INFERENCE_API_KEY}"; -const nativeNvidiaEndpoint = "https://integrate.api.nvidia.com/v1"; - -function buildOpenClawNativeConfigBatchInvocation( - sandboxName: string, - updates: readonly OpenClawConfigUpdate[], - gateway?: string | OpenShellRuntimeSelection, -) { - const nativeNvidiaUpdate = updates.some( - ({ dotpath, value }) => - dotpath === "models.providers.inference" && - isConfigObject(value) && - value.apiKey === nativeNvidiaPlaceholder, - ); - const materializeCommand = nativeNvidiaUpdate - ? `python3 -c ${shellQuote(materializeNativeNvidiaHandle)} "$file" ${shellQuote(nativeNvidiaEndpoint)} ${shellQuote(nativeNvidiaPlaceholder)} || exit $?; ` - : ""; - return { - nativeNvidiaUpdate, - ...(!gateway || typeof gateway === "string" - ? {} - : { - env: buildSelectedOpenShellSubprocessEnv(gateway), - replaceEnv: true, - }), - args: [ - ...(gateway ? ["-g", typeof gateway === "string" ? gateway : gateway.gatewayName] : []), - "sandbox", - "exec", - "--name", - sandboxName, - "--env", - "HOME=/sandbox", - "--", - "sh", - "-c", - `umask 077; file=$(mktemp /tmp/nemoclaw-openclaw-config.XXXXXX) || exit $?; trap 'rm -f "$file"' EXIT; cat >"$file" || exit $?; ${materializeCommand}openclaw config set --batch-file "$file"`, - "nemoclaw-openclaw-config-set-batch", - ], - input: JSON.stringify(updates.map(({ dotpath, value }) => ({ path: dotpath, value }))), - }; -} - function setOpenClawConfigValue( sandboxName: string, dotpath: string, @@ -752,24 +625,16 @@ function setOpenClawConfigValue( ): void { validateName(sandboxName, "sandbox name"); const validation = validateConfigDotpath(dotpath); - if (!validation.ok) { + if (!validation.ok) throw new Error(`Invalid OpenClaw config key '${dotpath}': ${validation.reason}.`); - } - const invocation = buildOpenClawNativeConfigSetInvocation(sandboxName, dotpath, value, gateway); - const result = runOpenshellCommand(getOpenshellBinary(), invocation.args, { - env: invocation.env, - replaceEnv: invocation.replaceEnv, - ignoreError: true, - input: invocation.input, - maxBuffer: CONFIG_CAPTURE_MAX_BUFFER, - stdio: ["pipe", "pipe", "pipe"], - timeout: OPENSHELL_OPERATION_TIMEOUT_MS, - }); - if (!result.error && !result.signal && result.status === 0) return; - const detail = redactFull( - result.error?.message || String(result.stderr ?? "").trim() || "command failed", + executeOpenClawNativeConfigSet( + getOpenshellBinary(), + CONFIG_CAPTURE_MAX_BUFFER, + sandboxName, + dotpath, + value, + gateway, ); - throw new Error(`Native OpenClaw config command failed: ${detail}`); } function setOpenClawConfigValues( @@ -778,75 +643,38 @@ function setOpenClawConfigValues( gateway?: string | OpenShellRuntimeSelection, ): void { validateName(sandboxName, "sandbox name"); - if (updates.length === 0) { + if (updates.length === 0) throw new Error("Native OpenClaw config update requires at least one value."); - } for (const { dotpath } of updates) { const validation = validateConfigDotpath(dotpath); - if (!validation.ok) { + if (!validation.ok) throw new Error(`Invalid OpenClaw config key '${dotpath}': ${validation.reason}.`); - } } - const invocation = buildOpenClawNativeConfigBatchInvocation(sandboxName, updates, gateway); - runOpenClawNativeConfigBatchUntilHandleReady(invocation.nativeNvidiaUpdate, () => - runOpenshellCommand(getOpenshellBinary(), invocation.args, { - env: invocation.env, - replaceEnv: invocation.replaceEnv, - ignoreError: true, - input: invocation.input, - maxBuffer: CONFIG_CAPTURE_MAX_BUFFER, - stdio: ["pipe", "pipe", "pipe"], - timeout: OPENSHELL_OPERATION_TIMEOUT_MS, - }), + executeOpenClawNativeConfigBatch( + getOpenshellBinary(), + CONFIG_CAPTURE_MAX_BUFFER, + sandboxName, + updates, + gateway, ); } -type NativeConfigBatchResult = Pick< - ReturnType, - "error" | "signal" | "status" | "stderr" ->; - -function runOpenClawNativeConfigBatchUntilHandleReady( - nativeNvidiaUpdate: boolean, - run: () => NativeConfigBatchResult, - wait: (ms: number) => void = (ms) => - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms), - warn: (message: string) => void = console.warn, -): void { - // OpenShell 0.0.116 attach can confirm desired state before a fresh process - // receives the new environment. This retry is owned by native inference and - // applies only when the materializer exited before OpenClaw changed config. - const maxAttempts = nativeNvidiaUpdate ? 10 : 1; - for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { - const result = run(); - if (!result.error && !result.signal && result.status === 0) return; - const handlePending = - !result.error && - !result.signal && - result.status === 75 && - String(result.stderr ?? "").includes("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING"); - if (handlePending && attempt < maxAttempts) { - warn(`Native NVIDIA provider handle pending; config attempt ${attempt}/${maxAttempts}`); - wait(2_000); - continue; - } - const detail = redactFull( - result.error?.message || String(result.stderr ?? "").trim() || "command failed", - ); - throw new Error(`Native OpenClaw config command failed after ${attempt} attempt(s): ${detail}`); - } -} - function unsetOpenClawConfigValue( sandboxName: string, dotpath: string, gateway?: string | OpenShellRuntimeSelection, ): void { const validation = validateConfigDotpath(dotpath); - if (!validation.ok) { + if (!validation.ok) throw new Error(`Invalid OpenClaw config key '${dotpath}': ${validation.reason}.`); - } - runOpenClawNativeConfigCommand(sandboxName, ["unset", dotpath], gateway); + validateName(sandboxName, "sandbox name"); + runOpenClawNativeConfigCommand( + getOpenshellBinary(), + CONFIG_CAPTURE_MAX_BUFFER, + sandboxName, + ["unset", dotpath], + gateway, + ); } // --------------------------------------------------------------------------- diff --git a/src/lib/sandbox/openclaw-native-config.ts b/src/lib/sandbox/openclaw-native-config.ts new file mode 100644 index 00000000000..a72da9a2cd1 --- /dev/null +++ b/src/lib/sandbox/openclaw-native-config.ts @@ -0,0 +1,235 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// Host-side OpenClaw native config commands and scoped NVIDIA handle materialization. + +import type { OpenShellRuntimeSelection } from "../adapters/openshell/client"; +import type { ConfigValue } from "../security/credential-filter"; +const { + buildSelectedOpenShellSubprocessEnv, + captureOpenshellCommand, + runOpenshellCommand, +}: typeof import("../adapters/openshell/client") = require("../adapters/openshell/client"); +const { + OPENSHELL_OPERATION_TIMEOUT_MS, +}: typeof import("../adapters/openshell/timeouts") = require("../adapters/openshell/timeouts"); +const { shellQuote }: typeof import("../core/shell-quote") = require("../core/shell-quote"); +const { + NVIDIA_INFERENCE_PLACEHOLDER, +}: typeof import("../inference-credential") = require("../inference-credential"); +const { + NVIDIA_HOSTED_NATIVE_ENDPOINT, +}: typeof import("../inference/native-nvidia/contract") = require("../inference/native-nvidia/contract"); +const { + isConfigObject, +}: typeof import("../security/credential-filter") = require("../security/credential-filter"); +const { redactFull }: typeof import("../security/redact") = require("../security/redact"); + +export function runOpenClawNativeConfigCommand( + binary: string, + maxBuffer: number, + sandboxName: string, + args: string[], + gateway?: string | OpenShellRuntimeSelection, +): void { + const result = captureOpenshellCommand( + binary, + [ + ...(gateway ? ["-g", typeof gateway === "string" ? gateway : gateway.gatewayName] : []), + "sandbox", + "exec", + "--name", + sandboxName, + "--env", + "HOME=/sandbox", + "--", + "openclaw", + "config", + ...args, + ], + { + ...(!gateway || typeof gateway === "string" + ? {} + : { + env: buildSelectedOpenShellSubprocessEnv(gateway), + replaceEnv: true, + }), + ignoreError: true, + includeStreams: true, + maxBuffer, + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }, + ); + if (!result.error && !result.signal && result.status === 0) return; + const detail = redactFull(result.error?.message || result.stderr?.trim() || "command failed"); + throw new Error(`Native OpenClaw config command failed: ${detail}`); +} + +export function buildOpenClawNativeConfigSetInvocation( + sandboxName: string, + dotpath: string, + value: ConfigValue, + gateway?: string | OpenShellRuntimeSelection, +) { + return buildOpenClawNativeConfigBatchInvocation(sandboxName, [{ dotpath, value }], gateway); +} + +export interface OpenClawConfigUpdate { + dotpath: string; + value: ConfigValue; +} + +// A provider attached after sandbox creation appears in fresh OpenShell exec +// processes, but not in the existing OpenClaw gateway's environment. The +// gateway restart replaces that process image with its old environment. Pin +// the supervisor-issued handle in the native config batch before restarting; +// the actual credential remains outside the sandbox and endpoint-bound. +const materializeNativeNvidiaHandle = [ + "import json, os, re, sys", + 'handle = os.environ.get("NVIDIA_INFERENCE_API_KEY", "")', + "if not handle:", + ' sys.stderr.write("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\\n")', + " raise SystemExit(75)", + 'if not re.fullmatch(r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY", handle):', + ' raise SystemExit("Native NVIDIA provider handle is unavailable or invalid")', + 'with open(sys.argv[1], "r+", encoding="utf-8") as stream:', + " updates = json.load(stream)", + " if not isinstance(updates, list):", + ' raise SystemExit("Invalid OpenClaw config batch")', + " matched = 0", + " for update in updates:", + ' if not isinstance(update, dict) or update.get("path") != "models.providers.inference":', + " continue", + ' provider = update.get("value")', + ' if not isinstance(provider, dict) or provider.get("apiKey") != sys.argv[3]:', + " continue", + ' if provider.get("baseUrl") != sys.argv[2]:', + ' raise SystemExit("Native NVIDIA provider endpoint does not match")', + ' provider["apiKey"] = handle', + " matched += 1", + " if matched != 1:", + ' raise SystemExit("Expected one native NVIDIA provider config update")', + " stream.seek(0)", + ' json.dump(updates, stream, separators=(",", ":"))', + " stream.truncate()", +].join("\n"); +export function buildOpenClawNativeConfigBatchInvocation( + sandboxName: string, + updates: readonly OpenClawConfigUpdate[], + gateway?: string | OpenShellRuntimeSelection, +) { + const nativeNvidiaUpdate = updates.some( + ({ dotpath, value }) => + dotpath === "models.providers.inference" && + isConfigObject(value) && + value.apiKey === NVIDIA_INFERENCE_PLACEHOLDER, + ); + const materializeCommand = nativeNvidiaUpdate + ? `python3 -c ${shellQuote(materializeNativeNvidiaHandle)} "$file" ${shellQuote(NVIDIA_HOSTED_NATIVE_ENDPOINT)} ${shellQuote(NVIDIA_INFERENCE_PLACEHOLDER)} || exit $?; ` + : ""; + return { + nativeNvidiaUpdate, + ...(!gateway || typeof gateway === "string" + ? {} + : { + env: buildSelectedOpenShellSubprocessEnv(gateway), + replaceEnv: true, + }), + args: [ + ...(gateway ? ["-g", typeof gateway === "string" ? gateway : gateway.gatewayName] : []), + "sandbox", + "exec", + "--name", + sandboxName, + "--env", + "HOME=/sandbox", + "--", + "sh", + "-c", + `umask 077; file=$(mktemp /tmp/nemoclaw-openclaw-config.XXXXXX) || exit $?; trap 'rm -f "$file"' EXIT; cat >"$file" || exit $?; ${materializeCommand}openclaw config set --batch-file "$file"`, + "nemoclaw-openclaw-config-set-batch", + ], + input: JSON.stringify(updates.map(({ dotpath, value }) => ({ path: dotpath, value }))), + }; +} + +export function executeOpenClawNativeConfigSet( + binary: string, + maxBuffer: number, + sandboxName: string, + dotpath: string, + value: ConfigValue, + gateway?: string | OpenShellRuntimeSelection, +): void { + const invocation = buildOpenClawNativeConfigSetInvocation(sandboxName, dotpath, value, gateway); + const result = runOpenshellCommand(binary, invocation.args, { + env: invocation.env, + replaceEnv: invocation.replaceEnv, + ignoreError: true, + input: invocation.input, + maxBuffer, + stdio: ["pipe", "pipe", "pipe"], + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + if (!result.error && !result.signal && result.status === 0) return; + const detail = redactFull( + result.error?.message || String(result.stderr ?? "").trim() || "command failed", + ); + throw new Error(`Native OpenClaw config command failed: ${detail}`); +} + +export function executeOpenClawNativeConfigBatch( + binary: string, + maxBuffer: number, + sandboxName: string, + updates: readonly OpenClawConfigUpdate[], + gateway?: string | OpenShellRuntimeSelection, +): void { + const invocation = buildOpenClawNativeConfigBatchInvocation(sandboxName, updates, gateway); + runOpenClawNativeConfigBatchUntilHandleReady(invocation.nativeNvidiaUpdate, () => + runOpenshellCommand(binary, invocation.args, { + env: invocation.env, + replaceEnv: invocation.replaceEnv, + ignoreError: true, + input: invocation.input, + maxBuffer, + stdio: ["pipe", "pipe", "pipe"], + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }), + ); +} + +type NativeConfigBatchResult = Pick< + ReturnType, + "error" | "signal" | "status" | "stderr" +>; + +export function runOpenClawNativeConfigBatchUntilHandleReady( + nativeNvidiaUpdate: boolean, + run: () => NativeConfigBatchResult, + wait: (ms: number) => void = (ms) => + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms), + warn: (message: string) => void = console.warn, +): void { + // OpenShell 0.0.116 attach can confirm desired state before a fresh process + // receives the new environment. This retry is owned by native inference and + // applies only when the materializer exited before OpenClaw changed config. + const maxAttempts = nativeNvidiaUpdate ? 10 : 1; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + const result = run(); + if (!result.error && !result.signal && result.status === 0) return; + const handlePending = + !result.error && + !result.signal && + result.status === 75 && + String(result.stderr ?? "").includes("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING"); + if (handlePending && attempt < maxAttempts) { + warn(`Native NVIDIA provider handle pending; config attempt ${attempt}/${maxAttempts}`); + wait(2_000); + continue; + } + const detail = redactFull( + result.error?.message || String(result.stderr ?? "").trim() || "command failed", + ); + throw new Error(`Native OpenClaw config command failed after ${attempt} attempt(s): ${detail}`); + } +} From e194f3fbb6aa96b9b84fb34e7388ecdb34acee2c Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:48:30 -0700 Subject: [PATCH 09/11] fix(openclaw): refresh native provider handle at startup Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/test-file-size-budget.json | 2 +- scripts/nemoclaw-start.sh | 28 +- .../openclaw/runtime/nemoclaw-start.test.ts | 663 ---------------- .../provider-placeholder-refresh.test.ts | 746 ++++++++++++++++++ 4 files changed, 774 insertions(+), 665 deletions(-) create mode 100644 test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index 246e8940458..f6be7aef711 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -6,7 +6,7 @@ "src/lib/onboard/preflight.test.ts": 1875, "test/generation/generate-openclaw-config.test.ts": 1844, "test/installer-integration/install-preflight.test.ts": 2995, - "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 3376, + "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 2713, "test/onboarding/onboard-messaging.test.ts": 1960, "test/onboarding/onboard-selection.test.ts": 4125 } diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 56b034bfd93..6246dac61bb 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -877,6 +877,32 @@ parsed = subprocess.run( config = json.loads(parsed.stdout) refreshed = set() +native_refreshed = False + +# A native NVIDIA handle persisted by the host-side config batch belongs to +# the provider revision that issued it. After a supervisor restart, only the +# current revision is available, so replace that exact config field before +# OpenClaw starts. Never copy a raw value or rewrite another provider's config. +models = config.get("models") if isinstance(config, dict) else None +providers = models.get("providers") if isinstance(models, dict) else None +native = providers.get("inference") if isinstance(providers, dict) else None +if isinstance(native, dict) and native.get("baseUrl") == "https://integrate.api.nvidia.com/v1": + key = "NVIDIA_INFERENCE_API_KEY" + scoped = re.compile(rf"^{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{key}$") + saved = native.get("apiKey") + state = runtime_state(key) + current = state.get("value", "") + if ( + isinstance(saved, str) + and scoped.fullmatch(saved) + and state.get("kind") == "placeholder" + and isinstance(current, str) + and scoped.fullmatch(current) + and saved != current + ): + native["apiKey"] = current + refreshed.add(key) + native_refreshed = True # Match each canonical placeholder only as an exact token. The OpenShell # placeholder grammar is "openshell:resolve:env:[A-Za-z_][A-Za-z0-9_]*", @@ -1005,7 +1031,7 @@ def walk_for_warnings(value, path): walk_for_warnings(updated, []) -if updated != config: +if updated != config or native_refreshed: with open(config_file, "w", encoding="utf-8") as f: json.dump(updated, f, indent=2) f.write("\n") diff --git a/test/agents/openclaw/runtime/nemoclaw-start.test.ts b/test/agents/openclaw/runtime/nemoclaw-start.test.ts index 4cca048c5c1..c9803357c68 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start.test.ts @@ -7,7 +7,6 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; -import JSON5 from "json5"; import * as ts from "typescript"; import { describe, expect, it, vi } from "vitest"; import { extractShellFunctionFromSource } from "../../../helpers/shell-source"; @@ -41,17 +40,6 @@ const runCommand = promisify(execFile); // Concurrent process fixtures are independent, but keep their host load bounded. vi.setConfig({ maxConcurrency: 4 }); -function execFileResult(file, args, options) { - return new Promise((resolve) => - execFile(file, args, options, (error, stdout, stderr) => - resolve({ - status: Number(error?.code) || (error ? -1 : 0), - stdout, - stderr, - }), - ), - ); -} function runtimeShellEnvBlock(src: string): string { const start = src.indexOf("write_runtime_shell_env() {"); const end = src.indexOf("# cleanup_on_signal", start); @@ -2242,657 +2230,6 @@ describe("Slack secrets-on-disk tripwire (#2085)", () => { }); }); -describe.concurrent("provider placeholder refresh (#4251)", () => { - const src = fs.readFileSync(START_SCRIPT, "utf-8"); - const extraPlaceholderKeys = require( - path.join( - import.meta.dirname, - "../../../..", - "src", - "lib", - "onboard", - "extra-placeholder-keys.ts", - ), - ); - const canonicalKeys: string[] = Array.from( - extraPlaceholderKeys.canonicalPlaceholderKeys(), - ).sort(); - async function runRefresh( - config: unknown, - env: Record = {}, - rootMode = false, - runtimePlan: unknown = { credentialBindings: [] }, - ) { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-provider-placeholders-")); - try { - const openclawDir = path.join(tmpDir, ".openclaw"); - const configPath = path.join(openclawDir, "openclaw.json"); - const handoffEnvPath = path.join(tmpDir, "handoff-env"); - const runtimePlanPath = path.join(tmpDir, "messaging-runtime-plan.json"); - const scriptPath = path.join(tmpDir, "run.sh"); - fs.mkdirSync(openclawDir, { recursive: true }); - fs.writeFileSync( - configPath, - `// Native OpenClaw JSON5\n${JSON.stringify(config, null, 2)}\n`, - ); - fs.writeFileSync(runtimePlanPath, JSON.stringify(runtimePlan)); - const fn = extractShellFunctionFromSource(src, "refresh_openclaw_provider_placeholders") - .replaceAll("/sandbox/.openclaw", openclawDir) - .replaceAll("/usr/local/share/nemoclaw/messaging-runtime-plan.json", runtimePlanPath) - .replaceAll("/usr/local/lib/node_modules/openclaw/node_modules/json5", JSON5_MODULE) - .replaceAll("/usr/local/bin/node", process.execPath); - fs.writeFileSync( - scriptPath, - [ - "#!/usr/bin/env bash", - "set -euo pipefail\nrefresh_openclaw_wechat_account_placeholder() { :; }", - ...(rootMode - ? [ - "id() { printf '0\\n'; }", - `STEP_DOWN_PREFIX_SANDBOX=(/bin/bash -c 'env >${JSON.stringify(handoffEnvPath)}; exec "$@"' sandbox-step-down)`, - extractShellFunctionFromSource(src, "run_openclaw_config_as_owner"), - ] - : ['run_openclaw_config_as_owner() { "$@"; }']), - fn, - "refresh_openclaw_provider_placeholders", - ].join("\n"), - { mode: 0o700 }, - ); - const result = await execFileResult("bash", [scriptPath], { - encoding: "utf-8", - env: { PATH: process.env.PATH || "", ...env }, - timeout: 5000, - }); - const updatedConfig = JSON5.parse(fs.readFileSync(configPath, "utf-8")); - const handoffEnv = fs.existsSync(handoffEnvPath) - ? fs.readFileSync(handoffEnvPath, "utf-8") - : ""; - return { config: updatedConfig, handoffEnv, result }; - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - } - - function placeholderPlan(envKeys: string[]): string { - return Buffer.from( - JSON.stringify({ - credentialBindings: envKeys.map((envKey) => ({ - providerEnvKey: envKey, - })), - }), - ).toString("base64"); - } - - it("withholds raw provider values from the root-to-sandbox config handoff", async () => { - const rawToken = "SENTINEL_RAW_PROVIDER_VALUE"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, - }, - }, - }, - }, - { - NEMOCLAW_MESSAGING_PLAN_B64: placeholderPlan(["TELEGRAM_BOT_TOKEN"]), - TELEGRAM_BOT_TOKEN: rawToken, - }, - true, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe( - "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - ); - expect(run.result.stderr).toContain("refusing to write raw credentials"); - expect(run.handoffEnv).not.toContain(rawToken); - expect(run.handoffEnv).not.toContain("TELEGRAM_BOT_TOKEN"); - }); - - it("rewrites Telegram canonical placeholders to OpenShell runtime-scoped placeholders", async () => { - const scoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }, - { TELEGRAM_BOT_TOKEN: scoped }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe(scoped); - expect(run.result.stderr).toContain( - "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN", - ); - expect(run.result.stderr).not.toContain("v42_TELEGRAM_BOT_TOKEN"); - }); - - it("does not write raw provider credentials into openclaw.json", async () => { - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }, - { TELEGRAM_BOT_TOKEN: "123456:SECRET" }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe( - "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - ); - expect(JSON.stringify(run.config)).not.toContain("123456:SECRET"); - expect(run.result.stderr).toContain("refusing to write raw credentials"); - }); - - it("warns when Telegram is configured but the runtime placeholder env is missing", async () => { - const run = await runRefresh({ - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "telegram.default.botToken is an OpenShell placeholder but TELEGRAM_BOT_TOKEN is missing", - ); - }); - - it("warns when the Slack config alias is present but SLACK_BOT_TOKEN is missing", async () => { - const run = await runRefresh({ - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", - }, - }, - }, - }, - }); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "slack.default.botToken expects the SLACK_BOT_TOKEN provider placeholder but it is missing", - ); - expect(run.result.stderr).toContain( - "slack.default.appToken expects the SLACK_APP_TOKEN provider placeholder but it is missing", - ); - }); - - it.each(["v42", `s${"a".repeat(64)}`])( - "does not warn when the Slack config alias matches an OpenShell %s runtime placeholder", - async (credentialHandle) => { - const run = await runRefresh( - { - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", - }, - }, - }, - }, - }, - { - SLACK_BOT_TOKEN: `openshell:resolve:env:${credentialHandle}_SLACK_BOT_TOKEN`, - SLACK_APP_TOKEN: `openshell:resolve:env:${credentialHandle}_SLACK_APP_TOKEN`, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).not.toContain("slack.default"); - expect(run.config.channels.slack.accounts.default.botToken).toBe( - `xoxb-OPENSHELL-RESOLVE-ENV-${credentialHandle}_SLACK_BOT_TOKEN`, - ); - expect(run.config.channels.slack.accounts.default.appToken).toBe( - `xapp-OPENSHELL-RESOLVE-ENV-${credentialHandle}_SLACK_APP_TOKEN`, - ); - }, - ); - - it("does not warn when the Slack runtime env holds a genuine xoxb-/xapp- token", async () => { - const run = await runRefresh( - { - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", - }, - }, - }, - }, - }, - { - SLACK_BOT_TOKEN: "xoxb-1-real-bot-token", - SLACK_APP_TOKEN: "xapp-1-real-app-token", - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).not.toContain("slack.default"); - expect(JSON.stringify(run.config)).not.toContain("xoxb-1-real-bot-token"); - }); - - it("warns when the Slack runtime env holds neither a placeholder nor a Slack token", async () => { - const run = await runRefresh( - { - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - }, - }, - }, - }, - }, - { SLACK_BOT_TOKEN: "garbage-not-a-token" }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "slack.default.botToken runtime SLACK_BOT_TOKEN is neither the SLACK_BOT_TOKEN OpenShell placeholder nor a xoxb- token", - ); - }); - - it("warns when the Slack runtime env resolves a different key than expected", async () => { - const run = await runRefresh( - { - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - }, - }, - }, - }, - }, - { SLACK_BOT_TOKEN: "openshell:resolve:env:v51_OTHER_KEY" }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "slack.default.botToken runtime SLACK_BOT_TOKEN is neither the SLACK_BOT_TOKEN OpenShell placeholder nor a xoxb- token", - ); - }); - - it("emits the accepted-extras signal from canonical keys in the default runtime plan (#10967)", async () => { - const run = await runRefresh( - {}, - { - NEMOCLAW_MESSAGING_RUNTIME_PLAN_PATH: "", - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", - }, - false, - { credentialBindings: [{ providerEnvKey: "TELEGRAM_BOT_TOKEN" }] }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toMatch(/accepted 1 entry\(ies\): TELEGRAM_BOT_TOKEN_AGENT_A/u); - }); - - it("does not emit the accepted-extras breadcrumb when NEMOCLAW_EXTRA_PLACEHOLDER_KEYS is unset", async () => { - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, - }, - }, - }, - }, - {}, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).not.toContain("[config] NEMOCLAW_EXTRA_PLACEHOLDER_KEYS accepted"); - }); - - it("splits NEMOCLAW_EXTRA_PLACEHOLDER_KEYS on commas the same way as whitespace", async () => { - const scopedA = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_A"; - const scopedB = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_B"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - a: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - }, - b: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_B", - }, - }, - }, - }, - }, - { - // Comma- and whitespace-mixed input — the bash for-loop only splits on - // default IFS (whitespace), so without the comma->space normalization - // both keys would arrive concatenated as a single token and fail the - // regex check. - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A,TELEGRAM_BOT_TOKEN_AGENT_B", - TELEGRAM_BOT_TOKEN_AGENT_A: scopedA, - TELEGRAM_BOT_TOKEN_AGENT_B: scopedB, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.a.botToken).toBe(scopedA); - expect(run.config.channels.telegram.accounts.b.botToken).toBe(scopedB); - expect(run.result.stderr).toContain( - "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN_AGENT_A,TELEGRAM_BOT_TOKEN_AGENT_B", - ); - }); - - it("revision-collapses NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entries the same way as canonical keys", async () => { - const scoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_A"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - }, - }, - }, - }, - }, - { - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", - TELEGRAM_BOT_TOKEN_AGENT_A: scoped, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe(scoped); - expect(run.result.stderr).toContain( - "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN_AGENT_A", - ); - }); - - it("does not let canonical TELEGRAM_BOT_TOKEN rewrite the suffixed extra placeholder", async () => { - // Pre-fix bug: the python rewrite did `if old in value: value.replace(old, new)`, - // so the canonical replacement for `openshell:resolve:env:TELEGRAM_BOT_TOKEN` - // greedily rewrote the prefix of `openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A`, - // routing the per-profile placeholder to the wrong canonical revision and - // making rotation of an extra key unsafe. The grammar-aware regex now - // matches each placeholder as an exact token only. - const canonicalScoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; - const extraScoped = "openshell:resolve:env:v51_TELEGRAM_BOT_TOKEN_AGENT_A"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, - agentA: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - }, - }, - }, - }, - }, - { - TELEGRAM_BOT_TOKEN: canonicalScoped, - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", - TELEGRAM_BOT_TOKEN_AGENT_A: extraScoped, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe(canonicalScoped); - expect(run.config.channels.telegram.accounts.agentA.botToken).toBe(extraScoped); - }); - - it("leaves the suffixed extra placeholder unchanged when only the canonical revision is set", async () => { - // Companion to the canonical-vs-extra collision test: when the operator - // staged a revision for TELEGRAM_BOT_TOKEN but not for the extra key, - // the extra placeholder must stay on its canonical form rather than be - // partially rewritten by the prefix replacement. - const canonicalScoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, - agentA: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - }, - }, - }, - }, - }, - { - TELEGRAM_BOT_TOKEN: canonicalScoped, - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe(canonicalScoped); - expect(run.config.channels.telegram.accounts.agentA.botToken).toBe( - "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - ); - }); - - it("rejects malformed and canonical-collision NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entries without faulting", async () => { - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }, - { - TELEGRAM_BOT_TOKEN: "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: - "telegram_bot_token 9NUM_START Path$Bad TELEGRAM_BOT_TOKEN TELEGRAM_BOT_TOKEN_VALID", - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'telegram_bot_token'", - ); - expect(run.result.stderr).toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '9NUM_START'", - ); - expect(run.result.stderr).toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'Path$Bad'", - ); - // Canonical-collision tokens are filtered silently by the case statement. - expect(run.result.stderr).not.toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'TELEGRAM_BOT_TOKEN'", - ); - // The canonical-key revision-collapse still runs end-to-end. - expect(run.config.channels.telegram.accounts.default.botToken).toBe( - "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", - ); - }); - - it.each([ - "GITHUB_TOKEN", - "AWS_SECRET_ACCESS_KEY", - "NPM_TOKEN", - "KUBECONFIG", - "NEMOCLAW_EXTRA_PLACEHOLDER_KEYS", - ])( - "refuses arbitrary host secret names that do not extend a discovered provider envKey inside the sandbox [%s]", - async (blocked) => { - // Defence-in-depth: even if an operator clobbers NEMOCLAW_EXTRA_PLACEHOLDER_KEYS - // inside a running sandbox after the host-side parser already filtered it, - // the container-side refresh helper must mirror the host's canonical-prefix - // restriction so a noncanonical name such as GITHUB_TOKEN never reaches the - // python placeholder walker. - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }, - { - TELEGRAM_BOT_TOKEN: "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: - "GITHUB_TOKEN AWS_SECRET_ACCESS_KEY NPM_TOKEN KUBECONFIG NEMOCLAW_EXTRA_PLACEHOLDER_KEYS TELEGRAM_BOT_TOKEN_KEPT", - // Stage host secrets that would leak if the bash refresh ever - // accepted their names. The assertion below confirms none of these - // values appear in any output produced by the python heredoc. - GITHUB_TOKEN: "ghp-host-secret-would-leak", - AWS_SECRET_ACCESS_KEY: "aws-host-secret-would-leak", - NPM_TOKEN: "npm-host-secret-would-leak", - KUBECONFIG: "/host/path/would-leak", - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - - expect(run.result.stderr).toContain( - `[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '${blocked}' — must extend a discovered provider envKey such as TELEGRAM_BOT_TOKEN_`, - ); - - expect(run.result.stderr).not.toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'TELEGRAM_BOT_TOKEN_KEPT'", - ); - // None of the staged host secret values should reach any stdout/stderr - // line the python heredoc emits, because their names were rejected before - // the heredoc ran. - expect(run.result.stderr).not.toContain("ghp-host-secret-would-leak"); - expect(run.result.stderr).not.toContain("aws-host-secret-would-leak"); - expect(run.result.stderr).not.toContain("npm-host-secret-would-leak"); - expect(run.result.stdout).not.toContain("ghp-host-secret-would-leak"); - expect(run.result.stdout).not.toContain("aws-host-secret-would-leak"); - expect(run.result.stdout).not.toContain("npm-host-secret-would-leak"); - expect(JSON.stringify(run.config)).not.toContain("ghp-host-secret-would-leak"); - expect(JSON.stringify(run.config)).not.toContain("aws-host-secret-would-leak"); - }, - ); - - it.each(canonicalKeys)( - "accepts manifest credential envKey %s as an extension prefix", - async (canonical) => { - // Behavioural parity guard: the in-container parser should not hardcode - // channel env keys. It consumes the messaging plan's credentialBindings, - // then accepts a per-profile extension for each discovered key. - const extension = `${canonical}_PARITY`; - const scoped = `openshell:resolve:env:v77_${extension}`; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - parity: { botToken: `openshell:resolve:env:${extension}` }, - }, - }, - }, - }, - { - NEMOCLAW_MESSAGING_PLAN_B64: placeholderPlan([canonical]), - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: extension, - [extension]: scoped, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect( - run.result.stderr, - `bash refresh refused manifest credential extension '${extension}'`, - ).not.toContain(`[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '${extension}'`); - expect(run.config.channels.telegram.accounts.parity.botToken).toBe(scoped); - }, - ); - - it("caps NEMOCLAW_EXTRA_PLACEHOLDER_KEYS at 32 entries inside the sandbox", async () => { - // The first 32 extension keys are accepted; the planted 33rd must remain unchanged. - const tokens = Array.from({ length: 33 }, (_, i) => `TELEGRAM_BOT_TOKEN_FILLER_${i}`); - const beyondCap = tokens[32]; - const beyondCapScoped = `openshell:resolve:env:v42_${beyondCap}`; - const env: Record = { - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: tokens.join(" "), - // Only the 33rd key has a scoped value, so any rewrite proves the cap was exceeded. - [beyondCap]: beyondCapScoped, - // Deliberately leave TELEGRAM_BOT_TOKEN / DISCORD_BOT_TOKEN / etc. - // unset so no canonical replacement is added; that sidesteps the - // python heredoc's substring-match path which would otherwise let a - // shorter canonical replacement bleed into beyondCap regardless of - // the cap state. - }; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - beyondCap: { - botToken: `openshell:resolve:env:${beyondCap}`, - }, - }, - }, - }, - }, - env, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "[config] NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: capped at 32 entries; ignoring remainder", - ); - // The beyondCap key must not be processed by the python heredoc, so the - // beyondCap canonical placeholder must stay unchanged on disk. - expect(run.config.channels.telegram.accounts.beyondCap.botToken).toBe( - `openshell:resolve:env:${beyondCap}`, - ); - expect(run.result.stderr).not.toContain( - `Refreshed provider placeholders from OpenShell runtime env: ${beyondCap}`, - ); - expect(run.result.stdout).not.toContain(beyondCapScoped); - }); -}); - describe("Telegram diagnostics (#2766)", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); const telegramDiagnosticsScript = startScriptHeredoc(src, "TELEGRAM_DIAGNOSTICS_EOF"); diff --git a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts new file mode 100644 index 00000000000..95c4a25f47c --- /dev/null +++ b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts @@ -0,0 +1,746 @@ +// @ts-nocheck +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFile } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import JSON5 from "json5"; +import { describe, expect, it, vi } from "vitest"; +import { extractShellFunctionFromSource } from "../../../helpers/shell-source"; + +const START_SCRIPT = path.resolve(import.meta.dirname, "../../../../scripts/nemoclaw-start.sh"); +const JSON5_MODULE = path.resolve(import.meta.dirname, "../../../../nemoclaw/node_modules/json5"); + +vi.setConfig({ maxConcurrency: 4 }); + +function execFileResult(file, args, options) { + return new Promise((resolve) => + execFile(file, args, options, (error, stdout, stderr) => + resolve({ + status: Number(error?.code) || (error ? -1 : 0), + stdout, + stderr, + }), + ), + ); +} + +describe.concurrent("provider placeholder refresh (#4251)", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const extraPlaceholderKeys = require( + path.join( + import.meta.dirname, + "../../../..", + "src", + "lib", + "onboard", + "extra-placeholder-keys.ts", + ), + ); + const canonicalKeys: string[] = Array.from( + extraPlaceholderKeys.canonicalPlaceholderKeys(), + ).sort(); + async function runRefresh( + config: unknown, + env: Record = {}, + rootMode = false, + runtimePlan: unknown = { credentialBindings: [] }, + ) { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-provider-placeholders-")); + try { + const openclawDir = path.join(tmpDir, ".openclaw"); + const configPath = path.join(openclawDir, "openclaw.json"); + const handoffEnvPath = path.join(tmpDir, "handoff-env"); + const runtimePlanPath = path.join(tmpDir, "messaging-runtime-plan.json"); + const scriptPath = path.join(tmpDir, "run.sh"); + fs.mkdirSync(openclawDir, { recursive: true }); + fs.writeFileSync( + configPath, + `// Native OpenClaw JSON5\n${JSON.stringify(config, null, 2)}\n`, + ); + fs.writeFileSync(runtimePlanPath, JSON.stringify(runtimePlan)); + const fn = extractShellFunctionFromSource(src, "refresh_openclaw_provider_placeholders") + .replaceAll("/sandbox/.openclaw", openclawDir) + .replaceAll("/usr/local/share/nemoclaw/messaging-runtime-plan.json", runtimePlanPath) + .replaceAll("/usr/local/lib/node_modules/openclaw/node_modules/json5", JSON5_MODULE) + .replaceAll("/usr/local/bin/node", process.execPath); + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail\nrefresh_openclaw_wechat_account_placeholder() { :; }", + ...(rootMode + ? [ + "id() { printf '0\\n'; }", + `STEP_DOWN_PREFIX_SANDBOX=(/bin/bash -c 'env >${JSON.stringify(handoffEnvPath)}; exec "$@"' sandbox-step-down)`, + extractShellFunctionFromSource(src, "run_openclaw_config_as_owner"), + ] + : ['run_openclaw_config_as_owner() { "$@"; }']), + fn, + "refresh_openclaw_provider_placeholders", + ].join("\n"), + { mode: 0o700 }, + ); + const result = await execFileResult("bash", [scriptPath], { + encoding: "utf-8", + env: { PATH: process.env.PATH || "", ...env }, + timeout: 5000, + }); + const updatedConfig = JSON5.parse(fs.readFileSync(configPath, "utf-8")); + const handoffEnv = fs.existsSync(handoffEnvPath) + ? fs.readFileSync(handoffEnvPath, "utf-8") + : ""; + return { config: updatedConfig, handoffEnv, result }; + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + } + + function placeholderPlan(envKeys: string[]): string { + return Buffer.from( + JSON.stringify({ + credentialBindings: envKeys.map((envKey) => ({ + providerEnvKey: envKey, + })), + }), + ).toString("base64"); + } + + it("withholds raw provider values from the root-to-sandbox config handoff", async () => { + const rawToken = "SENTINEL_RAW_PROVIDER_VALUE"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, + }, + }, + }, + }, + { + NEMOCLAW_MESSAGING_PLAN_B64: placeholderPlan(["TELEGRAM_BOT_TOKEN"]), + TELEGRAM_BOT_TOKEN: rawToken, + }, + true, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe( + "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + ); + expect(run.result.stderr).toContain("refusing to write raw credentials"); + expect(run.handoffEnv).not.toContain(rawToken); + expect(run.handoffEnv).not.toContain("TELEGRAM_BOT_TOKEN"); + }); + + it("rewrites Telegram canonical placeholders to OpenShell runtime-scoped placeholders", async () => { + const scoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }, + { TELEGRAM_BOT_TOKEN: scoped }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe(scoped); + expect(run.result.stderr).toContain( + "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN", + ); + expect(run.result.stderr).not.toContain("v42_TELEGRAM_BOT_TOKEN"); + }); + + it.each([false, true])( + "refreshes a persisted native NVIDIA handle after provider revision and supervisor restart (root=%s)", + async (rootMode) => { + const oldHandle = "openshell:resolve:env:v42_NVIDIA_INFERENCE_API_KEY"; + const currentHandle = "openshell:resolve:env:v43_NVIDIA_INFERENCE_API_KEY"; + const run = await runRefresh( + { + models: { + providers: { + inference: { + baseUrl: "https://integrate.api.nvidia.com/v1", + apiKey: oldHandle, + }, + }, + }, + channels: { telegram: { botToken: oldHandle } }, + }, + { NVIDIA_INFERENCE_API_KEY: currentHandle }, + rootMode, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.models.providers.inference.apiKey).toBe(currentHandle); + expect(run.config.channels.telegram.botToken).toBe(oldHandle); + expect(run.result.stderr).toContain( + "Refreshed provider placeholders from OpenShell runtime env: NVIDIA_INFERENCE_API_KEY", + ); + }, + ); + + it.each([ + { + reason: "raw credential in root environment", + endpoint: "https://integrate.api.nvidia.com/v1", + runtime: "nvapi-raw-secret", + rootMode: true, + }, + { + reason: "different endpoint", + endpoint: "https://example.com/v1", + runtime: "openshell:resolve:env:v43_NVIDIA_INFERENCE_API_KEY", + rootMode: false, + }, + { + reason: "missing runtime handle", + endpoint: "https://integrate.api.nvidia.com/v1", + runtime: "", + rootMode: false, + }, + ])( + "keeps a persisted native NVIDIA handle when refresh has $reason", + async ({ endpoint, runtime, rootMode }) => { + const saved = "openshell:resolve:env:v42_NVIDIA_INFERENCE_API_KEY"; + const run = await runRefresh( + { models: { providers: { inference: { baseUrl: endpoint, apiKey: saved } } } }, + runtime ? { NVIDIA_INFERENCE_API_KEY: runtime } : {}, + rootMode, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.models.providers.inference.apiKey).toBe(saved); + expect(JSON.stringify(run.config)).not.toContain("nvapi-raw-secret"); + expect(run.result.stderr).not.toContain("nvapi-raw-secret"); + expect(run.handoffEnv).not.toContain("nvapi-raw-secret"); + }, + ); + + it("does not write raw provider credentials into openclaw.json", async () => { + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }, + { TELEGRAM_BOT_TOKEN: "123456:SECRET" }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe( + "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + ); + expect(JSON.stringify(run.config)).not.toContain("123456:SECRET"); + expect(run.result.stderr).toContain("refusing to write raw credentials"); + }); + + it("warns when Telegram is configured but the runtime placeholder env is missing", async () => { + const run = await runRefresh({ + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "telegram.default.botToken is an OpenShell placeholder but TELEGRAM_BOT_TOKEN is missing", + ); + }); + + it("warns when the Slack config alias is present but SLACK_BOT_TOKEN is missing", async () => { + const run = await runRefresh({ + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", + }, + }, + }, + }, + }); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "slack.default.botToken expects the SLACK_BOT_TOKEN provider placeholder but it is missing", + ); + expect(run.result.stderr).toContain( + "slack.default.appToken expects the SLACK_APP_TOKEN provider placeholder but it is missing", + ); + }); + + it.each(["v42", `s${"a".repeat(64)}`])( + "does not warn when the Slack config alias matches an OpenShell %s runtime placeholder", + async (credentialHandle) => { + const run = await runRefresh( + { + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", + }, + }, + }, + }, + }, + { + SLACK_BOT_TOKEN: `openshell:resolve:env:${credentialHandle}_SLACK_BOT_TOKEN`, + SLACK_APP_TOKEN: `openshell:resolve:env:${credentialHandle}_SLACK_APP_TOKEN`, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).not.toContain("slack.default"); + expect(run.config.channels.slack.accounts.default.botToken).toBe( + `xoxb-OPENSHELL-RESOLVE-ENV-${credentialHandle}_SLACK_BOT_TOKEN`, + ); + expect(run.config.channels.slack.accounts.default.appToken).toBe( + `xapp-OPENSHELL-RESOLVE-ENV-${credentialHandle}_SLACK_APP_TOKEN`, + ); + }, + ); + + it("does not warn when the Slack runtime env holds a genuine xoxb-/xapp- token", async () => { + const run = await runRefresh( + { + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", + }, + }, + }, + }, + }, + { + SLACK_BOT_TOKEN: "xoxb-1-real-bot-token", + SLACK_APP_TOKEN: "xapp-1-real-app-token", + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).not.toContain("slack.default"); + expect(JSON.stringify(run.config)).not.toContain("xoxb-1-real-bot-token"); + }); + + it("warns when the Slack runtime env holds neither a placeholder nor a Slack token", async () => { + const run = await runRefresh( + { + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + }, + }, + }, + }, + }, + { SLACK_BOT_TOKEN: "garbage-not-a-token" }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "slack.default.botToken runtime SLACK_BOT_TOKEN is neither the SLACK_BOT_TOKEN OpenShell placeholder nor a xoxb- token", + ); + }); + + it("warns when the Slack runtime env resolves a different key than expected", async () => { + const run = await runRefresh( + { + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + }, + }, + }, + }, + }, + { SLACK_BOT_TOKEN: "openshell:resolve:env:v51_OTHER_KEY" }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "slack.default.botToken runtime SLACK_BOT_TOKEN is neither the SLACK_BOT_TOKEN OpenShell placeholder nor a xoxb- token", + ); + }); + + it("emits the accepted-extras signal from canonical keys in the default runtime plan (#10967)", async () => { + const run = await runRefresh( + {}, + { + NEMOCLAW_MESSAGING_RUNTIME_PLAN_PATH: "", + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", + }, + false, + { credentialBindings: [{ providerEnvKey: "TELEGRAM_BOT_TOKEN" }] }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toMatch(/accepted 1 entry\(ies\): TELEGRAM_BOT_TOKEN_AGENT_A/u); + }); + + it("does not emit the accepted-extras breadcrumb when NEMOCLAW_EXTRA_PLACEHOLDER_KEYS is unset", async () => { + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, + }, + }, + }, + }, + {}, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).not.toContain("[config] NEMOCLAW_EXTRA_PLACEHOLDER_KEYS accepted"); + }); + + it("splits NEMOCLAW_EXTRA_PLACEHOLDER_KEYS on commas the same way as whitespace", async () => { + const scopedA = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_A"; + const scopedB = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_B"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + a: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + }, + b: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_B", + }, + }, + }, + }, + }, + { + // Comma- and whitespace-mixed input — the bash for-loop only splits on + // default IFS (whitespace), so without the comma->space normalization + // both keys would arrive concatenated as a single token and fail the + // regex check. + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A,TELEGRAM_BOT_TOKEN_AGENT_B", + TELEGRAM_BOT_TOKEN_AGENT_A: scopedA, + TELEGRAM_BOT_TOKEN_AGENT_B: scopedB, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.a.botToken).toBe(scopedA); + expect(run.config.channels.telegram.accounts.b.botToken).toBe(scopedB); + expect(run.result.stderr).toContain( + "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN_AGENT_A,TELEGRAM_BOT_TOKEN_AGENT_B", + ); + }); + + it("revision-collapses NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entries the same way as canonical keys", async () => { + const scoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_A"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + }, + }, + }, + }, + }, + { + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", + TELEGRAM_BOT_TOKEN_AGENT_A: scoped, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe(scoped); + expect(run.result.stderr).toContain( + "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN_AGENT_A", + ); + }); + + it("does not let canonical TELEGRAM_BOT_TOKEN rewrite the suffixed extra placeholder", async () => { + // Pre-fix bug: the python rewrite did `if old in value: value.replace(old, new)`, + // so the canonical replacement for `openshell:resolve:env:TELEGRAM_BOT_TOKEN` + // greedily rewrote the prefix of `openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A`, + // routing the per-profile placeholder to the wrong canonical revision and + // making rotation of an extra key unsafe. The grammar-aware regex now + // matches each placeholder as an exact token only. + const canonicalScoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; + const extraScoped = "openshell:resolve:env:v51_TELEGRAM_BOT_TOKEN_AGENT_A"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, + agentA: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + }, + }, + }, + }, + }, + { + TELEGRAM_BOT_TOKEN: canonicalScoped, + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", + TELEGRAM_BOT_TOKEN_AGENT_A: extraScoped, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe(canonicalScoped); + expect(run.config.channels.telegram.accounts.agentA.botToken).toBe(extraScoped); + }); + + it("leaves the suffixed extra placeholder unchanged when only the canonical revision is set", async () => { + // Companion to the canonical-vs-extra collision test: when the operator + // staged a revision for TELEGRAM_BOT_TOKEN but not for the extra key, + // the extra placeholder must stay on its canonical form rather than be + // partially rewritten by the prefix replacement. + const canonicalScoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, + agentA: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + }, + }, + }, + }, + }, + { + TELEGRAM_BOT_TOKEN: canonicalScoped, + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe(canonicalScoped); + expect(run.config.channels.telegram.accounts.agentA.botToken).toBe( + "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + ); + }); + + it("rejects malformed and canonical-collision NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entries without faulting", async () => { + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }, + { + TELEGRAM_BOT_TOKEN: "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: + "telegram_bot_token 9NUM_START Path$Bad TELEGRAM_BOT_TOKEN TELEGRAM_BOT_TOKEN_VALID", + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'telegram_bot_token'", + ); + expect(run.result.stderr).toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '9NUM_START'", + ); + expect(run.result.stderr).toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'Path$Bad'", + ); + // Canonical-collision tokens are filtered silently by the case statement. + expect(run.result.stderr).not.toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'TELEGRAM_BOT_TOKEN'", + ); + // The canonical-key revision-collapse still runs end-to-end. + expect(run.config.channels.telegram.accounts.default.botToken).toBe( + "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", + ); + }); + + it.each([ + "GITHUB_TOKEN", + "AWS_SECRET_ACCESS_KEY", + "NPM_TOKEN", + "KUBECONFIG", + "NEMOCLAW_EXTRA_PLACEHOLDER_KEYS", + ])( + "refuses arbitrary host secret names that do not extend a discovered provider envKey inside the sandbox [%s]", + async (blocked) => { + // Defence-in-depth: even if an operator clobbers NEMOCLAW_EXTRA_PLACEHOLDER_KEYS + // inside a running sandbox after the host-side parser already filtered it, + // the container-side refresh helper must mirror the host's canonical-prefix + // restriction so a noncanonical name such as GITHUB_TOKEN never reaches the + // python placeholder walker. + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }, + { + TELEGRAM_BOT_TOKEN: "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: + "GITHUB_TOKEN AWS_SECRET_ACCESS_KEY NPM_TOKEN KUBECONFIG NEMOCLAW_EXTRA_PLACEHOLDER_KEYS TELEGRAM_BOT_TOKEN_KEPT", + // Stage host secrets that would leak if the bash refresh ever + // accepted their names. The assertion below confirms none of these + // values appear in any output produced by the python heredoc. + GITHUB_TOKEN: "ghp-host-secret-would-leak", + AWS_SECRET_ACCESS_KEY: "aws-host-secret-would-leak", + NPM_TOKEN: "npm-host-secret-would-leak", + KUBECONFIG: "/host/path/would-leak", + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + + expect(run.result.stderr).toContain( + `[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '${blocked}' — must extend a discovered provider envKey such as TELEGRAM_BOT_TOKEN_`, + ); + + expect(run.result.stderr).not.toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'TELEGRAM_BOT_TOKEN_KEPT'", + ); + // None of the staged host secret values should reach any stdout/stderr + // line the python heredoc emits, because their names were rejected before + // the heredoc ran. + expect(run.result.stderr).not.toContain("ghp-host-secret-would-leak"); + expect(run.result.stderr).not.toContain("aws-host-secret-would-leak"); + expect(run.result.stderr).not.toContain("npm-host-secret-would-leak"); + expect(run.result.stdout).not.toContain("ghp-host-secret-would-leak"); + expect(run.result.stdout).not.toContain("aws-host-secret-would-leak"); + expect(run.result.stdout).not.toContain("npm-host-secret-would-leak"); + expect(JSON.stringify(run.config)).not.toContain("ghp-host-secret-would-leak"); + expect(JSON.stringify(run.config)).not.toContain("aws-host-secret-would-leak"); + }, + ); + + it.each(canonicalKeys)( + "accepts manifest credential envKey %s as an extension prefix", + async (canonical) => { + // Behavioural parity guard: the in-container parser should not hardcode + // channel env keys. It consumes the messaging plan's credentialBindings, + // then accepts a per-profile extension for each discovered key. + const extension = `${canonical}_PARITY`; + const scoped = `openshell:resolve:env:v77_${extension}`; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + parity: { botToken: `openshell:resolve:env:${extension}` }, + }, + }, + }, + }, + { + NEMOCLAW_MESSAGING_PLAN_B64: placeholderPlan([canonical]), + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: extension, + [extension]: scoped, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect( + run.result.stderr, + `bash refresh refused manifest credential extension '${extension}'`, + ).not.toContain(`[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '${extension}'`); + expect(run.config.channels.telegram.accounts.parity.botToken).toBe(scoped); + }, + ); + + it("caps NEMOCLAW_EXTRA_PLACEHOLDER_KEYS at 32 entries inside the sandbox", async () => { + // The first 32 extension keys are accepted; the planted 33rd must remain unchanged. + const tokens = Array.from({ length: 33 }, (_, i) => `TELEGRAM_BOT_TOKEN_FILLER_${i}`); + const beyondCap = tokens[32]; + const beyondCapScoped = `openshell:resolve:env:v42_${beyondCap}`; + const env: Record = { + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: tokens.join(" "), + // Only the 33rd key has a scoped value, so any rewrite proves the cap was exceeded. + [beyondCap]: beyondCapScoped, + // Deliberately leave TELEGRAM_BOT_TOKEN / DISCORD_BOT_TOKEN / etc. + // unset so no canonical replacement is added; that sidesteps the + // python heredoc's substring-match path which would otherwise let a + // shorter canonical replacement bleed into beyondCap regardless of + // the cap state. + }; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + beyondCap: { + botToken: `openshell:resolve:env:${beyondCap}`, + }, + }, + }, + }, + }, + env, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "[config] NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: capped at 32 entries; ignoring remainder", + ); + // The beyondCap key must not be processed by the python heredoc, so the + // beyondCap canonical placeholder must stay unchanged on disk. + expect(run.config.channels.telegram.accounts.beyondCap.botToken).toBe( + `openshell:resolve:env:${beyondCap}`, + ); + expect(run.result.stderr).not.toContain( + `Refreshed provider placeholders from OpenShell runtime env: ${beyondCap}`, + ); + expect(run.result.stdout).not.toContain(beyondCapScoped); + }); +}); From aec30bad5d324f4b5a2fba16a16a11e2f0778df6 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:51:51 -0700 Subject: [PATCH 10/11] test(openclaw): isolate native handle restart regression Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/test-file-size-budget.json | 2 +- .../openclaw/runtime/nemoclaw-start.test.ts | 663 ++++++++++++++++++ .../provider-placeholder-refresh.test.ts | 594 +--------------- 3 files changed, 665 insertions(+), 594 deletions(-) diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index f6be7aef711..246e8940458 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -6,7 +6,7 @@ "src/lib/onboard/preflight.test.ts": 1875, "test/generation/generate-openclaw-config.test.ts": 1844, "test/installer-integration/install-preflight.test.ts": 2995, - "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 2713, + "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 3376, "test/onboarding/onboard-messaging.test.ts": 1960, "test/onboarding/onboard-selection.test.ts": 4125 } diff --git a/test/agents/openclaw/runtime/nemoclaw-start.test.ts b/test/agents/openclaw/runtime/nemoclaw-start.test.ts index c9803357c68..4cca048c5c1 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start.test.ts @@ -7,6 +7,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; +import JSON5 from "json5"; import * as ts from "typescript"; import { describe, expect, it, vi } from "vitest"; import { extractShellFunctionFromSource } from "../../../helpers/shell-source"; @@ -40,6 +41,17 @@ const runCommand = promisify(execFile); // Concurrent process fixtures are independent, but keep their host load bounded. vi.setConfig({ maxConcurrency: 4 }); +function execFileResult(file, args, options) { + return new Promise((resolve) => + execFile(file, args, options, (error, stdout, stderr) => + resolve({ + status: Number(error?.code) || (error ? -1 : 0), + stdout, + stderr, + }), + ), + ); +} function runtimeShellEnvBlock(src: string): string { const start = src.indexOf("write_runtime_shell_env() {"); const end = src.indexOf("# cleanup_on_signal", start); @@ -2230,6 +2242,657 @@ describe("Slack secrets-on-disk tripwire (#2085)", () => { }); }); +describe.concurrent("provider placeholder refresh (#4251)", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const extraPlaceholderKeys = require( + path.join( + import.meta.dirname, + "../../../..", + "src", + "lib", + "onboard", + "extra-placeholder-keys.ts", + ), + ); + const canonicalKeys: string[] = Array.from( + extraPlaceholderKeys.canonicalPlaceholderKeys(), + ).sort(); + async function runRefresh( + config: unknown, + env: Record = {}, + rootMode = false, + runtimePlan: unknown = { credentialBindings: [] }, + ) { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-provider-placeholders-")); + try { + const openclawDir = path.join(tmpDir, ".openclaw"); + const configPath = path.join(openclawDir, "openclaw.json"); + const handoffEnvPath = path.join(tmpDir, "handoff-env"); + const runtimePlanPath = path.join(tmpDir, "messaging-runtime-plan.json"); + const scriptPath = path.join(tmpDir, "run.sh"); + fs.mkdirSync(openclawDir, { recursive: true }); + fs.writeFileSync( + configPath, + `// Native OpenClaw JSON5\n${JSON.stringify(config, null, 2)}\n`, + ); + fs.writeFileSync(runtimePlanPath, JSON.stringify(runtimePlan)); + const fn = extractShellFunctionFromSource(src, "refresh_openclaw_provider_placeholders") + .replaceAll("/sandbox/.openclaw", openclawDir) + .replaceAll("/usr/local/share/nemoclaw/messaging-runtime-plan.json", runtimePlanPath) + .replaceAll("/usr/local/lib/node_modules/openclaw/node_modules/json5", JSON5_MODULE) + .replaceAll("/usr/local/bin/node", process.execPath); + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail\nrefresh_openclaw_wechat_account_placeholder() { :; }", + ...(rootMode + ? [ + "id() { printf '0\\n'; }", + `STEP_DOWN_PREFIX_SANDBOX=(/bin/bash -c 'env >${JSON.stringify(handoffEnvPath)}; exec "$@"' sandbox-step-down)`, + extractShellFunctionFromSource(src, "run_openclaw_config_as_owner"), + ] + : ['run_openclaw_config_as_owner() { "$@"; }']), + fn, + "refresh_openclaw_provider_placeholders", + ].join("\n"), + { mode: 0o700 }, + ); + const result = await execFileResult("bash", [scriptPath], { + encoding: "utf-8", + env: { PATH: process.env.PATH || "", ...env }, + timeout: 5000, + }); + const updatedConfig = JSON5.parse(fs.readFileSync(configPath, "utf-8")); + const handoffEnv = fs.existsSync(handoffEnvPath) + ? fs.readFileSync(handoffEnvPath, "utf-8") + : ""; + return { config: updatedConfig, handoffEnv, result }; + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + } + + function placeholderPlan(envKeys: string[]): string { + return Buffer.from( + JSON.stringify({ + credentialBindings: envKeys.map((envKey) => ({ + providerEnvKey: envKey, + })), + }), + ).toString("base64"); + } + + it("withholds raw provider values from the root-to-sandbox config handoff", async () => { + const rawToken = "SENTINEL_RAW_PROVIDER_VALUE"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, + }, + }, + }, + }, + { + NEMOCLAW_MESSAGING_PLAN_B64: placeholderPlan(["TELEGRAM_BOT_TOKEN"]), + TELEGRAM_BOT_TOKEN: rawToken, + }, + true, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe( + "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + ); + expect(run.result.stderr).toContain("refusing to write raw credentials"); + expect(run.handoffEnv).not.toContain(rawToken); + expect(run.handoffEnv).not.toContain("TELEGRAM_BOT_TOKEN"); + }); + + it("rewrites Telegram canonical placeholders to OpenShell runtime-scoped placeholders", async () => { + const scoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }, + { TELEGRAM_BOT_TOKEN: scoped }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe(scoped); + expect(run.result.stderr).toContain( + "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN", + ); + expect(run.result.stderr).not.toContain("v42_TELEGRAM_BOT_TOKEN"); + }); + + it("does not write raw provider credentials into openclaw.json", async () => { + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }, + { TELEGRAM_BOT_TOKEN: "123456:SECRET" }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe( + "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + ); + expect(JSON.stringify(run.config)).not.toContain("123456:SECRET"); + expect(run.result.stderr).toContain("refusing to write raw credentials"); + }); + + it("warns when Telegram is configured but the runtime placeholder env is missing", async () => { + const run = await runRefresh({ + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "telegram.default.botToken is an OpenShell placeholder but TELEGRAM_BOT_TOKEN is missing", + ); + }); + + it("warns when the Slack config alias is present but SLACK_BOT_TOKEN is missing", async () => { + const run = await runRefresh({ + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", + }, + }, + }, + }, + }); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "slack.default.botToken expects the SLACK_BOT_TOKEN provider placeholder but it is missing", + ); + expect(run.result.stderr).toContain( + "slack.default.appToken expects the SLACK_APP_TOKEN provider placeholder but it is missing", + ); + }); + + it.each(["v42", `s${"a".repeat(64)}`])( + "does not warn when the Slack config alias matches an OpenShell %s runtime placeholder", + async (credentialHandle) => { + const run = await runRefresh( + { + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", + }, + }, + }, + }, + }, + { + SLACK_BOT_TOKEN: `openshell:resolve:env:${credentialHandle}_SLACK_BOT_TOKEN`, + SLACK_APP_TOKEN: `openshell:resolve:env:${credentialHandle}_SLACK_APP_TOKEN`, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).not.toContain("slack.default"); + expect(run.config.channels.slack.accounts.default.botToken).toBe( + `xoxb-OPENSHELL-RESOLVE-ENV-${credentialHandle}_SLACK_BOT_TOKEN`, + ); + expect(run.config.channels.slack.accounts.default.appToken).toBe( + `xapp-OPENSHELL-RESOLVE-ENV-${credentialHandle}_SLACK_APP_TOKEN`, + ); + }, + ); + + it("does not warn when the Slack runtime env holds a genuine xoxb-/xapp- token", async () => { + const run = await runRefresh( + { + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", + }, + }, + }, + }, + }, + { + SLACK_BOT_TOKEN: "xoxb-1-real-bot-token", + SLACK_APP_TOKEN: "xapp-1-real-app-token", + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).not.toContain("slack.default"); + expect(JSON.stringify(run.config)).not.toContain("xoxb-1-real-bot-token"); + }); + + it("warns when the Slack runtime env holds neither a placeholder nor a Slack token", async () => { + const run = await runRefresh( + { + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + }, + }, + }, + }, + }, + { SLACK_BOT_TOKEN: "garbage-not-a-token" }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "slack.default.botToken runtime SLACK_BOT_TOKEN is neither the SLACK_BOT_TOKEN OpenShell placeholder nor a xoxb- token", + ); + }); + + it("warns when the Slack runtime env resolves a different key than expected", async () => { + const run = await runRefresh( + { + channels: { + slack: { + accounts: { + default: { + botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + }, + }, + }, + }, + }, + { SLACK_BOT_TOKEN: "openshell:resolve:env:v51_OTHER_KEY" }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "slack.default.botToken runtime SLACK_BOT_TOKEN is neither the SLACK_BOT_TOKEN OpenShell placeholder nor a xoxb- token", + ); + }); + + it("emits the accepted-extras signal from canonical keys in the default runtime plan (#10967)", async () => { + const run = await runRefresh( + {}, + { + NEMOCLAW_MESSAGING_RUNTIME_PLAN_PATH: "", + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", + }, + false, + { credentialBindings: [{ providerEnvKey: "TELEGRAM_BOT_TOKEN" }] }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toMatch(/accepted 1 entry\(ies\): TELEGRAM_BOT_TOKEN_AGENT_A/u); + }); + + it("does not emit the accepted-extras breadcrumb when NEMOCLAW_EXTRA_PLACEHOLDER_KEYS is unset", async () => { + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, + }, + }, + }, + }, + {}, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).not.toContain("[config] NEMOCLAW_EXTRA_PLACEHOLDER_KEYS accepted"); + }); + + it("splits NEMOCLAW_EXTRA_PLACEHOLDER_KEYS on commas the same way as whitespace", async () => { + const scopedA = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_A"; + const scopedB = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_B"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + a: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + }, + b: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_B", + }, + }, + }, + }, + }, + { + // Comma- and whitespace-mixed input — the bash for-loop only splits on + // default IFS (whitespace), so without the comma->space normalization + // both keys would arrive concatenated as a single token and fail the + // regex check. + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A,TELEGRAM_BOT_TOKEN_AGENT_B", + TELEGRAM_BOT_TOKEN_AGENT_A: scopedA, + TELEGRAM_BOT_TOKEN_AGENT_B: scopedB, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.a.botToken).toBe(scopedA); + expect(run.config.channels.telegram.accounts.b.botToken).toBe(scopedB); + expect(run.result.stderr).toContain( + "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN_AGENT_A,TELEGRAM_BOT_TOKEN_AGENT_B", + ); + }); + + it("revision-collapses NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entries the same way as canonical keys", async () => { + const scoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_A"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + }, + }, + }, + }, + }, + { + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", + TELEGRAM_BOT_TOKEN_AGENT_A: scoped, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe(scoped); + expect(run.result.stderr).toContain( + "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN_AGENT_A", + ); + }); + + it("does not let canonical TELEGRAM_BOT_TOKEN rewrite the suffixed extra placeholder", async () => { + // Pre-fix bug: the python rewrite did `if old in value: value.replace(old, new)`, + // so the canonical replacement for `openshell:resolve:env:TELEGRAM_BOT_TOKEN` + // greedily rewrote the prefix of `openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A`, + // routing the per-profile placeholder to the wrong canonical revision and + // making rotation of an extra key unsafe. The grammar-aware regex now + // matches each placeholder as an exact token only. + const canonicalScoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; + const extraScoped = "openshell:resolve:env:v51_TELEGRAM_BOT_TOKEN_AGENT_A"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, + agentA: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + }, + }, + }, + }, + }, + { + TELEGRAM_BOT_TOKEN: canonicalScoped, + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", + TELEGRAM_BOT_TOKEN_AGENT_A: extraScoped, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe(canonicalScoped); + expect(run.config.channels.telegram.accounts.agentA.botToken).toBe(extraScoped); + }); + + it("leaves the suffixed extra placeholder unchanged when only the canonical revision is set", async () => { + // Companion to the canonical-vs-extra collision test: when the operator + // staged a revision for TELEGRAM_BOT_TOKEN but not for the extra key, + // the extra placeholder must stay on its canonical form rather than be + // partially rewritten by the prefix replacement. + const canonicalScoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, + agentA: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + }, + }, + }, + }, + }, + { + TELEGRAM_BOT_TOKEN: canonicalScoped, + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.channels.telegram.accounts.default.botToken).toBe(canonicalScoped); + expect(run.config.channels.telegram.accounts.agentA.botToken).toBe( + "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", + ); + }); + + it("rejects malformed and canonical-collision NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entries without faulting", async () => { + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }, + { + TELEGRAM_BOT_TOKEN: "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: + "telegram_bot_token 9NUM_START Path$Bad TELEGRAM_BOT_TOKEN TELEGRAM_BOT_TOKEN_VALID", + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'telegram_bot_token'", + ); + expect(run.result.stderr).toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '9NUM_START'", + ); + expect(run.result.stderr).toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'Path$Bad'", + ); + // Canonical-collision tokens are filtered silently by the case statement. + expect(run.result.stderr).not.toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'TELEGRAM_BOT_TOKEN'", + ); + // The canonical-key revision-collapse still runs end-to-end. + expect(run.config.channels.telegram.accounts.default.botToken).toBe( + "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", + ); + }); + + it.each([ + "GITHUB_TOKEN", + "AWS_SECRET_ACCESS_KEY", + "NPM_TOKEN", + "KUBECONFIG", + "NEMOCLAW_EXTRA_PLACEHOLDER_KEYS", + ])( + "refuses arbitrary host secret names that do not extend a discovered provider envKey inside the sandbox [%s]", + async (blocked) => { + // Defence-in-depth: even if an operator clobbers NEMOCLAW_EXTRA_PLACEHOLDER_KEYS + // inside a running sandbox after the host-side parser already filtered it, + // the container-side refresh helper must mirror the host's canonical-prefix + // restriction so a noncanonical name such as GITHUB_TOKEN never reaches the + // python placeholder walker. + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + }, + }, + }, + }, + { + TELEGRAM_BOT_TOKEN: "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: + "GITHUB_TOKEN AWS_SECRET_ACCESS_KEY NPM_TOKEN KUBECONFIG NEMOCLAW_EXTRA_PLACEHOLDER_KEYS TELEGRAM_BOT_TOKEN_KEPT", + // Stage host secrets that would leak if the bash refresh ever + // accepted their names. The assertion below confirms none of these + // values appear in any output produced by the python heredoc. + GITHUB_TOKEN: "ghp-host-secret-would-leak", + AWS_SECRET_ACCESS_KEY: "aws-host-secret-would-leak", + NPM_TOKEN: "npm-host-secret-would-leak", + KUBECONFIG: "/host/path/would-leak", + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + + expect(run.result.stderr).toContain( + `[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '${blocked}' — must extend a discovered provider envKey such as TELEGRAM_BOT_TOKEN_`, + ); + + expect(run.result.stderr).not.toContain( + "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'TELEGRAM_BOT_TOKEN_KEPT'", + ); + // None of the staged host secret values should reach any stdout/stderr + // line the python heredoc emits, because their names were rejected before + // the heredoc ran. + expect(run.result.stderr).not.toContain("ghp-host-secret-would-leak"); + expect(run.result.stderr).not.toContain("aws-host-secret-would-leak"); + expect(run.result.stderr).not.toContain("npm-host-secret-would-leak"); + expect(run.result.stdout).not.toContain("ghp-host-secret-would-leak"); + expect(run.result.stdout).not.toContain("aws-host-secret-would-leak"); + expect(run.result.stdout).not.toContain("npm-host-secret-would-leak"); + expect(JSON.stringify(run.config)).not.toContain("ghp-host-secret-would-leak"); + expect(JSON.stringify(run.config)).not.toContain("aws-host-secret-would-leak"); + }, + ); + + it.each(canonicalKeys)( + "accepts manifest credential envKey %s as an extension prefix", + async (canonical) => { + // Behavioural parity guard: the in-container parser should not hardcode + // channel env keys. It consumes the messaging plan's credentialBindings, + // then accepts a per-profile extension for each discovered key. + const extension = `${canonical}_PARITY`; + const scoped = `openshell:resolve:env:v77_${extension}`; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + parity: { botToken: `openshell:resolve:env:${extension}` }, + }, + }, + }, + }, + { + NEMOCLAW_MESSAGING_PLAN_B64: placeholderPlan([canonical]), + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: extension, + [extension]: scoped, + }, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect( + run.result.stderr, + `bash refresh refused manifest credential extension '${extension}'`, + ).not.toContain(`[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '${extension}'`); + expect(run.config.channels.telegram.accounts.parity.botToken).toBe(scoped); + }, + ); + + it("caps NEMOCLAW_EXTRA_PLACEHOLDER_KEYS at 32 entries inside the sandbox", async () => { + // The first 32 extension keys are accepted; the planted 33rd must remain unchanged. + const tokens = Array.from({ length: 33 }, (_, i) => `TELEGRAM_BOT_TOKEN_FILLER_${i}`); + const beyondCap = tokens[32]; + const beyondCapScoped = `openshell:resolve:env:v42_${beyondCap}`; + const env: Record = { + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: tokens.join(" "), + // Only the 33rd key has a scoped value, so any rewrite proves the cap was exceeded. + [beyondCap]: beyondCapScoped, + // Deliberately leave TELEGRAM_BOT_TOKEN / DISCORD_BOT_TOKEN / etc. + // unset so no canonical replacement is added; that sidesteps the + // python heredoc's substring-match path which would otherwise let a + // shorter canonical replacement bleed into beyondCap regardless of + // the cap state. + }; + const run = await runRefresh( + { + channels: { + telegram: { + accounts: { + default: { + botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + }, + beyondCap: { + botToken: `openshell:resolve:env:${beyondCap}`, + }, + }, + }, + }, + }, + env, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.result.stderr).toContain( + "[config] NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: capped at 32 entries; ignoring remainder", + ); + // The beyondCap key must not be processed by the python heredoc, so the + // beyondCap canonical placeholder must stay unchanged on disk. + expect(run.config.channels.telegram.accounts.beyondCap.botToken).toBe( + `openshell:resolve:env:${beyondCap}`, + ); + expect(run.result.stderr).not.toContain( + `Refreshed provider placeholders from OpenShell runtime env: ${beyondCap}`, + ); + expect(run.result.stdout).not.toContain(beyondCapScoped); + }); +}); + describe("Telegram diagnostics (#2766)", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); const telegramDiagnosticsScript = startScriptHeredoc(src, "TELEGRAM_DIAGNOSTICS_EOF"); diff --git a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts index 95c4a25f47c..c99aa6eadeb 100644 --- a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts +++ b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts @@ -27,21 +27,8 @@ function execFileResult(file, args, options) { ); } -describe.concurrent("provider placeholder refresh (#4251)", () => { +describe.concurrent("native NVIDIA handle refresh", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); - const extraPlaceholderKeys = require( - path.join( - import.meta.dirname, - "../../../..", - "src", - "lib", - "onboard", - "extra-placeholder-keys.ts", - ), - ); - const canonicalKeys: string[] = Array.from( - extraPlaceholderKeys.canonicalPlaceholderKeys(), - ).sort(); async function runRefresh( config: unknown, env: Record = {}, @@ -98,69 +85,6 @@ describe.concurrent("provider placeholder refresh (#4251)", () => { } } - function placeholderPlan(envKeys: string[]): string { - return Buffer.from( - JSON.stringify({ - credentialBindings: envKeys.map((envKey) => ({ - providerEnvKey: envKey, - })), - }), - ).toString("base64"); - } - - it("withholds raw provider values from the root-to-sandbox config handoff", async () => { - const rawToken = "SENTINEL_RAW_PROVIDER_VALUE"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, - }, - }, - }, - }, - { - NEMOCLAW_MESSAGING_PLAN_B64: placeholderPlan(["TELEGRAM_BOT_TOKEN"]), - TELEGRAM_BOT_TOKEN: rawToken, - }, - true, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe( - "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - ); - expect(run.result.stderr).toContain("refusing to write raw credentials"); - expect(run.handoffEnv).not.toContain(rawToken); - expect(run.handoffEnv).not.toContain("TELEGRAM_BOT_TOKEN"); - }); - - it("rewrites Telegram canonical placeholders to OpenShell runtime-scoped placeholders", async () => { - const scoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }, - { TELEGRAM_BOT_TOKEN: scoped }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe(scoped); - expect(run.result.stderr).toContain( - "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN", - ); - expect(run.result.stderr).not.toContain("v42_TELEGRAM_BOT_TOKEN"); - }); - it.each([false, true])( "refreshes a persisted native NVIDIA handle after provider revision and supervisor restart (root=%s)", async (rootMode) => { @@ -227,520 +151,4 @@ describe.concurrent("provider placeholder refresh (#4251)", () => { expect(run.handoffEnv).not.toContain("nvapi-raw-secret"); }, ); - - it("does not write raw provider credentials into openclaw.json", async () => { - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }, - { TELEGRAM_BOT_TOKEN: "123456:SECRET" }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe( - "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - ); - expect(JSON.stringify(run.config)).not.toContain("123456:SECRET"); - expect(run.result.stderr).toContain("refusing to write raw credentials"); - }); - - it("warns when Telegram is configured but the runtime placeholder env is missing", async () => { - const run = await runRefresh({ - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "telegram.default.botToken is an OpenShell placeholder but TELEGRAM_BOT_TOKEN is missing", - ); - }); - - it("warns when the Slack config alias is present but SLACK_BOT_TOKEN is missing", async () => { - const run = await runRefresh({ - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", - }, - }, - }, - }, - }); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "slack.default.botToken expects the SLACK_BOT_TOKEN provider placeholder but it is missing", - ); - expect(run.result.stderr).toContain( - "slack.default.appToken expects the SLACK_APP_TOKEN provider placeholder but it is missing", - ); - }); - - it.each(["v42", `s${"a".repeat(64)}`])( - "does not warn when the Slack config alias matches an OpenShell %s runtime placeholder", - async (credentialHandle) => { - const run = await runRefresh( - { - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", - }, - }, - }, - }, - }, - { - SLACK_BOT_TOKEN: `openshell:resolve:env:${credentialHandle}_SLACK_BOT_TOKEN`, - SLACK_APP_TOKEN: `openshell:resolve:env:${credentialHandle}_SLACK_APP_TOKEN`, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).not.toContain("slack.default"); - expect(run.config.channels.slack.accounts.default.botToken).toBe( - `xoxb-OPENSHELL-RESOLVE-ENV-${credentialHandle}_SLACK_BOT_TOKEN`, - ); - expect(run.config.channels.slack.accounts.default.appToken).toBe( - `xapp-OPENSHELL-RESOLVE-ENV-${credentialHandle}_SLACK_APP_TOKEN`, - ); - }, - ); - - it("does not warn when the Slack runtime env holds a genuine xoxb-/xapp- token", async () => { - const run = await runRefresh( - { - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - appToken: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", - }, - }, - }, - }, - }, - { - SLACK_BOT_TOKEN: "xoxb-1-real-bot-token", - SLACK_APP_TOKEN: "xapp-1-real-app-token", - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).not.toContain("slack.default"); - expect(JSON.stringify(run.config)).not.toContain("xoxb-1-real-bot-token"); - }); - - it("warns when the Slack runtime env holds neither a placeholder nor a Slack token", async () => { - const run = await runRefresh( - { - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - }, - }, - }, - }, - }, - { SLACK_BOT_TOKEN: "garbage-not-a-token" }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "slack.default.botToken runtime SLACK_BOT_TOKEN is neither the SLACK_BOT_TOKEN OpenShell placeholder nor a xoxb- token", - ); - }); - - it("warns when the Slack runtime env resolves a different key than expected", async () => { - const run = await runRefresh( - { - channels: { - slack: { - accounts: { - default: { - botToken: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - }, - }, - }, - }, - }, - { SLACK_BOT_TOKEN: "openshell:resolve:env:v51_OTHER_KEY" }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "slack.default.botToken runtime SLACK_BOT_TOKEN is neither the SLACK_BOT_TOKEN OpenShell placeholder nor a xoxb- token", - ); - }); - - it("emits the accepted-extras signal from canonical keys in the default runtime plan (#10967)", async () => { - const run = await runRefresh( - {}, - { - NEMOCLAW_MESSAGING_RUNTIME_PLAN_PATH: "", - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", - }, - false, - { credentialBindings: [{ providerEnvKey: "TELEGRAM_BOT_TOKEN" }] }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toMatch(/accepted 1 entry\(ies\): TELEGRAM_BOT_TOKEN_AGENT_A/u); - }); - - it("does not emit the accepted-extras breadcrumb when NEMOCLAW_EXTRA_PLACEHOLDER_KEYS is unset", async () => { - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, - }, - }, - }, - }, - {}, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).not.toContain("[config] NEMOCLAW_EXTRA_PLACEHOLDER_KEYS accepted"); - }); - - it("splits NEMOCLAW_EXTRA_PLACEHOLDER_KEYS on commas the same way as whitespace", async () => { - const scopedA = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_A"; - const scopedB = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_B"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - a: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - }, - b: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_B", - }, - }, - }, - }, - }, - { - // Comma- and whitespace-mixed input — the bash for-loop only splits on - // default IFS (whitespace), so without the comma->space normalization - // both keys would arrive concatenated as a single token and fail the - // regex check. - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A,TELEGRAM_BOT_TOKEN_AGENT_B", - TELEGRAM_BOT_TOKEN_AGENT_A: scopedA, - TELEGRAM_BOT_TOKEN_AGENT_B: scopedB, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.a.botToken).toBe(scopedA); - expect(run.config.channels.telegram.accounts.b.botToken).toBe(scopedB); - expect(run.result.stderr).toContain( - "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN_AGENT_A,TELEGRAM_BOT_TOKEN_AGENT_B", - ); - }); - - it("revision-collapses NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entries the same way as canonical keys", async () => { - const scoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN_AGENT_A"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - }, - }, - }, - }, - }, - { - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", - TELEGRAM_BOT_TOKEN_AGENT_A: scoped, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe(scoped); - expect(run.result.stderr).toContain( - "Refreshed provider placeholders from OpenShell runtime env: TELEGRAM_BOT_TOKEN_AGENT_A", - ); - }); - - it("does not let canonical TELEGRAM_BOT_TOKEN rewrite the suffixed extra placeholder", async () => { - // Pre-fix bug: the python rewrite did `if old in value: value.replace(old, new)`, - // so the canonical replacement for `openshell:resolve:env:TELEGRAM_BOT_TOKEN` - // greedily rewrote the prefix of `openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A`, - // routing the per-profile placeholder to the wrong canonical revision and - // making rotation of an extra key unsafe. The grammar-aware regex now - // matches each placeholder as an exact token only. - const canonicalScoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; - const extraScoped = "openshell:resolve:env:v51_TELEGRAM_BOT_TOKEN_AGENT_A"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, - agentA: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - }, - }, - }, - }, - }, - { - TELEGRAM_BOT_TOKEN: canonicalScoped, - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", - TELEGRAM_BOT_TOKEN_AGENT_A: extraScoped, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe(canonicalScoped); - expect(run.config.channels.telegram.accounts.agentA.botToken).toBe(extraScoped); - }); - - it("leaves the suffixed extra placeholder unchanged when only the canonical revision is set", async () => { - // Companion to the canonical-vs-extra collision test: when the operator - // staged a revision for TELEGRAM_BOT_TOKEN but not for the extra key, - // the extra placeholder must stay on its canonical form rather than be - // partially rewritten by the prefix replacement. - const canonicalScoped = "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN"; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN" }, - agentA: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - }, - }, - }, - }, - }, - { - TELEGRAM_BOT_TOKEN: canonicalScoped, - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.config.channels.telegram.accounts.default.botToken).toBe(canonicalScoped); - expect(run.config.channels.telegram.accounts.agentA.botToken).toBe( - "openshell:resolve:env:TELEGRAM_BOT_TOKEN_AGENT_A", - ); - }); - - it("rejects malformed and canonical-collision NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entries without faulting", async () => { - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }, - { - TELEGRAM_BOT_TOKEN: "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: - "telegram_bot_token 9NUM_START Path$Bad TELEGRAM_BOT_TOKEN TELEGRAM_BOT_TOKEN_VALID", - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'telegram_bot_token'", - ); - expect(run.result.stderr).toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '9NUM_START'", - ); - expect(run.result.stderr).toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'Path$Bad'", - ); - // Canonical-collision tokens are filtered silently by the case statement. - expect(run.result.stderr).not.toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'TELEGRAM_BOT_TOKEN'", - ); - // The canonical-key revision-collapse still runs end-to-end. - expect(run.config.channels.telegram.accounts.default.botToken).toBe( - "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", - ); - }); - - it.each([ - "GITHUB_TOKEN", - "AWS_SECRET_ACCESS_KEY", - "NPM_TOKEN", - "KUBECONFIG", - "NEMOCLAW_EXTRA_PLACEHOLDER_KEYS", - ])( - "refuses arbitrary host secret names that do not extend a discovered provider envKey inside the sandbox [%s]", - async (blocked) => { - // Defence-in-depth: even if an operator clobbers NEMOCLAW_EXTRA_PLACEHOLDER_KEYS - // inside a running sandbox after the host-side parser already filtered it, - // the container-side refresh helper must mirror the host's canonical-prefix - // restriction so a noncanonical name such as GITHUB_TOKEN never reaches the - // python placeholder walker. - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - }, - }, - }, - }, - { - TELEGRAM_BOT_TOKEN: "openshell:resolve:env:v42_TELEGRAM_BOT_TOKEN", - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: - "GITHUB_TOKEN AWS_SECRET_ACCESS_KEY NPM_TOKEN KUBECONFIG NEMOCLAW_EXTRA_PLACEHOLDER_KEYS TELEGRAM_BOT_TOKEN_KEPT", - // Stage host secrets that would leak if the bash refresh ever - // accepted their names. The assertion below confirms none of these - // values appear in any output produced by the python heredoc. - GITHUB_TOKEN: "ghp-host-secret-would-leak", - AWS_SECRET_ACCESS_KEY: "aws-host-secret-would-leak", - NPM_TOKEN: "npm-host-secret-would-leak", - KUBECONFIG: "/host/path/would-leak", - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - - expect(run.result.stderr).toContain( - `[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '${blocked}' — must extend a discovered provider envKey such as TELEGRAM_BOT_TOKEN_`, - ); - - expect(run.result.stderr).not.toContain( - "[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry 'TELEGRAM_BOT_TOKEN_KEPT'", - ); - // None of the staged host secret values should reach any stdout/stderr - // line the python heredoc emits, because their names were rejected before - // the heredoc ran. - expect(run.result.stderr).not.toContain("ghp-host-secret-would-leak"); - expect(run.result.stderr).not.toContain("aws-host-secret-would-leak"); - expect(run.result.stderr).not.toContain("npm-host-secret-would-leak"); - expect(run.result.stdout).not.toContain("ghp-host-secret-would-leak"); - expect(run.result.stdout).not.toContain("aws-host-secret-would-leak"); - expect(run.result.stdout).not.toContain("npm-host-secret-would-leak"); - expect(JSON.stringify(run.config)).not.toContain("ghp-host-secret-would-leak"); - expect(JSON.stringify(run.config)).not.toContain("aws-host-secret-would-leak"); - }, - ); - - it.each(canonicalKeys)( - "accepts manifest credential envKey %s as an extension prefix", - async (canonical) => { - // Behavioural parity guard: the in-container parser should not hardcode - // channel env keys. It consumes the messaging plan's credentialBindings, - // then accepts a per-profile extension for each discovered key. - const extension = `${canonical}_PARITY`; - const scoped = `openshell:resolve:env:v77_${extension}`; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - parity: { botToken: `openshell:resolve:env:${extension}` }, - }, - }, - }, - }, - { - NEMOCLAW_MESSAGING_PLAN_B64: placeholderPlan([canonical]), - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: extension, - [extension]: scoped, - }, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect( - run.result.stderr, - `bash refresh refused manifest credential extension '${extension}'`, - ).not.toContain(`[config] Ignoring NEMOCLAW_EXTRA_PLACEHOLDER_KEYS entry '${extension}'`); - expect(run.config.channels.telegram.accounts.parity.botToken).toBe(scoped); - }, - ); - - it("caps NEMOCLAW_EXTRA_PLACEHOLDER_KEYS at 32 entries inside the sandbox", async () => { - // The first 32 extension keys are accepted; the planted 33rd must remain unchanged. - const tokens = Array.from({ length: 33 }, (_, i) => `TELEGRAM_BOT_TOKEN_FILLER_${i}`); - const beyondCap = tokens[32]; - const beyondCapScoped = `openshell:resolve:env:v42_${beyondCap}`; - const env: Record = { - NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: tokens.join(" "), - // Only the 33rd key has a scoped value, so any rewrite proves the cap was exceeded. - [beyondCap]: beyondCapScoped, - // Deliberately leave TELEGRAM_BOT_TOKEN / DISCORD_BOT_TOKEN / etc. - // unset so no canonical replacement is added; that sidesteps the - // python heredoc's substring-match path which would otherwise let a - // shorter canonical replacement bleed into beyondCap regardless of - // the cap state. - }; - const run = await runRefresh( - { - channels: { - telegram: { - accounts: { - default: { - botToken: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - }, - beyondCap: { - botToken: `openshell:resolve:env:${beyondCap}`, - }, - }, - }, - }, - }, - env, - ); - - expect(run.result.status, run.result.stderr).toBe(0); - expect(run.result.stderr).toContain( - "[config] NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: capped at 32 entries; ignoring remainder", - ); - // The beyondCap key must not be processed by the python heredoc, so the - // beyondCap canonical placeholder must stay unchanged on disk. - expect(run.config.channels.telegram.accounts.beyondCap.botToken).toBe( - `openshell:resolve:env:${beyondCap}`, - ); - expect(run.result.stderr).not.toContain( - `Refreshed provider placeholders from OpenShell runtime env: ${beyondCap}`, - ); - expect(run.result.stdout).not.toContain(beyondCapScoped); - }); }); From 52d8abf0d16b2259a6a7e95b8cd8ee51e067c1ee Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Sat, 10 Oct 2026 14:05:28 -0700 Subject: [PATCH 11/11] fix(openclaw): keep startup heredoc compatible with macOS Bash Signed-off-by: Prekshi Vyas --- scripts/nemoclaw-start.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 6246dac61bb..2b7eda0b7a6 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -882,7 +882,7 @@ native_refreshed = False # A native NVIDIA handle persisted by the host-side config batch belongs to # the provider revision that issued it. After a supervisor restart, only the # current revision is available, so replace that exact config field before -# OpenClaw starts. Never copy a raw value or rewrite another provider's config. +# OpenClaw starts. Never copy a raw value or rewrite config for other providers. models = config.get("models") if isinstance(config, dict) else None providers = models.get("providers") if isinstance(models, dict) else None native = providers.get("inference") if isinstance(providers, dict) else None