trusty_code/permissions/matcher.rs
1//! Glob matching, subject extraction, and precedence for a compiled
2//! `PermissionMap` (#7948).
3//!
4//! Why: a permission map is written as an unordered YAML table, so "which rule
5//! applies" cannot be "the first one that matches" — an operator writing
6//! `bash: { "git status*": allow, "*": ask }` expects the narrow rule to win
7//! regardless of key order. This module owns the total order that makes that
8//! mechanical.
9//! What: `PermissionMap::evaluate` (one subject), `PermissionMap::evaluate_call`
10//! (every subject of one call), and `subjects_for`. Precedence, highest first:
11//! 1. an argument-level rule beats a tool-level rule;
12//! 2. at the same level, the longest LITERAL PREFIX wins;
13//! 3. at equal specificity, `deny` > `ask` > `allow`.
14//!
15//! A call that matches no rule returns `None`, which every caller reads as
16//! `allow` — the pre-#7948 behaviour.
17//!
18//! A `bash` rule matches the command TEXT, never the program that ends up
19//! running: `sh -c 'rm x'`, `/bin/rm x`, and `true; rm x` all miss a `rm *`
20//! deny. Treat a bash rule as a guard against an accident, not against an
21//! adversary — an agent that wants to get around it can.
22//! Test: `permissions::tests::matcher_tests` — the whole module.
23
24use std::path::Path;
25
26use serde_json::Value;
27
28use super::config::{PermissionMap, RuleBody, RuleDecision};
29
30/// The rule that decided one call, and what it decided.
31///
32/// What: `rule` is the pattern as written, in `tool` form for a tool-level
33/// rule and `tool[arg]` form for an argument-level one.
34/// Test: `arg_level_rule_beats_tool_level_rule`, `rule_text_names_the_arg_pattern`.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct RuleMatch {
37 pub decision: RuleDecision,
38 pub rule: String,
39}
40
41/// `(level, literal-prefix, decision rank)` — every field ordered "higher wins".
42type Specificity = (u8, usize, u8);
43
44impl PermissionMap {
45 /// Decide `tool` with at most one `subject`, or `None` when no rule matches.
46 ///
47 /// Why: the single precedence implementation; `evaluate_call` and every
48 /// test go through it.
49 /// What: collects tool-level candidates and argument-level candidates whose
50 /// subject glob matches, and keeps the maximum `Specificity`. An `Args`
51 /// body contributes nothing when `subject` is `None` or no glob matches.
52 /// Test: `arg_level_rule_beats_tool_level_rule`,
53 /// `longest_literal_prefix_wins_among_arg_rules`,
54 /// `deny_beats_ask_beats_allow_at_equal_specificity`,
55 /// `unmatched_tool_has_no_rule`,
56 /// `arg_table_with_no_matching_subject_contributes_nothing`.
57 pub fn evaluate(&self, tool: &str, subject: Option<&str>) -> Option<RuleMatch> {
58 let mut best: Option<(Specificity, RuleMatch)> = None;
59 for rule in self.rules.iter().filter(|r| r.glob.is_match(tool)) {
60 match &rule.body {
61 RuleBody::Tool(decision) => consider(
62 &mut best,
63 (0, rule.glob.literal_prefix_len(), decision.rank()),
64 *decision,
65 rule.glob.pattern().to_string(),
66 ),
67 RuleBody::Args(args) => {
68 let Some(subject) = subject else { continue };
69 for arg in args.iter().filter(|a| a.glob.is_match(subject)) {
70 consider(
71 &mut best,
72 (1, arg.glob.literal_prefix_len(), arg.decision.rank()),
73 arg.decision,
74 format!("{}[{}]", rule.glob.pattern(), arg.glob.pattern()),
75 );
76 }
77 }
78 }
79 }
80 best.map(|(_, m)| m)
81 }
82
83 /// Decide one call that may carry several subjects.
84 ///
85 /// Why (#7948): `write_files` writes many paths in one call. Evaluating
86 /// only one of them would let a `write_files: { "src/**": allow, "*": deny }`
87 /// map pass a denied path hidden behind an allowed one.
88 /// What: no subjects evaluates once with `None`. Otherwise each subject is
89 /// evaluated on its own and the SAFEST result wins (`deny` > `ask` >
90 /// `allow`); a subject no rule matches counts as `allow`.
91 /// Test: `write_files_is_decided_by_its_most_restrictive_path`.
92 pub fn evaluate_call(&self, tool: &str, subjects: &[String]) -> Option<RuleMatch> {
93 if subjects.is_empty() {
94 return self.evaluate(tool, None);
95 }
96 subjects
97 .iter()
98 .filter_map(|s| self.evaluate(tool, Some(s)))
99 .max_by_key(|m| m.decision.rank())
100 }
101}
102
103/// Keep the candidate when it is strictly more specific than `best`.
104///
105/// Why: strictly-greater keeps the result independent of iteration order — two
106/// candidates tying on all three axes carry the same decision.
107fn consider(
108 best: &mut Option<(Specificity, RuleMatch)>,
109 spec: Specificity,
110 decision: RuleDecision,
111 rule: String,
112) {
113 if best.as_ref().is_none_or(|(current, _)| spec > *current) {
114 *best = Some((spec, RuleMatch { decision, rule }));
115 }
116}
117
118/// The argument(s) a tool call is discriminated by.
119///
120/// Why: a map says "bash may run `git status*`", not "bash may receive this
121/// JSON object", so rules match against the string that names what the tool
122/// acts on. Probing by argument NAME rather than a tool-name table keeps a
123/// renamed or new file tool covered instead of silently dropping it to
124/// tool-level matching.
125/// What: MCP tools (`mcp__<server>__<tool>`) have no subject — their argument
126/// shape belongs to a third-party server. A `files` array (`write_files`)
127/// yields every entry's string `path`. Otherwise the first string among
128/// `command` (bash), `path` (file tools), and `pattern` (glob/grep).
129///
130/// Every PATH subject (a `files[].path` or a `path`) yields its raw form and,
131/// when different, its [`normalise_path_subject`] form. `evaluate_call` takes
132/// the most restrictive decision across subjects, so `./secrets/x` meets the
133/// same `secrets/**` deny as `secrets/x`, and a rewrite never loosens the raw
134/// form's decision.
135/// Test: `subject_for_bash_is_the_command`, `subject_for_read_file_is_the_path`,
136/// `subject_for_grep_is_the_pattern`, `mcp_tools_have_no_subject`,
137/// `subjects_for_write_files_are_every_path`,
138/// `subject_is_none_when_no_known_argument_is_present`,
139/// `path_deny_holds_for_every_lexical_spelling`.
140pub fn subjects_for(tool: &str, args: &Value) -> Vec<String> {
141 subjects_for_in_root(tool, args, None)
142}
143
144/// [`subjects_for`] with the run's working root supplied.
145///
146/// Why (#7948): `tools::fs::scoped_path` accepts an ABSOLUTE path that resolves
147/// inside the working root (`scoped_path_accepts_absolute_inside_dir`), so the
148/// same file has two spellings the model may pick between. An operator writes a
149/// path rule relative — `secrets/**` — and a purely lexical subject keeps
150/// `/<root>/secrets/token` absolute, so the deny never matched it.
151/// What: on top of every form [`subjects_for`] yields, a path subject that
152/// normalises to an absolute path UNDER `root` also yields its root-relative
153/// spelling. `evaluate_call` folds every subject to the safest decision, so the
154/// extra form can only add restriction. `root` of `None` is exactly
155/// [`subjects_for`].
156/// Test: `absolute_in_root_path_also_yields_its_root_relative_form`,
157/// `path_deny_holds_for_the_absolute_in_root_spelling`,
158/// `absolute_path_outside_the_root_yields_no_relative_form`.
159pub fn subjects_for_in_root(tool: &str, args: &Value, root: Option<&Path>) -> Vec<String> {
160 if tool.starts_with("mcp__") {
161 return Vec::new();
162 }
163 let mut subjects = Vec::new();
164 if let Some(files) = args.get("files").and_then(Value::as_array) {
165 for path in files
166 .iter()
167 .filter_map(|f| f.get("path").and_then(Value::as_str))
168 {
169 push_path_forms(&mut subjects, path, root);
170 }
171 return subjects;
172 }
173 if let Some(command) = args.get("command").and_then(Value::as_str) {
174 subjects.push(command.to_string());
175 } else if let Some(path) = args.get("path").and_then(Value::as_str) {
176 push_path_forms(&mut subjects, path, root);
177 } else if let Some(pattern) = args.get("pattern").and_then(Value::as_str) {
178 subjects.push(pattern.to_string());
179 }
180 subjects
181}
182
183/// Push `raw`, its normalised form when that differs, and its root-relative
184/// form when it names a file under `root`.
185// #7948: every form is decided, so a rewrite can only add restriction.
186fn push_path_forms(subjects: &mut Vec<String>, raw: &str, root: Option<&Path>) {
187 subjects.push(raw.to_string());
188 let normalised = normalise_path_subject(raw);
189 if normalised != raw {
190 subjects.push(normalised.clone());
191 }
192 if let Some(relative) = root.and_then(|root| root_relative_subject(&normalised, root)) {
193 subjects.push(relative);
194 }
195}
196
197/// The root-relative spelling of an absolute path subject under `root`, or
198/// `None` when either side is relative or the subject is outside the root.
199///
200/// Why (#7948): see [`subjects_for_in_root`].
201/// What: pure string work, comparing the [`normalise_path_subject`] form of
202/// both sides at a path-SEGMENT boundary — `/a/bc/x` is not under `/a/b`. The
203/// root itself yields `None`; a rule names a file, not the tree's own entry.
204///
205/// Known limit (#7948): lexical only, matching this module's other path work —
206/// a root reached through a symlink (macOS `/var` → `/private/var`) is not
207/// recognised in its other spelling. `scoped_path` still confines the call.
208/// Test: `absolute_in_root_path_also_yields_its_root_relative_form`,
209/// `absolute_path_outside_the_root_yields_no_relative_form`.
210fn root_relative_subject(normalised: &str, root: &Path) -> Option<String> {
211 if !normalised.starts_with('/') {
212 return None;
213 }
214 let root = normalise_path_subject(root.to_string_lossy().as_ref());
215 if !root.starts_with('/') {
216 return None;
217 }
218 let relative = normalised
219 .strip_prefix(root.trim_end_matches('/'))?
220 .strip_prefix('/')?;
221 (!relative.is_empty()).then(|| relative.to_string())
222}
223
224/// Lexically normalise a path subject: drop `.` segments and empty segments
225/// from repeated `/`, fold `name/..`, and strip a trailing `/`.
226///
227/// Why (#7948): rules glob-match the path the model wrote, while
228/// `tools::fs::scoped_path` resolves it only later. Without this,
229/// `secrets/**: deny` blocks `secrets/x` but not `./secrets/x`,
230/// `secrets/./x`, `a/../secrets/x`, or `secrets//x`.
231/// What: pure string work with no filesystem I/O. A relative `..` with nothing
232/// left to fold is KEPT (`a/../../x` becomes `../x`), so a path that climbs
233/// above the root never normalises into an in-tree path; an absolute path's
234/// `..` at `/` stays at `/`. An empty relative result is `.`. The caller still
235/// decides the raw form too, so normalisation never widens a decision.
236///
237/// Known limits (#7948): no case-folding, so `Secrets/x` misses a `secrets/**`
238/// rule on a case-insensitive filesystem; no symlink resolution, so a symlink
239/// into a denied tree, or a `link/..` fold that differs from the physical
240/// path, is not caught here. `scoped_path` still confines the call to the tree.
241/// Test: `normalise_path_subject_folds_lexical_spellings`,
242/// `path_deny_holds_for_every_lexical_spelling`,
243/// `path_climbing_above_the_root_is_never_more_permissive`.
244pub fn normalise_path_subject(raw: &str) -> String {
245 let absolute = raw.starts_with('/');
246 let mut parts: Vec<&str> = Vec::new();
247 for segment in raw.split('/') {
248 match segment {
249 "" | "." => {}
250 ".." => match parts.last() {
251 Some(&last) if last != ".." => {
252 parts.pop();
253 }
254 _ if absolute => {}
255 _ => parts.push(".."),
256 },
257 name => parts.push(name),
258 }
259 }
260 let joined = parts.join("/");
261 if absolute {
262 format!("/{joined}")
263 } else if joined.is_empty() {
264 ".".to_string()
265 } else {
266 joined
267 }
268}