Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 8 additions & 2 deletions nemoclaw/src/blueprint/state.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { describe, it, expect, beforeEach, vi } from "vitest";
import type fs from "node:fs";
import { homedir } from "node:os";
import { loadState, saveState, clearState, type NemoClawState } from "./state.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { clearState, loadState, type NemoClawState, saveState } from "./state.js";

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

Expand All @@ -22,6 +22,12 @@ vi.mock("node:fs", async (importOriginal) => {
writeFileSync: (p: string, data: string) => {
store.set(p, data);
},
renameSync: (from: string, to: string) => {
const content = store.get(from);
if (content === undefined) throw new Error(`ENOENT: ${from}`);
store.set(to, content);
store.delete(from);
},
};
});

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

import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";

Expand Down Expand Up @@ -144,17 +145,21 @@ export function loadState(): NemoClawState {
}
}

function writeStateFile(state: NemoClawState): void {
const finalPath = statePath();
const tmpPath = `${finalPath}.${process.pid}.${randomUUID()}.tmp`;
writeFileSync(tmpPath, JSON.stringify(state, null, 2), { mode: 0o600 });
renameSync(tmpPath, finalPath);
}

export function saveState(state: NemoClawState): void {
ensureStateDir();
state.updatedAt = new Date().toISOString();
state.createdAt ??= state.updatedAt;
writeFileSync(statePath(), JSON.stringify(state, null, 2));
writeStateFile(state);
}

