From 730e4477e894cc553616af58fd3c5e3b5c280d9a Mon Sep 17 00:00:00 2001 From: Ashish Jha Date: Mon, 16 Nov 2026 15:43:57 +0530 Subject: [PATCH] fix: make policy add place rules where they take effect Rules are first-match, but policy add appended the new rule, so an earlier rule with the opposite action (allow *.npmjs.org) shadowed it and a deny for evil.npmjs.org was never reached, while the CLI reported success. - Add placeRule(), which returns the index just ahead of the first earlier rule that matches the new host with the opposite action (else the end). - policy add inserts there and says which rule it was placed before. - Say so when policy add bootstraps a policy file from the standard preset. - Reject negated patterns (!host): they match every other host. - Update policy-engine.md and cli-reference.md to describe the behaviour. Fixes #19 --- docs/cli-reference.md | 4 +- docs/policy-engine.md | 6 ++- src/commands/policy.ts | 28 +++++++++++-- src/policy/engine.ts | 24 +++++++++++ tests/policy/engine.test.ts | 81 +++++++++++++++++++++++++++++++++++++ 5 files changed, 137 insertions(+), 6 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index e300514..440b6e1 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -393,7 +393,9 @@ silo policy add [--action ] [--comment ] | `--comment ` | string | — | Optional comment for the rule | - **Idempotent** — skips if the host already exists in the policy -- **Auto-creates** the policy file if it doesn't exist +- **Takes effect** — rules are first-match, so a rule is inserted ahead of any earlier rule with the opposite action that matches the host (a `deny` for `evil.npmjs.org` goes before `allow *.npmjs.org`); otherwise it's appended +- **Rejects negated patterns** (`!host`), which would match every other host +- **Auto-creates** the policy file from the `standard` preset if it doesn't exist - **Auto-reloads** the proxy daemon via SIGHUP - **Persists** the policy file path in config if not already set diff --git a/docs/policy-engine.md b/docs/policy-engine.md index 845ec64..5d61354 100644 --- a/docs/policy-engine.md +++ b/docs/policy-engine.md @@ -192,11 +192,13 @@ silo policy add pypi.org --comment "PyPI package index" ``` **Behaviour:** -1. If no policy file exists, bootstraps one from the baseline (using the mode chosen during onboard) +1. If no policy file exists, bootstraps one from the `standard` preset (`llm.gateway` plus its allow rules) and says so 2. Checks for duplicate host patterns (skips if already present) -3. Appends the new rule to the rules list +3. Places the new rule where it takes effect. Rules are first-match, so if an earlier rule with the opposite action already matches the host, the new rule goes just ahead of it. For example, `silo policy add evil.npmjs.org --action deny` lands before `*.npmjs.org`. Otherwise the rule is appended. 4. Writes the updated policy and hot-reloads the proxy +Negated patterns such as `!evil.com` are rejected: in picomatch they match every host *except* the one named, so a single rule would decide almost all traffic. + --- ## Hot-Reload diff --git a/src/commands/policy.ts b/src/commands/policy.ts index 913d090..66c6dab 100644 --- a/src/commands/policy.ts +++ b/src/commands/policy.ts @@ -12,7 +12,7 @@ import chalk from "chalk"; import Table from "cli-table3"; import { readConfig, patchConfig } from "../config/manager.js"; -import { parsePolicyFile, evaluate } from "../policy/engine.js"; +import { parsePolicyFile, evaluate, placeRule } from "../policy/engine.js"; import { listPresets, getPreset, @@ -212,6 +212,16 @@ export function runPolicyAdd( process.exit(1); } + // picomatch treats a leading "!" as negation, so "!evil.com" matches every + // host except evil.com: as a first-match rule it would decide almost all traffic. + if (host.startsWith("!")) { + log.error(`Negated host patterns aren't supported: "${host}".`); + log.info( + `A rule for "${host}" would match every host except ${host.slice(1)}. Use a positive pattern instead.`, + ); + process.exit(1); + } + const targetPath = resolve(config.sandbox.policyFile ?? defaultPolicyPath()); let policy: ReturnType; @@ -230,6 +240,9 @@ export function runPolicyAdd( ...(standardPreset?.rules ?? []), ], }; + log.info( + `No policy file yet: creating one from the standard preset (${policy.rules.length} allow rules). Review them with ${chalk.cyan("silo policy show")}.`, + ); } // Check if host already exists @@ -239,8 +252,11 @@ export function runPolicyAdd( return; } + // Rules are first-match: insert ahead of any earlier rule that would + // otherwise decide this host the other way, or the new rule never applies. const newRule = { host, action, ...(opts.comment ? { comment: opts.comment } : {}) }; - policy.rules.push(newRule); + const { index, ahead } = placeRule(policy, newRule); + policy.rules.splice(index, 0, newRule); writePolicyFile(targetPath, policy); @@ -249,7 +265,13 @@ export function runPolicyAdd( patchConfig({ sandbox: { policyFile: targetPath } }); } - log.success(`Added rule: ${chalk.cyan(host)} → ${chalk.green(action)}`); + const shown = action === "allow" ? chalk.green(action) : chalk.red(action); + log.success(`Added rule: ${chalk.cyan(host)} → ${shown}`); + if (ahead) { + log.info( + `Placed before "${ahead.host}" (${ahead.action}), which would otherwise decide ${host} first.`, + ); + } log.info(`Policy file: ${chalk.dim(targetPath)}`); reloadProxyIfRunning(); diff --git a/src/policy/engine.ts b/src/policy/engine.ts index 331f7fc..fa39c63 100644 --- a/src/policy/engine.ts +++ b/src/policy/engine.ts @@ -171,6 +171,30 @@ export function evaluate(policy: Policy, host: string): "allow" | "deny" { return evaluateCompiled(compilePolicy(policy), host); } +/** + * Work out where a new rule must go for it to take effect. + * + * Rules are first-match, so appending a rule does nothing when an earlier rule + * with the opposite action already matches its host: `deny evil.npmjs.org` + * placed after `allow *.npmjs.org` is never reached. This returns the index of + * the first such earlier rule (the new rule goes there, just ahead of it) and + * the rule it has to precede. With no conflict, the rule is appended. + * + * The new rule's host is tested as a literal against the existing patterns, so + * `*.evil.npmjs.org` is also placed ahead of `*.npmjs.org`. + */ +export function placeRule( + policy: Policy, + rule: PolicyRule, +): { index: number; ahead?: PolicyRule } { + const index = policy.rules.findIndex( + (r) => r.action !== rule.action && picomatch(r.host, { nocase: true })(rule.host), + ); + return index === -1 + ? { index: policy.rules.length } + : { index, ahead: policy.rules[index] }; +} + // --------------------------------------------------------------------------- // Hot-reload watcher // --------------------------------------------------------------------------- diff --git a/tests/policy/engine.test.ts b/tests/policy/engine.test.ts index e80ae61..affed88 100644 --- a/tests/policy/engine.test.ts +++ b/tests/policy/engine.test.ts @@ -7,6 +7,7 @@ import { compilePolicy, evaluateCompiled, parsePolicyFile, + placeRule, } from "../../src/policy/engine.js"; import type { Policy } from "../../src/policy/engine.js"; @@ -258,3 +259,83 @@ rules: [] expect(policy.description).toBe("A test policy"); }); }); + +// --------------------------------------------------------------------------- +// placeRule: where `policy add` inserts a rule so that it takes effect +// --------------------------------------------------------------------------- + +describe("placeRule", () => { + const npmPolicy = (): Policy => ({ + version: "1", + name: "npm", + default: "deny", + rules: [ + { host: "llm.gateway", action: "allow" }, + { host: "registry.npmjs.org", action: "allow" }, + { host: "*.npmjs.org", action: "allow" }, + { host: "github.com", action: "allow" }, + ], + }); + + function add(policy: Policy, rule: Policy["rules"][number]): Policy { + const { index } = placeRule(policy, rule); + policy.rules.splice(index, 0, rule); + return policy; + } + + it("puts a deny ahead of the allow wildcard that would shadow it", () => { + const policy = npmPolicy(); + const rule = { host: "evil.npmjs.org", action: "deny" as const }; + const placed = placeRule(policy, rule); + expect(placed.index).toBe(2); + expect(placed.ahead?.host).toBe("*.npmjs.org"); + expect(evaluate(add(policy, rule), "evil.npmjs.org")).toBe("deny"); + // Other hosts under the wildcard are still allowed. + expect(evaluate(policy, "cdn.npmjs.org")).toBe("allow"); + }); + + it("appending is what used to happen, and it left the host allowed", () => { + const policy = npmPolicy(); + policy.rules.push({ host: "evil.npmjs.org", action: "deny" }); + expect(evaluate(policy, "evil.npmjs.org")).toBe("allow"); + }); + + it("places a deny wildcard ahead of a broader allow wildcard", () => { + const policy = npmPolicy(); + const rule = { host: "*.evil.npmjs.org", action: "deny" as const }; + expect(placeRule(policy, rule).ahead?.host).toBe("*.npmjs.org"); + expect(evaluate(add(policy, rule), "x.evil.npmjs.org")).toBe("deny"); + }); + + it("appends a rule that no earlier rule contradicts", () => { + const policy = npmPolicy(); + const placed = placeRule(policy, { host: "api.example.com", action: "allow" }); + expect(placed).toEqual({ index: policy.rules.length }); + }); + + it("appends when the earlier match already has the same action", () => { + const policy = npmPolicy(); + const placed = placeRule(policy, { host: "cdn.npmjs.org", action: "allow" }); + expect(placed.index).toBe(policy.rules.length); + expect(placed.ahead).toBeUndefined(); + }); + + it("matches existing patterns case-insensitively, like evaluation does", () => { + const policy = npmPolicy(); + const rule = { host: "EVIL.NPMJS.ORG", action: "deny" as const }; + expect(placeRule(policy, rule).ahead?.host).toBe("*.npmjs.org"); + expect(evaluate(add(policy, rule), "evil.npmjs.org")).toBe("deny"); + }); + + it("puts an allow ahead of a deny that would block it", () => { + const policy: Policy = { + version: "1", + name: "blocklist", + default: "allow", + rules: [{ host: "*.example.com", action: "deny" }], + }; + const rule = { host: "docs.example.com", action: "allow" as const }; + expect(placeRule(policy, rule)).toEqual({ index: 0, ahead: policy.rules[0] }); + expect(evaluate(add(policy, rule), "docs.example.com")).toBe("allow"); + }); +});