1use serde::{Deserialize, Serialize};
14
15use crate::pattern::GlobPattern;
16use crate::policy::{PolicyError, RuleGroup};
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(untagged)]
21pub enum ArgNames {
22 One(String),
24 Many(Vec<String>),
26}
27
28impl ArgNames {
29 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "lowercase")]
42pub enum Provenance {
43 Untrusted,
46}
47
48#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct Predicate {
59 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub arg: Option<ArgNames>,
63 #[serde(default, skip_serializing_if = "Vec::is_empty")]
65 pub under: Vec<String>,
66 #[serde(default, skip_serializing_if = "Vec::is_empty")]
68 pub not_under: Vec<String>,
69 #[serde(default, skip_serializing_if = "Vec::is_empty")]
71 pub host_in: Vec<String>,
72 #[serde(default, skip_serializing_if = "Vec::is_empty")]
74 pub host_not_in: Vec<String>,
75 #[serde(default, rename = "in", skip_serializing_if = "Vec::is_empty")]
78 pub is_in: Vec<String>,
79 #[serde(default, skip_serializing_if = "Vec::is_empty")]
82 pub not_in: Vec<String>,
83 #[serde(default, skip_serializing_if = "Vec::is_empty")]
85 pub matches: Vec<String>,
86 #[serde(default, skip_serializing_if = "Vec::is_empty")]
88 pub not_matches: Vec<String>,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub provenance: Option<Provenance>,
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub(crate) enum Test {
98 Under,
100 HostIn,
102 In,
104 Matches,
106 Untrusted,
108}
109
110impl Predicate {
111 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 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
153pub(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}