Skip to main content

vtcode_config/core/
permissions.rs

1use crate::constants::tools;
2use crate::env_helpers::default_enabled;
3use anyhow::{Result, bail};
4use serde::Deserializer;
5use serde::de::{MapAccess, Visitor};
6use serde::{Deserialize, Serialize};
7use std::fmt;
8use vtcode_commons::VtCodePaths;
9
10#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
11#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
12#[serde(rename_all = "snake_case")]
13pub enum PermissionDefault {
14    Ask,
15    Allow,
16    Auto,
17    Deny,
18}
19
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
22pub struct AgentPermissionsConfig {
23    /// Default permission for unmatched tool calls.
24    /// Options: `"ask"`, `"allow"`, `"auto"`, `"deny"`.
25    pub default: PermissionDefault,
26
27    /// Rules that allow matching tool calls without prompting.
28    ///
29    /// Recommended semantic rules: `"read"`, `"write"`, `"edit"`, `"bash"`.
30    /// Tool-name rules like `"read_file"` are normalized to semantic rules
31    /// automatically. Supports path specifiers: `"read(/src/**/*.rs)"`.
32    #[serde(default)]
33    pub allow: Vec<String>,
34
35    /// Rules that require an interactive prompt when they match.
36    /// Same syntax as [`Self::allow`].
37    #[serde(default)]
38    pub ask: Vec<String>,
39
40    /// Rules that auto-approve with classifier-backed review.
41    /// Same syntax as [`Self::allow`].
42    #[serde(default)]
43    pub auto: Vec<String>,
44
45    /// Rules that deny matching tool calls.
46    /// Same syntax as [`Self::allow`].
47    #[serde(default)]
48    pub deny: Vec<String>,
49}
50
51impl AgentPermissionsConfig {
52    #[must_use]
53    pub fn new(default: PermissionDefault) -> Self {
54        Self {
55            default,
56            allow: Vec::new(),
57            ask: Vec::new(),
58            auto: Vec::new(),
59            deny: Vec::new(),
60        }
61    }
62
63    /// Reject rules that would silently auto-approve computer use.
64    ///
65    /// # Errors
66    ///
67    /// Returns an error when the allow list names the computer-use tool:
68    /// its approval stays per-turn by design.
69    pub fn validate(&self) -> Result<()> {
70        reject_computer_use_allow(&self.allow, "agent allow rules")
71    }
72}
73
74/// Reject allow rules matching the computer-use tool exactly as the rule
75/// compiler normalizes them, so no spelling smuggles it past validation.
76fn reject_computer_use_allow(rules: &[String], owner: &str) -> Result<()> {
77    if rules.iter().any(|rule| normalize_permission_rule(rule) == tools::COMPUTER_USE) {
78        bail!("{owner} must not allowlist '{}': computer-use approval is always per-turn", tools::COMPUTER_USE);
79    }
80    Ok(())
81}
82
83// ---------------------------------------------------------------------------
84// Permission rule normalization
85// ---------------------------------------------------------------------------
86
87/// Semantic permission categories that tool names normalize into.
88///
89/// Semantic rules operate on `PermissionRequestKind` rather than exact tool
90/// names, so they work across current and internal helper routes. Keeping the
91/// closed set typed means the rule check and the normalizer cannot drift on
92/// their five spellings.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94enum SemanticRule {
95    Read,
96    Write,
97    Edit,
98    Bash,
99    WebFetch,
100}
101
102impl SemanticRule {
103    const ALL: [Self; 5] = [Self::Read, Self::Write, Self::Edit, Self::Bash, Self::WebFetch];
104
105    const fn as_str(self) -> &'static str {
106        match self {
107            Self::Read => "read",
108            Self::Write => "write",
109            Self::Edit => "edit",
110            Self::Bash => "bash",
111            Self::WebFetch => "webfetch",
112        }
113    }
114
115    fn parse(value: &str) -> Option<Self> {
116        Self::ALL.into_iter().find(|rule| rule.as_str() == value)
117    }
118
119    /// Map a lowercased tool name (or one of its config aliases) to its
120    /// semantic category. Unknown names stay `None` so they become ExactTool.
121    fn from_tool_name(tool_name: &str) -> Option<Self> {
122        match tool_name {
123            tools::READ_FILE
124            | "read"
125            | tools::GREP_FILE
126            | tools::GREP
127            | tools::LIST_FILES
128            | tools::LIST
129            | "glob"
130            | "listfiles"
131            | "grepfile"
132            | tools::CODE_SEARCH
133            | "codesearch" => Some(Self::Read),
134            tools::WRITE_FILE
135            | "write"
136            | tools::CREATE_FILE
137            | "createfile"
138            | tools::DELETE_FILE
139            | "deletefile"
140            | tools::MOVE_FILE
141            | "movefile"
142            | tools::COPY_FILE
143            | "copyfile" => Some(Self::Write),
144            tools::EDIT_FILE
145            | "edit"
146            | tools::APPLY_PATCH
147            | "applypatch"
148            | tools::SEARCH_REPLACE
149            | "searchreplace"
150            | tools::FILE_OP
151            | "fileop"
152            | "patch" => Some(Self::Edit),
153            "bash"
154            | tools::SHELL
155            | "command"
156            | tools::EXEC_COMMAND
157            | "execcommand"
158            | tools::RUN_PTY_CMD
159            | "runptycmd"
160            | tools::EXECUTE_CODE
161            | "executecode" => Some(Self::Bash),
162            "webfetch" | tools::WEB_FETCH | tools::FETCH => Some(Self::WebFetch),
163            _ => None,
164        }
165    }
166}
167
168/// Check whether a rule string is already a recognized semantic rule.
169fn is_semantic_rule(rule: &str) -> bool {
170    SemanticRule::parse(&rule.to_ascii_lowercase()).is_some()
171}
172
173/// Normalize a tool-name permission rule to its semantic category.
174///
175/// Raw helper names like `"read_file"` are mapped to semantic rules so they
176/// correctly match the underlying operation.
177fn normalize_tool_name_to_semantic(tool_name: &str) -> String {
178    let tool_name = tool_name.to_ascii_lowercase();
179    SemanticRule::from_tool_name(&tool_name).map_or(tool_name, |rule| rule.as_str().to_string())
180}
181
182/// Parse a rule string into its tool name and optional path specifier.
183///
184/// For example, `"read_file(/src/**/*.rs)"` returns `Some(("read_file", "/src/**/*.rs"))`.
185/// A rule without parentheses returns `None`.
186fn parse_tool_specifier_parts(rule: &str) -> Option<(&str, &str)> {
187    let trimmed = rule.trim();
188    if let Some(open) = trimmed.find('(') {
189        let tool_part = trimmed[..open].trim();
190        let specifier = trimmed[open + 1..].strip_suffix(')').map(str::trim)?;
191        if !tool_part.is_empty() && !specifier.is_empty() {
192            return Some((tool_part, specifier));
193        }
194    }
195    None
196}
197
198/// Normalize a permission rule string to its semantic form.
199///
200/// This transforms raw tool-name rules into semantic rules before compilation.
201/// For example:
202/// - `"read_file"` → `"read"`
203/// - `"read_file(/src/**/*.rs)"` → `"read(/src/**/*.rs)"`
204/// - `"mcp__server__tool"` → unchanged (MCP rules pass through)
205/// - `"read"` → unchanged (already semantic)
206#[must_use]
207pub fn normalize_permission_rule(raw: &str) -> String {
208    let trimmed = raw.trim();
209
210    // Already a semantic rule - normalize to lowercase and pass through
211    if is_semantic_rule(trimmed) {
212        return trimmed.to_ascii_lowercase();
213    }
214
215    // Already an MCP rule - pass through
216    if trimmed.starts_with("mcp__") {
217        return trimmed.to_string();
218    }
219
220    // Has path specifier - normalize the tool name part
221    if let Some((tool_part, specifier)) = parse_tool_specifier_parts(trimmed) {
222        let normalized_tool = normalize_tool_name_to_semantic(tool_part);
223        return format!("{normalized_tool}({specifier})");
224    }
225
226    // Raw tool name - normalize to semantic
227    normalize_tool_name_to_semantic(trimmed)
228}
229
230/// Permission system configuration - Controls command resolution, audit logging, and caching
231#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
232#[derive(Debug, Clone, Deserialize, Serialize)]
233pub struct PermissionsConfig {
234    /// Classifier-backed auto permission review policy and environment settings.
235    #[serde(
236        default,
237        rename = "auto",
238        alias = "auto_permission",
239        deserialize_with = "deserialize_auto_permission_config"
240    )]
241    pub auto_permission: AutoPermissionConfig,
242
243    /// Rules that allow matching tool calls without prompting.
244    #[serde(default)]
245    pub allow: Vec<String>,
246
247    /// Rules that require an interactive prompt when they match.
248    #[serde(default)]
249    pub ask: Vec<String>,
250
251    /// Rules that deny matching tool calls.
252    #[serde(default)]
253    pub deny: Vec<String>,
254
255    /// Enable the enhanced permission system (resolver + audit logger + cache)
256    #[serde(default = "default_enabled")]
257    pub enabled: bool,
258
259    /// Enable command resolution to actual paths (helps identify suspicious commands)
260    #[serde(default = "default_resolve_commands")]
261    pub resolve_commands: bool,
262
263    /// Enable audit logging of all permission decisions
264    #[serde(default = "default_audit_enabled")]
265    pub audit_enabled: bool,
266
267    /// Directory for audit logs (created if not exists)
268    /// Defaults to the VT Code state directory's `audit` subdirectory.
269    #[serde(default = "default_audit_directory")]
270    pub audit_directory: String,
271
272    /// Log allowed commands to audit trail
273    #[serde(default = "default_log_allowed_commands")]
274    pub log_allowed_commands: bool,
275
276    /// Log denied commands to audit trail
277    #[serde(default = "default_log_denied_commands")]
278    pub log_denied_commands: bool,
279
280    /// Log permission prompts (when user is asked for confirmation)
281    #[serde(default = "default_log_permission_prompts")]
282    pub log_permission_prompts: bool,
283
284    /// Enable permission decision caching to avoid redundant evaluations
285    #[serde(default = "default_cache_enabled")]
286    pub cache_enabled: bool,
287
288    /// Cache time-to-live in seconds (how long to cache decisions)
289    /// Default: 300 seconds (5 minutes)
290    #[serde(default = "default_cache_ttl_seconds")]
291    pub cache_ttl_seconds: u64,
292}
293
294impl PermissionsConfig {
295    /// Reject rules that would silently auto-approve computer use.
296    ///
297    /// # Errors
298    ///
299    /// Returns an error when the allow list names the computer-use tool:
300    /// its approval stays per-turn by design.
301    pub fn validate(&self) -> Result<()> {
302        reject_computer_use_allow(&self.allow, "permissions.allow")
303    }
304}
305
306/// Classifier-backed auto permission review configuration.
307#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
308#[derive(Debug, Clone, Deserialize, Serialize)]
309pub struct AutoPermissionConfig {
310    /// Optional model override for the transcript reviewer.
311    #[serde(default)]
312    pub model: String,
313
314    /// Optional model override for the prompt-injection probe.
315    #[serde(default)]
316    pub probe_model: String,
317
318    /// Experimental OpenAI Decisions tool-output probe. Direct OpenAI API-key
319    /// TUI or full-auto sessions at the standard endpoint only; billed to your OpenAI API account.
320    /// Inconclusive requests fall back to the generation probe within its deadline.
321    /// Manual approvals and tool permissions remain unchanged; no full-auto acknowledgement is needed in TUI.
322    #[serde(default)]
323    pub use_decisions_probe: bool,
324
325    /// Maximum consecutive denials before auto permission review falls back.
326    #[serde(default = "default_auto_permission_max_consecutive_denials")]
327    pub max_consecutive_denials: u32,
328
329    /// Maximum total denials before auto permission review falls back.
330    #[serde(default = "default_auto_permission_max_total_denials")]
331    pub max_total_denials: u32,
332
333    /// Drop broad code-execution allow rules while auto permission review is active.
334    #[serde(default = "default_auto_permission_drop_broad_allow_rules")]
335    pub drop_broad_allow_rules: bool,
336
337    /// Classifier block rules applied in stage 2 reasoning.
338    #[serde(default = "default_auto_permission_block_rules")]
339    pub block_rules: Vec<String>,
340
341    /// Narrow allow exceptions applied after block rules.
342    #[serde(default = "default_auto_permission_allow_exceptions")]
343    pub allow_exceptions: Vec<String>,
344
345    /// Trusted environment boundaries for the classifier.
346    #[serde(default)]
347    pub environment: AutoPermissionEnvironmentConfig,
348}
349
350fn deserialize_auto_permission_config<'de, D>(deserializer: D) -> Result<AutoPermissionConfig, D::Error>
351where
352    D: Deserializer<'de>,
353{
354    struct AutoPermissionConfigVisitor;
355
356    impl<'de> Visitor<'de> for AutoPermissionConfigVisitor {
357        type Value = AutoPermissionConfig;
358
359        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
360            formatter.write_str("a table of auto permission settings")
361        }
362
363        fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
364        where
365            M: MapAccess<'de>,
366        {
367            AutoPermissionConfig::deserialize(serde::de::value::MapAccessDeserializer::new(map))
368        }
369    }
370
371    deserializer.deserialize_map(AutoPermissionConfigVisitor)
372}
373
374/// Trust-boundary configuration for auto permission review.
375#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
376#[derive(Debug, Clone, Default, Deserialize, Serialize)]
377pub struct AutoPermissionEnvironmentConfig {
378    #[serde(default)]
379    pub trusted_paths: Vec<String>,
380
381    #[serde(default)]
382    pub trusted_domains: Vec<String>,
383
384    #[serde(default)]
385    pub trusted_git_hosts: Vec<String>,
386
387    #[serde(default)]
388    pub trusted_git_orgs: Vec<String>,
389
390    #[serde(default)]
391    pub trusted_services: Vec<String>,
392}
393
394impl Default for AutoPermissionConfig {
395    fn default() -> Self {
396        Self {
397            model: String::new(),
398            probe_model: String::new(),
399            use_decisions_probe: false,
400            max_consecutive_denials: default_auto_permission_max_consecutive_denials(),
401            max_total_denials: default_auto_permission_max_total_denials(),
402            drop_broad_allow_rules: default_auto_permission_drop_broad_allow_rules(),
403            block_rules: default_auto_permission_block_rules(),
404            allow_exceptions: default_auto_permission_allow_exceptions(),
405            environment: AutoPermissionEnvironmentConfig::default(),
406        }
407    }
408}
409
410#[inline]
411const fn default_resolve_commands() -> bool {
412    default_enabled()
413}
414
415#[inline]
416const fn default_audit_enabled() -> bool {
417    default_enabled()
418}
419
420#[inline]
421fn default_audit_directory() -> String {
422    VtCodePaths::resolve()
423        .and_then(|paths| paths.state_path("audit"))
424        .map(|path| path.display().to_string())
425        .unwrap_or_else(|_| String::from("state/vtcode/audit"))
426}
427
428#[inline]
429const fn default_log_allowed_commands() -> bool {
430    true
431}
432
433#[inline]
434const fn default_log_denied_commands() -> bool {
435    true
436}
437
438#[inline]
439const fn default_log_permission_prompts() -> bool {
440    true
441}
442
443#[inline]
444const fn default_cache_enabled() -> bool {
445    true
446}
447
448#[inline]
449const fn default_cache_ttl_seconds() -> u64 {
450    300 // 5 minutes
451}
452
453#[inline]
454const fn default_auto_permission_max_consecutive_denials() -> u32 {
455    3
456}
457
458#[inline]
459const fn default_auto_permission_max_total_denials() -> u32 {
460    20
461}
462
463#[inline]
464const fn default_auto_permission_drop_broad_allow_rules() -> bool {
465    true
466}
467
468fn default_auto_permission_block_rules() -> Vec<String> {
469    vec![
470        "Block destructive source-control actions such as force-pushes, direct pushes to protected branches, or remote branch deletion unless the user explicitly authorized that exact blast radius.".to_string(),
471        "Block remote code download-and-execute flows, including curl-or-wget pipes into interpreters or shells, and running code from freshly cloned external repositories.".to_string(),
472        "Block sending workspace contents, credentials, environment variables, or other sensitive data to external endpoints unless the user explicitly named both the destination and the data.".to_string(),
473        "Block credential hunting, secret discovery, or scanning config and environment stores for alternative tokens unless the user explicitly asked for that credential workflow.".to_string(),
474        "Block commands that bypass safety checks, disable verification, install persistence, or weaken the host security posture.".to_string(),
475        "Block destructive or production/shared-infrastructure actions unless the user explicitly authorized the target and the action.".to_string(),
476        "Block destructive actions against inferred, fuzzy-matched, or agent-selected targets when the user did not name the exact target.".to_string(),
477    ]
478}
479
480fn default_auto_permission_allow_exceptions() -> Vec<String> {
481    vec![
482        "Allow read-only tools and read-only browsing/search actions.".to_string(),
483        "Allow file edits and writes inside the current workspace when the path is not protected.".to_string(),
484        "Allow pushes only to the current session branch or configured git remotes inside the trusted environment."
485            .to_string(),
486    ]
487}
488
489impl Default for PermissionsConfig {
490    fn default() -> Self {
491        Self {
492            auto_permission: AutoPermissionConfig::default(),
493            allow: Vec::new(),
494            ask: Vec::new(),
495            deny: Vec::new(),
496            enabled: default_enabled(),
497            resolve_commands: default_resolve_commands(),
498            audit_enabled: default_audit_enabled(),
499            audit_directory: default_audit_directory(),
500            log_allowed_commands: default_log_allowed_commands(),
501            log_denied_commands: default_log_denied_commands(),
502            log_permission_prompts: default_log_permission_prompts(),
503            cache_enabled: default_cache_enabled(),
504            cache_ttl_seconds: default_cache_ttl_seconds(),
505        }
506    }
507}
508
509#[cfg(test)]
510mod tests {
511    use super::{AgentPermissionsConfig, PermissionDefault, PermissionsConfig};
512
513    #[test]
514    fn computer_use_cannot_join_allow_lists() {
515        for spelling in ["computer_use", " Computer_Use ", "COMPUTER_USE"] {
516            let global: PermissionsConfig =
517                toml::from_str(&format!(r#"allow = ["{spelling}"]"#)).expect("global permissions");
518            let error = global.validate().unwrap_err();
519            assert!(error.to_string().contains("per-turn"), "{spelling}: {error:#}");
520
521            let agent: AgentPermissionsConfig =
522                toml::from_str(&format!("default = \"ask\"\nallow = [\"{spelling}\"]")).expect("agent permissions");
523            agent.validate().unwrap_err();
524        }
525        let clean: PermissionsConfig =
526            toml::from_str("allow = [\"read\"]\nask = [\"computer_use\"]\ndeny = [\"computer_use\"]")
527                .expect("clean permissions");
528        clean.validate().expect("ask/deny lists may name computer use");
529    }
530
531    #[test]
532    fn parses_agent_permission_defaults_and_empty_buckets() {
533        for (value, expected) in [
534            ("ask", PermissionDefault::Ask),
535            ("allow", PermissionDefault::Allow),
536            ("auto", PermissionDefault::Auto),
537            ("deny", PermissionDefault::Deny),
538        ] {
539            let config: AgentPermissionsConfig =
540                toml::from_str(&format!(r#"default = "{value}""#)).expect("agent permissions");
541            assert_eq!(config.default, expected);
542            assert!(config.allow.is_empty());
543            assert!(config.ask.is_empty());
544            assert!(config.auto.is_empty());
545            assert!(config.deny.is_empty());
546        }
547
548        let err = toml::from_str::<AgentPermissionsConfig>(r#"default = "plan""#).unwrap_err();
549        assert!(err.to_string().contains("unknown variant"));
550    }
551
552    #[test]
553    fn parses_exact_tool_rules() {
554        let config: PermissionsConfig = toml::from_str(
555            r#"
556            allow = ["read_file", "code_search"]
557            deny = ["exec_command"]
558            "#,
559        )
560        .expect("permissions config");
561
562        assert_eq!(config.allow, vec!["read_file".to_string(), "code_search".to_string()]);
563        assert_eq!(config.deny, vec!["exec_command".to_string()]);
564    }
565
566    #[test]
567    fn normalizes_code_search_rules_to_read_semantics() {
568        assert_eq!(super::normalize_permission_rule("code_search"), "read");
569        assert_eq!(super::normalize_permission_rule("code_search(/src/**)"), "read(/src/**)");
570    }
571
572    #[test]
573    fn ignores_unknown_fields_for_forward_compatibility() {
574        // Unknown fields are silently ignored so that a config written by a newer
575        // vtcode version does not break older binaries.
576        let removed_field = format!("default_{}", "mode");
577        let input = format!(
578            r#"
579            {removed_field} = "ask"
580            "#,
581        );
582        let config: PermissionsConfig = toml::from_str(&input).unwrap();
583        // The unknown field is ignored; defaults are used.
584        assert!(config.allow.is_empty());
585
586        // "auto" as a string value for the top-level field is still rejected
587        // because the struct field expects AutoPermissionConfig, not a list.
588        let err = toml::from_str::<PermissionsConfig>(
589            r#"
590            auto = ["exec_command"]
591            "#,
592        )
593        .unwrap_err();
594        assert!(err.to_string().contains("invalid type"));
595    }
596
597    #[test]
598    fn parses_auto_permission_settings_from_canonical_auto_table() {
599        let config: PermissionsConfig = toml::from_str(
600            r#"
601            [auto]
602            model = "gpt-5-mini"
603            use_decisions_probe = true
604            max_consecutive_denials = 2
605            drop_broad_allow_rules = false
606
607            [auto.environment]
608            trusted_paths = ["/work/project"]
609            trusted_domains = ["example.com"]
610            "#,
611        )
612        .expect("permissions config");
613
614        assert_eq!(config.auto_permission.model, "gpt-5-mini");
615        assert!(config.auto_permission.use_decisions_probe);
616        let serialized = toml::to_string(&config).expect("serialize permissions");
617        assert!(serialized.contains("[auto]"));
618        assert!(serialized.contains("use_decisions_probe = true"));
619        let roundtrip: PermissionsConfig = toml::from_str(&serialized).expect("roundtrip permissions");
620        assert!(roundtrip.auto_permission.use_decisions_probe);
621        assert_eq!(config.auto_permission.max_consecutive_denials, 2);
622        assert!(!config.auto_permission.drop_broad_allow_rules);
623        assert_eq!(config.auto_permission.environment.trusted_paths, vec!["/work/project".to_string()]);
624        assert_eq!(config.auto_permission.environment.trusted_domains, vec!["example.com".to_string()]);
625    }
626
627    #[test]
628    fn auto_permission_defaults_are_conservative() {
629        let config = PermissionsConfig::default();
630        assert!(!config.auto_permission.use_decisions_probe);
631
632        assert_eq!(config.auto_permission.max_consecutive_denials, 3);
633        assert_eq!(config.auto_permission.max_total_denials, 20);
634        assert!(config.auto_permission.drop_broad_allow_rules);
635        assert!(!config.auto_permission.block_rules.is_empty());
636        assert!(!config.auto_permission.allow_exceptions.is_empty());
637        assert!(config.auto_permission.environment.trusted_paths.is_empty());
638    }
639
640    #[cfg(feature = "schema")]
641    #[test]
642    fn decisions_probe_schema_exposes_default_off_toggle() {
643        let schema = serde_json::to_value(schemars::schema_for!(super::AutoPermissionConfig)).expect("schema");
644        let field = &schema["properties"]["use_decisions_probe"];
645        assert_eq!(field["type"], "boolean");
646        assert_eq!(field["default"], false);
647    }
648
649    #[test]
650    fn normalizes_read_tool_names_to_semantic_rule() {
651        for input in ["read_file", "Read_File", "READ_FILE", "read", "Read"] {
652            assert_eq!(super::normalize_permission_rule(input), "read", "input: {input}");
653        }
654    }
655
656    #[test]
657    fn normalizes_write_tool_names_to_semantic_rule() {
658        for input in ["write_file", "Write_File", "create_file", "delete_file"] {
659            assert_eq!(super::normalize_permission_rule(input), "write", "input: {input}");
660        }
661    }
662
663    #[test]
664    fn normalizes_edit_tool_names_to_semantic_rule() {
665        for input in ["edit_file", "Edit_File", "apply_patch", "file_op"] {
666            assert_eq!(super::normalize_permission_rule(input), "edit", "input: {input}");
667        }
668    }
669
670    #[test]
671    fn normalizes_bash_tool_names_to_semantic_rule() {
672        for input in ["bash", "Bash", "exec_command", "run_pty_cmd"] {
673            assert_eq!(super::normalize_permission_rule(input), "bash", "input: {input}");
674        }
675    }
676
677    #[test]
678    fn public_permission_tool_names_use_semantic_rules_when_known() {
679        assert_eq!(super::normalize_permission_rule("exec_command"), "bash");
680        assert_eq!(super::normalize_permission_rule("apply_patch"), "edit");
681        assert_eq!(super::normalize_permission_rule("code_search"), "read");
682    }
683
684    #[test]
685    fn normalizes_tool_name_with_path_specifier() {
686        assert_eq!(super::normalize_permission_rule("read_file(/src/**/*.rs)"), "read(/src/**/*.rs)");
687        assert_eq!(super::normalize_permission_rule("write_file(/docs/**)"), "write(/docs/**)");
688    }
689
690    #[test]
691    fn mcp_rules_pass_through_unchanged() {
692        assert_eq!(super::normalize_permission_rule("mcp__server__tool"), "mcp__server__tool");
693        assert_eq!(super::normalize_permission_rule("mcp__context7__*"), "mcp__context7__*");
694    }
695
696    #[test]
697    fn semantic_rules_pass_through_unchanged() {
698        for input in ["read", "write", "edit", "bash", "webfetch"] {
699            assert_eq!(super::normalize_permission_rule(input), input, "input: {input}");
700        }
701    }
702
703    #[test]
704    fn unknown_rules_pass_through_unchanged() {
705        assert_eq!(super::normalize_permission_rule("some_custom_tool"), "some_custom_tool");
706    }
707}