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