Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
56 changes: 21 additions & 35 deletions src/lib/onboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3986,11 +3986,6 @@ async function _setupPolicies(sandboxName, options = {}) {
break;
} catch (err) {
const message = err && err.message ? err.message : String(err);
if (message.includes("Unimplemented")) {
console.error(" OpenShell policy updates are not supported by this gateway build.");
console.error(" This is a known issue tracked in NemoClaw #536.");
throw err;
}
if (!message.includes("sandbox not found") || attempt === 2) {
throw err;
}
Expand Down Expand Up @@ -4030,30 +4025,12 @@ async function _setupPolicies(sandboxName, options = {}) {
.map((s) => s.trim())
.filter(Boolean);
for (const name of selected) {
try {
policies.applyPreset(sandboxName, name);
} catch (err) {
const message = err && err.message ? err.message : String(err);
if (message.includes("Unimplemented")) {
console.error(" OpenShell policy updates are not supported by this gateway build.");
console.error(" This is a known issue tracked in NemoClaw #536.");
}
throw err;
}
policies.applyPreset(sandboxName, name);
}
} else {
// Apply suggested
for (const name of suggestions) {
try {
policies.applyPreset(sandboxName, name);
} catch (err) {
const message = err && err.message ? err.message : String(err);
if (message.includes("Unimplemented")) {
console.error(" OpenShell policy updates are not supported by this gateway build.");
console.error(" This is a known issue tracked in NemoClaw #536.");
}
throw err;
}
policies.applyPreset(sandboxName, name);
}
}
}
Expand Down Expand Up @@ -4580,11 +4557,6 @@ async function setupPoliciesWithSelection(sandboxName, options = {}) {
break;
} catch (err) {
const message = err && err.message ? err.message : String(err);
if (message.includes("Unimplemented")) {
console.error(" OpenShell policy updates are not supported by this gateway build.");
console.error(" This is a known issue tracked in NemoClaw #536.");
throw err;
}
if (!message.includes("sandbox not found") || attempt === 2) {
throw err;
}
Expand Down Expand Up @@ -4616,6 +4588,25 @@ async function setupPoliciesWithSelection(sandboxName, options = {}) {
const accessByName = {};
for (const p of resolvedPresets) accessByName[p.name] = p.access;
const newlySelected = interactiveChoice.filter((name) => !applied.includes(name));
const deselected = applied.filter((name) => !interactiveChoice.includes(name));

for (const name of deselected) {
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
if (!policies.removePreset(sandboxName, name)) {
throw new Error(`Failed to remove preset '${name}'.`);
}
break;
} catch (err) {
const message = err && err.message ? err.message : String(err);
if (!message.includes("sandbox not found") || attempt === 2) {
throw err;
}
sleep(2);
}
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

for (const name of newlySelected) {
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
Expand All @@ -4625,11 +4616,6 @@ async function setupPoliciesWithSelection(sandboxName, options = {}) {
break;
} catch (err) {
const message = err && err.message ? err.message : String(err);
if (message.includes("Unimplemented")) {
console.error(" OpenShell policy updates are not supported by this gateway build.");
console.error(" This is a known issue tracked in NemoClaw #536.");
throw err;
}
if (!message.includes("sandbox not found") || attempt === 2) {
throw err;
}
Expand Down
184 changes: 184 additions & 0 deletions src/lib/policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,187 @@ function mergePresetIntoPolicy(currentPolicy, presetEntries) {

return YAML.stringify(output);
}

/**
* Remove preset entries from existing policy YAML using structured YAML
* parsing. Identifies which network_policies keys belong to the preset,
* removes them, and returns the resulting YAML.
*
* @param {string} currentPolicy - Existing policy YAML
* @param {string} presetEntries - Indented network_policies entries from preset
* @returns {string} Policy YAML with the preset's entries removed
*/
function removePresetFromPolicy(currentPolicy, presetEntries) {
const normalizedCurrentPolicy = parseCurrentPolicy(currentPolicy);
if (!presetEntries) {
return normalizedCurrentPolicy || "version: 1\n\nnetwork_policies:\n";
}

if (!normalizedCurrentPolicy) return "version: 1\n\nnetwork_policies:\n";

// Parse preset entries to extract the network_policies key names.
// They come as indented content under network_policies:,
// so we wrap them to make valid YAML for parsing.
let presetKeys;
try {
const wrapped = "network_policies:\n" + presetEntries;
const parsed = YAML.parse(wrapped);
presetKeys = parsed?.network_policies
? Object.keys(parsed.network_policies)
: [];
} catch {
presetKeys = [];
}

if (presetKeys.length === 0) return normalizedCurrentPolicy;

// Parse the current policy as structured YAML
let current;
try {
current = YAML.parse(normalizedCurrentPolicy);
} catch {
return normalizedCurrentPolicy;
}

if (!current || typeof current !== "object") return normalizedCurrentPolicy;

// Guard: network_policies may be an array in legacy policies — only
// delete keys when it is a plain object.
const existingNp = current.network_policies;
if (!existingNp || typeof existingNp !== "object" || Array.isArray(existingNp)) {
return normalizedCurrentPolicy;
}

for (const key of presetKeys) {
delete existingNp[key];
}

current.network_policies = existingNp;
return YAML.stringify(current);
}

function removePreset(sandboxName, presetName) {
// Guard against truncated sandbox names — WSL can truncate hyphenated
// names during argument parsing, e.g. "my-assistant" → "m"
const isRfc1123Label = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(sandboxName);
if (!sandboxName || sandboxName.length > 63 || !isRfc1123Label) {
throw new Error(
`Invalid or truncated sandbox name: '${sandboxName}'. ` +
`Names must be 1-63 chars, lowercase alphanumeric, with optional internal hyphens.`,
);
}

const presetContent = loadPreset(presetName);
if (!presetContent) {
console.error(` Cannot load preset: ${presetName}`);
return false;
}

const presetEntries = extractPresetEntries(presetContent);
if (!presetEntries) {
console.error(` Preset ${presetName} has no network_policies section.`);
return false;
}

// Get current policy YAML from sandbox
let rawPolicy = "";
try {
rawPolicy = runCapture(buildPolicyGetCommand(sandboxName), { ignoreError: true });
} catch {
/* ignored */
}

const currentPolicy = parseCurrentPolicy(rawPolicy);
if (!currentPolicy) {
console.error(` Could not read current policy for sandbox '${sandboxName}'.`);
return false;
}

const updated = removePresetFromPolicy(currentPolicy, presetEntries);

if (updated === currentPolicy) {
console.error(` Preset '${presetName}' could not be removed from the current policy.`);
return false;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const endpoints = getPresetEndpoints(presetContent);
if (endpoints.length > 0) {
console.log(` Narrowing sandbox egress — removing: ${endpoints.join(", ")}`);
}

const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-"));
const tmpFile = path.join(tmpDir, "policy.yaml");
fs.writeFileSync(tmpFile, updated, { encoding: "utf-8", mode: 0o600 });

try {
run(buildPolicySetCommand(tmpFile, sandboxName));
console.log(` Removed preset: ${presetName}`);
} finally {
try {
fs.unlinkSync(tmpFile);
} catch {
/* ignored */
}
try {
fs.rmdirSync(tmpDir);
} catch {
/* ignored */
}
}

const sandbox = registry.getSandbox(sandboxName);
if (sandbox) {
const pols = (sandbox.policies || []).filter((p) => p !== presetName);
registry.updateSandbox(sandboxName, { policies: pols });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

return true;
}

function selectForRemoval(items, { applied = [] } = {}) {
return new Promise((resolve) => {
const appliedItems = items.filter((item) => applied.includes(item.name));
if (appliedItems.length === 0) {
process.stderr.write("\n No presets are currently applied.\n\n");
resolve(null);
return;
}
process.stderr.write("\n Applied presets:\n");
appliedItems.forEach((item, i) => {
const description = item.description ? ` — ${item.description}` : "";
process.stderr.write(` ${i + 1}) ${item.name}${description}\n`);
});
process.stderr.write("\n");
const question = " Choose preset to remove: ";
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
rl.question(question, (answer) => {
rl.close();
if (!process.stdin.isTTY) {
if (typeof process.stdin.pause === "function") process.stdin.pause();
if (typeof process.stdin.unref === "function") process.stdin.unref();
}
const trimmed = answer.trim();
if (!trimmed) {
resolve(null);
return;
}
if (!/^\d+$/.test(trimmed)) {
process.stderr.write("\n Invalid preset number.\n");
resolve(null);
return;
}
const num = Number(trimmed);
const item = appliedItems[num - 1];
if (!item) {
process.stderr.write("\n Invalid preset number.\n");
resolve(null);
return;
}
resolve(item.name);
});
});
}

function applyPreset(sandboxName, presetName, _options = {}) {
// Guard against truncated sandbox names — WSL can truncate hyphenated
// names during argument parsing, e.g. "my-assistant" → "m"
Expand Down Expand Up @@ -403,8 +584,11 @@ export {
buildPolicySetCommand,
buildPolicyGetCommand,
mergePresetIntoPolicy,
removePresetFromPolicy,
applyPreset,
removePreset,
applyPermissivePolicy,
getAppliedPresets,
selectFromList,
selectForRemoval,
};
35 changes: 34 additions & 1 deletion src/nemoclaw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1374,6 +1374,35 @@ async function sandboxSkillInstall(sandboxName, args = []) {
}
}

async function sandboxPolicyRemove(sandboxName, args = []) {
const dryRun = args.includes("--dry-run");
const allPresets = policies.listPresets();
const applied = policies.getAppliedPresets(sandboxName);

const answer = await policies.selectForRemoval(allPresets, { applied });
if (!answer) return;

const presetContent = policies.loadPreset(answer);
if (!presetContent) return;

const endpoints = policies.getPresetEndpoints(presetContent);
if (endpoints.length > 0) {
console.log(` Endpoints that would be removed: ${endpoints.join(", ")}`);
}

if (dryRun) {
console.log(" --dry-run: no changes applied.");
return;
}

const confirm = await askPrompt(` Remove '${answer}' from sandbox '${sandboxName}'? [Y/n]: `);
if (confirm.toLowerCase() === "n") return;

if (!policies.removePreset(sandboxName, answer)) {
process.exit(1);
}
}

function cleanupSandboxServices(sandboxName, { stopHostServices = false } = {}) {
if (stopHostServices) {
const { stopAll } = require("./lib/services");
Expand Down Expand Up @@ -1477,6 +1506,7 @@ function help() {

${G}Policy Presets:${R}
nemoclaw <name> policy-add Add a network or filesystem policy preset ${D}(--dry-run to preview)${R}
nemoclaw <name> policy-remove Remove an applied policy preset ${D}(--dry-run to preview)${R}
nemoclaw <name> policy-list List presets ${D}(● = applied)${R}

${G}Compatibility Commands:${R}
Expand Down Expand Up @@ -1599,6 +1629,9 @@ const [cmd, ...args] = process.argv.slice(2);
case "policy-add":
await sandboxPolicyAdd(cmd, actionArgs);
break;
case "policy-remove":
await sandboxPolicyRemove(cmd, actionArgs);
break;
case "policy-list":
sandboxPolicyList(cmd);
break;
Expand All @@ -1610,7 +1643,7 @@ const [cmd, ...args] = process.argv.slice(2);
break;
default:
console.error(` Unknown action: ${action}`);
console.error(` Valid actions: connect, status, logs, policy-add, policy-list, skill, destroy`);
console.error(` Valid actions: connect, status, logs, policy-add, policy-remove, policy-list, skill, destroy`);
process.exit(1);
}
return;
Expand Down
Loading
Loading