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