Skip to content

Commit 0feaea6

Browse files
committed
fix(policies): allow preset application for versionless policies (Fixes #35)
Fixes #35 Signed-off-by: Deepak Jain <[email protected]>
1 parent dbfd78c commit 0feaea6

2 files changed

Lines changed: 95 additions & 50 deletions

File tree

‎bin/lib/policies.js‎

Lines changed: 60 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -83,52 +83,28 @@ function buildPolicyGetCommand(sandboxName) {
8383
return `openshell policy get --full "${sandboxName}" 2>/dev/null`;
8484
}
8585

86-
function applyPreset(sandboxName, presetName) {
87-
// Guard against truncated sandbox names — WSL can truncate hyphenated
88-
// names during argument parsing, e.g. "my-assistant" → "m"
89-
const isRfc1123Label = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(sandboxName);
90-
if (!sandboxName || sandboxName.length > 63 || !isRfc1123Label) {
91-
throw new Error(
92-
`Invalid or truncated sandbox name: '${sandboxName}'. ` +
93-
`Names must be 1-63 chars, lowercase alphanumeric, with optional internal hyphens.`
94-
);
95-
}
96-
97-
const presetContent = loadPreset(presetName);
98-
if (!presetContent) {
99-
console.error(` Cannot load preset: ${presetName}`);
100-
return false;
101-
}
102-
103-
const presetEntries = extractPresetEntries(presetContent);
104-
if (!presetEntries) {
105-
console.error(` Preset ${presetName} has no network_policies section.`);
106-
return false;
86+
/**
87+
* Merge preset entries into existing policy YAML. Handles versionless policies
88+
* by ensuring the merged result has a version header when the current policy
89+
* has content but no version field. Pure function for testing.
90+
*
91+
* @param {string} currentPolicy - Existing policy YAML (may be versionless)
92+
* @param {string} presetEntries - Indented network_policies entries from preset
93+
* @returns {string} Merged YAML with version header when missing
94+
*/
95+
function mergePresetIntoPolicy(currentPolicy, presetEntries) {
96+
if (!currentPolicy || !presetEntries) {
97+
return "version: 1\n\nnetwork_policies:\n" + (presetEntries || "");
10798
}
10899

109-
// Get current policy YAML from sandbox
110-
let rawPolicy = "";
111-
try {
112-
rawPolicy = runCapture(
113-
buildPolicyGetCommand(sandboxName),
114-
{ ignoreError: true }
115-
);
116-
} catch {}
117-
118-
let currentPolicy = parseCurrentPolicy(rawPolicy);
119-
120-
// Merge: inject preset entries under the existing network_policies key
121100
let merged;
122-
if (currentPolicy && currentPolicy.includes("network_policies:")) {
123-
// Find the network_policies: line and append the new entries after it
124-
// We need to insert before the next top-level key or end of file
101+
if (currentPolicy.includes("network_policies:")) {
125102
const lines = currentPolicy.split("\n");
126103
const result = [];
127104
let inNetworkPolicies = false;
128105
let inserted = false;
129106

130107
for (const line of lines) {
131-
// Detect top-level keys (no leading whitespace, ends with colon)
132108
const isTopLevel = /^\S.*:/.test(line);
133109

134110
if (line.trim() === "network_policies:" || line.trim().startsWith("network_policies:")) {
@@ -138,7 +114,6 @@ function applyPreset(sandboxName, presetName) {
138114
}
139115

140116
if (inNetworkPolicies && isTopLevel && !inserted) {
141-
// We hit the next top-level key — insert preset entries before it
142117
result.push(presetEntries);
143118
inserted = true;
144119
inNetworkPolicies = false;
@@ -147,25 +122,60 @@ function applyPreset(sandboxName, presetName) {
147122
result.push(line);
148123
}
149124

150-
// If network_policies was the last section, append at end
151125
if (inNetworkPolicies && !inserted) {
152126
result.push(presetEntries);
153127
}
154128

155129
merged = result.join("\n");
156-
} else if (currentPolicy) {
157-
// No network_policies section yet — append one
158-
// Ensure version field exists
159-
if (!currentPolicy.includes("version:")) {
160-
currentPolicy = "version: 1\n" + currentPolicy;
161-
}
162-
merged = currentPolicy + "\n\nnetwork_policies:\n" + presetEntries;
163130
} else {
164-
// No current policy at all
165-
merged = "version: 1\n\nnetwork_policies:\n" + presetEntries;
131+
const withVersion = currentPolicy.includes("version:")
132+
? currentPolicy
133+
: "version: 1\n" + currentPolicy;
134+
merged = withVersion + "\n\nnetwork_policies:\n" + presetEntries;
135+
}
136+
137+
if (!merged.trimStart().startsWith("version:")) {
138+
merged = "version: 1\n" + merged;
166139
}
140+
return merged;
141+
}
142+
143+
function applyPreset(sandboxName, presetName) {
144+
// Guard against truncated sandbox names — WSL can truncate hyphenated
145+
// names during argument parsing, e.g. "my-assistant" → "m"
146+
const isRfc1123Label = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(sandboxName);
147+
if (!sandboxName || sandboxName.length > 63 || !isRfc1123Label) {
148+
throw new Error(
149+
`Invalid or truncated sandbox name: '${sandboxName}'. ` +
150+
`Names must be 1-63 chars, lowercase alphanumeric, with optional internal hyphens.`
151+
);
152+
}
153+
154+
const presetContent = loadPreset(presetName);
155+
if (!presetContent) {
156+
console.error(` Cannot load preset: ${presetName}`);
157+
return false;
158+
}
159+
160+
const presetEntries = extractPresetEntries(presetContent);
161+
if (!presetEntries) {
162+
console.error(` Preset ${presetName} has no network_policies section.`);
163+
return false;
164+
}
165+
166+
let rawPolicy = "";
167+
try {
168+
rawPolicy = runCapture(
169+
buildPolicyGetCommand(sandboxName),
170+
{ ignoreError: true }
171+
);
172+
} catch {
173+
// Policy may not exist yet — treat as empty policy
174+
}
175+
176+
const currentPolicy = parseCurrentPolicy(rawPolicy);
177+
const merged = mergePresetIntoPolicy(currentPolicy, presetEntries);
167178

168-
// Write temp file and apply
169179
const tmpFile = path.join(os.tmpdir(), `nemoclaw-policy-${Date.now()}.yaml`);
170180
fs.writeFileSync(tmpFile, merged, "utf-8");
171181

@@ -177,7 +187,6 @@ function applyPreset(sandboxName, presetName) {
177187
fs.unlinkSync(tmpFile);
178188
}
179189

180-
// Update registry
181190
const sandbox = registry.getSandbox(sandboxName);
182191
if (sandbox) {
183192
const pols = sandbox.policies || [];
@@ -204,6 +213,7 @@ module.exports = {
204213
parseCurrentPolicy,
205214
buildPolicySetCommand,
206215
buildPolicyGetCommand,
216+
mergePresetIntoPolicy,
207217
applyPreset,
208218
getAppliedPresets,
209219
};

‎test/policies.test.js‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,41 @@ describe("policies", () => {
9191
});
9292
});
9393

94+
describe("mergePresetIntoPolicy", () => {
95+
const sampleEntries = " - host: example.com\n allow: true";
96+
97+
it("appends network_policies when current policy has content but no version header", () => {
98+
const versionless = "some_key:\n foo: bar";
99+
const merged = policies.mergePresetIntoPolicy(versionless, sampleEntries);
100+
assert.ok(merged.startsWith("version: 1\n"), "merged must start with version header");
101+
assert.ok(merged.includes("some_key:"), "merged must preserve existing content");
102+
assert.ok(merged.includes("network_policies:"), "merged must include network_policies section");
103+
assert.ok(merged.includes("example.com"), "merged must include preset entries");
104+
});
105+
106+
it("appends preset entries when current policy has network_policies but no version", () => {
107+
const versionlessWithNp =
108+
"network_policies:\n - host: existing.com\n allow: true";
109+
const merged = policies.mergePresetIntoPolicy(versionlessWithNp, sampleEntries);
110+
assert.ok(merged.trimStart().startsWith("version: 1\n"), "merged must have version header");
111+
assert.ok(merged.includes("existing.com"), "merged must preserve existing entries");
112+
assert.ok(merged.includes("example.com"), "merged must include new preset entries");
113+
});
114+
115+
it("keeps existing version when present", () => {
116+
const withVersion = "version: 2\n\nnetwork_policies:\n - host: old.com";
117+
const merged = policies.mergePresetIntoPolicy(withVersion, sampleEntries);
118+
assert.ok(merged.includes("version: 2"), "merged must keep existing version");
119+
assert.ok(merged.includes("example.com"), "merged must include preset entries");
120+
});
121+
122+
it("returns version + network_policies when current policy is empty", () => {
123+
const merged = policies.mergePresetIntoPolicy("", sampleEntries);
124+
assert.ok(merged.startsWith("version: 1\n\nnetwork_policies:"), "empty policy gets version and section");
125+
assert.ok(merged.includes("example.com"), "merged must include preset entries");
126+
});
127+
});
128+
94129
describe("preset YAML schema", () => {
95130
it("no preset has rules at NetworkPolicyRuleDef level", () => {
96131
// rules must be inside endpoints, not as sibling of endpoints/binaries

0 commit comments

Comments
 (0)