diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index 8e5e23c44c7..1a2181684a4 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -7,7 +7,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": 4309, + "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 4187, "test/onboarding/onboard-messaging.test.ts": 1960, "test/onboarding/onboard-selection.test.ts": 4125 } diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index fac86b93dd2..04b732338a6 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -290,12 +290,15 @@ A registry-side tag change cannot silently select another managed sandbox image. ## Auth Profile Permissions -The entrypoint and migration flows enforce `chmod 600` on all `auth-profiles.json` files under `~/.openclaw`. -This prevents other users on the host from reading stored credentials. +For managed `inference.local` routes, the entrypoint clears the NVIDIA credential aliases before setup and command execution. +It removes only the exact legacy NemoClaw-generated profile for the selected managed provider and preserves other profiles. +Direct inference routes outside `inference.local` retain supplied credentials. +The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. +This prevents other users on the host from reading stored credentials that remain. | Aspect | Detail | |---|---| -| Default | `600` permissions applied recursively at startup and after migration restores. | +| Default | The selected managed provider's generated profile is removed. Other auth profiles receive `600` permissions recursively at startup and after migration restores. | | What you can change | This is not a user-facing knob. The entrypoint enforces it. | | Risk if relaxed | Looser permissions let other users or processes on the host read provider API keys and tokens stored in auth profiles. | | Recommendation | No action needed. If you see a `permission denied` error when reading auth profiles, verify that you are running as the same user who created them. | diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 0b9bf213c29..b6e9459713a 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -74,6 +74,21 @@ unset NEMOCLAW_ENTRYPOINT_NORMALIZED_ARGC NEMOCLAW_ENTRYPOINT_NORMALIZED_ARGV \ unset -f nemoclaw_normalize_entrypoint_env_wrapper # managed-entrypoint-env-wrapper end +# OpenShell owns inference.local authentication. Clear its credential aliases +# after entrypoint overrides are normalized, before setup can launch children. +# Direct inference routes retain their credentials. +is_managed_inference_route() { + # Match URL scheme and host case without spawning a credential-bearing child. + [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Ff][Ee][Rr][Ee][Nn][Cc][Ee]\.[Ll][Oo][Cc][Aa][Ll](:443)?(/.*)?$ ]] +} + +clear_managed_inference_credentials() { + if is_managed_inference_route; then + unset NVIDIA_INFERENCE_API_KEY NVIDIA_API_KEY + fi +} +clear_managed_inference_credentials + # Reject an invalid explicit dashboard port before installing the tee/fd startup # capture below. Some CI Docker runners can drop very early fd4 output from # short-lived containers, and this validation is meant to be fail-fast and @@ -2410,8 +2425,140 @@ prepare_gateway_token_for_current_command() { fi } -# Write an auth profile JSON for the NVIDIA API key so the gateway can authenticate. +# Reconcile this function's legacy generated auth profile for the selected provider. +# OpenShell authenticates managed inference.local routes on the host, so remove +# that generated credential reference. Preserve other user-managed profiles. +# Direct routes retain their existing profile-writing behavior. write_auth_profile() { + local provider_key="${NEMOCLAW_INFERENCE_PROVIDER_ID:-${NEMOCLAW_PROVIDER_KEY:-inference}}" + + if is_managed_inference_route; then + # Remove only the exact entries this function historically generated. + # Preserve user-managed direct-provider profiles if they share the file. + python3 - "$provider_key" <<'PYAUTH' +import json +import os +import secrets +import stat +import sys + +provider_key = sys.argv[1] +managed_profile_id = f'{provider_key}:manual' +profile_name = 'auth-profiles.json' +openclaw_path = os.path.expanduser('~/.openclaw') +directory_flags = os.O_RDONLY | os.O_DIRECTORY | getattr(os, 'O_NOFOLLOW', 0) + +def security_failure(detail): + print(f'[SECURITY] Refusing auth-profile cleanup: {detail}', file=sys.stderr) + raise SystemExit(1) + +def open_profile_directory(): + try: + directory_fd = os.open(openclaw_path, directory_flags) + except FileNotFoundError: + raise SystemExit(0) + except OSError: + security_failure('the .openclaw root is not a trusted directory') + + for component in ('agents', 'main', 'agent'): + try: + child_fd = os.open(component, directory_flags, dir_fd=directory_fd) + except FileNotFoundError: + os.close(directory_fd) + raise SystemExit(0) + except OSError: + os.close(directory_fd) + security_failure(f'{component} is not a trusted directory') + os.close(directory_fd) + directory_fd = child_fd + return directory_fd + +directory_fd = open_profile_directory() +try: + try: + profile_fd = os.open( + profile_name, + os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0), + dir_fd=directory_fd, + ) + except FileNotFoundError: + raise SystemExit(0) + except OSError: + security_failure('auth-profiles.json is not a trusted regular file') + + if not stat.S_ISREG(os.fstat(profile_fd).st_mode): + os.close(profile_fd) + security_failure('auth-profiles.json is not a regular file') + + try: + with os.fdopen(profile_fd, encoding='utf-8') as profile_file: + profiles = json.load(profile_file) + except (OSError, UnicodeError, json.JSONDecodeError): + # Unknown or user-managed state is not ours to replace or delete. + raise SystemExit(0) + + if not isinstance(profiles, dict): + raise SystemExit(0) + + def is_legacy_managed_profile(profile_id, profile): + if profile_id != managed_profile_id or not isinstance(profile, dict): + return False + return profile == { + 'type': 'api_key', + 'provider': provider_key, + 'keyRef': {'source': 'env', 'id': 'NVIDIA_INFERENCE_API_KEY'}, + 'profileId': managed_profile_id, + } + + retained = { + profile_id: profile + for profile_id, profile in profiles.items() + if not is_legacy_managed_profile(profile_id, profile) + } + if retained == profiles: + raise SystemExit(0) + if not retained: + os.unlink(profile_name, dir_fd=directory_fd) + raise SystemExit(0) + + temporary_name = f'.auth-profiles.{secrets.token_hex(16)}' + try: + temporary_fd = os.open( + temporary_name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), + mode=0o600, + dir_fd=directory_fd, + ) + except OSError: + security_failure('could not create a private replacement file') + + try: + with os.fdopen(temporary_fd, 'w', encoding='utf-8') as profile_file: + json.dump(retained, profile_file) + profile_file.flush() + os.fsync(profile_file.fileno()) + os.replace( + temporary_name, + profile_name, + src_dir_fd=directory_fd, + dst_dir_fd=directory_fd, + ) + except BaseException: + try: + os.close(temporary_fd) + except OSError: + pass + try: + os.unlink(temporary_name, dir_fd=directory_fd) + except FileNotFoundError: + pass + raise +finally: + os.close(directory_fd) +PYAUTH + return + fi + if [ -z "${NVIDIA_INFERENCE_API_KEY:-}" ] && [ -n "${NVIDIA_API_KEY:-}" ]; then export NVIDIA_INFERENCE_API_KEY="$NVIDIA_API_KEY" fi @@ -2427,7 +2574,6 @@ write_auth_profile() { # through v0.0.89 so pre-existing custom images keep routing. Remove this # fallback in v0.0.90. # See: https://github.com/NVIDIA/NemoClaw/issues/1332 - local provider_key="${NEMOCLAW_INFERENCE_PROVIDER_ID:-${NEMOCLAW_PROVIDER_KEY:-inference}}" python3 - "$provider_key" <<'PYAUTH' import json import os @@ -4736,6 +4882,7 @@ setup_auth_profile_as_sandbox() { run_step_down_as_sandbox \ "export HOME=/sandbox; write_auth_profile; harden_auth_profiles" \ openclaw_config_dir_owner \ + is_managed_inference_route \ write_auth_profile \ harden_auth_profiles } @@ -5406,6 +5553,10 @@ if [ "$(id -u)" -ne 0 ]; then # Apply manifest-declared runtime env aliases before any child inherits the # env. This covers both one-shot commands and the gateway launch. apply_messaging_runtime_env_aliases + if is_managed_inference_route; then + write_auth_profile + harden_auth_profiles + fi if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then install_messaging_runtime_preloads @@ -5444,7 +5595,9 @@ if [ "$(id -u)" -ne 0 ]; then fix_openclaw_ownership normalize_mutable_config_perms seed_default_workspace_templates /sandbox/.openclaw/workspace "" /sandbox/.openclaw/openclaw.json - write_auth_profile + if ! is_managed_inference_route; then + write_auth_profile + fi harden_auth_profiles prepare_auto_pair_log @@ -5496,6 +5649,10 @@ apply_model_override reconcile_agent_model_with_provider apply_cors_override configure_messaging_channels +# Remove the obsolete managed reference before Doctor can import it into SQLite. +if is_managed_inference_route; then + setup_auth_profile_as_sandbox +fi run_requested_openclaw_post_upgrade_doctor || exit 1 refresh_openclaw_provider_placeholders ensure_mutable_openclaw_config_hash @@ -5518,10 +5675,10 @@ apply_messaging_runtime_env_aliases install_messaging_runtime_preloads verify_messaging_runtime_secret_scans -# Write auth profile as sandbox user and recursively re-tighten any -# auth-profiles.json files under ~/.openclaw. See -# setup_auth_profile_as_sandbox for the HOME-handling rationale. -setup_auth_profile_as_sandbox +# Write direct-route profiles after Doctor has migrated existing user profiles. +if ! is_managed_inference_route; then + setup_auth_profile_as_sandbox +fi # If a command was passed (e.g., "openclaw agent ..."), run it as sandbox user if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts new file mode 100644 index 00000000000..51ad2e4a98f --- /dev/null +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -0,0 +1,309 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; +import { extractShellFunctionFromSource } from "../../../helpers/shell-source"; + +const START_SCRIPT = path.resolve(import.meta.dirname, "../../../../scripts/nemoclaw-start.sh"); +const START_SOURCE = fs.readFileSync(START_SCRIPT, "utf-8"); +const credentialProbe = + 'bash -c \'printf "%s\\n" "${NVIDIA_INFERENCE_API_KEY-unset}" "${NVIDIA_API_KEY-unset}"\''; +const managedEnv = { + NVIDIA_INFERENCE_API_KEY: "primary-secret", + NVIDIA_API_KEY: "legacy-secret", + NEMOCLAW_INFERENCE_BASE_URL: "hTtPs://InFeReNcE.LoCaL/v1", +}; +const homes: string[] = []; +afterEach(() => { + for (const home of homes.splice(0)) fs.rmSync(home, { recursive: true, force: true }); +}); +const AUTH_FUNCTIONS = [ + "set -euo pipefail", + extractShellFunctionFromSource(START_SOURCE, "is_managed_inference_route"), + extractShellFunctionFromSource(START_SOURCE, "write_auth_profile"), + extractShellFunctionFromSource(START_SOURCE, "clear_managed_inference_credentials"), +].join("\n"); + +function runBashAuthFixture( + env: Record, + prepare: (authPath: string) => void = () => undefined, + commands = `clear_managed_inference_credentials\nwrite_auth_profile\n${credentialProbe}`, +) { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-test-")); + homes.push(home); + const authPath = path.join(home, ".openclaw", "agents", "main", "agent", "auth-profiles.json"); + prepare(authPath); + const result = spawnSync("bash", ["-s", "--", START_SCRIPT], { + input: `${AUTH_FUNCTIONS}\n${commands}`, + env: { PATH: process.env.PATH, HOME: home, ...env }, + encoding: "utf-8", + timeout: 15_000, + killSignal: "SIGKILL", + }); + return { authPath, ...result }; +} + +function seedAuthProfile(profile: Record): (authPath: string) => void { + return (authPath) => { + fs.mkdirSync(path.dirname(authPath), { recursive: true }); + fs.writeFileSync(authPath, JSON.stringify(profile)); + }; +} + +function startupSection(startMarker: string, endMarker: string, region: string): string { + const regionStart = START_SOURCE.indexOf(region); + const start = START_SOURCE.indexOf(startMarker, regionStart); + const end = START_SOURCE.indexOf(endMarker, start); + expect( + regionStart !== -1 && start !== -1 && end !== -1 && end > start, + `Expected startup section ${startMarker}`, + ).toBe(true); + return START_SOURCE.slice(start, end); +} + +function doctorBlock(kind: "non-root" | "root" = "root"): string { + return startupSection( + kind === "root" ? "configure_messaging_channels\n" : " apply_messaging_runtime_env_aliases\n", + "refresh_openclaw_provider_placeholders\n", + kind === "root" ? "# ── Root path" : "# ── Non-root fallback", + ); +} + +function startupCredentialBoundaryBlock(kind: "non-root" | "root"): string { + return kind === "root" + ? `${doctorBlock()}\n${startupSection("# Write direct-route profiles after Doctor", "\nprepare_auto_pair_log", "# ── Root path")}` + : startupSection( + " apply_messaging_runtime_env_aliases\n", + "\n configure_messaging_channels", + "# ── Non-root fallback", + ); +} + +function runStartupCredentialBoundary( + kind: "non-root" | "root", + route = "managed", + failCleanup = false, +) { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-startup-")); + homes.push(home); + const script = path.join(home, "run.sh"); + const command = path.join(home, "command.sh"); + fs.writeFileSync(command, `#!/usr/bin/env bash\necho command\n${credentialProbe}\n`, { + mode: 0o700, + }); + const bootstrap = START_SOURCE.slice( + START_SOURCE.indexOf("# managed-entrypoint-env-wrapper end"), + START_SOURCE.indexOf("# Reject an invalid explicit dashboard port"), + ); + const wrapper = [ + START_SOURCE.match(/^set -[a-z]+ pipefail$/m)?.[0] ?? "", + ...[ + "is_managed_inference_route", + "clear_managed_inference_credentials", + "_step_down_extract_function", + "run_step_down_as_sandbox", + "setup_auth_profile_as_sandbox", + "run_oneshot_command", + ].map((name) => extractShellFunctionFromSource(START_SOURCE, name)), + 'NEMOCLAW_CMD=("$AUTH_TEST_COMMAND")', + '_RUNTIME_SHELL_ENV_FILE="$HOME/no-runtime-env"', + "STEP_DOWN_PREFIX_SANDBOX=(env)", + "apply_messaging_runtime_env_aliases() { :; }", + "openclaw_config_dir_owner() { echo sandbox; }", + `write_auth_profile() { ${credentialProbe}; return ${failCleanup ? 41 : 0}; }`, + "harden_auth_profiles() { :; }", + "install_messaging_runtime_preloads() { :; }", + "verify_messaging_runtime_secret_scans() { :; }", + "normalize_mutable_config_perms() { :; }", + "configure_messaging_channels() { :; }", + "run_requested_openclaw_post_upgrade_doctor() { :; }", + bootstrap, + credentialProbe, + startupCredentialBoundaryBlock(kind), + ].join("\n"); + fs.writeFileSync(script, wrapper); + return spawnSync("bash", [script], { + env: { + PATH: process.env.PATH, + HOME: home, + AUTH_TEST_COMMAND: command, + ...managedEnv, + ...(route === "direct" ? { NEMOCLAW_INFERENCE_BASE_URL: "https://direct.example/v1" } : {}), + }, + encoding: "utf-8", + }); +} + +function legacyProfile(provider = "inference", keyId = "NVIDIA_INFERENCE_API_KEY") { + return { + type: "api_key", + provider, + keyRef: { source: "env", id: keyId }, + profileId: `${provider}:manual`, + }; +} +const legacyManagedProfile = legacyProfile(); + +describe("OpenClaw auth-profile boundary", () => { + it.each([ + ["default", undefined, "inference"], + ["configured", "openai", "openai"], + ["literal", "$(echo pwned)", "$(echo pwned)"], + ] as const)("writes a private direct profile for the %s route", (_label, route, provider) => { + const fixture = runBashAuthFixture({ + NVIDIA_INFERENCE_API_KEY: "secret", + ...(route === undefined ? {} : { NEMOCLAW_INFERENCE_PROVIDER_ID: route }), + }); + expect(fixture.status, fixture.stderr).toBe(0); + expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ + [`${provider}:manual`]: legacyProfile(provider), + }); + expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); + }); + + it("leaves direct auth state absent when no credential is supplied", () => { + const fixture = runBashAuthFixture({}); + expect(fixture.status, fixture.stderr).toBe(0); + expect(fs.existsSync(fixture.authPath)).toBe(false); + }); + + it.each([ + ["fresh", "https://inference.local/v1"], + ["legacy", "https://inference.local/v1"], + ["fresh", "HTTPS://inference.local:443/v1"], + ["legacy", "https://INFERENCE.LOCAL:443"], + ] as const)( + "leaves no managed profile or inherited credentials in %s state at %s", + (state, baseUrl) => { + const fixture = runBashAuthFixture( + { ...(state === "fresh" ? managedEnv : {}), NEMOCLAW_INFERENCE_BASE_URL: baseUrl }, + state === "legacy" + ? seedAuthProfile({ "inference:manual": legacyManagedProfile }) + : undefined, + ); + expect(fixture.status, fixture.stderr).toBe(0); + expect(fs.existsSync(fixture.authPath)).toBe(false); + expect(fixture.stdout.trim()).toBe("unset\nunset"); + }, + ); + + it("preserves other profiles when removing the managed entry", () => { + const customProfile = legacyProfile("custom"); + const fixture = runBashAuthFixture( + managedEnv, + seedAuthProfile({ "inference:manual": legacyManagedProfile, "custom:manual": customProfile }), + ); + expect(fixture.status, fixture.stderr).toBe(0); + expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ + "custom:manual": customProfile, + }); + expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); + }); + + it("preserves a near-match profile byte for byte", () => { + const profiles = { "inference:manual": { ...legacyManagedProfile, label: "user-managed" } }; + const fixture = runBashAuthFixture(managedEnv, seedAuthProfile(profiles)); + expect(fixture.status, fixture.stderr).toBe(0); + expect(fs.readFileSync(fixture.authPath, "utf-8")).toBe(JSON.stringify(profiles)); + }); + + // This component fixture observes the profiles passed to Doctor. + it.each([ + ["root", "managed"], + ["root", "direct"], + ["non-root", "managed"], + ["non-root", "direct"], + ] as const)("presents configured %s %s profiles to Doctor", (kind, route) => { + const custom = legacyProfile("custom", "CUSTOM_API_KEY"); + const profiles = { "openai:manual": legacyProfile("openai"), "custom:manual": custom }; + const fixture = runBashAuthFixture( + { + ...managedEnv, + NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", + ...(route === "direct" ? { NEMOCLAW_INFERENCE_BASE_URL: "https://direct.example/v1" } : {}), + }, + seedAuthProfile(profiles), + [ + extractShellFunctionFromSource(START_SOURCE, "setup_auth_profile_as_sandbox"), + // Keep fixture HOME instead of switching users; reconciliation remains real. + "run_step_down_as_sandbox() { write_auth_profile; }", + "NEMOCLAW_CMD=()", + "apply_messaging_runtime_env_aliases() { :; }", + "harden_auth_profiles() { :; }", + "configure_messaging_channels() { :; }", + `run_requested_openclaw_post_upgrade_doctor() { ${credentialProbe} >&2; cat "$HOME/.openclaw/agents/main/agent/auth-profiles.json"; }`, + "clear_managed_inference_credentials", + doctorBlock(kind), + ].join("\n"), + ); + expect(fixture.status, fixture.stderr).toBe(0); + expect(JSON.parse(fixture.stdout)).toEqual( + route === "managed" ? { "custom:manual": custom } : profiles, + ); + expect(fixture.stderr.trim()).toBe( + route === "managed" ? "unset\nunset" : "primary-secret\nlegacy-secret", + ); + }); + + it.each([ + ["non-root", "managed", true], + ["root", "managed", true], + ["non-root", "direct", false], + ["root", "direct", true], + ] as const)( + "passes only allowed credentials to setup and command children in %s startup for %s routes", + (kind, route, writesProfile) => { + const result = runStartupCredentialBoundary(kind, route); + const credentials = route === "managed" ? "unset\nunset" : "primary-secret\nlegacy-secret"; + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe( + [credentials, ...(writesProfile ? [credentials] : []), "command", credentials].join("\n"), + ); + }, + ); + + it.each(["non-root", "root"] as const)( + "stops %s startup when auth-profile reconciliation fails", + (kind) => { + const result = runStartupCredentialBoundary(kind, "managed", true); + expect(result.status, result.stderr).toBe(41); + expect(result.stdout).not.toContain("command"); + }, + ); + + it("rejects a FIFO profile without waiting for a writer", () => { + const fixture = runBashAuthFixture( + managedEnv, + (authPath) => { + fs.mkdirSync(path.dirname(authPath), { recursive: true }); + expect(spawnSync("mkfifo", [authPath]).status).toBe(0); + }, + 'python3() { exec python3 "$@"; }; write_auth_profile', + ); + expect(fixture.error).toBeUndefined(); + expect(fixture.status).toBe(1); + expect(fixture.stderr).toContain("auth-profiles.json is not a regular file"); + }); + + it("rejects a symlinked parent without changing its target", () => { + const externalContents = JSON.stringify({ "inference:manual": legacyManagedProfile }); + let externalProfile = ""; + const fixture = runBashAuthFixture(managedEnv, (authPath) => { + const openclawDir = path.resolve(authPath, "../../../../"); + const externalAgents = path.join(path.dirname(openclawDir), "external-agents"); + externalProfile = path.join(externalAgents, "main", "agent", "auth-profiles.json"); + fs.mkdirSync(path.dirname(externalProfile), { recursive: true }); + fs.writeFileSync(externalProfile, externalContents); + fs.mkdirSync(openclawDir, { recursive: true }); + fs.symlinkSync(externalAgents, path.join(openclawDir, "agents")); + }); + expect(fixture.status).not.toBe(0); + expect(fixture.stderr).toContain("[SECURITY] Refusing auth-profile cleanup"); + expect(fs.readFileSync(externalProfile, "utf-8")).toBe(externalContents); + }); +}); diff --git a/test/agents/openclaw/runtime/nemoclaw-start.test.ts b/test/agents/openclaw/runtime/nemoclaw-start.test.ts index 423163a1844..e045f2d6ecd 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start.test.ts @@ -3005,6 +3005,7 @@ describe("Telegram diagnostics (#2766)", () => { "seed_default_workspace_templates() { :; }", "seed_default_workspace_templates_as_sandbox() { seed_default_workspace_templates; }", "write_auth_profile() { :; }", + "clear_managed_inference_credentials() { :; }", "harden_auth_profiles() { :; }", "run_step_down_as_sandbox() { :; }", "setup_auth_profile_as_sandbox() { :; }", @@ -3296,128 +3297,6 @@ process.stderr.write('FailoverError: token=123456:LATER\\n'); }); }); -describe("write_auth_profile (#1332)", () => { - // Invokes write_auth_profile from the production start script in an isolated - // HOME, then asserts on the resulting auth-profiles.json — observable - // behavior, not source-text shape. - const wrapper = [ - "set -euo pipefail", - `eval "$(sed -n '/^write_auth_profile() {$/,/^}$/p' "$1")"`, - "write_auth_profile", - ].join("\n"); - - function runWriteAuthProfile(env: Record): { - home: string; - authPath: string; - status: number; - stderr: string; - } { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-test-")); - const result = spawnSync("bash", ["-s", "--", START_SCRIPT], { - input: wrapper, - env: { PATH: process.env.PATH, HOME: home, ...env }, - encoding: "utf-8", - }); - return { - home, - authPath: path.join(home, ".openclaw", "agents", "main", "agent", "auth-profiles.json"), - status: result.status ?? -1, - stderr: result.stderr ?? "", - }; - } - - it("writes profile under the route identifier from NEMOCLAW_INFERENCE_PROVIDER_ID", () => { - const { home, authPath, status, stderr } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", - }); - try { - expect(status, stderr).toBe(0); - const profile = JSON.parse(fs.readFileSync(authPath, "utf-8")); - expect(profile).toEqual({ - "openai:manual": { - type: "api_key", - provider: "openai", - keyRef: { source: "env", id: "NVIDIA_INFERENCE_API_KEY" }, - profileId: "openai:manual", - }, - }); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("falls back to 'inference' when neither route identifier is set", () => { - const { home, authPath, status, stderr } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - }); - try { - expect(status, stderr).toBe(0); - const profile = JSON.parse(fs.readFileSync(authPath, "utf-8")); - expect(profile).toHaveProperty("inference:manual"); - expect(profile["inference:manual"].provider).toBe("inference"); - expect(profile).not.toHaveProperty("nvidia:manual"); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("does not use 'nvidia' as the default provider key", () => { - const { home, authPath, status } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - }); - try { - expect(status).toBe(0); - const profile = JSON.parse(fs.readFileSync(authPath, "utf-8")); - expect(Object.keys(profile).every((key) => !/^nvidia:/.test(key))).toBe(true); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("treats provider_key as a literal (no shell command substitution)", () => { - // If the provider_key were interpolated into the heredoc instead of - // passed as argv, $(...) inside the value would execute and replace it. - const { home, authPath, status, stderr } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_PROVIDER_ID: "$(echo pwned)", - }); - try { - expect(status, stderr).toBe(0); - const profile = JSON.parse(fs.readFileSync(authPath, "utf-8")); - expect(profile).toHaveProperty("$(echo pwned):manual"); - expect(profile["$(echo pwned):manual"].provider).toBe("$(echo pwned)"); - expect(profile).not.toHaveProperty("pwned:manual"); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("is a no-op when NVIDIA_INFERENCE_API_KEY is unset", () => { - const { home, authPath, status } = runWriteAuthProfile({}); - try { - expect(status).toBe(0); - expect(fs.existsSync(authPath)).toBe(false); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("writes the auth profile with 0600 permissions", () => { - const { home, authPath, status } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", - }); - try { - expect(status).toBe(0); - const mode = fs.statSync(authPath).mode & 0o777; - expect(mode).toBe(0o600); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); -}); - // Recover truncated config from native last-good state or the protected baseline (#3118). describe("openclaw.json baseline + recovery (#3118)", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); @@ -3989,17 +3868,13 @@ describe("run_step_down_as_sandbox", () => { describe("setup_auth_profile_as_sandbox", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); const helper = [ + extractShellFunctionFromSource(src, "is_managed_inference_route"), extractShellFunctionFromSource(src, "_step_down_extract_function"), extractShellFunctionFromSource(src, "run_step_down_as_sandbox"), ].join("\n"); const setup = extractShellFunctionFromSource(src, "setup_auth_profile_as_sandbox"); it("runs the auth-profile setup under HOME=/sandbox even when the parent env has HOME=/root", () => { - // setpriv preserves the parent shell's environment, so the root - // entrypoint's HOME=/root would otherwise leak into the step-down - // shell and `write_auth_profile`'s `~/.openclaw/...` expansion - // would target /root. Stub `write_auth_profile` to record the - // HOME the step-down shell actually observed and assert it was - // overridden to /sandbox. + // setpriv preserves HOME; profile setup must replace /root with /sandbox. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-setup-auth-profile-")); const observedHome = path.join(tmpDir, "observed-home"); const scriptPath = path.join(tmpDir, "run.sh"); @@ -4235,7 +4110,10 @@ describe("direct-root entrypoint composition under CAP_DAC_OVERRIDE drop", () => extractShellFunctionFromSource(src, "_step_down_extract_function"), extractShellFunctionFromSource(src, "run_step_down_as_sandbox"), ].join("\n"); - const setupAuth = extractShellFunctionFromSource(src, "setup_auth_profile_as_sandbox"); + const setupAuth = [ + extractShellFunctionFromSource(src, "is_managed_inference_route"), + extractShellFunctionFromSource(src, "setup_auth_profile_as_sandbox"), + ].join("\n"); fs.writeFileSync( scriptPath, [ diff --git a/test/e2e/README.md b/test/e2e/README.md index f5d6055b799..83d8e8fefb5 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -848,10 +848,15 @@ supported outcomes now have these owners: | Removed assertion | Retained owner | |---|---| | Install, PATH setup, list, status, hosted inference, and sandbox inference succeed. | `full-e2e` | -| Sandbox state contains no `auth-profiles.json` or secret-shaped credential values. | `full-e2e` and `test/e2e/support/sandbox-credential-boundary.test.ts` | +| Fresh managed sandbox state contains no `auth-profiles.json` or secret-shaped credential values. | `full-e2e` and `test/e2e/support/sandbox-credential-boundary.test.ts` | | Repository skills contain valid frontmatter and content. | `test/repository/repo-skills-validation.test.ts` | | `/sandbox/.openclaw` and `openclaw.json` have the required image layout. | `test/e2e-runtime/managed-image-openclaw-security.test.ts` | +The fresh-sandbox check starts without user-managed profiles. Existing-state cleanup preserves +unrelated profiles, as covered by `test/agents/openclaw/runtime/auth-profile-boundary.test.ts`. +That component fixture also observes which profiles reach Doctor in root and non-root startup. +`full-e2e` exercises native Doctor lint and agent turns. + The optional `/sandbox/.openclaw/skills` directory had no pass or fail state. The deleted provider retry classifier and sandbox-layout wrapper served only the retired target.