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