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::sync::Arc;
16
17#[derive(Clone, Debug, PartialEq)]
19pub enum EvaluationReason {
20 PolicyAllow(String),
22 PolicyDeny(String),
24 SafetyAllow,
26 SafetyDeny(String),
28 DangerousCommand(String),
30 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#[derive(Clone, Debug)]
51pub struct EvaluationResult {
52 pub allowed: bool,
54 pub primary_reason: EvaluationReason,
56 pub(crate) secondary_reasons: Vec<String>,
58}
59
60#[derive(Clone)]
62pub struct UnifiedCommandEvaluator {
63 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 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 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 let command_text: String = command.iter().map(|arg| format!("{}:{arg}", arg.len())).collect();
107
108 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 return Ok(EvaluationResult {
113 allowed: cached_decision.is_safe,
114 primary_reason: reason,
115 secondary_reasons: vec![],
116 });
117 }
118
119 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 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 }
150 SafetyDecision::Unknown => {
151 }
153 }
154
155 if let Some(scripts) = parse_bash_lc_commands(command) {
164 for script in scripts {
165 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 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 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 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_allowed {
222 return Ok(EvaluationResult {
223 allowed: false,
224 primary_reason: EvaluationReason::PolicyDeny(policy_reason.into()),
225 secondary_reasons: vec![],
226 });
227 }
228
229 self.evaluate(command).await
231 }
232
233 pub fn cache(&self) -> &SafetyDecisionCache {
235 &self.cache
236 }
237
238 fn audit_logger(&self) -> &SafetyAuditLogger {
240 &self.audit_logger
241 }
242
243 pub fn registry(&self) -> &SafeCommandRegistry {
245 &self.registry
246 }
247
248 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 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 let result1 = evaluator.evaluate(&cmd).await.unwrap();
297 assert!(result1.allowed);
298
299 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 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 }
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 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 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 let result = evaluator.evaluate(&["git".to_string(), "push".to_string()]).await.unwrap();
419 assert!(!result.allowed);
420 }
421}
422
423#[derive(Clone)]
428pub struct PolicyAwareEvaluator {
429 unified: Arc<UnifiedCommandEvaluator>,
430 allow_policy_decision: Option<bool>,
432 policy_reason: Option<String>,
433}
434
435impl PolicyAwareEvaluator {
436 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 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 pub(crate) async fn evaluate(&self, command: &[String]) -> Result<EvaluationResult> {
456 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 self.unified.evaluate(command).await
462 }
463 }
464
465 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 pub(crate) fn clear_policy(&mut self) {
473 self.allow_policy_decision = None;
474 self.policy_reason = None;
475 }
476
477 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 assert!(!result.allowed);
517 }
518
519 #[tokio::test]
520 async fn policy_aware_mutable_set_policy() {
521 let mut evaluator = PolicyAwareEvaluator::new();
522 let result1 = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
524 assert!(result1.allowed);
525
526 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 evaluator.clear_policy();
533 let result3 = evaluator.evaluate(&["git".to_string(), "status".to_string()]).await.unwrap();
534 assert!(result3.allowed);
535 }
536}