vtcode-core 0.104.1

Core library for VT Code - a Rust-based terminal coding agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Execution policy manager.
//!
//! Coordinates policy evaluation, approval requirements, and sandbox enforcement.
//! Inspired by Codex's ExecPolicyManager pattern.

use super::{
    approval::{AskForApproval, ExecApprovalRequirement, ExecPolicyAmendment},
    policy::{Decision, Policy, PolicyEvaluation, RuleMatch},
};
use crate::command_safety::command_might_be_dangerous;
use crate::sandboxing::SandboxPolicy;
use anyhow::{Context, Result};
use std::{
    collections::HashSet,
    path::{Path, PathBuf},
    sync::Arc,
};
use tokio::sync::RwLock;

const PROMPT_CONFLICT_REASON: &str =
    "approval required by policy, but AskForApproval is set to Never";
const REJECT_SANDBOX_APPROVAL_REASON: &str =
    "approval required by policy, but AskForApproval::Reject.sandbox_approval is set";
const REJECT_RULES_APPROVAL_REASON: &str =
    "approval required by policy rule, but AskForApproval::Reject.rules is set";

fn prompt_is_rejected_by_policy(
    approval_policy: AskForApproval,
    prompt_is_rule: bool,
) -> Option<&'static str> {
    if prompt_is_rule {
        if !approval_policy.rejects_rule_prompt() {
            return None;
        }

        return Some(if matches!(approval_policy, AskForApproval::Never) {
            PROMPT_CONFLICT_REASON
        } else {
            REJECT_RULES_APPROVAL_REASON
        });
    }

    if !approval_policy.rejects_sandbox_prompt() {
        return None;
    }

    Some(if matches!(approval_policy, AskForApproval::Never) {
        PROMPT_CONFLICT_REASON
    } else {
        REJECT_SANDBOX_APPROVAL_REASON
    })
}

/// Configuration for the execution policy manager.
#[derive(Debug, Clone)]
pub struct ExecPolicyConfig {
    /// Default sandbox policy for commands.
    pub default_sandbox_policy: SandboxPolicy,

    /// Default approval behavior.
    pub default_approval: AskForApproval,

    /// Whether to apply heuristics for unknown commands.
    pub use_heuristics: bool,

    /// Maximum command length before requiring confirmation.
    pub max_auto_approve_length: usize,
}

impl Default for ExecPolicyConfig {
    fn default() -> Self {
        Self {
            default_sandbox_policy: SandboxPolicy::read_only(),
            default_approval: AskForApproval::UnlessTrusted,
            use_heuristics: true,
            max_auto_approve_length: 256,
        }
    }
}

/// Manages execution policies and authorization decisions.
pub struct ExecPolicyManager {
    /// The current policy.
    policy: RwLock<Policy>,

    /// Trusted command patterns.
    trusted_patterns: RwLock<Vec<ExecPolicyAmendment>>,

    /// Active sandbox policy.
    sandbox_policy: RwLock<SandboxPolicy>,

    /// Configuration.
    config: ExecPolicyConfig,

    /// Workspace root for path validation.
    #[allow(dead_code)]
    workspace_root: PathBuf,

    /// Commands that have been pre-approved this session.
    session_approved: RwLock<HashSet<String>>,
}

impl ExecPolicyManager {
    /// Create a new policy manager.
    pub fn new(workspace_root: PathBuf, config: ExecPolicyConfig) -> Self {
        Self {
            policy: RwLock::new(Policy::empty()),
            trusted_patterns: RwLock::new(Vec::new()),
            sandbox_policy: RwLock::new(config.default_sandbox_policy.clone()),
            config,
            workspace_root,
            session_approved: RwLock::new(HashSet::new()),
        }
    }

    /// Create with default configuration.
    pub fn with_defaults(workspace_root: PathBuf) -> Self {
        Self::new(workspace_root, ExecPolicyConfig::default())
    }

    /// Load policy from a file.
    pub async fn load_policy(&self, path: &Path) -> Result<()> {
        let parser = super::parser::PolicyParser::new();
        let loaded_policy = parser
            .load_file(path)
            .await
            .context("Failed to load policy file")?;

        let mut policy = self.policy.write().await;
        *policy = loaded_policy;
        Ok(())
    }

    /// Add a prefix rule to the policy.
    pub async fn add_prefix_rule(&self, pattern: &[String], decision: Decision) -> Result<()> {
        let mut policy = self.policy.write().await;
        policy.add_prefix_rule(pattern, decision)
    }

    /// Add a trusted pattern amendment.
    pub async fn add_trusted_pattern(&self, amendment: ExecPolicyAmendment) {
        let mut patterns = self.trusted_patterns.write().await;
        patterns.push(amendment);
    }

    /// Set the sandbox policy.
    pub async fn set_sandbox_policy(&self, policy: SandboxPolicy) {
        let mut sandbox = self.sandbox_policy.write().await;
        *sandbox = policy;
    }

    /// Get the current sandbox policy.
    pub async fn sandbox_policy(&self) -> SandboxPolicy {
        self.sandbox_policy.read().await.clone()
    }

