Skip to content

Commit 6fb00de

Browse files
committed
fix: align deploy hardening with centralized shellQuote pattern
Align with ericksoa's #584 approach: - Centralize shellQuote in runner.js, remove local copy from nemoclaw.js - Replace double-quoting with shellQuote() single-quote wrapping - Switch execSync to execFileSync in deploy() - Quote env values (API keys, tokens) with shellQuote - Max 63 chars (RFC 1123 label) instead of 253 (subdomain) - Update tests to verify shellQuote patterns
1 parent a1b2e96 commit 6fb00de

3 files changed

Lines changed: 51 additions & 59 deletions

File tree

‎bin/lib/runner.js‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,12 @@ function runCapture(cmd, opts = {}) {
5858
}
5959
}
6060

61-
module.exports = { ROOT, SCRIPTS, run, runCapture, runInteractive };
61+
/**
62+
* Shell-quote a value for safe interpolation into bash -c strings.
63+
* Wraps in single quotes and escapes embedded single quotes.
64+
*/
65+
function shellQuote(value) {
66+
return `'${String(value).replace(/'/g, `'\\''`)}'`;
67+
}
68+
69+
module.exports = { ROOT, SCRIPTS, run, runCapture, runInteractive, shellQuote };

‎bin/nemoclaw.js‎

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
33
// SPDX-License-Identifier: Apache-2.0
44

5-
const { execSync, spawnSync } = require("child_process");
5+
const { execFileSync, spawnSync } = require("child_process");
66
const path = require("path");
77
const fs = require("fs");
88
const os = require("os");
99

10-
const { ROOT, SCRIPTS, run, runCapture, runInteractive } = require("./lib/runner");
10+
const { ROOT, SCRIPTS, run, runCapture, runInteractive, shellQuote } = require("./lib/runner");
1111
const {
1212
ensureApiKey,
1313
ensureGithubToken,
@@ -28,10 +28,6 @@ const GLOBAL_COMMANDS = new Set([
2828

2929
const REMOTE_UNINSTALL_URL = "https://raw.githubusercontent.com/NVIDIA/NemoClaw/refs/heads/main/uninstall.sh";
3030

31-
function shellQuote(value) {
32-
return `'${String(value).replace(/'/g, `'\\''`)}'`;
33-
}
34-
3531
function resolveUninstallScript() {
3632
const candidates = [
3733
path.join(ROOT, "uninstall.sh"),
@@ -107,14 +103,15 @@ async function deploy(instanceName) {
107103
}
108104
const name = instanceName.trim();
109105

110-
// Validate: same RFC 1123 subdomain rules used for sandbox names — lowercase
111-
// alphanumeric and hyphens, must start and end with alphanumeric.
112-
if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(name) || name.length > 253) {
106+
// Validate: RFC 1123 label — lowercase alphanumeric and hyphens,
107+
// must start and end with alphanumeric, max 63 chars.
108+
if (!name || name.length > 63 || !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(name)) {
113109
console.error(` Invalid instance name: '${name}'`);
114110
console.error(" Names must be lowercase, contain only letters, numbers, and hyphens,");
115-
console.error(" and must start and end with a letter or number (max 253 chars).");
111+
console.error(" and must start and end with a letter or number (max 63 chars).");
116112
process.exit(1);
117113
}
114+
const qname = shellQuote(name);
118115

119116
const gpu = process.env.NEMOCLAW_GPU || "a2-highgpu-1g:nvidia-tesla-a100:1";
120117

@@ -123,21 +120,24 @@ async function deploy(instanceName) {
123120
console.log("");
124121

125122
try {
126-
execSync("which brev", { stdio: "ignore" });
123+
execFileSync("which", ["brev"], { stdio: "ignore" });
127124
} catch {
128125
console.error("brev CLI not found. Install: https://brev.nvidia.com");
129126
process.exit(1);
130127
}
131128

132129
let exists = false;
133130
try {
134-
const out = execSync("brev ls 2>&1", { encoding: "utf-8" });
131+
const out = execFileSync("brev", ["ls"], { encoding: "utf-8" });
135132
exists = out.includes(name);
136-
} catch {}
133+
} catch (err) {
134+
if (err.stdout && err.stdout.includes(name)) exists = true;
135+
if (err.stderr && err.stderr.includes(name)) exists = true;
136+
}
137137

138138
if (!exists) {
139139
console.log(` Creating Brev instance '${name}' (${gpu})...`);
140-
run(`brev create "${name}" --gpu "${gpu}"`);
140+
run(`brev create ${qname} --gpu ${shellQuote(gpu)}`);
141141
} else {
142142
console.log(` Brev instance '${name}' already exists.`);
143143
}
@@ -147,7 +147,7 @@ async function deploy(instanceName) {
147147
console.log(" Waiting for SSH...");
148148
for (let i = 0; i < 60; i++) {
149149
try {
150-
execSync(`ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "${name}" 'echo ok' 2>/dev/null`, { encoding: "utf-8", stdio: "pipe" });
150+
execFileSync("ssh", ["-o", "ConnectTimeout=5", "-o", "StrictHostKeyChecking=no", name, "echo", "ok"], { encoding: "utf-8", stdio: "ignore" });
151151
break;
152152
} catch {
153153
if (i === 59) {
@@ -159,35 +159,36 @@ async function deploy(instanceName) {
159159
}
160160

161161
console.log(" Syncing NemoClaw to VM...");
162-
run(`ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR "${name}" 'mkdir -p /home/ubuntu/nemoclaw'`);
163-
run(`rsync -az --delete --exclude node_modules --exclude .git --exclude src -e "ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR" "${ROOT}/scripts" "${ROOT}/Dockerfile" "${ROOT}/nemoclaw" "${ROOT}/nemoclaw-blueprint" "${ROOT}/bin" "${ROOT}/package.json" "${name}":/home/ubuntu/nemoclaw/`);
162+
run(`ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR ${qname} 'mkdir -p /home/ubuntu/nemoclaw'`);
163+
run(`rsync -az --delete --exclude node_modules --exclude .git --exclude src -e "ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR" "${ROOT}/scripts" "${ROOT}/Dockerfile" "${ROOT}/nemoclaw" "${ROOT}/nemoclaw-blueprint" "${ROOT}/bin" "${ROOT}/package.json" ${qname}:/home/ubuntu/nemoclaw/`);
164164

165-
const envLines = [`NVIDIA_API_KEY=${process.env.NVIDIA_API_KEY}`];
165+
const envLines = [`NVIDIA_API_KEY=${shellQuote(process.env.NVIDIA_API_KEY || "")}`];
166166
const ghToken = process.env.GITHUB_TOKEN;
167-
if (ghToken) envLines.push(`GITHUB_TOKEN=${ghToken}`);
167+
if (ghToken) envLines.push(`GITHUB_TOKEN=${shellQuote(ghToken)}`);
168168
const tgToken = getCredential("TELEGRAM_BOT_TOKEN");
169-
if (tgToken) envLines.push(`TELEGRAM_BOT_TOKEN=${tgToken}`);
169+
if (tgToken) envLines.push(`TELEGRAM_BOT_TOKEN=${shellQuote(tgToken)}`);
170170
const envDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-"));
171-
const envTmp = path.join(envDir, ".env");
171+
const envTmp = path.join(envDir, "env");
172+
fs.writeFileSync(envTmp, envLines.join("\n") + "\n", { mode: 0o600 });
172173
try {
173-
fs.writeFileSync(envTmp, envLines.join("\n") + "\n", { mode: 0o600, flag: "wx" });
174-
run(`scp -q -o StrictHostKeyChecking=no -o LogLevel=ERROR "${envTmp}" "${name}":/home/ubuntu/nemoclaw/.env`);
174+
run(`scp -q -o StrictHostKeyChecking=no -o LogLevel=ERROR ${shellQuote(envTmp)} ${qname}:/home/ubuntu/nemoclaw/.env`);
175175
} finally {
176-
fs.rmSync(envDir, { recursive: true, force: true });
176+
try { fs.unlinkSync(envTmp); } catch {}
177+
try { fs.rmdirSync(envDir); } catch {}
177178
}
178179

179180
console.log(" Running setup...");
180-
runInteractive(`ssh -t -o StrictHostKeyChecking=no -o LogLevel=ERROR "${name}" 'cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && bash scripts/brev-setup.sh'`);
181+
runInteractive(`ssh -t -o StrictHostKeyChecking=no -o LogLevel=ERROR ${qname} 'cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && bash scripts/brev-setup.sh'`);
181182

182183
if (tgToken) {
183184
console.log(" Starting services...");
184-
run(`ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR "${name}" 'cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && bash scripts/start-services.sh'`);
185+
run(`ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR ${qname} 'cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && bash scripts/start-services.sh'`);
185186
}
186187

187188
console.log("");
188189
console.log(" Connecting to sandbox...");
189190
console.log("");
190-
runInteractive(`ssh -t -o StrictHostKeyChecking=no -o LogLevel=ERROR "${name}" 'cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && openshell sandbox connect nemoclaw'`);
191+
runInteractive(`ssh -t -o StrictHostKeyChecking=no -o LogLevel=ERROR ${qname} 'cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && openshell sandbox connect nemoclaw'`);
191192
}
192193

193194
async function start() {

‎test/deploy-instance-name.test.js‎

Lines changed: 14 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
22
// SPDX-License-Identifier: Apache-2.0
33
//
4-
// Verify that deploy() validates and quotes the instance name in shell
4+
// Verify that deploy() validates and shell-quotes the instance name in
55
// commands to prevent command injection.
66

77
const { describe, it } = require("node:test");
@@ -45,53 +45,36 @@ describe("deploy instance name hardening", () => {
4545
assert.match(
4646
deployBody,
4747
/\^\[a-z0-9\]/,
48-
"deploy() must validate the instance name against RFC 1123 subdomain rules"
48+
"deploy() must validate the instance name against RFC 1123 label rules"
4949
);
5050
});
5151

52-
it("rejects names longer than 253 characters inside deploy()", () => {
52+
it("enforces max 63 character limit", () => {
5353
assert.match(
5454
deployBody,
55-
/name\.length\s*>\s*253/,
56-
"deploy() must enforce a 253-character limit on instance names"
55+
/length\s*>\s*63/,
56+
"deploy() must enforce a 63-character limit on instance names"
5757
);
5858
});
5959

60-
it("does not interpolate unquoted instance name in shell commands", () => {
61-
// Every ${name} in a shell command string must be exactly "${name}".
62-
// Skip console.log/error lines which are display-only.
63-
const lines = deployBody.split("\n");
64-
for (const line of lines) {
65-
if (line.includes("${name}") && !line.match(/console\.(log|error)/)) {
66-
const all = [...line.matchAll(/\$\{name\}/g)].length;
67-
const quoted = [...line.matchAll(/"\$\{name\}"/g)].length;
68-
assert.equal(
69-
quoted,
70-
all,
71-
`Unquoted \${name} in shell command: ${line.trim()}`
72-
);
73-
}
74-
}
75-
});
76-
77-
it("quotes instance name in brev create", () => {
60+
it("uses shellQuote for instance name in shell commands", () => {
7861
assert.ok(
79-
deployBody.includes('brev create "${name}"'),
80-
'brev create must quote the instance name: brev create "${name}"'
62+
deployBody.includes("qname = shellQuote(name)"),
63+
"deploy() must create a shellQuoted name variable"
8164
);
8265
});
8366

84-
it("quotes instance name in rsync destination", () => {
67+
it("does not use execSync (prefer execFileSync)", () => {
8568
assert.ok(
86-
deployBody.includes('"${name}":/home/ubuntu/nemoclaw/'),
87-
'rsync destination must quote the instance name: "${name}":/path'
69+
!deployBody.includes("execSync("),
70+
"deploy() must use execFileSync instead of execSync"
8871
);
8972
});
9073

91-
it("quotes instance name in scp destination", () => {
74+
it("shell-quotes env values", () => {
9275
assert.ok(
93-
deployBody.includes('"${name}":/home/ubuntu/nemoclaw/.env'),
94-
'scp destination must quote the instance name: "${name}":/path'
76+
deployBody.includes("shellQuote(process.env.NVIDIA_API_KEY"),
77+
"NVIDIA_API_KEY must be shellQuoted in env file"
9578
);
9679
});
9780
});

0 commit comments

Comments
 (0)