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 pub default: PermissionDefault,
26
27 #[serde(default)]
33 pub allow: Vec<String>,
34
35 #[serde(default)]
38 pub ask: Vec<String>,
39
40 #[serde(default)]
43 pub auto: Vec<String>,
44
45 #[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 pub fn validate(&self) -> Result<()> {
70 reject_computer_use_allow(&self.allow, "agent allow rules")
71 }
72}
73
74fn 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#[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 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
168fn is_semantic_rule(rule: &str) -> bool {
170 SemanticRule::parse(&rule.to_ascii_lowercase()).is_some()
171}
172
173fn 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
182fn 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#[must_use]
207pub fn normalize_permission_rule(raw: &str) -> String {
208 let trimmed = raw.trim();
209
210 if is_semantic_rule(trimmed) {
212 return trimmed.to_ascii_lowercase();
213 }
214
215 if trimmed.starts_with("mcp__") {
217 return trimmed.to_string();
218 }
219
220 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 normalize_tool_name_to_semantic(trimmed)
228}
229
230#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
232#[derive(Debug, Clone, Deserialize, Serialize)]
233pub struct PermissionsConfig {
234 #[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 #[serde(default)]
245 pub allow: Vec<String>,
246
247 #[serde(default)]
249 pub ask: Vec<String>,
250
251 #[serde(default)]
253 pub deny: Vec<String>,
254
255 #[serde(default = "default_enabled")]
257 pub enabled: bool,
258
259 #[serde(default = "default_resolve_commands")]
261 pub resolve_commands: bool,
262
263 #[serde(default = "default_audit_enabled")]
265 pub audit_enabled: bool,
266
267 #[serde(default = "default_audit_directory")]
270 pub audit_directory: String,
271
272 #[serde(default = "default_log_allowed_commands")]
274 pub log_allowed_commands: bool,
275
276 #[serde(default = "default_log_denied_commands")]
278 pub log_denied_commands: bool,
279
280 #[serde(default = "default_log_permission_prompts")]
282 pub log_permission_prompts: bool,
283
284 #[serde(default = "default_cache_enabled")]
286 pub cache_enabled: bool,
287
288 #[serde(default = "default_cache_ttl_seconds")]
291 pub cache_ttl_seconds: u64,
292}
293
294impl PermissionsConfig {
295 pub fn validate(&self) -> Result<()> {
302 reject_computer_use_allow(&self.allow, "permissions.allow")
303 }
304}
305
306#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
308#[derive(Debug, Clone, Deserialize, Serialize)]
309pub struct AutoPermissionConfig {
310 #[serde(default)]
312 pub model: String,
313
314 #[serde(default)]
316 pub probe_model: String,
317
318 #[serde(default)]
323 pub use_decisions_probe: bool,
324
325 #[serde(default = "default_auto_permission_max_consecutive_denials")]
327 pub max_consecutive_denials: u32,
328
329 #[serde(default = "default_auto_permission_max_total_denials")]
331 pub max_total_denials: u32,
332
333 #[serde(default = "default_auto_permission_drop_broad_allow_rules")]
335 pub drop_broad_allow_rules: bool,
336
337 #[serde(default = "default_auto_permission_block_rules")]
339 pub block_rules: Vec<String>,
340
341 #[serde(default = "default_auto_permission_allow_exceptions")]
343 pub allow_exceptions: Vec<String>,
344
345 #[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#[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 }
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 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 assert!(config.allow.is_empty());
585
586 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}