Skip to content

Commit fc4e389

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

2 files changed

Lines changed: 90 additions & 50 deletions

File tree

‎bin/lib/policies.js‎

Lines changed: 55 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -87,62 +87,40 @@ function buildPolicyGetCommand(sandboxName) {
8787
return `openshell policy get --full ${shellQuote(sandboxName)} 2>/dev/null`;
8888
}
8989

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

113-
// Get current policy YAML from sandbox
114-
let rawPolicy = "";
115-
try {
116-
rawPolicy = runCapture(
117-
buildPolicyGetCommand(sandboxName),
118-
{ ignoreError: true }
119-
);
120-
} catch {}
121-
122-
let currentPolicy = parseCurrentPolicy(rawPolicy);
123-
124-
// Merge: inject preset entries under the existing network_policies key
125107
let merged;
126-
if (currentPolicy && currentPolicy.includes("network_policies:")) {
127-
// Find the network_policies: line and append the new entries after it
128-
// We need to insert before the next top-level key or end of file
108+
if (/^network_policies\s*:/m.test(currentPolicy)) {
129109
const lines = currentPolicy.split("\n");
130110
const result = [];
131111
let inNetworkPolicies = false;
132112
let inserted = false;
133113

134114
for (const line of lines) {
135-
// Detect top-level keys (no leading whitespace, ends with colon)
136115
const isTopLevel = /^\S.*:/.test(line);
137116

138-
if (line.trim() === "network_policies:" || line.trim().startsWith("network_policies:")) {
117+
if (/^network_policies\s*:/.test(line)) {
139118
inNetworkPolicies = true;
140119
result.push(line);
141120
continue;
142121
}
143122

144123
if (inNetworkPolicies && isTopLevel && !inserted) {
145-
// We hit the next top-level key — insert preset entries before it
146124
result.push(presetEntries);
147125
inserted = true;
148126
inNetworkPolicies = false;
@@ -151,25 +129,52 @@ function applyPreset(sandboxName, presetName) {
151129
result.push(line);
152130
}
153131

154-
// If network_policies was the last section, append at end
155132
if (inNetworkPolicies && !inserted) {
156133
result.push(presetEntries);
157134
}
158135

159136
merged = result.join("\n");
160-
} else if (currentPolicy) {
161-
// No network_policies section yet — append one
162-
// Ensure version field exists
163-
if (!currentPolicy.includes("version:")) {
164-
currentPolicy = "version: 1\n" + currentPolicy;
165-
}
166-
merged = currentPolicy + "\n\nnetwork_policies:\n" + presetEntries;
167137
} else {
168-
// No current policy at all
169-
merged = "version: 1\n\nnetwork_policies:\n" + presetEntries;
138+
merged = currentPolicy.trimEnd() + "\n\nnetwork_policies:\n" + presetEntries;
170139
}
171140

172-
// Write temp file and apply
141+
if (!merged.trimStart().startsWith("version:")) {
142+
merged = "version: 1\n" + merged;
143+
}
144+
return merged;
145+
}
146+
147+
function applyPreset(sandboxName, presetName) {
148+
// Guard against truncated sandbox names — WSL can truncate hyphenated
149+
// names during argument parsing, e.g. "my-assistant" → "m"
150+
const isRfc1123Label = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(sandboxName);
151+
if (!sandboxName || sandboxName.length > 63 || !isRfc1123Label) {
152+
throw new Error(
153+
`Invalid or truncated sandbox name: '${sandboxName}'. ` +
154+
`Names must be 1-63 chars, lowercase alphanumeric, with optional internal hyphens.`
155+
);
156+
}
157+
158+
const presetContent = loadPreset(presetName);
159+
if (!presetContent) {
160+
console.error(` Cannot load preset: ${presetName}`);
161+
return false;
162+
}
163+
164+
const presetEntries = extractPresetEntries(presetContent);
165+
if (!presetEntries) {
166+
console.error(` Preset ${presetName} has no network_policies section.`);
167+
return false;
168+
}
169+
170+
const rawPolicy = runCapture(
171+
buildPolicyGetCommand(sandboxName),
172+
{ ignoreError: true }
173+
);
174+
175+
const currentPolicy = parseCurrentPolicy(rawPolicy);
176+
const merged = mergePresetIntoPolicy(currentPolicy, presetEntries);
177+
173178
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-"));
174179
const tmpFile = path.join(tmpDir, "policy.yaml");
175180
fs.writeFileSync(tmpFile, merged, { encoding: "utf-8", mode: 0o600 });
@@ -183,7 +188,6 @@ function applyPreset(sandboxName, presetName) {
183188
try { fs.rmdirSync(tmpDir); } catch {}
184189
}
185190

186-
// Update registry
187191
const sandbox = registry.getSandbox(sandboxName);
188192
if (sandbox) {
189193
const pols = sandbox.policies || [];
@@ -210,6 +214,7 @@ module.exports = {
210214
parseCurrentPolicy,
211215
buildPolicySetCommand,
212216
buildPolicyGetCommand,
217+
mergePresetIntoPolicy,
213218
applyPreset,
214219
getAppliedPresets,
215220
};

‎test/policies.test.js‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,41 @@ describe("policies", () => {
9494
});
9595
});
9696

97+
describe("mergePresetIntoPolicy", () => {
98+
const sampleEntries = " - host: example.com\n allow: true";
99+
100+
it("appends network_policies when current policy has content but no version header", () => {
101+
const versionless = "some_key:\n foo: bar";
102+
const merged = policies.mergePresetIntoPolicy(versionless, sampleEntries);
103+
expect(merged.startsWith("version: 1\n")).toBe(true);
104+
expect(merged).toContain("some_key:");
105+
expect(merged).toContain("network_policies:");
106+
expect(merged).toContain("example.com");
107+
});
108+
109+
it("appends preset entries when current policy has network_policies but no version", () => {
110+
const versionlessWithNp =
111+
"network_policies:\n - host: existing.com\n allow: true";
112+
const merged = policies.mergePresetIntoPolicy(versionlessWithNp, sampleEntries);
113+
expect(merged.trimStart().startsWith("version: 1\n")).toBe(true);
114+
expect(merged).toContain("existing.com");
115+
expect(merged).toContain("example.com");
116+
});
117+
118+
it("keeps existing version when present", () => {
119+
const withVersion = "version: 2\n\nnetwork_policies:\n - host: old.com";
120+
const merged = policies.mergePresetIntoPolicy(withVersion, sampleEntries);
121+
expect(merged).toContain("version: 2");
122+
expect(merged).toContain("example.com");
123+
});
124+
125+
it("returns version + network_policies when current policy is empty", () => {
126+
const merged = policies.mergePresetIntoPolicy("", sampleEntries);
127+
expect(merged.startsWith("version: 1\n\nnetwork_policies:")).toBe(true);
128+
expect(merged).toContain("example.com");
129+
});
130+
});
131+
97132
describe("preset YAML schema", () => {
98133
it("no preset has rules at NetworkPolicyRuleDef level", () => {
99134
// rules must be inside endpoints, not as sibling of endpoints/binaries

0 commit comments

Comments
 (0)