export function clearState(): void {
ensureStateDir();
const path = statePath();
if (existsSync(path)) {
writeFileSync(path, JSON.stringify(blankState(), null, 2));
}
writeStateFile(blankState());
}
14 changes: 6 additions & 8 deletions src/lib/actions/sandbox/gateway-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -457,14 +457,12 @@ export async function ensureLiveSandboxOrExit(
if (lookup.state === "identity_drift") {
console.error(" Gateway SSH identity changed after restart — clearing stale host keys...");
const knownHostsPath = path.join(os.homedir(), ".ssh", "known_hosts");
if (fs.existsSync(knownHostsPath)) {
try {
const kh = fs.readFileSync(knownHostsPath, "utf8");
const cleaned = pruneKnownHostsEntries(kh);
if (cleaned !== kh) fs.writeFileSync(knownHostsPath, cleaned);
} catch {
/* best-effort cleanup */
}
try {
const kh = fs.readFileSync(knownHostsPath, "utf8");
const cleaned = pruneKnownHostsEntries(kh);
if (cleaned !== kh) fs.writeFileSync(knownHostsPath, cleaned);
} catch {
/* best-effort cleanup */
}
const retry = await getReconciledSandboxGatewayState(sandboxName);
if (retry.state === "present") {
Expand Down
20 changes: 19 additions & 1 deletion src/lib/actions/uninstall/plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
import { classifyNemoclawShim, type ShimClassification } from "../../domain/uninstall/shims";

export interface FileSystemDeps {
closeSync?: typeof fs.closeSync;
fstatSync?: typeof fs.fstatSync;
lstatSync?: typeof fs.lstatSync;
openSync?: typeof fs.openSync;
readFileSync?: typeof fs.readFileSync;
}

Expand All @@ -19,12 +22,27 @@

export function classifyShimPath(shimPath: string, deps: FileSystemDeps = {}): ShimClassification {
const lstatSync = deps.lstatSync ?? fs.lstatSync;
const openSync = deps.openSync ?? fs.openSync;
const fstatSync = deps.fstatSync ?? fs.fstatSync;
const readFileSync = deps.readFileSync ?? fs.readFileSync;
const closeSync = deps.closeSync ?? fs.closeSync;
try {
const stat = lstatSync(shimPath);
const isFile = stat.isFile();
let contents: string | undefined;
if (isFile) {
const fd = openSync(shimPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
try {
const fdStat = fstatSync(fd);
if (fdStat.isFile()) {
contents = String(readFileSync(fd, "utf-8"));
}
} finally {
closeSync(fd);
}
}
return classifyNemoclawShim({
contents: isFile ? String(readFileSync(shimPath, "utf-8")) : undefined,
contents,
exists: true,
isFile,
isSymlink: stat.isSymbolicLink(),
Expand Down
22 changes: 19 additions & 3 deletions src/lib/actions/uninstall/run-plan.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { spawnSync, type SpawnSyncOptions, type SpawnSyncReturns } from "node:child_process";
import { type SpawnSyncOptions, type SpawnSyncReturns, spawnSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

import { dockerSpawnSync } from "../../adapters/docker/exec";
import { getAgentBranding, type AgentBranding } from "../../cli/branding";
import { type AgentBranding, getAgentBranding } from "../../cli/branding";
import { sleepMs } from "../../core/wait";
import { defaultUninstallPaths, NEMOCLAW_OLLAMA_MODELS, NEMOCLAW_PROVIDERS, type UninstallPaths } from "../../domain/uninstall/paths";
import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan";
Expand Down Expand Up @@ -65,7 +65,23 @@ function defaultRunDocker(args: string[], options: SpawnSyncOptions = {}): RunRe
}

function defaultCommandExists(command: string, env: NodeJS.ProcessEnv): boolean {
return defaultRun("sh", ["-c", `command -v ${JSON.stringify(command)} >/dev/null 2>&1`], { env }).status === 0;
if (!command || command.includes("\0")) return false;
const hasPathSeparator = command.includes(path.sep) || command.includes(path.posix.sep) || command.includes(path.win32.sep);
const candidates = hasPathSeparator
? [command]
: String(env.PATH || "")
.split(path.delimiter)
.filter(Boolean)
.map((entry) => path.join(entry, command));
for (const candidate of candidates) {
try {
fs.accessSync(candidate, fs.constants.X_OK);
return true;
} catch {
// Try the next PATH entry.
}
}
return false;
}

function defaultReadLine(env: NodeJS.ProcessEnv): string | null {
Expand Down
28 changes: 28 additions & 0 deletions src/lib/adapters/http/probe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,34 @@ describe("http-probe helpers", () => {
expect(result.curlStatus).toBe(-110);
expect(result.message).toContain("ETIMEDOUT");
});

it("rejects non-http probe URLs before spawning curl", () => {
let spawned = false;
const result = runCurlProbe(["-sS", "file:///etc/passwd"], {
spawnSyncImpl: () => {
spawned = true;
throw new Error("should not spawn");
},
});

expect(spawned).toBe(false);
expect(result.ok).toBe(false);
expect(result.message).toContain("curl probe URL must use http or https");
});

it("rejects curl probe request bodies that read from local files", () => {
let spawned = false;
const result = runCurlProbe(["-sS", "--data-binary", "@/etc/passwd", "https://example.test/models"], {
spawnSyncImpl: () => {
spawned = true;
throw new Error("should not spawn");
},
});

expect(spawned).toBe(false);
expect(result.ok).toBe(false);
expect(result.message).toContain("must not read request data from a file");
});
});

describe("runChatCompletionsStreamingProbe", () => {
Expand Down
84 changes: 75 additions & 9 deletions src/lib/adapters/http/probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,66 @@
}
}

const CURL_OPTIONS_THAT_READ_FILES = new Set(["--config", "-K", "--cookie", "-b", "--netrc-file"]);
const CURL_DATA_OPTIONS = new Set([
"--data",
"--data-raw",
"--data-binary",
"--data-ascii",
"--json",
"--form",
"-d",
"-F",
]);

function normalizeHttpProbeUrl(rawUrl: unknown): string {
if (typeof rawUrl !== "string" || rawUrl.trim() === "") {
throw new Error("curl probe URL is required");
}
const url = new URL(rawUrl);
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error(`curl probe URL must use http or https: ${url.protocol}`);
}
if (url.username || url.password) {
throw new Error("curl probe URL must not embed credentials");
}
return url.toString();
}

function curlValueReadsFromFile(value: string): boolean {
return (value.startsWith("@") && value !== "@-") || /(^|=)@[^-]/.test(value);
}

function validateCurlProbeArgs(argv: string[]): { args: string[]; url: string } {
const args = [...argv];
const url = normalizeHttpProbeUrl(args.pop());
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
const [option, inlineValue] = arg.includes("=") ? arg.split(/=(.*)/s, 2) : [arg, undefined];
if (CURL_OPTIONS_THAT_READ_FILES.has(option)) {
throw new Error(`curl probe option is not allowed because it reads local files: ${option}`);
}
if (arg === "--url" || arg.startsWith("--url=")) {
throw new Error("curl probe URLs must be passed as the final argv entry");
}
if ((arg.startsWith("-d") || arg.startsWith("-F")) && arg.length > 2 && !arg.startsWith("--")) {
const value = arg.slice(2);
if (curlValueReadsFromFile(value)) {
throw new Error(`curl probe option must not read request data from a file: ${arg.slice(0, 2)}`);
}
continue;
}
if (CURL_DATA_OPTIONS.has(option)) {
const value = inlineValue ?? args[index + 1] ?? "";
if (curlValueReadsFromFile(value)) {
throw new Error(`curl probe option must not read request data from a file: ${option}`);
}
if (inlineValue === undefined) index += 1;
}
}
return { args, url };
}

function getCurlProbeTraceAttributes(argv: string[], opts: CurlProbeOptions): Record<string, unknown> {
const url = argv.at(-1) || "";
const methodIndex = argv.findIndex((arg) => arg === "-X" || arg === "--request");
Expand Down Expand Up @@ -212,13 +272,15 @@
function runCurlProbeImpl(argv: string[], opts: CurlProbeOptions = {}): CurlProbeResult {
const bodyFile = secureTempFile("nemoclaw-curl-probe", ".json");
try {
const args = [...argv];
const url = args.pop();
const { args, url } = validateCurlProbeArgs(argv);
const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync;
const timeout = resolveCurlProcessTimeoutMs(argv, opts);
// The URL is normalized to http(s) and curl argv is screened for options
// that make curl read local files into the outbound request.
// lgtm[js/file-access-to-http]
const result = spawnSyncImpl(
"curl",
[...args, "-o", bodyFile, "-w", "%{http_code}", String(url || "")],
[...args, "-o", bodyFile, "-w", "%{http_code}", url],
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
{
cwd: opts.cwd ?? ROOT,
encoding: "utf8",
Expand Down Expand Up @@ -320,13 +382,15 @@
): CurlProbeResult {
const bodyFile = secureTempFile("nemoclaw-chat-streaming-probe", ".sse");
try {
const args = [...argv];
const url = args.pop();
const { args, url } = validateCurlProbeArgs(argv);
const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync;
const timeout = resolveCurlProcessTimeoutMs(argv, opts);
// The URL is normalized to http(s) and curl argv is screened for options
// that make curl read local files into the outbound request.
// lgtm[js/file-access-to-http]
const result = spawnSyncImpl(
"curl",
[...args, "-N", "-o", bodyFile, "-w", "%{http_code}", String(url || "")],
[...args, "-N", "-o", bodyFile, "-w", "%{http_code}", url],
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
{
cwd: opts.cwd ?? ROOT,
encoding: "utf8",
Expand Down Expand Up @@ -440,11 +504,13 @@
): StreamingProbeResult {
const bodyFile = secureTempFile("nemoclaw-streaming-probe", ".sse");
try {
const args = [...argv];
const url = args.pop();
const { args, url } = validateCurlProbeArgs(argv);
const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync;
const timeout = resolveCurlProcessTimeoutMs(argv, opts);
const result = spawnSyncImpl("curl", [...args, "-N", "-o", bodyFile, String(url || "")], {
// The URL is normalized to http(s) and curl argv is screened for options
// that make curl read local files into the outbound request.
// lgtm[js/file-access-to-http]
const result = spawnSyncImpl("curl", [...args, "-N", "-o", bodyFile, url], {
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
cwd: opts.cwd ?? ROOT,
encoding: "utf8",
timeout,
Expand Down
29 changes: 14 additions & 15 deletions src/lib/credentials/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,18 +235,14 @@ export function listCredentialKeys(): string[] {
* backup tools and same-user processes tend to read.
*/
function secureUnlink(filePath: string): void {
let opened = false;
try {
const stat = fs.lstatSync(filePath);
if (stat.isSymbolicLink()) {
// The credentials path was a symlink; remove the link itself without
// touching whatever it pointed at.
fs.unlinkSync(filePath);
return;
}
if (!stat.isFile()) return;
if (stat.size > 0) {
const fd = fs.openSync(filePath, fs.constants.O_RDWR | fs.constants.O_NOFOLLOW);
try {
const fd = fs.openSync(filePath, fs.constants.O_RDWR | fs.constants.O_NOFOLLOW);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
opened = true;
try {
const stat = fs.fstatSync(fd);
if (!stat.isFile()) return;
if (stat.size > 0) {
const chunkSize = Math.min(stat.size, 64 * 1024);
const zeros = Buffer.alloc(chunkSize);
let written = 0;
Expand All @@ -256,15 +252,18 @@ function secureUnlink(filePath: string): void {
written += len;
}
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
} finally {
fs.closeSync(fd);
}
} catch {
// best effort
// best effort; a final-component symlink will fail O_NOFOLLOW and is
// removed below as a link without touching its target.
}
try {
fs.unlinkSync(filePath);
if (opened || fs.lstatSync(filePath).isSymbolicLink()) {
fs.unlinkSync(filePath);
}
} catch {
// best effort
}
Expand Down
Loading
Loading