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))]
26#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
27#[serde(rename_all = "snake_case")]
28pub enum DefaultPermissionMode {
29 #[default]
31 Ask,
32 AutoApprove,
34}
35
36impl DefaultPermissionMode {
37 #[must_use]
39 pub fn skips_confirmations(self) -> bool {
40 matches!(self, Self::AutoApprove)
41 }
42}
43
44#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
45#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
46pub struct AgentPermissionsConfig {
47 pub default: PermissionDefault,
50
51 #[serde(default)]
57 pub allow: Vec<String>,
58
59 #[serde(default)]
62 pub ask: Vec<String>,
63
64 #[serde(default)]
67 pub auto: Vec<String>,
68
69 #[serde(default)]
72 pub deny: Vec<String>,
73}
74
75impl AgentPermissionsConfig {
76 #[must_use]
77 pub fn new(default: PermissionDefault) -> Self {
78 Self {
79 default,
80 allow: Vec::new(),
81 ask: Vec::new(),
82 auto: Vec::new(),
83 deny: Vec::new(),
84 }
85 }
86
87 pub fn validate(&self) -> Result<()> {
94 reject_computer_use_allow(&self.allow, "agent allow rules")
95 }
96}
97
98fn reject_computer_use_allow(rules: &[String], owner: &str) -> Result<()> {
101 if rules.iter().any(|rule| normalize_permission_rule(rule) == tools::COMPUTER_USE) {
102 bail!("{owner} must not allowlist '{}': computer-use approval is always per-turn", tools::COMPUTER_USE);
103 }
104 Ok(())
105}
106
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118enum SemanticRule {
119 Read,
120 Write,
121 Edit,
122 Bash,
123 WebFetch,
124}
125
126impl SemanticRule {
127 const ALL: [Self; 5] = [Self::Read, Self::Write, Self::Edit, Self::Bash, Self::WebFetch];
128
129 const fn as_str(self) -> &'static str {
130 match self {
131 Self::Read => "read",
132 Self::Write => "write",
133 Self::Edit => "edit",
134 Self::Bash => "bash",
135 Self::WebFetch => "webfetch",
136 }
137 }
138
139 fn parse(value: &str) -> Option<Self> {
140 Self::ALL.into_iter().find(|rule| rule.as_str() == value)
141 }
142
143 fn from_tool_name(tool_name: &str) -> Option<Self> {
146 match tool_name {
147 tools::READ_FILE
148 | "read"
149 | tools::GREP_FILE
150 | tools::GREP
151 | tools::LIST_FILES
152 | tools::LIST
153 | "glob"
154 | "listfiles"
155 | "grepfile"
156 | tools::CODE_SEARCH
157 | "codesearch" => Some(Self::Read),
158 tools::WRITE_FILE
159 | "write"
160 | tools::CREATE_FILE
161 | "createfile"
162 | tools::DELETE_FILE
163 | "deletefile"
164 | tools::MOVE_FILE
165 | "movefile"
166 | tools::COPY_FILE
167 | "copyfile" => Some(Self::Write),
168 tools::EDIT_FILE
169 | "edit"
170 | tools::APPLY_PATCH
171 | "applypatch"
172 | tools::SEARCH_REPLACE
173 | "searchreplace"
174 | tools::FILE_OP
175 | "fileop"
176 | "patch" => Some(Self::Edit),
177 "bash"
178 | tools::SHELL
179 | "command"
180 | tools::EXEC_COMMAND
181 | "execcommand"
182 | tools::RUN_PTY_CMD
183 | "runptycmd"
184 | tools::EXECUTE_CODE
185 | "executecode" => Some(Self::Bash),
186 "webfetch" | tools::WEB_FETCH | tools::FETCH => Some(Self::WebFetch),
187 _ => None,
188 }
189 }
190}
191
192fn is_semantic_rule(rule: &str) -> bool {
194 SemanticRule::parse(&rule.to_ascii_lowercase()).is_some()
195}
196
197fn normalize_tool_name_to_semantic(tool_name: &str) -> String {
202 let tool_name = tool_name.to_ascii_lowercase();
203 SemanticRule::from_tool_name(&tool_name).map_or(tool_name, |rule| rule.as_str().to_string())
204}
205
206fn parse_tool_specifier_parts(rule: &str) -> Option<(&str, &str)> {
211 let trimmed = rule.trim();
212 if let Some(open) = trimmed.find('(') {
213 let tool_part = trimmed[..open].trim();
214 let specifier = trimmed[open + 1..].strip_suffix(')').map(str::trim)?;
215 if !tool_part.is_empty() && !specifier.is_empty() {
216 return Some((tool_part, specifier));
217 }
218 }
219 None
220}
221
222#[must_use]
231pub fn normalize_permission_rule(raw: &str) -> String {
232 let trimmed = raw.trim();
233
234 if is_semantic_rule(trimmed) {
236 return trimmed.to_ascii_lowercase();
237 }
238
239 if trimmed.starts_with("mcp__") {
241 return trimmed.to_string();
242 }
243
244 if let Some((tool_part, specifier)) = parse_tool_specifier_parts(trimmed) {
246 let normalized_tool = normalize_tool_name_to_semantic(tool_part);
247 return format!("{normalized_tool}({specifier})");
248 }
249
250 normalize_tool_name_to_semantic(trimmed)
252}
253
254#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
256#[derive(Debug, Clone, Deserialize, Serialize)]
257pub struct PermissionsConfig {
258 #[serde(
260 default,
261 rename = "auto",
262 alias = "auto_permission",
263 deserialize_with = "deserialize_auto_permission_config"
264 )]
265 pub auto_permission: AutoPermissionConfig,
266
267 #[serde(default)]
269 pub allow: Vec<String>,
270
271 #[serde(default)]
273 pub ask: Vec<String>,
274
275 #[serde(default)]
277 pub deny: Vec<String>,
278
279 #[serde(default = "default_enabled")]
281 pub enabled: bool,
282
283 #[serde(default = "default_resolve_commands")]
285 pub resolve_commands: bool,
286
287 #[serde(default = "default_audit_enabled")]
289 pub audit_enabled: bool,
290
291 #[serde(default = "default_audit_directory")]
294 pub audit_directory: String,
295
296 #[serde(default = "default_log_allowed_commands")]
298 pub log_allowed_commands: bool,
299
300 #[serde(default = "default_log_denied_commands")]
302 pub log_denied_commands: bool,
303
304 #[serde(default = "default_log_permission_prompts")]
306 pub log_permission_prompts: bool,
307
308 #[serde(default = "default_cache_enabled")]
310 pub cache_enabled: bool,
311
312 #[serde(default = "default_cache_ttl_seconds")]
315 pub cache_ttl_seconds: u64,
316
317 #[serde(default)]
321 pub default_mode: DefaultPermissionMode,
322}
323
324impl PermissionsConfig {
325 pub fn validate(&self) -> Result<()> {
332 reject_computer_use_allow(&self.allow, "permissions.allow")
333 }
334}
335
336#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
338#[derive(Debug, Clone, Deserialize, Serialize)]
339pub struct AutoPermissionConfig {
340 #[serde(default)]
342 pub model: String,
343
344 #[serde(default)]
346 pub probe_model: String,
347
348 #[serde(default)]
353 pub use_decisions_probe: bool,
354
355 #[serde(default = "default_auto_permission_max_consecutive_denials")]
357 pub max_consecutive_denials: u32,
358
359 #[serde(default = "default_auto_permission_max_total_denials")]
361 pub max_total_denials: u32,
362
363 #[serde(default = "default_auto_permission_drop_broad_allow_rules")]
365 pub drop_broad_allow_rules: bool,
366
367 #[serde(default = "default_auto_permission_block_rules")]
369 pub block_rules: Vec<String>,
370
371 #[serde(default = "default_auto_permission_allow_exceptions")]
373 pub allow_exceptions: Vec<String>,
374
375 #[serde(default)]
377 pub environment: AutoPermissionEnvironmentConfig,
378}
379
380fn deserialize_auto_permission_config<'de, D>(deserializer: D) -> Result<AutoPermissionConfig, D::Error>
381where
382 D: Deserializer<'de>,
383{
384 struct AutoPermissionConfigVisitor;
385
386 impl<'de> Visitor<'de> for AutoPermissionConfigVisitor {
387 type Value = AutoPermissionConfig;
388
389 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
390 formatter.write_str("a table of auto permission settings")
391 }
392
393 fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
394 where
395 M: MapAccess<'de>,
396 {
397 AutoPermissionConfig::deserialize(serde::de::value::MapAccessDeserializer::new(map))
398 }
399 }
400
401 deserializer.deserialize_map(AutoPermissionConfigVisitor)
402}
403
404#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
406#[derive(Debug, Clone, Default, Deserialize, Serialize)]
407pub struct AutoPermissionEnvironmentConfig {
408 #[serde(default)]
409 pub trusted_paths: Vec<String>,
410
411 #[serde(default)]
412 pub trusted_domains: Vec<String>,
413
414 #[serde(default)]
415 pub trusted_git_hosts: Vec<String>,
416
417 #[serde(default)]
418 pub trusted_git_orgs: Vec<String>,
419
420 #[serde(default)]
421 pub trusted_services: Vec<String>,
422}
423
424impl Default for AutoPermissionConfig {
425 fn default() -> Self {
426 Self {
427 model: String::new(),
428 probe_model: String::new(),
429 use_decisions_probe: false,
430 max_consecutive_denials: default_auto_permission_max_consecutive_denials(),
431 max_total_denials: default_auto_permission_max_total_denials(),
432 drop_broad_allow_rules: default_auto_permission_drop_broad_allow_rules(),
433 block_rules: default_auto_permission_block_rules(),
434 allow_exceptions: default_auto_permission_allow_exceptions(),
435 environment: AutoPermissionEnvironmentConfig::default(),
436 }
437 }
438}
439
440#[inline]
441const fn default_resolve_commands() -> bool {
442 default_enabled()
443}
444
445#[inline]
446const fn default_audit_enabled() -> bool {
447 default_enabled()
448}
449
450#[inline]
451fn default_audit_directory() -> String {
452 VtCodePaths::resolve()
453 .and_then(|paths| paths.state_path("audit"))
454 .map(|path| path.display().to_string())
455 .unwrap_or_else(|_| String::from("state/vtcode/audit"))
456}
457
458#[inline]
459const fn default_log_allowed_commands() -> bool {
460 true
461}
462
463#[inline]
464const fn default_log_denied_commands() -> bool {
465 true
466}
467
468#[inline]
469const fn default_log_permission_prompts() -> bool {
470 true
471}
472
473#[inline]
474const fn default_cache_enabled() -> bool {
475 true
476}
477
478#[inline]
479const fn default_cache_ttl_seconds() -> u64 {
480 300 }
482
483#[inline]
484const fn default_auto_permission_max_consecutive_denials() -> u32 {
485 3
486}
487
488#[inline]
489const fn default_auto_permission_max_total_denials() -> u32 {
490 20
491}
492
493#[inline]
494const fn default_auto_permission_drop_broad_allow_rules() -> bool {
495 true
496}
497
498fn default_auto_permission_block_rules() -> Vec<String> {
499 vec![
500 "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(),
501 "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(),
502 "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(),
503 "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(),
504 "Block commands that bypass safety checks, disable verification, install persistence, or weaken the host security posture.".to_string(),
505 "Block destructive or production/shared-infrastructure actions unless the user explicitly authorized the target and the action.".to_string(),
506 "Block destructive actions against inferred, fuzzy-matched, or agent-selected targets when the user did not name the exact target.".to_string(),
507 ]
508}
509
510fn default_auto_permission_allow_exceptions() -> Vec<String> {
511 vec![
512 "Allow read-only tools and read-only browsing/search actions.".to_string(),
513 "Allow file edits and writes inside the current workspace when the path is not protected.".to_string(),
514 "Allow pushes only to the current session branch or configured git remotes inside the trusted environment."
515 .to_string(),
516 ]
517}
518
519impl Default for PermissionsConfig {
520 fn default() -> Self {
521 Self {
522 auto_permission: AutoPermissionConfig::default(),
523 allow: Vec::new(),
524 ask: Vec::new(),
525 deny: Vec::new(),
526 enabled: default_enabled(),
527 resolve_commands: default_resolve_commands(),
528 audit_enabled: default_audit_enabled(),
529 audit_directory: default_audit_directory(),
530 log_allowed_commands: default_log_allowed_commands(),
531 log_denied_commands: default_log_denied_commands(),
532 log_permission_prompts: default_log_permission_prompts(),
533 cache_enabled: default_cache_enabled(),
534 cache_ttl_seconds: default_cache_ttl_seconds(),
535 default_mode: DefaultPermissionMode::default(),
536 }
537 }
538}
539
540#[cfg(test)]
541mod tests {
542 use super::{AgentPermissionsConfig, PermissionDefault, PermissionsConfig};
543
544 #[test]
545 fn computer_use_cannot_join_allow_lists() {
546 for spelling in ["computer_use", " Computer_Use ", "COMPUTER_USE"] {
547 let global: PermissionsConfig =
548 toml::from_str(&format!(r#"allow = ["{spelling}"]"#)).expect("global permissions");
549 let error = global.validate().unwrap_err();
550 assert!(error.to_string().contains("per-turn"), "{spelling}: {error:#}");
551
552 let agent: AgentPermissionsConfig =
553 toml::from_str(&format!("default = \"ask\"\nallow = [\"{spelling}\"]")).expect("agent permissions");
554 agent.validate().unwrap_err();
555 }
556 let clean: PermissionsConfig =
557 toml::from_str("allow = [\"read\"]\nask = [\"computer_use\"]\ndeny = [\"computer_use\"]")
558 .expect("clean permissions");
559 clean.validate().expect("ask/deny lists may name computer use");
560 }
561
562 #[test]
563 fn parses_agent_permission_defaults_and_empty_buckets() {
564 for (value, expected) in [
565 ("ask", PermissionDefault::Ask),
566 ("allow", PermissionDefault::Allow),
567 ("auto", PermissionDefault::Auto),
568 ("deny", PermissionDefault::Deny),
569 ] {
570 let config: AgentPermissionsConfig =
571 toml::from_str(&format!(r#"default = "{value}""#)).expect("agent permissions");
572 assert_eq!(config.default, expected);
573 assert!(config.allow.is_empty());
574 assert!(config.ask.is_empty());
575 assert!(config.auto.is_empty());
576 assert!(config.deny.is_empty());
577 }
578
579 let err = toml::from_str::<AgentPermissionsConfig>(r#"default = "plan""#).unwrap_err();
580 assert!(err.to_string().contains("unknown variant"));
581 }
582
583 #[test]
584 fn parses_exact_tool_rules() {
585 let config: PermissionsConfig = toml::from_str(
586 r#"
587 allow = ["read_file", "code_search"]
588 deny = ["exec_command"]
589 "#,
590 )
591 .expect("permissions config");
592
593 assert_eq!(config.allow, vec!["read_file".to_string(), "code_search".to_string()]);
594 assert_eq!(config.deny, vec!["exec_command".to_string()]);
595 }
596
597 #[test]
598 fn normalizes_code_search_rules_to_read_semantics() {
599 assert_eq!(super::normalize_permission_rule("code_search"), "read");
600 assert_eq!(super::normalize_permission_rule("code_search(/src/**)"), "read(/src/**)");
601 }
602
603 #[test]
604 fn ignores_unknown_fields_for_forward_compatibility() {
605 let removed_field = format!("default_{}", "mode");
608 let input = format!(
609 r#"
610 {removed_field} = "ask"
611 "#,
612 );
613 let config: PermissionsConfig = toml::from_str(&input).unwrap();
614 assert!(config.allow.is_empty());
616
617 let err = toml::from_str::<PermissionsConfig>(
620 r#"
621 auto = ["exec_command"]
622 "#,
623 )
624 .unwrap_err();
625 assert!(err.to_string().contains("invalid type"));
626 }
627
628 #[test]
629 fn parses_auto_permission_settings_from_canonical_auto_table() {
630 let config: PermissionsConfig = toml::from_str(
631 r#"
632 [auto]
633 model = "gpt-5-mini"
634 use_decisions_probe = true
635 max_consecutive_denials = 2
636 drop_broad_allow_rules = false
637
638 [auto.environment]
639 trusted_paths = ["/work/project"]
640 trusted_domains = ["example.com"]
641 "#,
642 )
643 .expect("permissions config");
644
645 assert_eq!(config.auto_permission.model, "gpt-5-mini");
646 assert!(config.auto_permission.use_decisions_probe);
647 let serialized = toml::to_string(&config).expect("serialize permissions");
648 assert!(serialized.contains("[auto]"));
649 assert!(serialized.contains("use_decisions_probe = true"));
650 let roundtrip: PermissionsConfig = toml::from_str(&serialized).expect("roundtrip permissions");
651 assert!(roundtrip.auto_permission.use_decisions_probe);
652 assert_eq!(config.auto_permission.max_consecutive_denials, 2);
653 assert!(!config.auto_permission.drop_broad_allow_rules);
654 assert_eq!(config.auto_permission.environment.trusted_paths, vec!["/work/project".to_string()]);
655 assert_eq!(config.auto_permission.environment.trusted_domains, vec!["example.com".to_string()]);
656 }
657
658 #[test]
659 fn auto_permission_defaults_are_conservative() {
660 let config = PermissionsConfig::default();
661 assert!(!config.auto_permission.use_decisions_probe);
662
663 assert_eq!(config.auto_permission.max_consecutive_denials, 3);
664 assert_eq!(config.auto_permission.max_total_denials, 20);
665 assert!(config.auto_permission.drop_broad_allow_rules);
666 assert!(!config.auto_permission.block_rules.is_empty());
667 assert!(!config.auto_permission.allow_exceptions.is_empty());
668 assert!(config.auto_permission.environment.trusted_paths.is_empty());
669 }
670
671 #[cfg(feature = "schema")]
672 #[test]
673 fn decisions_probe_schema_exposes_default_off_toggle() {
674 let schema = serde_json::to_value(schemars::schema_for!(super::AutoPermissionConfig)).expect("schema");
675 let field = &schema["properties"]["use_decisions_probe"];
676 assert_eq!(field["type"], "boolean");
677 assert_eq!(field["default"], false);
678 }
679
680 #[test]
681 fn normalizes_read_tool_names_to_semantic_rule() {
682 for input in ["read_file", "Read_File", "READ_FILE", "read", "Read"] {
683 assert_eq!(super::normalize_permission_rule(input), "read", "input: {input}");
684 }
685 }
686
687 #[test]
688 fn normalizes_write_tool_names_to_semantic_rule() {
689 for input in ["write_file", "Write_File", "create_file", "delete_file"] {
690 assert_eq!(super::normalize_permission_rule(input), "write", "input: {input}");
691 }
692 }
693
694 #[test]
695 fn normalizes_edit_tool_names_to_semantic_rule() {
696 for input in ["edit_file", "Edit_File", "apply_patch", "file_op"] {
697 assert_eq!(super::normalize_permission_rule(input), "edit", "input: {input}");
698 }
699 }
700
701 #[test]
702 fn normalizes_bash_tool_names_to_semantic_rule() {
703 for input in ["bash", "Bash", "exec_command", "run_pty_cmd"] {
704 assert_eq!(super::normalize_permission_rule(input), "bash", "input: {input}");
705 }
706 }
707
708 #[test]
709 fn public_permission_tool_names_use_semantic_rules_when_known() {
710 assert_eq!(super::normalize_permission_rule("exec_command"), "bash");
711 assert_eq!(super::normalize_permission_rule("apply_patch"), "edit");
712 assert_eq!(super::normalize_permission_rule("code_search"), "read");
713 }
714
715 #[test]
716 fn normalizes_tool_name_with_path_specifier() {
717 assert_eq!(super::normalize_permission_rule("read_file(/src/**/*.rs)"), "read(/src/**/*.rs)");
718 assert_eq!(super::normalize_permission_rule("write_file(/docs/**)"), "write(/docs/**)");
719 }
720
721 #[test]
722 fn mcp_rules_pass_through_unchanged() {
723 assert_eq!(super::normalize_permission_rule("mcp__server__tool"), "mcp__server__tool");
724 assert_eq!(super::normalize_permission_rule("mcp__context7__*"), "mcp__context7__*");
725 }
726
727 #[test]
728 fn semantic_rules_pass_through_unchanged() {
729 for input in ["read", "write", "edit", "bash", "webfetch"] {
730 assert_eq!(super::normalize_permission_rule(input), input, "input: {input}");
731 }
732 }
733
734 #[test]
735 fn unknown_rules_pass_through_unchanged() {
736 assert_eq!(super::normalize_permission_rule("some_custom_tool"), "some_custom_tool");
737 }
738}