    /// Check if a command requires approval.
    pub async fn check_approval(&self, command: &[String]) -> ExecApprovalRequirement {
        // Check if already approved this session
        let command_key = command.join(" ");
        {
            let approved = self.session_approved.read().await;
            if approved.contains(&command_key) {
                return ExecApprovalRequirement::skip();
            }
        }

        // Check trusted patterns
        {
            let patterns = self.trusted_patterns.read().await;
            for pattern in patterns.iter() {
                if pattern.matches(command) {
                    return ExecApprovalRequirement::skip();
                }
            }
        }

        // Check policy rules
        let policy = self.policy.read().await;
        let rule_match = policy.check(command);

        // Apply heuristics for non-policy matches
        let decision = match &rule_match {
            RuleMatch::PrefixRuleMatch { decision, .. } => *decision,
            RuleMatch::HeuristicsRuleMatch { .. } => self.heuristics_decision(command),
        };

        match decision {
            Decision::Allow => ExecApprovalRequirement::skip(),
            Decision::Prompt => {
                let prompt_is_rule = matches!(
                    rule_match,
                    RuleMatch::PrefixRuleMatch {
                        decision: Decision::Prompt,
                        ..
                    }
                );

                match prompt_is_rejected_by_policy(self.config.default_approval, prompt_is_rule) {
                    Some(reason) => ExecApprovalRequirement::forbidden(reason),
                    None => ExecApprovalRequirement::needs_approval(
                        self.format_approval_reason(command, &rule_match),
                    ),
                }
            }
            Decision::Forbidden => ExecApprovalRequirement::forbidden(
                self.format_forbidden_reason(command, &rule_match),
            ),
        }
    }

    /// Check multiple commands and return combined approval requirement.
    pub async fn check_approval_batch(&self, commands: &[Vec<String>]) -> ExecApprovalRequirement {
        let mut needs_approval_flag = false;
        let mut reasons = Vec::new();

        for command in commands {
            let approval = self.check_approval(command).await;
            if approval.is_forbidden() {
                return approval;
            }
            if approval.requires_approval() {
                needs_approval_flag = true;
                if let ExecApprovalRequirement::NeedsApproval {
                    reason: Some(r), ..
                } = &approval
                {
                    reasons.push(r.clone());
                }
            }
        }

        if needs_approval_flag {
            ExecApprovalRequirement::needs_approval(reasons.join("; "))
        } else {
            ExecApprovalRequirement::skip()
        }
    }

    /// Mark a command as approved for this session.
    pub async fn approve_command(&self, command: &[String]) {
        let command_key = command.join(" ");
        let mut approved = self.session_approved.write().await;
        approved.insert(command_key);
    }

    /// Clear all session approvals.
    pub async fn clear_session_approvals(&self) {
        let mut approved = self.session_approved.write().await;
        approved.clear();
    }

    /// Evaluate a command against the full policy stack.
    pub async fn evaluate(&self, command: &[String]) -> PolicyEvaluation {
        let policy = self.policy.read().await;
        let commands = [command.to_vec()];
        policy.check_multiple(commands.iter(), &|cmd| self.heuristics_decision(cmd))
    }

    /// Apply heuristics to determine decision for unknown commands.
    ///
    /// Uses the centralized `command_safety` module for dangerous command detection.
    fn heuristics_decision(&self, command: &[String]) -> Decision {
        if !self.config.use_heuristics {
            return Decision::Prompt;
        }

        if command.is_empty() {
            return Decision::Prompt;
        }

        let cmd = &command[0];

        // Known safe read-only commands that can proceed without approval
        let safe_commands = [
            "ls", "cat", "head", "tail", "grep", "find", "echo", "pwd", "which", "type", "less",
            "more", "wc", "sort", "uniq", "diff", "env", "printenv", "hostname", "uname", "date",
            "whoami", "id", "file", "stat", "tree", "df", "du", "uptime",
        ];

        if safe_commands.contains(&cmd.as_str()) {
            return Decision::Allow;
        }

        // Check dangerous commands using centralized logic
        if command_might_be_dangerous(command) {
            // Check for --dry-run flag to allow prompting instead of forbidding
            if command.iter().any(|arg| arg == "--dry-run" || arg == "-n") {
                return Decision::Prompt;
            }
            return Decision::Forbidden;
        }

        // For all other commands, default to prompting for approval
        Decision::Prompt
    }

    /// Format the reason for requiring approval.
    fn format_approval_reason(&self, command: &[String], rule_match: &RuleMatch) -> String {
        match rule_match {
            RuleMatch::PrefixRuleMatch { rule, .. } => {
                format!(
                    "Command '{}' matched rule '{}' requiring confirmation",
                    command.join(" "),
                    rule.pattern.join(" ")
                )
            }
            RuleMatch::HeuristicsRuleMatch { .. } => {
                format!(
                    "Command '{}' requires confirmation (no explicit policy rule)",
                    command.join(" ")
                )
            }
        }
    }

