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