Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,9 @@ silo policy add <host> [--action <allow|deny>] [--comment <text>]
| `--comment <text>` | 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

Expand Down
6 changes: 4 additions & 2 deletions docs/policy-engine.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 25 additions & 3 deletions src/commands/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<typeof parsePolicyFile>;

Expand All @@ -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
Expand All @@ -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);

Expand All @@ -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();
Expand Down
24 changes: 24 additions & 0 deletions src/policy/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
// ---------------------------------------------------------------------------
Expand Down
81 changes: 81 additions & 0 deletions tests/policy/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
compilePolicy,
evaluateCompiled,
parsePolicyFile,
placeRule,
} from "../../src/policy/engine.js";
import type { Policy } from "../../src/policy/engine.js";

Expand Down Expand Up @@ -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");
});
});
Loading