    /// Format the reason for forbidding a command.
    fn format_forbidden_reason(&self, command: &[String], rule_match: &RuleMatch) -> String {
        match rule_match {
            RuleMatch::PrefixRuleMatch { rule, .. } => {
                format!(
                    "Command '{}' is forbidden by rule '{}'",
                    command.join(" "),
                    rule.pattern.join(" ")
                )
            }
            RuleMatch::HeuristicsRuleMatch { .. } => {
                format!(
                    "Command '{}' is forbidden by safety heuristics",
                    command.join(" ")
                )
            }
        }
    }
}

/// Shared reference to an ExecPolicyManager.
pub type SharedExecPolicyManager = Arc<ExecPolicyManager>;

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_policy_manager_basic() {
        let dir = tempdir().unwrap();
        let manager = ExecPolicyManager::with_defaults(dir.path().to_path_buf());

        // Add a rule
        manager
            .add_prefix_rule(&["cargo".to_string(), "build".to_string()], Decision::Allow)
            .await
            .unwrap();

        // Check approval
        let result = manager
            .check_approval(&["cargo".to_string(), "build".to_string()])
            .await;
        assert!(result.can_proceed());

        // Unknown command should need approval
        let result = manager
            .check_approval(&["unknown".to_string(), "command".to_string()])
            .await;
        assert!(result.requires_approval());
    }

    #[tokio::test]
    async fn test_prompt_conflict_with_never_policy_forbids() {
        let dir = tempdir().unwrap();
        let manager = ExecPolicyManager::new(
            dir.path().to_path_buf(),
            ExecPolicyConfig {
                default_approval: AskForApproval::Never,
                ..ExecPolicyConfig::default()
            },
        );

        let result = manager
            .check_approval(&["unknown".to_string(), "command".to_string()])
            .await;
        assert_eq!(
            result,
            ExecApprovalRequirement::forbidden(PROMPT_CONFLICT_REASON)
        );
    }

    #[tokio::test]
    async fn test_reject_rules_policy_forbids_rule_prompt() {
        let dir = tempdir().unwrap();
        let manager = ExecPolicyManager::new(
            dir.path().to_path_buf(),
            ExecPolicyConfig {
                default_approval: AskForApproval::Reject(crate::exec_policy::RejectConfig {
                    sandbox_approval: false,
                    rules: true,
                    request_permissions: false,
                    mcp_elicitations: false,
                }),
                ..ExecPolicyConfig::default()
            },
        );
        manager
            .add_prefix_rule(&["git".to_string()], Decision::Prompt)
            .await
            .expect("add prompt rule");

        let result = manager.check_approval(&["git".to_string()]).await;
        assert_eq!(
            result,
            ExecApprovalRequirement::forbidden(REJECT_RULES_APPROVAL_REASON)
        );
    }

    #[tokio::test]
    async fn test_reject_sandbox_policy_forbids_non_rule_prompt() {
        let dir = tempdir().unwrap();
        let manager = ExecPolicyManager::new(
            dir.path().to_path_buf(),
            ExecPolicyConfig {
                default_approval: AskForApproval::Reject(crate::exec_policy::RejectConfig {
                    sandbox_approval: true,
                    rules: false,
                    request_permissions: false,
                    mcp_elicitations: false,
                }),
                ..ExecPolicyConfig::default()
            },
        );

        let result = manager
            .check_approval(&["unknown".to_string(), "command".to_string()])
            .await;
        assert_eq!(
            result,
            ExecApprovalRequirement::forbidden(REJECT_SANDBOX_APPROVAL_REASON)
        );
    }

    #[tokio::test]
    async fn test_trusted_patterns() {
        let dir = tempdir().unwrap();
        let manager = ExecPolicyManager::with_defaults(dir.path().to_path_buf());

        // Add trusted pattern
        let amendment = ExecPolicyAmendment::from_prefix("cargo");
        manager.add_trusted_pattern(amendment).await;

        // Check any cargo command
        let result = manager
            .check_approval(&["cargo".to_string(), "test".to_string()])
            .await;
        assert!(result.can_proceed());
    }

    #[tokio::test]
    async fn test_session_approval() {
        let dir = tempdir().unwrap();
        let manager = ExecPolicyManager::with_defaults(dir.path().to_path_buf());

        let cmd = vec!["git".to_string(), "status".to_string()];

        // Initially needs approval
        let result = manager.check_approval(&cmd).await;
        assert!(result.requires_approval());

        // Approve it
        manager.approve_command(&cmd).await;

        // Now it should skip
        let result = manager.check_approval(&cmd).await;
        assert!(result.can_proceed());

        // Clear approvals
        manager.clear_session_approvals().await;

        // Needs approval again
        let result = manager.check_approval(&cmd).await;
        assert!(result.requires_approval());
    }

    #[tokio::test]
    async fn test_heuristics() {
        let dir = tempdir().unwrap();
        let manager = ExecPolicyManager::with_defaults(dir.path().to_path_buf());

        // Safe command
        let result = manager.check_approval(&["ls".to_string()]).await;
        assert!(result.can_proceed());

        // Dangerous command (rm)
        let result = manager
            .check_approval(&["rm".to_string(), "-rf".to_string()])
            .await;
        assert!(result.is_forbidden());
    }
}