// The policy: which tool calls run, which ask the owner first, and which never run. // // The model proposes; the policy decides. Rules come from config (`policy.rules`) plus the // owner's "always allow" answers (stored in /policy-overrides.json). // // How a decision is made: // 1. If any matching rule says "deny", the answer is deny. Nothing overrides a deny. // 2. If the owner approved this exact program call with "always", the answer is allow. // 3. Otherwise the MOST SPECIFIC matching rule wins ("git status **" beats "git **"); // on a tie, the stricter decision wins (ask beats allow). // 4. A program argument that points outside the workspace (an absolute path, "~", or "..", // also as the value of "--flag=value") or that tells the program to write a file // ("--output", "-o") raises allow to ask. // 5. If nothing matches, the default decision applies (ask, in the example config). // // Command patterns are matched token by token against the argument vector: // "git log **" "git" then "log", then anything (including nothing) // "git * main" "git", any one token, then "main" import { readFile } from 'node:fs/promises'; import path from 'node:path'; import type { PolicyRule } from '../config/config.ts'; import { Mutex, writeFileAtomic } from '../runtime/atomic.ts'; export type Decision = 'allow' | 'ask' | 'deny'; export interface PolicyDecision { decision: Decision; reason: string; } export interface Override { tool: string; argv: string[]; } const STRICTNESS: Record = { allow: 0, ask: 1, deny: 2 }; /** Returns how specific the match is, or -1 when the pattern does not match. */ export function matchCommand(pattern: string, argv: readonly string[]): number { const tokens = pattern.trim().split(/\s+/); let literal = 0; for (let i = 0; i < tokens.length; i++) { const token = tokens[i]!; if (token === '**') { if (i !== tokens.length - 1) throw new Error(`"**" must be last in pattern "${pattern}"`); return literal; } const arg = argv[i]; if (arg === undefined) return -1; if (token === '*') continue; if (token !== arg) return -1; literal++; } // No trailing "**": the argument count must match exactly. Exact patterns rank a bit higher. return argv.length === tokens.length ? literal + 0.5 : -1; } export function pointsOutside(arg: string): boolean { // Also check the value of "--flag=value" and of a short flag with the value attached ("-C.."). const flagValue = /^--?[\w-]+=(.*)$/s.exec(arg) ?? /^-[A-Za-z](.+)$/s.exec(arg); const candidates = flagValue ? [arg, flagValue[1]!] : [arg]; return candidates.some( (value) => value.startsWith('/') || value.startsWith('~') || value.split(/[\\/]/).includes('..'), ); } /** Flags that make common programs write to a file the policy rule did not name. */ export function writesFile(arg: string): boolean { return /^(--output(-directory)?|--out-file)(=.*)?$/s.test(arg) || /^-o(.*)$/s.test(arg); } export class Policy { private readonly rules: readonly PolicyRule[]; private readonly defaultDecision: Decision; private overrides: Override[]; constructor(rules: readonly PolicyRule[], defaultDecision: Decision, overrides: Override[] = []) { this.rules = rules; this.defaultDecision = defaultDecision; this.overrides = overrides; } decide(tool: string, argv?: readonly string[]): PolicyDecision { const matches: { rule: PolicyRule; specificity: number }[] = []; for (const rule of this.rules) { if (rule.tool !== tool) continue; if (rule.command === undefined) { matches.push({ rule, specificity: 0 }); } else if (argv) { const specificity = matchCommand(rule.command, argv); if (specificity >= 0) matches.push({ rule, specificity }); } } const deny = matches.find((m) => m.rule.decision === 'deny'); if (deny) return { decision: 'deny', reason: `denied by rule ${describe(deny.rule)}` }; if (argv && this.overrides.some((o) => o.tool === tool && sameArgv(o.argv, argv))) { return { decision: 'allow', reason: 'the owner approved this exact command with "always"' }; } let result: PolicyDecision; if (matches.length === 0) { result = { decision: this.defaultDecision, reason: 'no rule matched; default decision' }; } else { matches.sort( (a, b) => b.specificity - a.specificity || STRICTNESS[b.rule.decision] - STRICTNESS[a.rule.decision], ); const best = matches[0]!.rule; result = { decision: best.decision, reason: `rule ${describe(best)}` }; } if (result.decision === 'allow' && argv?.slice(1).some(pointsOutside)) { return { decision: 'ask', reason: 'an argument points outside the workspace' }; } if (result.decision === 'allow' && argv?.slice(1).some(writesFile)) { return { decision: 'ask', reason: 'an argument tells the program to write a file' }; } return result; } addOverride(override: Override): void { if (!this.overrides.some((o) => o.tool === override.tool && sameArgv(o.argv, override.argv))) { this.overrides = [...this.overrides, override]; } } listOverrides(): readonly Override[] { return this.overrides; } } function describe(rule: PolicyRule): string { return rule.command ? `${rule.tool} "${rule.command}" -> ${rule.decision}` : `${rule.tool} -> ${rule.decision}`; } function sameArgv(a: readonly string[], b: readonly string[]): boolean { return a.length === b.length && a.every((value, i) => value === b[i]); } /** The owner's "always allow" answers, kept between runs. */ export class OverrideStore { readonly file: string; private readonly lock = new Mutex(); constructor(dataDir: string) { this.file = path.join(dataDir, 'policy-overrides.json'); } async load(): Promise { try { const parsed = JSON.parse(await readFile(this.file, 'utf8')) as { overrides?: Override[] }; return parsed.overrides ?? []; } catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []; throw err; } } async save(overrides: readonly Override[]): Promise { const content = JSON.stringify({ overrides }, null, 2) + '\n'; await this.lock.run(() => writeFileAtomic(this.file, content)); } }