Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/reference/architecture.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,13 @@ nemoclaw-blueprint/
│ └── presets/ Shared policy presets
```

The blueprint schema and runner enforce these name constraints before the runner invokes OpenShell:

| Field | Constraint |
|---|---|
| `components.sandbox.name` | Use 1–63 lowercase letters, numbers, or internal hyphens, starting with a letter and ending with a letter or number. |
| `components.inference.profiles.<profile>.provider_name` | Use 1–128 letters, numbers, dots, underscores, or hyphens, starting with a letter. |

<AgentOnly variant="openclaw">
The default OpenClaw policy starts from `nemoclaw-blueprint/policies/openclaw-sandbox.yaml`.
</AgentOnly>
Expand Down
225 changes: 225 additions & 0 deletions nemoclaw/src/blueprint/runner-name-validation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

// Integration tests for the runner's fail-closed name validation. Kept in a
// focused file so runner.test.ts stays under the test-file-size budget. The
// mocks mirror runner.test.ts so these exercise the real apply/rollback paths.

import type fs from "node:fs";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

interface FsEntry {
type: "file" | "dir";
content?: string;
}

/** Throw from an expression position so the fake fs stays branch-free. */
function raise(message: string): never {
throw new Error(message);
}

const store = new Map<string, FsEntry>();

function addFile(p: string, content: string): void {
store.set(p, { type: "file", content });
}

function addDir(p: string): void {
store.set(p, { type: "dir" });
}

const FAKE_HOME = "/fakehome";

vi.mock("node:os", () => ({
homedir: () => FAKE_HOME,
}));

vi.mock("node:crypto", () => ({
randomUUID: () => "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
}));

vi.mock("node:fs", async (importOriginal) => {
const original = await importOriginal<typeof fs>();
return {
...original,
existsSync: (p: string) => store.has(p),
mkdirSync: vi.fn((p: string) => {
addDir(p);
}),
readFileSync: (p: string) => {
const entry = store.get(p);
return entry?.type === "file" ? (entry.content ?? "") : raise(`ENOENT: ${p}`);
},
writeFileSync: vi.fn((p: string, data: string) => {
store.set(p, { type: "file", content: data });
}),
readdirSync: (p: string) => {
const prefix = p.endsWith("/") ? p : `${p}/`;
const entries = new Set(
[...store.keys()]
.filter((k) => k.startsWith(prefix))
.map((k) => k.slice(prefix.length).split("/")[0])
.filter((first): first is string => Boolean(first)),
);
return entries.size === 0 && !store.has(p) ? raise(`ENOENT: ${p}`) : [...entries].sort();
},
};
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const mockExeca = vi.fn();
vi.mock("execa", () => ({
execa: (...args: unknown[]) => mockExeca(...args),
}));

vi.mock("./ssrf.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("./ssrf.js")>();
return {
...actual,
validateEndpointUrl: vi.fn(async (url: string) => ({
url,
pinnedUrl: url,
protocol: url.startsWith("http:") ? "http:" : "https:",
hostname: new URL(url).hostname,
dnsResolved: false,
})),
};
});

const { actionApply, actionRollback } = await import("./runner.js");

const stdoutChunks: string[] = [];

function captureStdout(): void {
vi.spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array) => {
stdoutChunks.push(String(chunk));
return true;
});
}

function minimalBlueprint(): Record<string, unknown> {
return {
version: "1.0",
components: {
inference: {
profiles: {
default: {
provider_type: "openai",
provider_name: "my-provider",
endpoint: "https://api.example.com/v1",
model: "gpt-4",
credential_env: "MY_API_KEY",
},
},
},
sandbox: {
image: "openclaw",
name: "test-sandbox",
forward_ports: [18789],
},
policy: { additions: {} },
},
};
}

function createCalls(): unknown[] {
return mockExeca.mock.calls.filter(
(c) => Array.isArray(c[1]) && c[1][0] === "sandbox" && c[1][1] === "create",
);
}

type BlueprintComponents = {
sandbox: { name: string };
inference: { profiles: { default: { provider_name: string } } };
};

/** Each case corrupts one identifier so the table stays branch-free. */
const INVALID_NAME_CASES: ReadonlyArray<
readonly [string, (components: BlueprintComponents) => void, RegExp]
> = [
[
"sandbox name",
// "--help" would be consumed as a flag by `openshell sandbox create`.
(components) => {
components.sandbox.name = "--help";
},
/Invalid sandbox name/,
],
[
"provider name",
(components) => {
components.inference.profiles.default.provider_name = "$(id)";
},
/Invalid provider name/,
],
[
"provider name containing a line feed",
(components) => {
components.inference.profiles.default.provider_name = "provider\n::error::forged";
},
/Invalid provider name/,
],
[
"over-length provider name",
(components) => {
components.inference.profiles.default.provider_name = `a${"b".repeat(128)}`;
},
/Invalid provider name/,
],
];

const VALID_PROVIDER_NAMES = ["Provider_1.prod", `a${"b".repeat(127)}`] as const;

describe("blueprint name validation (fail-closed integration)", () => {
const RUNS_DIR = `${FAKE_HOME}/.nemoclaw/state/runs`;

beforeEach(() => {
store.clear();
stdoutChunks.length = 0;
vi.clearAllMocks();
captureStdout();
mockExeca.mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" });
});

afterEach(() => {
vi.restoreAllMocks();
});

it.each(
INVALID_NAME_CASES,
)("apply rejects a malformed %s and creates no sandbox", async (_label, corrupt, expected) => {
const bp = minimalBlueprint();
corrupt(bp.components as BlueprintComponents);

await expect(actionApply("default", bp)).rejects.toThrow(expected);
// Validation runs before any command, so no provider or sandbox command
// may have executed — not merely no sandbox create.
expect(mockExeca).not.toHaveBeenCalled();
expect(createCalls()).toEqual([]);
Comment thread
1PoPTRoN marked this conversation as resolved.
Resolved
});

it.each(
VALID_PROVIDER_NAMES,
)("apply accepts the supported provider name '%s'", async (providerName) => {
const bp = minimalBlueprint();
const components = bp.components as BlueprintComponents;
components.inference.profiles.default.provider_name = providerName;

await expect(actionApply("default", bp)).resolves.toBeUndefined();
expect(mockExeca).toHaveBeenCalledWith(
"openshell",
expect.arrayContaining(["provider", "create", "--name", providerName]),
expect.any(Object),
);
});

it("rollback rejects a plan whose sandbox_name is not an RFC 1035 label", async () => {
const runDir = `${RUNS_DIR}/nc-run-1`;
addDir(runDir);
// "--rm" would be consumed as a flag by `openshell sandbox stop/remove`.
addFile(`${runDir}/plan.json`, JSON.stringify({ sandbox_name: "--rm" }));

await expect(actionRollback("nc-run-1")).rejects.toThrow(/Invalid sandbox name/);
expect(mockExeca).not.toHaveBeenCalled();
expect(store.has(`${runDir}/rolled_back`)).toBe(false);
});
});
26 changes: 25 additions & 1 deletion nemoclaw/src/blueprint/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { DASHBOARD_PORT } from "../lib/ports.js";
import { buildSubprocessEnv } from "../lib/subprocess-env.js";
import { isPlainObject, type UnknownRecord } from "../shared/object-record.js";
import * as importedOpenShellPolicyBoundary from "../shared/openshell-policy-boundary.cjs";
import * as importedSandboxName from "../shared/sandbox-name.cjs";
import type { SnapshotCommandOptions } from "./snapshot-command.js";
import { actionSnapshots } from "./snapshot-command.js";
import { safeEndpointUrlForDownstream, validateEndpointUrl } from "./ssrf.js";
Expand All @@ -37,6 +38,13 @@ const sourceOrGeneratedOpenShellPolicyBoundary =
const { parseOpenShellPolicy, withoutProviderComposedPolicies } =
sourceOrGeneratedOpenShellPolicyBoundary.default ?? sourceOrGeneratedOpenShellPolicyBoundary;

// sourceOfTruth: nemoclaw/src/shared/sandbox-name.cts
const sourceOrGeneratedSandboxName = importedSandboxName as typeof importedSandboxName & {
default?: typeof importedSandboxName;
};
const { assertValidName, assertValidProviderName } =
sourceOrGeneratedSandboxName.default ?? sourceOrGeneratedSandboxName;

type Action = "plan" | "apply" | "status" | "rollback";

type RollbackPlanSource = { sandbox_name?: unknown };
Expand Down Expand Up @@ -295,7 +303,9 @@ function readRollbackSandboxName(value: RollbackPlanSource | null): string {
throw new Error("rollback plan sandbox_name must be a non-empty string");
}

return value.sandbox_name;
// The persisted plan is untrusted input at this boundary too: validate before
// the name reaches `openshell sandbox stop/remove`, mirroring the apply path.
return assertValidName(value.sandbox_name, "sandbox name");
}

// ── Utilities ───────────────────────────────────────────────────
Expand Down Expand Up @@ -452,6 +462,20 @@ async function resolveRunConfig(

const sandboxCfg = blueprint.components?.sandbox ?? {};
const routerCfg = blueprint.components?.router ?? {};

// A blueprint is untrusted input. Validate the identifiers that flow into
// `openshell ... --name <value>` argv slots (and onward to shell scripts and
// Kubernetes pod names) at this ingestion boundary and fail closed, so every
// downstream consumer receives a name that is safe by construction. Absent
// values fall back to validated defaults ("openclaw" / "default") at the use
// sites and are intentionally not rejected here.
if (sandboxCfg.name !== undefined) {
assertValidName(sandboxCfg.name, "sandbox name");
}
if (inferenceCfg.provider_name !== undefined) {
assertValidProviderName(inferenceCfg.provider_name);
}

return { inferenceProfiles, inferenceCfg, sandboxCfg, routerCfg };
}

Expand Down
10 changes: 6 additions & 4 deletions nemoclaw/src/blueprint/snapshot.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import type fs from "node:fs";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

const SNAP = "/snap/20260323";

// ── In-memory filesystem ────────────────────────────────────────
Expand Down Expand Up @@ -265,9 +266,10 @@ describe("snapshot", () => {

const error = await restoreIntoSandbox(SNAP, longName).catch((e: Error) => e);
expect(error).toBeInstanceOf(Error);
// The full 200-char name must NOT appear — only the first 80 chars + ellipsis
expect((error as Error).message).toContain("…");
expect((error as Error).message).not.toContain(longName);
const message = (error as Error).message;
expect(message).toContain(`"${"a".repeat(80)}..."`);
expect(message).not.toContain(longName);
expect(message).toMatch(/^[\x20-\x7e]+$/);
expect(mockExeca).not.toHaveBeenCalled();
});

Expand Down
21 changes: 9 additions & 12 deletions nemoclaw/src/blueprint/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,18 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";

import { execa } from "execa";

import * as importedSandboxName from "../shared/sandbox-name.cjs";

const HOME = homedir();
const OPENCLAW_DIR = join(HOME, ".openclaw");
const NEMOCLAW_DIR = join(HOME, ".nemoclaw");
const SNAPSHOTS_DIR = join(NEMOCLAW_DIR, "snapshots");
const SANDBOX_NAME_RE = /^[a-z]([a-z0-9-]*[a-z0-9])?$/;

// sourceOfTruth: nemoclaw/src/shared/sandbox-name.cts
const sourceOrGeneratedSandboxName = importedSandboxName as typeof importedSandboxName & {
default?: typeof importedSandboxName;
};
const { assertValidName } = sourceOrGeneratedSandboxName.default ?? sourceOrGeneratedSandboxName;

function compactTimestamp(): string {
return new Date()
Expand Down Expand Up @@ -93,16 +100,6 @@ function collectFiles(dir: string): { files: string[]; symlinks: string[] } {
return { files, symlinks };
}

function validateSandboxName(sandboxName: string): void {
if (!SANDBOX_NAME_RE.test(sandboxName) || sandboxName.length > 63) {
const preview = sandboxName.length > 80 ? `${sandboxName.slice(0, 80)}…` : sandboxName;
throw new Error(
`Invalid sandbox name: '${preview}'. ` +
"Allowed format: lowercase, starts with a letter, letters/numbers/internal hyphens only, ends with letter/number.",
);
}
}

export function createSnapshot(): string | null {
if (!existsSync(OPENCLAW_DIR)) {
return null;
Expand Down Expand Up @@ -144,7 +141,7 @@ export async function restoreIntoSandbox(
snapshotDir: string,
sandboxName = "openclaw",
): Promise<boolean> {
validateSandboxName(sandboxName);
assertValidName(sandboxName, "sandbox name");

const source = join(snapshotDir, "openclaw");
if (!existsSync(source)) {
Expand Down
Loading
Loading