1use 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#[derive(Clone, Debug, PartialEq)]
20pub enum EvaluationReason {
21 PolicyAllow(String),
23 PolicyDeny(String),
25 SafetyAllow,
27 SafetyDeny(String),
29 DangerousCommand(String),
31 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#[derive(Clone, Debug)]
52pub struct EvaluationResult {
53 pub allowed: bool,
55 pub primary_reason: EvaluationReason,
57 pub(crate) secondary_reasons: Vec<String>,
59 resolved_path: Option<PathBuf>,
61}
62
63#[derive(Clone)]
65pub struct UnifiedCommandEvaluator {
66 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 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 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 let command_text: String = command.iter().map(|arg| format!("{}:{arg}", arg.len())).collect();
111
112 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 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 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 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 }
157 SafetyDecision::Unknown => {
158 }
160 }
161
162 if let Some(scripts) = parse_bash_lc_commands(command) {
171 for script in scripts {
172 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 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 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 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_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 self.evaluate(command).await
242 }
243
244 pub fn cache(&self) -> &SafetyDecisionCache {
246 &self.cache
247 }
248
249 fn audit_logger(&self) -> &SafetyAuditLogger {
251 &self.audit_logger
252 }
253
254 pub fn registry(&self) -> &SafeCommandRegistry {
256 &self.registry
257 }
258
259 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 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 let result1 = evaluator.evaluate(&cmd).await.unwrap();
308 assert!(result1.allowed);
309
310 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 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 }
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 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 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 let result = evaluator.evaluate(&["git".to_string(), "push".to_string()]).await.unwrap();
430 assert!(!result.allowed);
431 }
432}
433
434#[derive(Clone)]
439pub struct PolicyAwareEvaluator {
440 unified: Arc<UnifiedCommandEvaluator>,
441 allow_policy_decision: Option<bool>,
443 policy_reason: Option<String>,
444}
445
446impl PolicyAwareEvaluator {
447 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 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 pub(crate) async fn evaluate(&self, command: &[String]) -> Result<EvaluationResult> {
467 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 self.unified.evaluate(command).await
473 }
474 }
475
476 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 pub(crate) fn clear_policy(&mut self) {
484 self.allow_policy_decision = None;
485 self.policy_reason = None;
486 }
487
488 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 assert!(!result.allowed);
528 }
529
530 #[tokio::test]
531 async fn policy_aware_mutable_set_policy() {
532 let mut evaluator = PolicyAwareEvaluator::new();
533 let result1 = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
535 assert!(result1.allowed);
536
537 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 evaluator.clear_policy();
544 let result3 = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
545 assert!(result3.allowed);
546 }
547}