Skip to main content

openmoat_core/
predicate.rs

1//! Argument conditions on a rule group (`when:`, ADR-113, docs/POLICY.md §2.4):
2//! typed tests of what a tool call's arguments hold, in the manner of Progent's
3//! tool-call privilege policies. A group with conditions matches a call only
4//! when one of its patterns matches the call and every condition holds, so a
5//! condition can only narrow the group it is on. Conditions are allowed on
6//! `deny` and `review` groups alone: they never make a call allowed, and an OS
7//! layer, which cannot read arguments, applies such a group to every access its
8//! patterns name (`ir::lower`), which is narrower still.
9//!
10//! The engine evaluates them in `engine/arguments.rs`; this module is the
11//! policy file's model and its checks.
12
13use serde::{Deserialize, Serialize};
14
15use crate::pattern::GlobPattern;
16use crate::policy::{PolicyError, RuleGroup};
17
18/// The argument names a condition reads: one, several, or `*` for every value.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(untagged)]
21pub enum ArgNames {
22    /// One name (`to`), or `*`.
23    One(String),
24    /// Several names (`[to, cc, bcc]`).
25    Many(Vec<String>),
26}
27
28impl ArgNames {
29    /// The names, in the order written.
30    #[must_use]
31    pub fn names(&self) -> Vec<&str> {
32        match self {
33            Self::One(name) => vec![name.as_str()],
34            Self::Many(names) => names.iter().map(String::as_str).collect(),
35        }
36    }
37}
38
39/// What a value an untrusted output gave counts as (`provenance:`).
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "lowercase")]
42pub enum Provenance {
43    /// A host or path in the value came from output the session read that
44    /// someone else may have written (ADR-057).
45    Untrusted,
46}
47
48/// One condition: `arg` (optional) and exactly one test.
49///
50/// A positive test (`under`, `host_in`, `in`, `matches`, `provenance`) holds
51/// when **some** value passes it. A negated one (`not_under`, `host_not_in`,
52/// `not_in`, `not_matches`) holds unless the call has values and **every**
53/// one passes the positive test: a call that names no such value, or more
54/// values than are read, is not shown to stay inside, so the condition holds
55/// (fail closed).
56#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct Predicate {
59    /// Which arguments the test reads, by name (snake case, or a dotted path
60    /// `message.to`); absent, the test's own default (§2.4).
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub arg: Option<ArgNames>,
63    /// Holds when a path is one of these or below one (globs, `~`, `${project}`).
64    #[serde(default, skip_serializing_if = "Vec::is_empty")]
65    pub under: Vec<String>,
66    /// Holds when a path is outside all of these, or the call names none.
67    #[serde(default, skip_serializing_if = "Vec::is_empty")]
68    pub not_under: Vec<String>,
69    /// Holds when a URL's host matches one of these host globs.
70    #[serde(default, skip_serializing_if = "Vec::is_empty")]
71    pub host_in: Vec<String>,
72    /// Holds when a URL's host matches none of these, or the call names none.
73    #[serde(default, skip_serializing_if = "Vec::is_empty")]
74    pub host_not_in: Vec<String>,
75    /// Holds when a value (each address of a recipient list) matches one of
76    /// these globs, ignoring case.
77    #[serde(default, rename = "in", skip_serializing_if = "Vec::is_empty")]
78    pub is_in: Vec<String>,
79    /// Holds when a value (each address of a recipient list) matches none of
80    /// these, or the call has none.
81    #[serde(default, skip_serializing_if = "Vec::is_empty")]
82    pub not_in: Vec<String>,
83    /// Holds when a whole value matches one of these globs.
84    #[serde(default, skip_serializing_if = "Vec::is_empty")]
85    pub matches: Vec<String>,
86    /// Holds when a value matches none of these globs, or the call has none.
87    #[serde(default, skip_serializing_if = "Vec::is_empty")]
88    pub not_matches: Vec<String>,
89    /// `untrusted`: holds when a host or path in a value came from untrusted
90    /// output the session read.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub provenance: Option<Provenance>,
93}
94
95/// The kind of test a [`Predicate`] makes.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub(crate) enum Test {
98    /// `under`, `not_under`.
99    Under,
100    /// `host_in`, `host_not_in`.
101    HostIn,
102    /// `in`, `not_in`.
103    In,
104    /// `matches`, `not_matches`.
105    Matches,
106    /// `provenance: untrusted`.
107    Untrusted,
108}
109
110impl Predicate {
111    /// Its one test, whether it is negated, and the patterns it lists; `None`
112    /// when it sets no test or more than one.
113    pub(crate) fn test(&self) -> Option<(Test, bool, &[String])> {
114        let lists: [(Test, bool, &[String]); 8] = [
115            (Test::Under, false, &self.under),
116            (Test::Under, true, &self.not_under),
117            (Test::HostIn, false, &self.host_in),
118            (Test::HostIn, true, &self.host_not_in),
119            (Test::In, false, &self.is_in),
120            (Test::In, true, &self.not_in),
121            (Test::Matches, false, &self.matches),
122            (Test::Matches, true, &self.not_matches),
123        ];
124        let mut set = lists.into_iter().filter(|(_, _, list)| !list.is_empty());
125        let first = set.next();
126        let provenance = self.provenance.map(|_| (Test::Untrusted, false, &[][..]));
127        match (first, set.next(), provenance) {
128            (Some(one), None, None) | (None, None, Some(one)) => Some(one),
129            _ => None,
130        }
131    }
132
133    /// The condition as the reason names it (`not_in [*@example.com]`).
134    pub(crate) fn describe(&self) -> String {
135        let Some((test, negated, list)) = self.test() else {
136            return String::new();
137        };
138        let name = match (test, negated) {
139            (Test::Under, false) => "under",
140            (Test::Under, true) => "not_under",
141            (Test::HostIn, false) => "host_in",
142            (Test::HostIn, true) => "host_not_in",
143            (Test::In, false) => "in",
144            (Test::In, true) => "not_in",
145            (Test::Matches, false) => "matches",
146            (Test::Matches, true) => "not_matches",
147            (Test::Untrusted, _) => return "provenance untrusted".to_owned(),
148        };
149        format!("{name} [{}]", list.join(", "))
150    }
151}
152
153/// Each group's conditions: only on `deny` and `review` groups (`allowed`),
154/// each with exactly one test, plain argument names and patterns that compile.
155pub(crate) fn check(group: &RuleGroup, allowed: bool) -> Result<(), PolicyError> {
156    if group.when.is_empty() {
157        return Ok(());
158    }
159    let problem = |problem: String| PolicyError::Rule {
160        rule: group.id.clone(),
161        problem,
162    };
163    if !allowed {
164        return Err(problem(
165            "`when` conditions narrow a `deny` or `review` rule only; an `allow` or `defer` \
166             rule with conditions could let a call through on what its arguments claim"
167                .to_owned(),
168        ));
169    }
170    for predicate in &group.when {
171        let Some((_, _, list)) = predicate.test() else {
172            return Err(problem(
173                "each `when` condition names exactly one test (`under`, `not_under`, `host_in`, \
174                 `host_not_in`, `in`, `not_in`, `matches`, `not_matches` or `provenance`) with \
175                 a non-empty list"
176                    .to_owned(),
177            ));
178        };
179        for name in predicate.arg.iter().flat_map(ArgNames::names) {
180            if !is_arg_name(name) {
181                return Err(problem(format!(
182                    "`{name}` is not an argument name (letters, digits, `_`, `-` and `.` \
183                     between names, or `*` alone)"
184                )));
185            }
186        }
187        for pattern in list {
188            if pattern.trim_start().starts_with('!') {
189                return Err(problem(format!(
190                    "`{pattern}` is an exclusion; a condition's list names what it tests for"
191                )));
192            }
193            GlobPattern::compile(pattern, false).map_err(|e| problem(e.to_string()))?;
194        }
195    }
196    Ok(())
197}
198
199fn is_arg_name(name: &str) -> bool {
200    name == "*"
201        || (!name.is_empty()
202            && name.split('.').all(|part| {
203                !part.is_empty()
204                    && part
205                        .chars()
206                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
207            }))
208}
209
210#[cfg(test)]
211mod tests {
212    use crate::policy::{Policy, PolicyError};
213
214    fn parse(group: &str, list: &str) -> Result<Policy, PolicyError> {
215        Policy::parse(&format!(
216            "version: 1\n{list}:\n  - id: g\n    mcp: ['mcp__mail__send_email']\n    when:\n{group}"
217        ))
218    }
219
220    #[test]
221    fn conditions_need_one_test_and_a_deny_or_review_group() {
222        let ok = "      - { arg: [to, cc], not_in: ['*@example.com'] }\n      - { provenance: untrusted }\n";
223        assert_eq!(parse(ok, "deny").unwrap().deny[0].when.len(), 2);
224        assert!(parse(ok, "review").is_ok());
225        for list in ["allow", "defer"] {
226            assert!(
227                matches!(parse(ok, list), Err(PolicyError::Rule { rule, .. }) if rule == "g"),
228                "{list} must refuse conditions"
229            );
230        }
231        for bad in [
232            "      - { arg: to }\n",
233            "      - { in: ['a'], not_in: ['b'] }\n",
234            "      - { in: ['a'], provenance: untrusted }\n",
235            "      - { arg: 'to cc', in: ['a'] }\n",
236            "      - { in: ['!a'] }\n",
237            "      - { in: ['[a'] }\n",
238            "      - { in: [] }\n",
239        ] {
240            assert!(parse(bad, "deny").is_err(), "{bad} must be refused");
241        }
242        assert!(parse("      - { bogus: ['a'] }\n", "deny").is_err());
243    }
244}