Skip to main content

vtcode_safety/command_safety/
unified.rs

1//! Unified Command Evaluator - Phase 5
2//!
3//! Merges CommandPolicyEvaluator with command_safety module to provide
4//! comprehensive command validation combining:
5//! - Policy-based rules (allow/deny prefixes, regexes, globs)
6//! - Safety rules (subcommand validation, dangerous patterns)
7//! - Shell parsing (decompose complex scripts)
8//! - Audit logging & caching
9
10use crate::command_safety::{
11    AuditEntry, CommandDatabase, SafeCommandRegistry, SafetyAuditLogger, SafetyDecision, SafetyDecisionCache,
12    command_might_be_dangerous, parse_bash_lc_commands,
13};
14use anyhow::Result;
15use std::path::PathBuf;
16use std::sync::Arc;
17
18/// Detailed reason for evaluation result
19#[derive(Clone, Debug, PartialEq)]
20pub enum EvaluationReason {
21    /// Command allowed by policy rule
22    PolicyAllow(String),
23    /// Command denied by policy rule
24    PolicyDeny(String),
25    /// Command passed safety checks
26    SafetyAllow,
27    /// Command failed safety checks
28    SafetyDeny(String),
29    /// Hardcoded dangerous command detected
30    DangerousCommand(String),
31    /// Retrieved from cache
32    CacheHit(bool, String),
33}
34
35impl std::fmt::Display for EvaluationReason {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match self {
38            Self::PolicyAllow(msg) => write!(f, "Policy Allow: {msg}"),
39            Self::PolicyDeny(msg) => write!(f, "Policy Deny: {msg}"),
40            Self::SafetyAllow => write!(f, "Safety Allow"),
41            Self::SafetyDeny(msg) => write!(f, "Safety Deny: {msg}"),
42            Self::DangerousCommand(msg) => write!(f, "Dangerous: {msg}"),
43            Self::CacheHit(allowed, msg) => {
44                write!(f, "Cache {} {}", if *allowed { "Allow" } else { "Deny" }, msg)
45            }
46        }
47    }
48}
49
50/// Complete evaluation result
51#[derive(Clone, Debug)]
52pub struct EvaluationResult {
53    /// Whether the command is allowed
54    pub allowed: bool,
55    /// Primary reason for decision
56    pub primary_reason: EvaluationReason,
57    /// Secondary reasons (e.g., policy rule that matched)
58    pub(crate) secondary_reasons: Vec<String>,
59    /// Resolved command path (if available)
60    resolved_path: Option<PathBuf>,
61}
62
63/// Unified command evaluator combining policies and safety rules
64#[derive(Clone)]
65pub struct UnifiedCommandEvaluator {
66    // Safety components
67    registry: SafeCommandRegistry,
68    database: CommandDatabase,
69    cache: SafetyDecisionCache,
70    audit_logger: SafetyAuditLogger,
71}
72
73impl UnifiedCommandEvaluator {
74    async fn log_audit_entry(&self, command: &[String], allowed: bool, reason: impl Into<String>, decision_type: &str) {
75        self.audit_logger
76            .log(AuditEntry::new(command.to_vec(), allowed, reason.into(), decision_type.to_string()))
77            .await;
78    }
79
80    /// Create a new unified evaluator with default components
81    pub fn new() -> Self {
82        Self {
83            registry: SafeCommandRegistry::new(),
84            database: CommandDatabase,
85            cache: SafetyDecisionCache::new(1000),
86            audit_logger: SafetyAuditLogger::new(true),
87        }
88    }
89
90    /// Evaluate a command with full context (async)
91    ///
92    /// # Evaluation Pipeline
93    /// 1. Check cache
94    /// 2. Apply dangerous command detection
95    /// 3. Apply safety registry rules (with subcommand validation)
96    /// 4. Handle shell parsing if needed (bash -lc)
97    /// 5. Log audit entry (async)
98    /// 6. Cache result
99    pub(crate) async fn evaluate(&self, command: &[String]) -> Result<EvaluationResult> {
100        if command.is_empty() {
101            return Ok(EvaluationResult {
102                allowed: false,
103                primary_reason: EvaluationReason::SafetyDeny("empty command".into()),
104                secondary_reasons: vec![],
105                resolved_path: None,
106            });
107        }
108
109        // Length prefixes preserve argument boundaries even when arguments contain spaces.
110        let command_text: String = command.iter().map(|arg| format!("{}:{arg}", arg.len())).collect();
111
112        // 1. Check cache first
113        if let Some(cached_decision) = self.cache.get(&command_text).await {
114            let reason = EvaluationReason::CacheHit(cached_decision.is_safe, cached_decision.reason.clone());
115            // Note: Audit logging skipped for cached decisions (logged on original evaluation)
116            return Ok(EvaluationResult {
117                allowed: cached_decision.is_safe,
118                primary_reason: reason,
119                secondary_reasons: vec![],
120                resolved_path: None,
121            });
122        }
123
124        // 2. Check dangerous commands first (fail-fast)
125        if command_might_be_dangerous(command) {
126            let result = EvaluationResult {
127                allowed: false,
128                primary_reason: EvaluationReason::DangerousCommand("matches dangerous patterns".into()),
129                secondary_reasons: vec![],
130                resolved_path: None,
131            };
132            self.log_audit_entry(command, false, "matches dangerous patterns", "Dangerous")
133                .await;
134            self.cache
135                .put(command_text.clone(), false, "dangerous command pattern".into())
136                .await;
137            return Ok(result);
138        }
139
140        // 3. Apply safety registry rules
141        let registry_decision = self.registry.is_safe(command);
142        match registry_decision {
143            SafetyDecision::Deny(reason) => {
144                let result = EvaluationResult {
145                    allowed: false,
146                    primary_reason: EvaluationReason::SafetyDeny(reason.clone()),
147                    secondary_reasons: vec!["registry rule".into()],
148                    resolved_path: None,
149                };
150                self.log_audit_entry(command, false, reason.clone(), "Deny").await;
151                self.cache.put(command_text.clone(), false, reason.clone()).await;
152                return Ok(result);
153            }
154            SafetyDecision::Allow => {
155                // Passed registry, continue to database checks
156            }
157            SafetyDecision::Unknown => {
158                // Continue to database checks
159            }
160        }
161
162        // 4. Apply command database rules
163        // Note: Database rules are optional. Currently the registry covers the main use cases.
164        // In a production system, this would merge database rules with registry rules.
165        // For now, we skip explicit database check as the registry is comprehensive.
166
167        // 5. Handle shell parsing for bash -lc and similar patterns
168        // Note: For simplicity, we evaluate each sub-command non-recursively
169        // by applying the same checks. In production, this could be refactored to support recursion.
170        if let Some(scripts) = parse_bash_lc_commands(command) {
171            for script in scripts {
172                // Apply the same checks to each script without recursive call
173                if command_might_be_dangerous(&script) {
174                    let result = EvaluationResult {
175                        allowed: false,
176                        primary_reason: EvaluationReason::DangerousCommand(format!(
177                            "dangerous in sub-script: {}",
178                            script.join(" ")
179                        )),
180                        secondary_reasons: vec![],
181                        resolved_path: None,
182                    };
183                    self.cache
184                        .put(command_text.clone(), false, result.primary_reason.to_string())
185                        .await;
186                    return Ok(result);
187                }
188
189                // Check safety registry for sub-command
190                if let SafetyDecision::Deny(reason) = self.registry.is_safe(&script) {
191                    let result = EvaluationResult {
192                        allowed: false,
193                        primary_reason: EvaluationReason::SafetyDeny(format!("sub-command denied: {reason}")),
194                        secondary_reasons: vec![],
195                        resolved_path: None,
196                    };
197                    self.cache
198                        .put(command_text.clone(), false, result.primary_reason.to_string())
199                        .await;
200                    return Ok(result);
201                }
202            }
203        }
204
205        // 6. All checks passed
206        let result = EvaluationResult {
207            allowed: true,
208            primary_reason: EvaluationReason::SafetyAllow,
209            secondary_reasons: vec!["passed all safety checks".into()],
210            resolved_path: None,
211        };
212        self.log_audit_entry(command, true, "passed all safety checks", "Allow").await;
213        self.cache.put(command_text, true, "passed all safety checks".into()).await;
214        Ok(result)
215    }
216
217    /// Evaluate with explicit policy check (requires external CommandPolicyEvaluator)
218    ///
219    /// This is a placeholder for integration with CommandPolicyEvaluator.
220    /// In a real implementation, this would:
221    /// 1. Check policy rules first (deny precedence)
222    /// 2. Then apply safety rules
223    /// 3. Merge results
224    pub async fn evaluate_with_policy(
225        &self,
226        command: &[String],
227        policy_allowed: bool,
228        policy_reason: &str,
229    ) -> Result<EvaluationResult> {
230        // If policy explicitly denies, stop here
231        if !policy_allowed {
232            return Ok(EvaluationResult {
233                allowed: false,
234                primary_reason: EvaluationReason::PolicyDeny(policy_reason.into()),
235                secondary_reasons: vec![],
236                resolved_path: None,
237            });
238        }
239
240        // Policy allows, continue with safety checks
241        self.evaluate(command).await
242    }
243
244    /// Get reference to the cache for metrics/debugging
245    pub fn cache(&self) -> &SafetyDecisionCache {
246        &self.cache
247    }
248
249    /// Get reference to the audit logger
250    fn audit_logger(&self) -> &SafetyAuditLogger {
251        &self.audit_logger
252    }
253
254    /// Get reference to the registry
255    pub fn registry(&self) -> &SafeCommandRegistry {
256        &self.registry
257    }
258
259    /// Get reference to the database
260    pub fn database(&self) -> &CommandDatabase {
261        &self.database
262    }
263}
264
265impl Default for UnifiedCommandEvaluator {
266    fn default() -> Self {
267        Self::new()
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[tokio::test]
276    async fn empty_command_denied() {
277        let evaluator = UnifiedCommandEvaluator::new();
278        let result = evaluator.evaluate(&[]).await.unwrap();
279        assert!(!result.allowed);
280    }
281
282    #[tokio::test]
283    async fn dangerous_command_denied() {
284        let evaluator = UnifiedCommandEvaluator::new();
285        let result = evaluator
286            .evaluate(&["rm".to_string(), "-rf".to_string(), "/".to_string()])
287            .await
288            .unwrap();
289        assert!(!result.allowed);
290        matches!(result.primary_reason, EvaluationReason::DangerousCommand(_));
291    }
292
293    #[tokio::test]
294    async fn safe_command_allowed() {
295        let evaluator = UnifiedCommandEvaluator::new();
296        // git is in the default safe registry
297        let result = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
298        assert!(result.allowed);
299    }
300
301    #[tokio::test]
302    async fn cache_hit_on_repeated_command() {
303        let evaluator = UnifiedCommandEvaluator::new();
304        let cmd = vec!["git".to_string(), "status".to_string()];
305
306        // First evaluation
307        let result1 = evaluator.evaluate(&cmd).await.unwrap();
308        assert!(result1.allowed);
309
310        // Second evaluation (should be cached)
311        let result2 = evaluator.evaluate(&cmd).await.unwrap();
312        assert!(result2.allowed);
313        matches!(result2.primary_reason, EvaluationReason::CacheHit(true, _));
314        assert_eq!(evaluator.audit_logger().count().await, 1);
315    }
316
317    #[tokio::test]
318    async fn cache_keeps_argument_boundaries_in_both_orders() {
319        let safe = vec!["find".to_string(), ". -delete".to_string()];
320        let dangerous = vec!["find".to_string(), ".".to_string(), "-delete".to_string()];
321        for safe_first in [true, false] {
322            let evaluator = UnifiedCommandEvaluator::new();
323            let (first, second) = if safe_first {
324                (&safe, &dangerous)
325            } else {
326                (&dangerous, &safe)
327            };
328            assert_eq!(evaluator.evaluate(first).await.unwrap().allowed, safe_first);
329            assert_eq!(evaluator.evaluate(second).await.unwrap().allowed, !safe_first);
330        }
331    }
332
333    #[tokio::test]
334    async fn dangerous_command_is_audited() {
335        let evaluator = UnifiedCommandEvaluator::new();
336        drop(
337            evaluator
338                .evaluate(&["rm".to_string(), "-rf".to_string(), "/".to_string()])
339                .await
340                .unwrap(),
341        );
342
343        let entries = evaluator.audit_logger().entries().await;
344        assert_eq!(entries.len(), 1);
345        assert!(!entries[0].allowed);
346        assert_eq!(entries[0].decision_type, "Dangerous");
347    }
348
349    #[tokio::test]
350    async fn safe_command_is_audited() {
351        let evaluator = UnifiedCommandEvaluator::new();
352        drop(evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap());
353
354        let entries = evaluator.audit_logger().entries().await;
355        assert_eq!(entries.len(), 1);
356        assert!(entries[0].allowed);
357        assert_eq!(entries[0].decision_type, "Allow");
358    }
359
360    #[tokio::test]
361    async fn bash_lc_decomposition() {
362        let evaluator = UnifiedCommandEvaluator::new();
363        // bash -lc with mixed safe/unsafe commands
364        let cmd = vec![
365            "bash".to_string(),
366            "-lc".to_string(),
367            "git status && rm -rf /".to_string(),
368        ];
369        let result = evaluator.evaluate(&cmd).await.unwrap();
370        assert!(!result.allowed);
371        // Should detect the rm -rf in the sub-command
372    }
373
374    #[test]
375    fn evaluation_reason_display() {
376        let reason = EvaluationReason::PolicyAllow("test".into());
377        assert_eq!(reason.to_string(), "Policy Allow: test");
378
379        let reason = EvaluationReason::SafetyDeny("forbidden".into());
380        assert_eq!(reason.to_string(), "Safety Deny: forbidden");
381    }
382
383    #[tokio::test]
384    async fn policy_deny_stops_evaluation() {
385        let evaluator = UnifiedCommandEvaluator::new();
386        let result = evaluator
387            .evaluate_with_policy(&["git".to_string(), "status".to_string()], false, "policy blocked")
388            .await
389            .unwrap();
390        assert!(!result.allowed);
391        matches!(result.primary_reason, EvaluationReason::PolicyDeny(_));
392    }
393
394    #[tokio::test]
395    async fn policy_allow_continues_to_safety_checks() {
396        let evaluator = UnifiedCommandEvaluator::new();
397        let result = evaluator
398            .evaluate_with_policy(&["git".to_string(), "status".to_string()], true, "policy allowed")
399            .await
400            .unwrap();
401        // Policy allows, git status passes safety checks
402        assert!(result.allowed);
403    }
404
405    #[tokio::test]
406    async fn safety_deny_overrides_policy_allow() {
407        let evaluator = UnifiedCommandEvaluator::new();
408        let result = evaluator
409            .evaluate_with_policy(&["rm".to_string(), "-rf".to_string(), "/".to_string()], true, "policy allowed")
410            .await
411            .unwrap();
412        // Policy allows but safety rules deny
413        assert!(!result.allowed);
414        matches!(result.primary_reason, EvaluationReason::DangerousCommand(_));
415    }
416
417    #[tokio::test]
418    async fn evaluation_result_contains_reasons() {
419        let evaluator = UnifiedCommandEvaluator::new();
420        let result = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
421        assert!(result.allowed);
422        assert!(!result.secondary_reasons.is_empty());
423    }
424
425    #[tokio::test]
426    async fn forbidden_git_subcommand_denied() {
427        let evaluator = UnifiedCommandEvaluator::new();
428        // git push is not in the allowed subcommands for git
429        let result = evaluator.evaluate(&["git".to_string(), "push".to_string()]).await.unwrap();
430        assert!(!result.allowed);
431    }
432}
433
434/// Policy-aware evaluator adapter for backward compatibility with CommandPolicyEvaluator
435///
436/// This adapter wraps UnifiedCommandEvaluator with policy rule evaluation,
437/// allowing gradual migration from CommandPolicyEvaluator to UnifiedCommandEvaluator.
438#[derive(Clone)]
439pub struct PolicyAwareEvaluator {
440    unified: Arc<UnifiedCommandEvaluator>,
441    /// Policy allow decision (if Some, policy layer is active)
442    allow_policy_decision: Option<bool>,
443    policy_reason: Option<String>,
444}
445
446impl PolicyAwareEvaluator {
447    /// Create a new policy-aware evaluator with default components
448    pub(crate) fn new() -> Self {
449        Self {
450            unified: Arc::new(UnifiedCommandEvaluator::new()),
451            allow_policy_decision: None,
452            policy_reason: None,
453        }
454    }
455
456    /// Create with explicit policy decision
457    pub(crate) fn with_policy(allow_policy_decision: bool, policy_reason: impl Into<String>) -> Self {
458        Self {
459            unified: Arc::new(UnifiedCommandEvaluator::new()),
460            allow_policy_decision: Some(allow_policy_decision),
461            policy_reason: Some(policy_reason.into()),
462        }
463    }
464
465    /// Evaluate command with optional policy layer
466    pub(crate) async fn evaluate(&self, command: &[String]) -> Result<EvaluationResult> {
467        // Apply policy layer if configured
468        if let (Some(policy_allowed), Some(reason)) = (&self.allow_policy_decision, &self.policy_reason) {
469            self.unified.evaluate_with_policy(command, *policy_allowed, reason).await
470        } else {
471            // No policy configured, use pure safety evaluation
472            self.unified.evaluate(command).await
473        }
474    }
475
476    /// Set policy decision (allows updating policy after creation)
477    pub(crate) fn set_policy(&mut self, allowed: bool, reason: impl Into<String>) {
478        self.allow_policy_decision = Some(allowed);
479        self.policy_reason = Some(reason.into());
480    }
481
482    /// Clear policy decision (revert to pure safety evaluation)
483    pub(crate) fn clear_policy(&mut self) {
484        self.allow_policy_decision = None;
485        self.policy_reason = None;
486    }
487
488    /// Get reference to the underlying evaluator for advanced access
489    pub fn unified(&self) -> Arc<UnifiedCommandEvaluator> {
490        Arc::clone(&self.unified)
491    }
492}
493
494impl Default for PolicyAwareEvaluator {
495    fn default() -> Self {
496        Self::new()
497    }
498}
499
500#[cfg(test)]
501mod adapter_tests {
502    use super::*;
503
504    #[tokio::test]
505    async fn policy_aware_without_policy_uses_safety() {
506        let evaluator = PolicyAwareEvaluator::new();
507        let result = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
508        assert!(result.allowed);
509    }
510
511    #[tokio::test]
512    async fn policy_aware_with_deny_policy_blocks_safe_command() {
513        let evaluator = PolicyAwareEvaluator::with_policy(false, "policy blocked");
514        let result = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
515        assert!(!result.allowed);
516        matches!(result.primary_reason, EvaluationReason::PolicyDeny(_));
517    }
518
519    #[tokio::test]
520    async fn policy_aware_with_allow_policy_still_blocks_dangerous() {
521        let evaluator = PolicyAwareEvaluator::with_policy(true, "policy allowed");
522        let result = evaluator
523            .evaluate(&["rm".to_string(), "-rf".to_string(), "/".to_string()])
524            .await
525            .unwrap();
526        // Policy allows, but safety rules should deny
527        assert!(!result.allowed);
528    }
529
530    #[tokio::test]
531    async fn policy_aware_mutable_set_policy() {
532        let mut evaluator = PolicyAwareEvaluator::new();
533        // Initially no policy
534        let result1 = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
535        assert!(result1.allowed);
536
537        // Set deny policy
538        evaluator.set_policy(false, "policy blocked");
539        let result2 = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
540        assert!(!result2.allowed);
541
542        // Clear policy
543        evaluator.clear_policy();
544        let result3 = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
545        assert!(result3.allowed);
546    }
547}