1use std::sync::Arc;
18
19use crate::adversarial_policy::{PolicyDecision, PolicyLlmClient, PolicyValidator};
20use crate::audit::{AuditEntry, AuditLogger, AuditResult, chrono_now};
21use crate::executor::{ClaimSource, ToolCall, ToolError, ToolExecutor, ToolOutput};
22use crate::registry::ToolDef;
23
24pub struct AdversarialPolicyGateExecutor<T: ToolExecutor> {
30 inner: T,
31 validator: Arc<PolicyValidator>,
32 llm: Arc<dyn PolicyLlmClient>,
33 audit: Option<Arc<AuditLogger>>,
34}
35
36impl<T: ToolExecutor + std::fmt::Debug> std::fmt::Debug for AdversarialPolicyGateExecutor<T> {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 f.debug_struct("AdversarialPolicyGateExecutor")
39 .field("inner", &self.inner)
40 .finish_non_exhaustive()
41 }
42}
43
44impl<T: ToolExecutor> AdversarialPolicyGateExecutor<T> {
45 #[must_use]
47 pub fn new(inner: T, validator: Arc<PolicyValidator>, llm: Arc<dyn PolicyLlmClient>) -> Self {
48 Self {
49 inner,
50 validator,
51 llm,
52 audit: None,
53 }
54 }
55
56 #[must_use]
58 pub fn with_audit(mut self, audit: Arc<AuditLogger>) -> Self {
59 self.audit = Some(audit);
60 self
61 }
62
63 async fn check_policy(&self, call: &ToolCall) -> Result<(), ToolError> {
64 tracing::info!(
65 tool = %call.tool_id,
66 status_spinner = true,
67 "Validating tool policy\u{2026}"
68 );
69
70 let decision = self
71 .validator
72 .validate(call.tool_id.as_str(), &call.params, self.llm.as_ref())
73 .await;
74
75 match decision {
76 PolicyDecision::Allow => {
77 tracing::debug!(tool = %call.tool_id, "adversarial policy: allow");
78 self.write_audit(call, "allow", AuditResult::Success, None)
79 .await;
80 Ok(())
81 }
82 PolicyDecision::Deny { reason } => {
83 tracing::warn!(
84 tool = %call.tool_id,
85 reason = %reason,
86 "adversarial policy: deny"
87 );
88 self.write_audit(
89 call,
90 &format!("deny:{reason}"),
91 AuditResult::Blocked {
92 reason: reason.clone(),
93 },
94 None,
95 )
96 .await;
97 Err(ToolError::Blocked {
99 command: "[adversarial] Tool call denied by policy".to_owned(),
100 })
101 }
102 PolicyDecision::Error { message } => {
103 tracing::warn!(
104 tool = %call.tool_id,
105 error = %message,
106 fail_open = self.validator.fail_open(),
107 "adversarial policy: LLM error"
108 );
109 if self.validator.fail_open() {
110 self.write_audit(
111 call,
112 &format!("error:{message}"),
113 AuditResult::Success,
114 None,
115 )
116 .await;
117 Ok(())
118 } else {
119 self.write_audit(
120 call,
121 &format!("error:{message}"),
122 AuditResult::Blocked {
123 reason: "adversarial policy LLM error (fail-closed)".to_owned(),
124 },
125 None,
126 )
127 .await;
128 Err(ToolError::Blocked {
129 command: "[adversarial] Tool call denied: policy check failed".to_owned(),
130 })
131 }
132 }
133 }
134 }
135
136 async fn write_audit(
137 &self,
138 call: &ToolCall,
139 decision: &str,
140 result: AuditResult,
141 claim_source: Option<ClaimSource>,
142 ) {
143 let Some(audit) = &self.audit else { return };
144 let entry = AuditEntry {
145 timestamp: chrono_now(),
146 tool: call.tool_id.clone(),
147 command: params_summary(&call.params),
148 result,
149 duration_ms: 0,
150 error_category: None,
151 error_domain: None,
152 error_phase: None,
153 claim_source,
154 mcp_server_id: None,
155 injection_flagged: false,
156 embedding_anomalous: false,
157 cross_boundary_mcp_to_acp: false,
158 adversarial_policy_decision: Some(decision.to_owned()),
159 exit_code: None,
160 truncated: false,
161 caller_id: call.caller_id.clone(),
162 policy_match: None,
163 correlation_id: None,
164 vigil_risk: None,
165 execution_env: None,
166 resolved_cwd: None,
167 scope_at_definition: None,
168 scope_at_dispatch: None,
169 };
170 audit.log(&entry).await;
171 }
172}
173
174impl<T: ToolExecutor> ToolExecutor for AdversarialPolicyGateExecutor<T> {
175 async fn execute(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
177 self.inner.execute(response).await
178 }
179
180 async fn execute_confirmed(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
181 self.inner.execute_confirmed(response).await
182 }
183
184 fn tool_definitions(&self) -> Vec<ToolDef> {
186 self.inner.tool_definitions()
187 }
188
189 async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
190 self.check_policy(call).await?;
191 let output = self.inner.execute_tool_call(call).await?;
192 if let Some(ref out) = output {
193 self.write_audit(
194 call,
195 "allow:executed",
196 AuditResult::Success,
197 out.claim_source,
198 )
199 .await;
200 }
201 Ok(output)
202 }
203
204 async fn execute_tool_call_confirmed(
206 &self,
207 call: &ToolCall,
208 ) -> Result<Option<ToolOutput>, ToolError> {
209 self.check_policy(call).await?;
210 let output = self.inner.execute_tool_call_confirmed(call).await?;
211 if let Some(ref out) = output {
212 self.write_audit(
213 call,
214 "allow:executed",
215 AuditResult::Success,
216 out.claim_source,
217 )
218 .await;
219 }
220 Ok(output)
221 }
222
223 fn set_skill_env(&self, env: Option<std::collections::HashMap<String, String>>) {
224 self.inner.set_skill_env(env);
225 }
226
227 fn set_effective_trust(&self, level: crate::SkillTrustLevel) {
228 self.inner.set_effective_trust(level);
229 }
230
231 fn is_tool_retryable(&self, tool_id: &str) -> bool {
232 self.inner.is_tool_retryable(tool_id)
233 }
234}
235
236fn params_summary(params: &serde_json::Map<String, serde_json::Value>) -> String {
237 let s = serde_json::to_string(params).unwrap_or_default();
238 if s.chars().count() > 500 {
239 let truncated: String = s.chars().take(497).collect();
240 format!("{truncated}\u{2026}")
241 } else {
242 s
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use std::future::Future;
249 use std::pin::Pin;
250 use std::sync::Arc;
251 use std::sync::atomic::{AtomicUsize, Ordering};
252 use std::time::Duration;
253
254 use super::*;
255 use crate::adversarial_policy::{PolicyMessage, PolicyValidator};
256 use crate::executor::{ToolCall, ToolOutput};
257
258 struct MockLlm {
261 response: String,
262 call_count: Arc<AtomicUsize>,
263 }
264
265 impl MockLlm {
266 fn new(response: impl Into<String>) -> (Arc<AtomicUsize>, Self) {
267 let counter = Arc::new(AtomicUsize::new(0));
268 let client = Self {
269 response: response.into(),
270 call_count: Arc::clone(&counter),
271 };
272 (counter, client)
273 }
274 }
275
276 impl PolicyLlmClient for MockLlm {
277 fn chat<'a>(
278 &'a self,
279 _messages: &'a [PolicyMessage],
280 ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>> {
281 self.call_count.fetch_add(1, Ordering::SeqCst);
282 let resp = self.response.clone();
283 Box::pin(async move { Ok(resp) })
284 }
285 }
286
287 #[derive(Debug)]
290 struct MockInner {
291 call_count: Arc<AtomicUsize>,
292 }
293
294 impl MockInner {
295 fn new() -> (Arc<AtomicUsize>, Self) {
296 let counter = Arc::new(AtomicUsize::new(0));
297 let exec = Self {
298 call_count: Arc::clone(&counter),
299 };
300 (counter, exec)
301 }
302 }
303
304 impl ToolExecutor for MockInner {
305 async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
306 Ok(None)
307 }
308
309 async fn execute_tool_call(
310 &self,
311 call: &ToolCall,
312 ) -> Result<Option<ToolOutput>, ToolError> {
313 self.call_count.fetch_add(1, Ordering::SeqCst);
314 Ok(Some(ToolOutput {
315 tool_name: call.tool_id.clone(),
316 summary: "ok".into(),
317 blocks_executed: 1,
318 filter_stats: None,
319 diff: None,
320 streamed: false,
321 terminal_id: None,
322 locations: None,
323 raw_response: None,
324 claim_source: None,
325 }))
326 }
327 }
328
329 fn make_call(tool_id: &str) -> ToolCall {
330 ToolCall {
331 tool_id: tool_id.into(),
332 params: serde_json::Map::new(),
333 caller_id: None,
334 context: None,
335 }
336 }
337
338 fn make_validator(fail_open: bool) -> Arc<PolicyValidator> {
339 Arc::new(PolicyValidator::new(
340 vec!["test policy".to_owned()],
341 Duration::from_millis(500),
342 fail_open,
343 Vec::new(),
344 ))
345 }
346
347 #[tokio::test]
348 async fn allow_path_delegates_to_inner() {
349 let (llm_count, llm) = MockLlm::new("ALLOW");
350 let (inner_count, inner) = MockInner::new();
351 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
352 let result = gate.execute_tool_call(&make_call("shell")).await;
353 assert!(result.is_ok());
354 assert_eq!(
355 llm_count.load(Ordering::SeqCst),
356 1,
357 "LLM must be called once"
358 );
359 assert_eq!(
360 inner_count.load(Ordering::SeqCst),
361 1,
362 "inner executor must be called on allow"
363 );
364 }
365
366 #[tokio::test]
367 async fn deny_path_blocks_and_does_not_call_inner() {
368 let (llm_count, llm) = MockLlm::new("DENY: unsafe command");
369 let (inner_count, inner) = MockInner::new();
370 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
371 let result = gate.execute_tool_call(&make_call("shell")).await;
372 assert!(matches!(result, Err(ToolError::Blocked { .. })));
373 assert_eq!(llm_count.load(Ordering::SeqCst), 1);
374 assert_eq!(
375 inner_count.load(Ordering::SeqCst),
376 0,
377 "inner must NOT be called on deny"
378 );
379 }
380
381 #[tokio::test]
382 async fn error_message_is_opaque() {
383 let (_, llm) = MockLlm::new("DENY: secret internal policy rule XYZ");
385 let (_, inner) = MockInner::new();
386 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
387 let err = gate
388 .execute_tool_call(&make_call("shell"))
389 .await
390 .unwrap_err();
391 if let ToolError::Blocked { command } = err {
392 assert!(
393 !command.contains("secret internal policy rule XYZ"),
394 "LLM denial reason must not leak to main LLM"
395 );
396 } else {
397 panic!("expected Blocked error");
398 }
399 }
400
401 #[tokio::test]
402 async fn fail_closed_blocks_on_llm_error() {
403 struct FailingLlm;
404 impl PolicyLlmClient for FailingLlm {
405 fn chat<'a>(
406 &'a self,
407 _: &'a [PolicyMessage],
408 ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>> {
409 Box::pin(async { Err("network error".to_owned()) })
410 }
411 }
412
413 let (_, inner) = MockInner::new();
414 let gate = AdversarialPolicyGateExecutor::new(
415 inner,
416 make_validator(false), Arc::new(FailingLlm),
418 );
419 let result = gate.execute_tool_call(&make_call("shell")).await;
420 assert!(
421 matches!(result, Err(ToolError::Blocked { .. })),
422 "fail-closed must block on LLM error"
423 );
424 }
425
426 #[tokio::test]
427 async fn fail_open_allows_on_llm_error() {
428 struct FailingLlm;
429 impl PolicyLlmClient for FailingLlm {
430 fn chat<'a>(
431 &'a self,
432 _: &'a [PolicyMessage],
433 ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>> {
434 Box::pin(async { Err("network error".to_owned()) })
435 }
436 }
437
438 let (inner_count, inner) = MockInner::new();
439 let gate = AdversarialPolicyGateExecutor::new(
440 inner,
441 make_validator(true), Arc::new(FailingLlm),
443 );
444 let result = gate.execute_tool_call(&make_call("shell")).await;
445 assert!(result.is_ok(), "fail-open must allow on LLM error");
446 assert_eq!(inner_count.load(Ordering::SeqCst), 1);
447 }
448
449 #[tokio::test]
450 async fn confirmed_also_enforces_policy() {
451 let (_, llm) = MockLlm::new("DENY: blocked");
452 let (_, inner) = MockInner::new();
453 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
454 let result = gate.execute_tool_call_confirmed(&make_call("shell")).await;
455 assert!(
456 matches!(result, Err(ToolError::Blocked { .. })),
457 "confirmed path must also enforce adversarial policy"
458 );
459 }
460
461 #[tokio::test]
462 async fn legacy_execute_bypasses_policy() {
463 let (llm_count, llm) = MockLlm::new("DENY: anything");
464 let (_, inner) = MockInner::new();
465 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
466 let result = gate.execute("```shell\necho hi\n```").await;
467 assert!(
468 result.is_ok(),
469 "legacy execute must bypass adversarial policy"
470 );
471 assert_eq!(
472 llm_count.load(Ordering::SeqCst),
473 0,
474 "LLM must NOT be called for legacy dispatch"
475 );
476 }
477
478 #[tokio::test]
479 async fn delegation_set_skill_env() {
480 let (_, llm) = MockLlm::new("ALLOW");
482 let (_, inner) = MockInner::new();
483 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
484 gate.set_skill_env(None);
485 }
486
487 #[tokio::test]
488 async fn delegation_set_effective_trust() {
489 use crate::SkillTrustLevel;
490 let (_, llm) = MockLlm::new("ALLOW");
491 let (_, inner) = MockInner::new();
492 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
493 gate.set_effective_trust(SkillTrustLevel::Trusted);
494 }
495
496 #[tokio::test]
497 async fn delegation_is_tool_retryable() {
498 let (_, llm) = MockLlm::new("ALLOW");
499 let (_, inner) = MockInner::new();
500 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
501 let retryable = gate.is_tool_retryable("shell");
502 assert!(!retryable, "MockInner returns false for is_tool_retryable");
503 }
504
505 #[tokio::test]
506 async fn delegation_tool_definitions() {
507 let (_, llm) = MockLlm::new("ALLOW");
508 let (_, inner) = MockInner::new();
509 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
510 let defs = gate.tool_definitions();
511 assert!(defs.is_empty(), "MockInner returns empty tool definitions");
512 }
513
514 #[tokio::test]
515 async fn audit_entry_contains_adversarial_decision() {
516 use tempfile::TempDir;
517
518 let dir = TempDir::new().unwrap();
519 let log_path = dir.path().join("audit.log");
520 let audit_config = crate::config::AuditConfig {
521 enabled: true,
522 destination: log_path.display().to_string(),
523 ..Default::default()
524 };
525 let audit_logger = Arc::new(
526 crate::audit::AuditLogger::from_config(&audit_config, false)
527 .await
528 .unwrap(),
529 );
530
531 let (_, llm) = MockLlm::new("ALLOW");
532 let (_, inner) = MockInner::new();
533 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm))
534 .with_audit(Arc::clone(&audit_logger));
535
536 gate.execute_tool_call(&make_call("shell")).await.unwrap();
537
538 let content = tokio::fs::read_to_string(&log_path).await.unwrap();
539 assert!(
540 content.contains("adversarial_policy_decision"),
541 "audit entry must contain adversarial_policy_decision field"
542 );
543 assert!(
544 content.contains("\"allow\""),
545 "allow decision must be recorded"
546 );
547 }
548
549 #[tokio::test]
550 async fn audit_entry_deny_contains_decision() {
551 use tempfile::TempDir;
552
553 let dir = TempDir::new().unwrap();
554 let log_path = dir.path().join("audit.log");
555 let audit_config = crate::config::AuditConfig {
556 enabled: true,
557 destination: log_path.display().to_string(),
558 ..Default::default()
559 };
560 let audit_logger = Arc::new(
561 crate::audit::AuditLogger::from_config(&audit_config, false)
562 .await
563 .unwrap(),
564 );
565
566 let (_, llm) = MockLlm::new("DENY: test denial");
567 let (_, inner) = MockInner::new();
568 let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm))
569 .with_audit(Arc::clone(&audit_logger));
570
571 let _ = gate.execute_tool_call(&make_call("shell")).await;
572
573 let content = tokio::fs::read_to_string(&log_path).await.unwrap();
574 assert!(
575 content.contains("deny:"),
576 "deny decision must be recorded in audit"
577 );
578 }
579
580 #[tokio::test]
581 async fn audit_entry_propagates_claim_source() {
582 use tempfile::TempDir;
583
584 #[derive(Debug)]
585 struct InnerWithClaimSource;
586
587 impl ToolExecutor for InnerWithClaimSource {
588 async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
589 Ok(None)
590 }
591
592 async fn execute_tool_call(
593 &self,
594 call: &ToolCall,
595 ) -> Result<Option<ToolOutput>, ToolError> {
596 Ok(Some(ToolOutput {
597 tool_name: call.tool_id.clone(),
598 summary: "ok".into(),
599 blocks_executed: 1,
600 filter_stats: None,
601 diff: None,
602 streamed: false,
603 terminal_id: None,
604 locations: None,
605 raw_response: None,
606 claim_source: Some(crate::executor::ClaimSource::Shell),
607 }))
608 }
609 }
610
611 let dir = TempDir::new().unwrap();
612 let log_path = dir.path().join("audit.log");
613 let audit_config = crate::config::AuditConfig {
614 enabled: true,
615 destination: log_path.display().to_string(),
616 ..Default::default()
617 };
618 let audit_logger = Arc::new(
619 crate::audit::AuditLogger::from_config(&audit_config, false)
620 .await
621 .unwrap(),
622 );
623
624 let (_, llm) = MockLlm::new("ALLOW");
625 let gate = AdversarialPolicyGateExecutor::new(
626 InnerWithClaimSource,
627 make_validator(false),
628 Arc::new(llm),
629 )
630 .with_audit(Arc::clone(&audit_logger));
631
632 gate.execute_tool_call(&make_call("shell")).await.unwrap();
633
634 let content = tokio::fs::read_to_string(&log_path).await.unwrap();
635 assert!(
636 content.contains("\"shell\""),
637 "claim_source must be propagated into the post-execution audit entry"
638 );
639 }
640}