diff --git a/.github/workflows/e2e-vitest-scenarios.yaml b/.github/workflows/e2e-vitest-scenarios.yaml index 02d5ca403be..8dfb4c96cbb 100644 --- a/.github/workflows/e2e-vitest-scenarios.yaml +++ b/.github/workflows/e2e-vitest-scenarios.yaml @@ -40,7 +40,7 @@ jobs: SCENARIOS: ${{ inputs.scenarios }} run: | set -euo pipefail - allowed_jobs="openshell-version-pin-vitest,onboard-negative-paths-vitest,credential-migration-vitest,hermes-e2e-vitest,network-policy-vitest,token-rotation-vitest,openclaw-tui-chat-correlation-vitest,gateway-guard-recovery" + allowed_jobs="openshell-version-pin-vitest,onboard-negative-paths-vitest,credential-migration-vitest,runtime-overrides-vitest,hermes-e2e-vitest,network-policy-vitest,token-rotation-vitest,openclaw-tui-chat-correlation-vitest,gateway-guard-recovery" if [ -n "${JOBS}" ] && [ -n "${SCENARIOS}" ]; then echo "::error::Use either scenarios or jobs, not both." >&2 exit 1 @@ -93,12 +93,12 @@ jobs: SCENARIOS: ${{ inputs.scenarios }} run: | set -euo pipefail - allowed_jobs="openshell-version-pin-vitest,onboard-negative-paths-vitest,credential-migration-vitest,hermes-e2e-vitest,network-policy-vitest,token-rotation-vitest,openclaw-tui-chat-correlation-vitest,gateway-guard-recovery" + allowed_jobs="openshell-version-pin-vitest,onboard-negative-paths-vitest,credential-migration-vitest,runtime-overrides-vitest,hermes-e2e-vitest,network-policy-vitest,token-rotation-vitest,openclaw-tui-chat-correlation-vitest,gateway-guard-recovery" args=(--emit-live-matrix) matrix="" hermes_selected=false registry_scenarios=() - free_standing_scenarios=(openshell-version-pin onboard-negative-paths hermes-e2e network-policy token-rotation openclaw-tui-chat-correlation) + free_standing_scenarios=(openshell-version-pin onboard-negative-paths runtime-overrides hermes-e2e network-policy token-rotation openclaw-tui-chat-correlation) is_free_standing_scenario() { local id="$1" local known @@ -441,6 +441,47 @@ jobs: + runtime-overrides-vitest: + needs: [validate-jobs, generate-matrix] + if: ${{ (inputs.jobs == '' && inputs.scenarios == '') || contains(format(',{0},', inputs.jobs), ',runtime-overrides-vitest,') || contains(format(',{0},', inputs.scenarios), ',runtime-overrides,') }} + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/vitest/runtime-overrides + NEMOCLAW_RUN_E2E_SCENARIOS: "1" + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - name: Set up Node + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.0.0 + with: + node-version: 22 + cache: npm + + - name: Install root dependencies + run: npm ci --ignore-scripts + + - name: Run runtime overrides live test + # Migrated from test/e2e/test-runtime-overrides.sh. Builds the real + # sandbox image and exercises the runtime ENTRYPOINT override boundary. + run: | + set -euo pipefail + npx vitest run --project e2e-scenarios-live \ + test/e2e-scenario/live/runtime-overrides.test.ts \ + --silent=false --reporter=default + + - name: Upload runtime overrides artifacts + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: e2e-vitest-scenarios-runtime-overrides + path: e2e-artifacts/vitest/runtime-overrides/ + include-hidden-files: false + if-no-files-found: ignore + retention-days: 14 + hermes-e2e-vitest: needs: [validate-jobs, generate-matrix] if: ${{ needs.generate-matrix.outputs.hermes_selected == 'true' }} @@ -822,6 +863,7 @@ jobs: openshell-version-pin-vitest, onboard-negative-paths-vitest, credential-migration-vitest, + runtime-overrides-vitest, hermes-e2e-vitest, network-policy-vitest, token-rotation-vitest, diff --git a/test/e2e-scenario/live/runtime-overrides.test.ts b/test/e2e-scenario/live/runtime-overrides.test.ts new file mode 100644 index 00000000000..c8a48a242ed --- /dev/null +++ b/test/e2e-scenario/live/runtime-overrides.test.ts @@ -0,0 +1,402 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import { testTimeoutOptions } from "../../helpers/timeouts"; +import { expect, test } from "../fixtures/e2e-test.ts"; + +// Migrated from test/e2e/test-runtime-overrides.sh. This keeps the real +// Docker-image/entrypoint boundary: build the NemoClaw sandbox image, start +// short-lived containers through the real ENTRYPOINT, then read the patched +// /sandbox/.openclaw/openclaw.json and .config-hash from inside the container. + +const REPO_ROOT = path.resolve(import.meta.dirname, "../../.."); +const TEST_TIMEOUT_MS = 45 * 60 * 1000; +const DOCKER_BUFFER_BYTES = 20 * 1024 * 1024; +const DOCKER_REQUIRED_MESSAGE = "Docker is required for runtime override coverage"; + +const runtimeOverridesTest = process.env.NEMOCLAW_RUN_E2E_SCENARIOS === "1" ? test : test.skip; + +type CommandResult = { + status: number | null; + stdout: string; + stderr: string; + error?: Error; +}; + +type ModelConfig = { + contextWindow: number; + maxTokens: number; + reasoning: boolean; + [key: string]: unknown; +}; + +type ProviderConfig = { + api?: string; + models: ModelConfig[]; + [key: string]: unknown; +}; + +type OpenClawConfig = { + agents: { defaults: { model: { primary: string } } }; + models: { providers: Record }; + gateway: { controlUi: { allowedOrigins: string[] } }; + [key: string]: unknown; +}; + +function commandResult(result: ReturnType): CommandResult { + return { + status: result.status, + stdout: + typeof result.stdout === "string" ? result.stdout : (result.stdout?.toString("utf8") ?? ""), + stderr: + typeof result.stderr === "string" ? result.stderr : (result.stderr?.toString("utf8") ?? ""), + error: result.error, + }; +} + +function run(command: string, args: string[]): CommandResult { + return commandResult( + spawnSync(command, args, { + cwd: REPO_ROOT, + encoding: "utf8", + maxBuffer: DOCKER_BUFFER_BYTES, + }), + ); +} + +function resultText(result: CommandResult): string { + return [ + `status=${result.status}`, + result.error ? `error=${result.error.message}` : "", + result.stdout ? `stdout:\n${result.stdout}` : "", + result.stderr ? `stderr:\n${result.stderr}` : "", + ] + .filter(Boolean) + .join("\n"); +} + +function formatLog(label: string, result: CommandResult): string { + return [`## ${label}`, resultText(result)].join("\n"); +} + +function firstProvider(config: OpenClawConfig): ProviderConfig { + const provider = Object.values(config.models.providers)[0]; + if (!provider) throw new Error("config must contain at least one provider"); + return provider; +} + +function firstProviderModel(config: OpenClawConfig): ModelConfig { + const model = firstProvider(config).models?.[0]; + if (!model) throw new Error("config must contain at least one provider model"); + return model; +} + +function parseConfig(stdout: string, label: string): OpenClawConfig { + let config: OpenClawConfig; + try { + config = JSON.parse(stdout.trim()) as OpenClawConfig; + } catch (error) { + throw new Error(`${label} did not emit valid JSON: ${(error as Error).message}\n${stdout}`); + } + + expect(typeof config.agents?.defaults?.model?.primary, `${label} primary model`).toBe("string"); + expect(config.agents.defaults.model.primary.length, `${label} primary model`).toBeGreaterThan(0); + expect(typeof config.models?.providers, `${label} providers`).toBe("object"); + const model = firstProviderModel(config); + expect(typeof model.contextWindow, `${label} contextWindow`).toBe("number"); + expect(typeof model.maxTokens, `${label} maxTokens`).toBe("number"); + expect(typeof model.reasoning, `${label} reasoning`).toBe("boolean"); + expect(Array.isArray(config.gateway?.controlUi?.allowedOrigins), `${label} allowedOrigins`).toBe( + true, + ); + return config; +} + +function primaryModel(config: OpenClawConfig): string { + return config.agents.defaults.model.primary; +} + +function allowedOrigins(config: OpenClawConfig): string[] { + return config.gateway.controlUi.allowedOrigins; +} + +function dockerRunArgs(image: string, env: Record, script: string): string[] { + return [ + "run", + "--rm", + ...Object.entries(env).flatMap(([key, value]) => ["-e", `${key}=${value}`]), + image, + "bash", + "-c", + script, + ]; +} + +function runContainer( + dockerLog: string[], + image: string, + label: string, + env: Record, + script: string, +): CommandResult { + const result = run("docker", dockerRunArgs(image, env, script)); + dockerLog.push(formatLog(label, result)); + return result; +} + +function captureConfig( + dockerLog: string[], + image: string, + label: string, + env: Record = {}, +): OpenClawConfig { + let lastResult: CommandResult | undefined; + let lastError: Error | undefined; + // Preserve the legacy script's Docker/ENTRYPOINT stdout tolerance: very short + // one-shot containers can race the entrypoint's tee process substitution even + // though the JSON is written to fd3. Keep this local retry until the startup + // capture path no longer uses tee for container stdout/stderr fanout. + for (let attempt = 1; attempt <= 3; attempt += 1) { + const result = runContainer( + dockerLog, + image, + `${label} config capture attempt ${attempt}`, + env, + 'cat /sandbox/.openclaw/openclaw.json >&3; printf "\\n" >&3', + ); + lastResult = result; + if (result.status === 0) { + try { + return parseConfig(result.stdout, label); + } catch (error) { + lastError = error as Error; + } + } + } + + throw new Error( + `${label} config capture failed after 3 attempts\n${lastError?.message ?? ""}\n${lastResult ? resultText(lastResult) : ""}`, + ); +} + +function runConfigHashCheck( + dockerLog: string[], + image: string, + label: string, + env: Record = {}, +): string { + const result = runContainer( + dockerLog, + image, + `${label} config hash check`, + env, + 'cd /sandbox/.openclaw && if sha256sum -c .config-hash --status; then printf "OK\\n" >&3; else printf "FAIL\\n" >&3; fi', + ); + expect(result.status, resultText(result)).toBe(0); + return result.stdout.trim(); +} + +function runOverrideStderr( + dockerLog: string[], + image: string, + label: string, + env: Record, +): string { + const result = runContainer(dockerLog, image, label, env, "true"); + return result.stderr; +} + +function dockerAvailable(): CommandResult { + return run("docker", ["info"]); +} + +function buildImage(dockerLog: string[], image: string): void { + const inspect = run("docker", ["image", "inspect", image]); + dockerLog.push(formatLog(`inspect ${image}`, inspect)); + if (inspect.status === 0) return; + + const build = run("docker", [ + "build", + "-t", + image, + "-f", + path.join(REPO_ROOT, "Dockerfile"), + "--build-arg", + "NEMOCLAW_DISABLE_DEVICE_AUTH=1", + "--build-arg", + `NEMOCLAW_BUILD_ID=${Date.now()}`, + "--quiet", + REPO_ROOT, + ]); + dockerLog.push(formatLog(`build ${image}`, build)); + expect(build.status, resultText(build)).toBe(0); +} + +runtimeOverridesTest( + "runtime config overrides patch OpenClaw config through the Docker entrypoint", + testTimeoutOptions(TEST_TIMEOUT_MS), + async ({ artifacts, secrets, skip }) => { + const dockerLog: string[] = []; + const image = + process.env.NEMOCLAW_TEST_IMAGE ?? `nemoclaw-runtime-overrides-vitest-${process.pid}`; + const cleanupImage = process.env.NEMOCLAW_TEST_IMAGE === undefined; + + try { + await artifacts.writeJson("scenario.json", { + id: "runtime-overrides", + runner: "vitest", + migratedFrom: "test/e2e/test-runtime-overrides.sh", + boundary: "docker-image-entrypoint", + image, + contract: [ + "baseline config hash validates", + "model/API/context/max-token/reasoning overrides patch openclaw.json", + "CORS origin override extends gateway.controlUi.allowedOrigins", + "combined overrides apply atomically", + "invalid override values are rejected without mutating config", + ], + }); + + const docker = dockerAvailable(); + dockerLog.push(formatLog("docker info", docker)); + if (docker.status !== 0) { + await artifacts.writeJson("scenario-result.json", { + id: "runtime-overrides", + status: "skipped", + reason: DOCKER_REQUIRED_MESSAGE, + }); + if (process.env.GITHUB_ACTIONS === "true") { + throw new Error(`${DOCKER_REQUIRED_MESSAGE}\n${resultText(docker)}`); + } + skip(DOCKER_REQUIRED_MESSAGE); + } + + buildImage(dockerLog, image); + + const baseline = captureConfig(dockerLog, image, "baseline"); + const baselineModel = primaryModel(baseline); + const baselineFirstModel = firstProviderModel(baseline); + const baselineContextWindow = baselineFirstModel.contextWindow; + const baselineOriginCount = allowedOrigins(baseline).length; + + expect(runConfigHashCheck(dockerLog, image, "baseline")).toBe("OK"); + + const overrideModel = "anthropic/claude-sonnet-4-6"; + const modelOverride = captureConfig(dockerLog, image, "model override", { + NEMOCLAW_MODEL_OVERRIDE: overrideModel, + }); + expect(primaryModel(modelOverride)).toBe(overrideModel); + expect( + runConfigHashCheck(dockerLog, image, "model override", { + NEMOCLAW_MODEL_OVERRIDE: overrideModel, + }), + ).toBe("OK"); + + const apiOverride = captureConfig(dockerLog, image, "inference API override", { + NEMOCLAW_INFERENCE_API_OVERRIDE: "anthropic-messages", + }); + expect(firstProvider(apiOverride).api).toBe("anthropic-messages"); + expect( + runConfigHashCheck(dockerLog, image, "inference API override", { + NEMOCLAW_INFERENCE_API_OVERRIDE: "anthropic-messages", + }), + ).toBe("OK"); + + const contextOverride = captureConfig(dockerLog, image, "context window override", { + NEMOCLAW_MODEL_OVERRIDE: overrideModel, + NEMOCLAW_CONTEXT_WINDOW: "32768", + }); + expect(firstProviderModel(contextOverride).contextWindow).toBe(32768); + + const maxTokensOverride = captureConfig(dockerLog, image, "max tokens override", { + NEMOCLAW_MODEL_OVERRIDE: overrideModel, + NEMOCLAW_MAX_TOKENS: "16384", + }); + expect(firstProviderModel(maxTokensOverride).maxTokens).toBe(16384); + + const reasoningOverride = captureConfig(dockerLog, image, "reasoning override", { + NEMOCLAW_MODEL_OVERRIDE: overrideModel, + NEMOCLAW_REASONING: "true", + }); + expect(firstProviderModel(reasoningOverride).reasoning).toBe(true); + + const corsOrigin = "https://custom.example.com:9999"; + const corsOverride = captureConfig(dockerLog, image, "CORS origin override", { + NEMOCLAW_CORS_ORIGIN: corsOrigin, + }); + expect(allowedOrigins(corsOverride)).toContain(corsOrigin); + expect(allowedOrigins(corsOverride).length).toBeGreaterThan(baselineOriginCount); + + const combined = captureConfig(dockerLog, image, "combined overrides", { + NEMOCLAW_MODEL_OVERRIDE: "nvidia/llama-3.3-nemotron-super-49b-v1.5", + NEMOCLAW_CONTEXT_WINDOW: "65536", + NEMOCLAW_MAX_TOKENS: "8192", + NEMOCLAW_REASONING: "true", + NEMOCLAW_CORS_ORIGIN: "https://multi.example.com", + }); + expect(primaryModel(combined)).toBe("nvidia/llama-3.3-nemotron-super-49b-v1.5"); + expect(firstProviderModel(combined)).toMatchObject({ + contextWindow: 65536, + maxTokens: 8192, + reasoning: true, + }); + expect(allowedOrigins(combined)).toContain("https://multi.example.com"); + + expect( + runOverrideStderr(dockerLog, image, "invalid model override", { + NEMOCLAW_MODEL_OVERRIDE: "bad\u0001model", + }), + ).toContain("control characters"); + expect( + runOverrideStderr(dockerLog, image, "invalid context window", { + NEMOCLAW_MODEL_OVERRIDE: "test", + NEMOCLAW_CONTEXT_WINDOW: "notanumber", + }), + ).toContain("must be a positive integer"); + expect( + runOverrideStderr(dockerLog, image, "invalid max tokens", { + NEMOCLAW_MODEL_OVERRIDE: "test", + NEMOCLAW_MAX_TOKENS: "abc", + }), + ).toContain("must be a positive integer"); + expect( + runOverrideStderr(dockerLog, image, "invalid reasoning", { + NEMOCLAW_MODEL_OVERRIDE: "test", + NEMOCLAW_REASONING: "maybe", + }), + ).toContain('must be "true" or "false"'); + expect( + runOverrideStderr(dockerLog, image, "invalid CORS origin", { + NEMOCLAW_CORS_ORIGIN: "ftp://evil.com", + }), + ).toContain("must start with http"); + expect( + runOverrideStderr(dockerLog, image, "invalid inference API", { + NEMOCLAW_MODEL_OVERRIDE: "test", + NEMOCLAW_INFERENCE_API_OVERRIDE: "graphql", + }), + ).toContain("openai-completions"); + + const rejected = captureConfig(dockerLog, image, "rejected override", { + NEMOCLAW_MODEL_OVERRIDE: "test", + NEMOCLAW_CONTEXT_WINDOW: "notanumber", + }); + expect(primaryModel(rejected)).toBe(baselineModel); + expect(firstProviderModel(rejected).contextWindow).toBe(baselineContextWindow); + + await artifacts.writeJson("scenario-result.json", { + id: "runtime-overrides", + status: "passed", + image, + }); + } finally { + if (cleanupImage) { + const cleanup = run("docker", ["image", "rm", "-f", image]); + dockerLog.push(formatLog(`cleanup ${image}`, cleanup)); + } + await artifacts.writeText("docker.log", `${secrets.redact(dockerLog.join("\n\n"))}\n`); + } + }, +); diff --git a/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts b/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts index c150e0be03f..e835cac272c 100644 --- a/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts +++ b/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts @@ -114,6 +114,22 @@ describe("e2e-vitest-scenarios workflow boundary", () => { selectedFreeStandingJobs: ["openshell-version-pin-vitest"], registryScenarios: [], }); + expect( + evaluateE2eVitestWorkflowDispatchSelectors({ jobs: "runtime-overrides-vitest" }), + ).toMatchObject({ + valid: true, + liveScenariosRuns: false, + selectedFreeStandingJobs: ["runtime-overrides-vitest"], + registryScenarios: [], + }); + expect( + evaluateE2eVitestWorkflowDispatchSelectors({ scenarios: "runtime-overrides" }), + ).toMatchObject({ + valid: true, + liveScenariosRuns: false, + selectedFreeStandingJobs: ["runtime-overrides-vitest"], + registryScenarios: [], + }); expect(evaluateE2eVitestWorkflowDispatchSelectors({ scenarios: "hermes-e2e" })).toMatchObject({ valid: true, liveScenariosRuns: false, @@ -139,6 +155,16 @@ describe("e2e-vitest-scenarios workflow boundary", () => { hermes_selected: "false", matrix: "[]", }); + expect( + generateMatrixForDispatch({ JOBS: "runtime-overrides-vitest", SCENARIOS: "" }), + ).toMatchObject({ + hermes_selected: "false", + matrix: "[]", + }); + expect(generateMatrixForDispatch({ JOBS: "", SCENARIOS: "runtime-overrides" })).toMatchObject({ + hermes_selected: "false", + matrix: "[]", + }); expect(generateMatrixForDispatch({ JOBS: "", SCENARIOS: "hermes-e2e" })).toMatchObject({ hermes_selected: "true", matrix: "[]", @@ -320,6 +346,7 @@ jobs: "step 'Validate free-standing job selector' run script must include Use either scenarios or jobs, not both", "step 'Validate free-standing job selector' run script must include Invalid scenario input; use comma-separated scenario ids", "step 'Validate free-standing job selector' run script must include allowed_jobs=", + "step 'Validate free-standing job selector' run script must include runtime-overrides-vitest", "step 'Validate free-standing job selector' run script must include hermes-e2e-vitest", "step 'Validate free-standing job selector' run script must include Invalid jobs input; use comma-separated job ids", "step 'Validate free-standing job selector' run script must not include Invalid jobs input: ${JOBS}", @@ -409,6 +436,7 @@ jobs: "onboard-negative-paths-vitest artifact upload retention-days must be 14", "credential-migration-vitest job must depend on validate-jobs", "credential-migration-vitest job must use the shared jobs selector condition", + "workflow missing runtime-overrides-vitest job", "network-policy-vitest checkout action must be pinned to a full commit SHA", "network-policy-vitest checkout step must set persist-credentials=false", "network-policy-vitest must not include unused Docker Hub authentication", @@ -432,6 +460,7 @@ jobs: "network-policy-vitest artifact upload must ignore missing fixture artifacts", "network-policy-vitest artifact upload retention-days must be 14", "report-to-pr job must wait for credential-migration-vitest", + "report-to-pr job must wait for runtime-overrides-vitest", "report-to-pr job must wait for network-policy-vitest", "workflow missing hermes-e2e-vitest job", "report-to-pr job must wait for hermes-e2e-vitest", @@ -457,6 +486,59 @@ jobs: } }); + it("requires runtime-overrides literals in selector allowlists", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-vitest-workflow-")); + const workflowPath = path.join(tmp, "workflow.yaml"); + const workflow = fs.readFileSync( + path.join(process.cwd(), ".github/workflows/e2e-vitest-scenarios.yaml"), + "utf8", + ); + fs.writeFileSync( + workflowPath, + workflow + .replace(/runtime-overrides-vitest/g, "runtime-overrides-missing") + .replace(/runtime-overrides/g, "runtime-overrides-missing"), + ); + + try { + const errors = validateE2eVitestScenariosWorkflowBoundary(workflowPath); + expect(errors).toEqual( + expect.arrayContaining([ + "step 'Validate free-standing job selector' run script must include runtime-overrides-vitest", + "step 'Generate Vitest scenario matrix' run script must include runtime-overrides-vitest", + "workflow missing runtime-overrides-vitest job", + ]), + ); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("rejects Docker Hub auth and inline secrets in runtime-overrides run steps", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-vitest-workflow-")); + const workflowPath = path.join(tmp, "workflow.yaml"); + const workflow = fs.readFileSync( + path.join(process.cwd(), ".github/workflows/e2e-vitest-scenarios.yaml"), + "utf8", + ); + fs.writeFileSync( + workflowPath, + workflow.replace( + "npx vitest run --project e2e-scenarios-live \\\n test/e2e-scenario/live/runtime-overrides.test.ts \\", + "docker login docker.io --username user --password ${{ secrets.DOCKERHUB_TOKEN }}\n npx vitest run --project e2e-scenarios-live \\\n test/e2e-scenario/live/runtime-overrides.test.ts \\", + ), + ); + + try { + const errors = validateE2eVitestScenariosWorkflowBoundary(workflowPath); + expect(errors).toContain( + "runtime-overrides-vitest step 'Run runtime overrides live test' run script must not use docker login or inline secret interpolation", + ); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + it("rejects raw jobs selector echo from matrix generation", () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-vitest-workflow-")); const workflowPath = path.join(tmp, "workflow.yaml"); diff --git a/tools/e2e-scenarios/workflow-boundary.mts b/tools/e2e-scenarios/workflow-boundary.mts index d9e45fff7b6..945e0972e0b 100644 --- a/tools/e2e-scenarios/workflow-boundary.mts +++ b/tools/e2e-scenarios/workflow-boundary.mts @@ -21,6 +21,7 @@ const SELECTOR_PATTERN = /^[A-Za-z0-9_-]+(,[A-Za-z0-9_-]+)*$/; const FREE_STANDING_SCENARIO_JOBS = new Map([ ["openshell-version-pin", "openshell-version-pin-vitest"], ["onboard-negative-paths", "onboard-negative-paths-vitest"], + ["runtime-overrides", "runtime-overrides-vitest"], ["hermes-e2e", "hermes-e2e-vitest"], ["network-policy", "network-policy-vitest"], ["token-rotation", "token-rotation-vitest"], @@ -276,6 +277,7 @@ function validateJobsSelector(errors: string[], jobs: WorkflowRecord): void { requireRunContains(errors, validate, "openshell-version-pin-vitest"); requireRunContains(errors, validate, "onboard-negative-paths-vitest"); requireRunContains(errors, validate, "credential-migration-vitest"); + requireRunContains(errors, validate, "runtime-overrides-vitest"); requireRunContains(errors, validate, "hermes-e2e-vitest"); requireRunContains(errors, validate, "network-policy-vitest"); requireRunContains(errors, validate, "token-rotation-vitest"); @@ -704,6 +706,91 @@ function validateOnboardNegativePathsVitestJob(errors: string[], jobs: WorkflowR } } +function requireNoDockerHubAuthInRun( + errors: string[], + owner: string, + runScript: string, +): void { + if (!runScript) return; + const usesDockerLogin = /\bdocker\s+login\b/i.test(runScript); + const referencesSecret = /\bsecrets\.[A-Za-z0-9_]+\b|\$\{\{\s*secrets\.[^}]+\}\}/.test(runScript); + if (usesDockerLogin || referencesSecret) { + errors.push(`${owner} run script must not use docker login or inline secret interpolation`); + } +} + +function validateRuntimeOverridesVitestJob(errors: string[], jobs: WorkflowRecord): void { + const jobName = "runtime-overrides-vitest"; + const job = asRecord(jobs[jobName]); + if (Object.keys(job).length === 0) { + errors.push("workflow missing runtime-overrides-vitest job"); + return; + } + + if (job["runs-on"] !== "ubuntu-latest") { + errors.push("runtime-overrides-vitest job must run on ubuntu-latest"); + } + validateFreeStandingJobSelector(errors, jobs, jobName, "runtime-overrides"); + + const jobEnv = asRecord(job.env); + if (jobEnv.NEMOCLAW_RUN_E2E_SCENARIOS !== "1") { + errors.push("runtime-overrides-vitest job must set NEMOCLAW_RUN_E2E_SCENARIOS=1"); + } + if (jobEnv.E2E_ARTIFACT_DIR !== "${{ github.workspace }}/e2e-artifacts/vitest/runtime-overrides") { + errors.push("runtime-overrides-vitest job must write artifacts under e2e-artifacts/vitest/runtime-overrides"); + } + requireEnvDoesNotExposeSecret(errors, "runtime-overrides-vitest job", jobEnv, "NVIDIA_API_KEY"); + requireEnvDoesNotExposeSecret(errors, "runtime-overrides-vitest job", jobEnv, "DOCKERHUB_USERNAME"); + requireEnvDoesNotExposeSecret(errors, "runtime-overrides-vitest job", jobEnv, "DOCKERHUB_TOKEN"); + + const steps = asSteps(job.steps); + requireNoDispatchInputInterpolation(errors, steps); + for (const step of steps) { + const stepName = `runtime-overrides-vitest step '${step.name ?? step.uses ?? ""}'`; + const stepEnv = asRecord(step.env); + requireEnvDoesNotExposeSecret(errors, stepName, stepEnv, "NVIDIA_API_KEY"); + requireEnvDoesNotExposeSecret(errors, stepName, stepEnv, "DOCKERHUB_USERNAME"); + requireEnvDoesNotExposeSecret(errors, stepName, stepEnv, "DOCKERHUB_TOKEN"); + requireNoDockerHubAuthInRun(errors, stepName, stringValue(step.run)); + } + + const checkout = steps.find((step) => stringValue(step.uses).startsWith("actions/checkout@")); + if (!checkout) errors.push("runtime-overrides-vitest job missing checkout step"); + requireFullShaAction(errors, checkout, "runtime-overrides-vitest checkout"); + if (asRecord(checkout?.with)["persist-credentials"] !== false) { + errors.push("runtime-overrides-vitest checkout step must set persist-credentials=false"); + } + + const setupNode = namedStep(steps, "Set up Node"); + if (!setupNode) errors.push("runtime-overrides-vitest job missing step: Set up Node"); + requireFullShaAction(errors, setupNode, "runtime-overrides-vitest setup-node"); + + const installRootDependencies = requireJobStep(errors, jobName, steps, "Install root dependencies"); + requireRunContains(errors, installRootDependencies, "npm ci --ignore-scripts"); + + const runVitest = requireJobStep(errors, jobName, steps, "Run runtime overrides live test"); + requireRunContains(errors, runVitest, "npx vitest run --project e2e-scenarios-live"); + requireRunContains(errors, runVitest, "test/e2e-scenario/live/runtime-overrides.test.ts"); + + const upload = requireJobStep(errors, jobName, steps, "Upload runtime overrides artifacts"); + requireFullShaAction(errors, upload, "runtime-overrides-vitest upload-artifact"); + const uploadWith = asRecord(upload?.with); + if (uploadWith.name !== "e2e-vitest-scenarios-runtime-overrides") { + errors.push("runtime-overrides-vitest artifact upload name must be stable"); + } + const uploadPath = stringValue(uploadWith.path); + requireUploadPathContains(errors, uploadPath, "e2e-artifacts/vitest/runtime-overrides/"); + if (uploadWith["include-hidden-files"] !== false) { + errors.push("runtime-overrides-vitest artifact upload must set include-hidden-files: false"); + } + if (uploadWith["if-no-files-found"] !== "ignore") { + errors.push("runtime-overrides-vitest artifact upload must ignore missing fixture artifacts"); + } + if (uploadWith["retention-days"] !== 14) { + errors.push("runtime-overrides-vitest artifact upload retention-days must be 14"); + } +} + function validateHermesE2EVitestJob(errors: string[], jobs: WorkflowRecord): void { const jobName = "hermes-e2e-vitest"; const job = asRecord(jobs[jobName]); @@ -862,6 +949,8 @@ export function validateE2eVitestScenariosWorkflowBoundary( requireRunContains(errors, generate, "allowed_jobs="); requireRunContains(errors, generate, "Use either scenarios or jobs, not both"); requireRunContains(errors, generate, "Unknown free-standing Vitest job"); + requireRunContains(errors, generate, "runtime-overrides-vitest"); + requireRunContains(errors, generate, "runtime-overrides"); requireRunContains(errors, generate, "hermes-e2e-vitest"); requireRunContains(errors, generate, "network-policy-vitest"); requireRunContains(errors, generate, "token-rotation-vitest"); @@ -1018,6 +1107,7 @@ export function validateE2eVitestScenariosWorkflowBoundary( validateOpenShellVersionPinVitestJob(errors, jobs); validateOnboardNegativePathsVitestJob(errors, jobs); validateFreeStandingJobSelector(errors, jobs, "credential-migration-vitest"); + validateRuntimeOverridesVitestJob(errors, jobs); validateHermesE2EVitestJob(errors, jobs); validateNetworkPolicyVitestJob(errors, jobs); validateTokenRotationVitestJob(errors, jobs); @@ -1041,6 +1131,7 @@ export function validateE2eVitestScenariosWorkflowBoundary( "openshell-version-pin-vitest", "onboard-negative-paths-vitest", "credential-migration-vitest", + "runtime-overrides-vitest", "hermes-e2e-vitest", "network-policy-vitest", "token-rotation-vitest",