Skip to main content

trusty_code/permissions/
config.rs

1//! Schema, parser, and validation for an agent's `permissions:` frontmatter
2//! block (#7948).
3//!
4//! Why: the TUI permission prompt (#3422) needs a declarative rule set to
5//! prompt from, and opencode's `permission` config (see the harness
6//! compatibility study) is the reference shape: tool globs mapped to
7//! `allow`/`ask`/`deny`, optionally discriminated by an argument glob. This
8//! module owns what an operator may write and what is rejected outright.
9//! What: `RuleDecision`, `PermissionMap` (compiled tool-glob rules, each a
10//! single decision or a table of argument globs), `PermissionConfigError`,
11//! and `parse_permissions` — the one entry point, which lifts the
12//! `permissions:` block out of an agent document's frontmatter and compiles it.
13//!
14//! FAIL-CLOSED: a malformed block is an error that fails the agent load. It is
15//! never degraded to "no permissions", because an empty map allows every tool.
16//! Test: `permissions::tests::config_tests` — the whole module.
17
18use globset::{Glob, GlobMatcher};
19use serde::{Deserialize, Serialize};
20
21/// The three decisions a permission rule can carry.
22///
23/// Why: mirrors opencode's `allow | ask | deny` vocabulary verbatim so an
24/// operator's existing config reads the same here.
25/// What: `Allow` dispatches; `Deny` refuses without dispatching; `Ask`
26/// suspends the call until a client answers (see `crate::permissions::gate`).
27/// `rank` orders them for the tie-break — at equal specificity the SAFEST
28/// decision wins.
29/// Test: `decision_parses_the_three_words`, `decision_rank_orders_deny_over_ask_over_allow`.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(rename_all = "snake_case")]
32pub enum RuleDecision {
33    Allow,
34    Ask,
35    Deny,
36}
37
38impl RuleDecision {
39    /// Parse one decision word exactly as written (lowercase, no aliases).
40    ///
41    /// Why: a typo like `allowed` or `ALLOW` must be rejected, not coerced —
42    /// guessing at intent is how a `deny` silently becomes an `allow`.
43    /// Test: `decision_parses_the_three_words`, `unknown_decision_word_is_rejected`.
44    pub fn parse(word: &str) -> Option<Self> {
45        match word {
46            "allow" => Some(Self::Allow),
47            "ask" => Some(Self::Ask),
48            "deny" => Some(Self::Deny),
49            _ => None,
50        }
51    }
52
53    /// The wire/display word for this decision.
54    /// Test: `decision_parses_the_three_words`.
55    pub fn as_str(self) -> &'static str {
56        match self {
57            Self::Allow => "allow",
58            Self::Ask => "ask",
59            Self::Deny => "deny",
60        }
61    }
62
63    /// Tie-break rank — higher is safer, and wins at equal specificity.
64    /// Test: `decision_rank_orders_deny_over_ask_over_allow`.
65    pub fn rank(self) -> u8 {
66        match self {
67            Self::Allow => 0,
68            Self::Ask => 1,
69            Self::Deny => 2,
70        }
71    }
72}
73
74/// One compiled glob plus the bookkeeping the precedence rule needs.
75///
76/// Why: `literal_prefix_len` is computed once at parse time because the
77/// "longest literal prefix wins" comparison runs on every tool call, and the
78/// `pattern` text is kept because a refusal reports it back ("denied by policy
79/// (`bash[rm *]`)") — a compiled `GlobMatcher` cannot be printed.
80/// What: `*` deliberately spans `/` (globset's default) so `rm *` matches
81/// `rm -rf /tmp/x`.
82/// Test: `literal_prefix_stops_at_the_first_metacharacter`.
83#[derive(Debug, Clone)]
84pub struct CompiledGlob {
85    pattern: String,
86    matcher: GlobMatcher,
87    literal_prefix_len: usize,
88}
89
90impl CompiledGlob {
91    /// Compile `pattern`, or report why it is not a usable glob.
92    ///
93    /// `pub` because `crate::permissions::session` also compiles the pattern a
94    /// client attaches to an `allow_for_session` grant.
95    /// Test: `bad_glob_is_rejected`.
96    pub fn compile(pattern: &str) -> Result<Self, String> {
97        let glob = Glob::new(pattern).map_err(|e| e.to_string())?;
98        Ok(Self {
99            pattern: pattern.to_string(),
100            matcher: glob.compile_matcher(),
101            literal_prefix_len: literal_prefix_len(pattern),
102        })
103    }
104
105    /// The pattern text as the operator wrote it.
106    pub fn pattern(&self) -> &str {
107        &self.pattern
108    }
109
110    /// Whether `candidate` matches this glob.
111    pub fn is_match(&self, candidate: &str) -> bool {
112        self.matcher.is_match(candidate)
113    }
114
115    /// How many leading characters of the pattern are literal.
116    pub fn literal_prefix_len(&self) -> usize {
117        self.literal_prefix_len
118    }
119}
120
121/// Count the leading characters of `pattern` before its first glob
122/// metacharacter (`*`, `?`, `[`, `{`); a pattern with none scores its length.
123///
124/// Why: the specificity tie-break — `git status*` (10) beats `git *` (4) beats
125/// `*` (0), which makes a catch-all `"*": ask` safe beside narrow allows.
126/// Test: `literal_prefix_stops_at_the_first_metacharacter`.
127fn literal_prefix_len(pattern: &str) -> usize {
128    pattern
129        .chars()
130        .take_while(|c| !matches!(c, '*' | '?' | '[' | '{'))
131        .count()
132}
133
134/// What a tool-glob key maps to.
135///
136/// Why: `read_file: allow` (the whole tool) and `bash: { "rm *": deny }` (one
137/// tool, discriminated by its subject) need different precedence tiers — see
138/// `crate::permissions::matcher`.
139/// What: `Tool` is one decision for every call of the matching tools; `Args`
140/// is a set of subject globs, each with its own decision. An `Args` body that
141/// matches no subject contributes nothing.
142/// Test: `tool_level_string_and_arg_level_table_both_parse`.
143#[derive(Debug, Clone)]
144pub enum RuleBody {
145    Tool(RuleDecision),
146    Args(Vec<ArgRule>),
147}
148
149/// One argument-glob rule inside a tool's table.
150#[derive(Debug, Clone)]
151pub struct ArgRule {
152    pub glob: CompiledGlob,
153    pub decision: RuleDecision,
154}
155
156/// One `<tool-glob>: <body>` entry.
157#[derive(Debug, Clone)]
158pub struct ToolRule {
159    pub glob: CompiledGlob,
160    pub body: RuleBody,
161}
162
163/// An agent's compiled permission map.
164///
165/// Why: the runtime artifact `crate::permissions::gate` consults before every
166/// dispatch, compiled once at agent-load time so the hot path only matches.
167/// What: entries in declaration order; order does NOT decide precedence (see
168/// `crate::permissions::matcher`). An empty map (`permissions:` with nothing
169/// under it) matches nothing, which is `allow` — the pre-#7948 behaviour.
170/// Test: `permissions::tests::config_tests`, `permissions::tests::matcher_tests`.
171#[derive(Debug, Clone, Default)]
172pub struct PermissionMap {
173    pub(crate) rules: Vec<ToolRule>,
174}
175
176impl PermissionMap {
177    /// How many tool-glob entries this map carries.
178    /// Test: `tool_level_string_and_arg_level_table_both_parse`.
179    pub fn len(&self) -> usize {
180        self.rules.len()
181    }
182
183    /// Whether this map carries no entries at all.
184    /// Test: `empty_mapping_parses_to_an_empty_map`.
185    pub fn is_empty(&self) -> bool {
186        self.rules.is_empty()
187    }
188}
189
190/// Every way a `permissions:` block is rejected (#7948 fail-closed contract).
191///
192/// Why: each variant names the file and the key, so an operator can find the
193/// defect among thirty roster agents.
194/// What: `source_label` is the agent file path (or embedded agent name).
195/// Test: `unknown_decision_word_is_rejected`, `bad_glob_is_rejected`,
196/// `non_string_non_table_value_is_rejected`, `malformed_yaml_is_rejected`,
197/// `scalar_permissions_value_is_rejected`.
198#[derive(Debug, thiserror::Error)]
199pub enum PermissionConfigError {
200    #[error(
201        "{source_label}: `permissions:` must be a mapping of tool globs to decisions, got {found}"
202    )]
203    NotAMapping {
204        source_label: String,
205        found: &'static str,
206    },
207    #[error(
208        "{source_label}: `permissions: {key}` has unknown decision `{value}` — expected one of allow, ask, deny"
209    )]
210    UnknownDecision {
211        source_label: String,
212        key: String,
213        value: String,
214    },
215    #[error("{source_label}: `permissions: {key}` is not a valid glob pattern: {reason}")]
216    BadGlob {
217        source_label: String,
218        key: String,
219        reason: String,
220    },
221    #[error(
222        "{source_label}: `permissions: {key}` must be a decision string or a table of argument globs, got {found}"
223    )]
224    BadValue {
225        source_label: String,
226        key: String,
227        found: &'static str,
228    },
229    #[error("{source_label}: `permissions:` block is not valid YAML: {reason}")]
230    Yaml {
231        source_label: String,
232        reason: String,
233    },
234}
235
236/// Parse the `permissions:` block out of one agent document, if it has one.
237///
238/// Why: the single entry point every fallible agent-loading path calls. It
239/// takes the whole document because `trusty_agents_common`'s frontmatter
240/// reader is flat and line-oriented, so the nested block must be lifted out
241/// and handed to a real YAML parser here.
242/// What: `Ok(None)` when the document has no `permissions:` key. Otherwise
243/// extracts the block's own text, YAML-parses only that (the surrounding
244/// frontmatter need not be valid YAML), and compiles every rule. Any defect is
245/// a `PermissionConfigError`, never an empty map.
246/// Test: `absent_key_parses_to_none`, `example_block_from_the_spec_parses`,
247/// `malformed_yaml_is_rejected`, `frontmatter_that_is_not_yaml_still_parses_permissions`.
248pub fn parse_permissions(
249    source_label: &str,
250    document: &str,
251) -> Result<Option<PermissionMap>, PermissionConfigError> {
252    let Some(block) = extract_permissions_block(document) else {
253        return Ok(None);
254    };
255    let value: serde_yaml::Value =
256        serde_yaml::from_str(&block).map_err(|e| PermissionConfigError::Yaml {
257            source_label: source_label.to_string(),
258            reason: e.to_string(),
259        })?;
260    // A bare `permissions:` line parses to null: the operator wrote an empty map.
261    let body = value
262        .get("permissions")
263        .cloned()
264        .unwrap_or(serde_yaml::Value::Null);
265    compile_map(source_label, &body).map(Some)
266}
267
268/// Lift the `permissions:` key and everything indented under it out of a
269/// document's frontmatter block.
270///
271/// Why: a composed agent's frontmatter is not guaranteed to be valid YAML
272/// (values are emitted unquoted), so parsing the whole block would fail agents
273/// that declare no permissions at all.
274/// What: returns the block re-indented to column 0, including its own
275/// `permissions:` line, or `None` when there is no frontmatter or no such key.
276/// Ends at the first non-blank line indented at or below the key, or at `---`.
277/// Test: `frontmatter_that_is_not_yaml_still_parses_permissions`,
278/// `block_stops_at_the_next_frontmatter_key`.
279fn extract_permissions_block(document: &str) -> Option<String> {
280    let mut lines = document.lines();
281    match lines.next() {
282        Some(first) if first.trim() == "---" => {}
283        _ => return None,
284    }
285
286    let mut collected: Vec<String> = Vec::new();
287    let mut key_indent = 0usize;
288    for line in lines {
289        if line.trim() == "---" {
290            break;
291        }
292        let indent = line.len() - line.trim_start().len();
293        if collected.is_empty() {
294            let rest = line.trim_start();
295            if rest.starts_with("permissions:") {
296                key_indent = indent;
297                collected.push(rest.to_string());
298            }
299            continue;
300        }
301        if line.trim().is_empty() {
302            collected.push(String::new());
303            continue;
304        }
305        if indent <= key_indent {
306            break;
307        }
308        collected.push(line[key_indent..].to_string());
309    }
310
311    (!collected.is_empty()).then(|| collected.join("\n"))
312}
313
314/// Compile one YAML value into a `PermissionMap`: null is an empty map, a
315/// mapping compiles entry by entry, anything else is `NotAMapping`.
316/// Test: `empty_mapping_parses_to_an_empty_map`, `scalar_permissions_value_is_rejected`.
317fn compile_map(
318    source_label: &str,
319    body: &serde_yaml::Value,
320) -> Result<PermissionMap, PermissionConfigError> {
321    let mapping = match body {
322        serde_yaml::Value::Null => return Ok(PermissionMap::default()),
323        serde_yaml::Value::Mapping(m) => m,
324        other => {
325            return Err(PermissionConfigError::NotAMapping {
326                source_label: source_label.to_string(),
327                found: yaml_kind(other),
328            });
329        }
330    };
331
332    let mut rules = Vec::with_capacity(mapping.len());
333    for (key, value) in mapping {
334        let key = scalar_key(key).ok_or_else(|| PermissionConfigError::BadValue {
335            source_label: source_label.to_string(),
336            key: "<non-scalar key>".to_string(),
337            found: yaml_kind(key),
338        })?;
339        let glob = compile_glob(source_label, &key, &key)?;
340        let body = compile_body(source_label, &key, value)?;
341        rules.push(ToolRule { glob, body });
342    }
343    Ok(PermissionMap { rules })
344}
345
346/// Compile one tool-glob key's value into a `RuleBody`.
347/// Test: `tool_level_string_and_arg_level_table_both_parse`,
348/// `non_string_non_table_value_is_rejected`.
349fn compile_body(
350    source_label: &str,
351    key: &str,
352    value: &serde_yaml::Value,
353) -> Result<RuleBody, PermissionConfigError> {
354    let bad_value = |key: String, found: &'static str| PermissionConfigError::BadValue {
355        source_label: source_label.to_string(),
356        key,
357        found,
358    };
359    match value {
360        serde_yaml::Value::String(word) => {
361            Ok(RuleBody::Tool(decision_word(source_label, key, word)?))
362        }
363        serde_yaml::Value::Mapping(args) => {
364            let mut compiled = Vec::with_capacity(args.len());
365            for (arg_key, arg_value) in args {
366                let arg_pattern = scalar_key(arg_key)
367                    .ok_or_else(|| bad_value(key.to_string(), yaml_kind(arg_key)))?;
368                let label = format!("{key}: {arg_pattern}");
369                let word = arg_value
370                    .as_str()
371                    .ok_or_else(|| bad_value(label.clone(), yaml_kind(arg_value)))?;
372                compiled.push(ArgRule {
373                    glob: compile_glob(source_label, &label, &arg_pattern)?,
374                    decision: decision_word(source_label, &label, word)?,
375                });
376            }
377            Ok(RuleBody::Args(compiled))
378        }
379        other => Err(bad_value(key.to_string(), yaml_kind(other))),
380    }
381}
382
383/// Parse a decision word or report it against `key`.
384fn decision_word(
385    source_label: &str,
386    key: &str,
387    word: &str,
388) -> Result<RuleDecision, PermissionConfigError> {
389    RuleDecision::parse(word).ok_or_else(|| PermissionConfigError::UnknownDecision {
390        source_label: source_label.to_string(),
391        key: key.to_string(),
392        value: word.to_string(),
393    })
394}
395
396/// Compile a glob or report it against `key`.
397fn compile_glob(
398    source_label: &str,
399    key: &str,
400    pattern: &str,
401) -> Result<CompiledGlob, PermissionConfigError> {
402    CompiledGlob::compile(pattern).map_err(|reason| PermissionConfigError::BadGlob {
403        source_label: source_label.to_string(),
404        key: key.to_string(),
405        reason,
406    })
407}
408
409/// Render a scalar YAML key as a string; a sequence or mapping key is `None`.
410fn scalar_key(value: &serde_yaml::Value) -> Option<String> {
411    match value {
412        serde_yaml::Value::String(s) => Some(s.clone()),
413        serde_yaml::Value::Bool(b) => Some(b.to_string()),
414        serde_yaml::Value::Number(n) => Some(n.to_string()),
415        _ => None,
416    }
417}
418
419/// A one-word name for a YAML value's shape, for error messages.
420fn yaml_kind(value: &serde_yaml::Value) -> &'static str {
421    match value {
422        serde_yaml::Value::Null => "null",
423        serde_yaml::Value::Bool(_) => "a boolean",
424        serde_yaml::Value::Number(_) => "a number",
425        serde_yaml::Value::String(_) => "a string",
426        serde_yaml::Value::Sequence(_) => "a list",
427        serde_yaml::Value::Mapping(_) => "a table",
428        serde_yaml::Value::Tagged(_) => "a tagged value",
429    }
430}