1use crate::frontmatter::Frontmatter;
4use crate::tool_names::{Capability, ParsedToolName, parse_mars_tool_name, render_scoped};
5use serde::ser::{Serialize, SerializeMap, Serializer};
6use serde_yaml::Value;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
10#[serde(rename_all = "lowercase")]
11pub enum ToolAction {
12 Allow,
13 Deny,
14 Ask,
15}
16
17impl ToolAction {
18 pub fn as_str(self) -> &'static str {
19 match self {
20 Self::Allow => "allow",
21 Self::Deny => "deny",
22 Self::Ask => "ask",
23 }
24 }
25
26 pub fn strictness(self) -> u8 {
28 match self {
29 Self::Allow => 0,
30 Self::Ask => 1,
31 Self::Deny => 2,
32 }
33 }
34
35 pub fn parse(raw: &str) -> Option<Self> {
36 match raw {
37 "allow" => Some(Self::Allow),
38 "deny" => Some(Self::Deny),
39 "ask" => Some(Self::Ask),
40 _ => None,
41 }
42 }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize)]
48#[serde(rename_all = "lowercase")]
49pub enum RuleOrigin {
50 #[default]
52 Profile,
53 Overlay,
55 Project,
57 Package,
59}
60
61impl RuleOrigin {
62 pub fn as_str(self) -> &'static str {
63 match self {
64 Self::Profile => "profile",
65 Self::Overlay => "overlay",
66 Self::Project => "project",
67 Self::Package => "package",
68 }
69 }
70}
71
72#[derive(Debug, Clone)]
79pub struct ToolRule {
80 pub capability: Capability,
81 pub pattern: Option<String>,
83 pub action: ToolAction,
84 pub origin: RuleOrigin,
85}
86
87impl PartialEq for ToolRule {
90 fn eq(&self, other: &Self) -> bool {
91 self.capability == other.capability
92 && self.pattern == other.pattern
93 && self.action == other.action
94 }
95}
96
97impl Eq for ToolRule {}
98
99impl ToolRule {
100 pub fn from_parsed(parsed: ParsedToolName, action: ToolAction) -> Self {
101 Self {
102 capability: parsed.capability,
103 pattern: parsed.pattern,
104 action,
105 origin: RuleOrigin::Profile,
106 }
107 }
108
109 pub fn from_wire(
112 capability: &str,
113 pattern: Option<&str>,
114 action: ToolAction,
115 ) -> Result<Self, crate::tool_names::ToolNameParseError> {
116 let key = match (capability, pattern) {
117 ("mcp", Some(pattern)) => format!("mcp({pattern})"),
118 _ => render_scoped(capability, pattern),
119 };
120 Ok(Self::from_parsed(parse_mars_tool_name(&key)?, action))
121 }
122
123 pub fn with_origin(mut self, origin: RuleOrigin) -> Self {
124 self.origin = origin;
125 self
126 }
127
128 pub fn is_wildcard(&self) -> bool {
129 matches!(self.capability, Capability::Any)
130 }
131
132 pub fn is_mcp(&self) -> bool {
133 matches!(self.capability, Capability::Mcp(_))
134 }
135
136 pub fn render(&self) -> String {
138 match &self.capability {
139 Capability::Mcp(mcp_ref) => mcp_ref.to_canonical(),
140 capability => render_scoped(capability.name(), self.pattern.as_deref()),
141 }
142 }
143
144 fn wire_pattern(&self) -> Option<String> {
146 match &self.capability {
147 Capability::Mcp(mcp_ref) => Some(mcp_ref.to_pattern()),
148 _ => self.pattern.clone(),
149 }
150 }
151}
152
153impl Serialize for ToolRule {
157 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
158 let mut map = serializer.serialize_map(None)?;
159 map.serialize_entry("capability", self.capability.name())?;
160 map.serialize_entry("pattern", &self.wire_pattern())?;
161 map.serialize_entry("action", self.action.as_str())?;
162 map.serialize_entry("origin", self.origin.as_str())?;
163 map.end()
164 }
165}
166
167#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize)]
169#[serde(transparent)]
170pub struct EffectiveToolPolicy {
171 pub rules: Vec<ToolRule>,
172}
173
174impl EffectiveToolPolicy {
175 pub fn with_action(&self, action: ToolAction) -> impl Iterator<Item = &ToolRule> {
176 self.rules.iter().filter(move |rule| rule.action == action)
177 }
178 pub fn describe(&self) -> Vec<String> {
179 self.rules
180 .iter()
181 .map(|rule| format!("{}:{}", rule.action.as_str(), rule.render()))
182 .collect()
183 }
184 pub fn rendered(&self, action: ToolAction) -> Vec<String> {
185 self.with_action(action)
186 .filter(|rule| !rule.is_wildcard())
187 .map(ToolRule::render)
188 .collect()
189 }
190 pub fn is_allowlist(&self) -> bool {
191 self.rules
192 .iter()
193 .any(|rule| rule.is_wildcard() && rule.action == ToolAction::Deny)
194 }
195 pub fn push_unique(&mut self, rule: ToolRule) {
200 if !self.rules.contains(&rule) {
201 self.rules.push(rule);
202 }
203 }
204}
205
206pub fn append_mcp_server_entries_to_tools(fm: &mut Frontmatter, servers: &[String]) -> bool {
208 let entries: Vec<String> = servers
209 .iter()
210 .map(|server| server.trim())
211 .filter(|server| !server.is_empty())
212 .map(|server| format!("mcp({server})"))
213 .collect();
214 if entries.is_empty() {
215 return false;
216 }
217
218 let Some(existing) = fm.get("tools").cloned() else {
219 let grants = entries
222 .into_iter()
223 .map(|entry| (Value::String(entry), Value::String("allow".into())))
224 .collect::<serde_yaml::Mapping>();
225 fm.insert("tools", Value::Mapping(grants));
226 return true;
227 };
228
229 match existing {
230 Value::Mapping(mut mapping) => {
231 let mut changed = false;
232 for entry in entries {
233 let key = Value::String(entry);
234 if !mapping.contains_key(&key) {
235 mapping.insert(key, Value::String("allow".into()));
236 changed = true;
237 }
238 }
239 if changed {
240 fm.insert("tools", Value::Mapping(mapping));
241 }
242 changed
243 }
244 other => {
245 let mut tools = tool_entries(&other);
246 let mut changed = false;
247 for entry in entries {
248 if !tools.iter().any(|existing| existing == &entry) {
249 tools.push(entry);
250 changed = true;
251 }
252 }
253 if changed {
254 fm.insert(
255 "tools",
256 Value::Sequence(tools.into_iter().map(Value::String).collect()),
257 );
258 }
259 changed
260 }
261 }
262}
263
264pub(crate) const DISALLOWED_SPELLINGS: [&str; 3] =
267 ["disallowedTools", "disallowed-tools", "disallowed_tools"];
268
269pub(crate) fn tool_entries(val: &Value) -> Vec<String> {
273 let Value::String(raw) = val else {
274 return yaml_str_list(val);
275 };
276 let mut entries = Vec::new();
277 let mut depth = 0usize;
278 let mut start = 0;
279 for (index, ch) in raw.char_indices() {
280 match ch {
281 '(' => depth += 1,
282 ')' => depth = depth.saturating_sub(1),
283 ',' | ' ' | '\t' | '\n' if depth == 0 => {
285 entries.push(&raw[start..index]);
286 start = index + 1;
287 }
288 _ => {}
289 }
290 }
291 entries.push(&raw[start..]);
292 entries
293 .into_iter()
294 .map(str::trim)
295 .filter(|entry| !entry.is_empty())
296 .map(str::to_owned)
297 .collect()
298}
299
300pub fn yaml_str_list(val: &Value) -> Vec<String> {
301 match val {
302 Value::Sequence(seq) => seq
303 .iter()
304 .filter_map(|v| v.as_str())
305 .map(str::to_owned)
306 .collect(),
307 Value::String(s) => vec![s.clone()],
308 _ => vec![],
309 }
310}
311
312type OnInvalid<'a> = &'a mut dyn FnMut(Vec<crate::diagnostic::PathSegment>, &str, &'static str);
313
314pub fn parse_tool_policy(tools: Option<&Value>, on_invalid: OnInvalid<'_>) -> EffectiveToolPolicy {
318 let mut policy = EffectiveToolPolicy::default();
319 if let Some(value) = tools {
320 for rule in parse_tools_field(value, on_invalid) {
321 policy.push_unique(rule);
322 }
323 }
324 policy
325}
326
327fn parse_tool_rule(
328 path: Vec<crate::diagnostic::PathSegment>,
329 raw: &str,
330 action: ToolAction,
331 on_invalid: OnInvalid<'_>,
332) -> Option<ToolRule> {
333 match parse_mars_tool_name(raw) {
334 Ok(parsed) => Some(ToolRule::from_parsed(parsed, action)),
335 Err(err) => {
336 on_invalid(path, raw, err.allowed());
337 None
338 }
339 }
340}
341
342fn parse_tools_field(val: &Value, on_invalid: OnInvalid<'_>) -> Vec<ToolRule> {
344 use crate::diagnostic::{PathSegment, key_path};
345 let field = key_path("tools");
346 if permission_replace_entries(val).is_some() {
347 on_invalid(
348 field.clone(),
349 &crate::ordered::plain(val),
350 "plain list or mapping of tool to allow|deny|ask; package profiles cannot replace a permission set",
351 );
352 return Vec::new();
353 }
354 match val {
355 Value::Mapping(mapping) => {
356 let mut rules = Vec::new();
357 for (key, value) in mapping {
358 let Some(tool_name) = key.as_str() else {
359 on_invalid(
360 field.clone(),
361 &crate::ordered::plain(key),
362 "string tool keys",
363 );
364 continue;
365 };
366
367 let mut entry_path = field.clone();
368 entry_path.push(PathSegment::Key(tool_name.to_owned()));
369 let Some(policy) = value.as_str() else {
370 on_invalid(entry_path, &crate::ordered::plain(value), ACTIONS_ALLOWED);
371 continue;
372 };
373 let Some(action) = ToolAction::parse(policy) else {
374 on_invalid(entry_path, policy, ACTIONS_ALLOWED);
375 continue;
376 };
377 if let Some(rule) = parse_tool_rule(entry_path, tool_name, action, on_invalid) {
378 rules.push(rule);
379 }
380 }
381 rules
382 }
383 Value::String(raw) if raw == "allow" || raw == "deny" => {
386 on_invalid(
387 field,
388 raw,
389 "list of tool names or mapping of tool to allow|deny|ask",
390 );
391 Vec::new()
392 }
393 _ => {
394 on_invalid(
395 field,
396 &crate::ordered::plain(val),
397 "mapping of tool to allow|deny|ask",
398 );
399 Vec::new()
400 }
401 }
402}
403
404fn permission_replace_entries(value: &Value) -> Option<&Value> {
405 let mapping = value.as_mapping()?;
406 (mapping.len() == 1)
407 .then(|| mapping.get(Value::String("replace".to_string())))
408 .flatten()
409}
410
411const ACTIONS_ALLOWED: &str = "allow, deny, or ask";
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 fn rule(origin: RuleOrigin) -> ToolRule {
418 ToolRule {
419 capability: Capability::Builtin("bash"),
420 pattern: Some("git push *".into()),
421 action: ToolAction::Deny,
422 origin,
423 }
424 }
425
426 #[test]
427 fn origin_is_not_part_of_identity() {
428 assert_eq!(rule(RuleOrigin::Profile), rule(RuleOrigin::Project));
429
430 let mut policy = EffectiveToolPolicy::default();
431 policy.push_unique(rule(RuleOrigin::Profile));
432 policy.push_unique(rule(RuleOrigin::Overlay));
433 assert_eq!(policy.rules.len(), 1);
434 assert_eq!(policy.rules[0].origin, RuleOrigin::Profile);
435 policy.push_unique(rule(RuleOrigin::Project));
436 assert_eq!(policy.rules.len(), 1);
437 assert_eq!(policy.rules[0].origin, RuleOrigin::Profile);
438 }
439}