Skip to main content

zeph_tools/
trust_gate.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Trust-level enforcement layer for tool execution.
5
6use std::collections::HashSet;
7use std::sync::{
8    Arc,
9    atomic::{AtomicU8, Ordering},
10};
11
12use parking_lot::RwLock;
13
14use crate::SkillTrustLevel;
15
16use crate::executor::{ToolCall, ToolError, ToolExecutor, ToolOutput};
17use crate::permissions::{AutonomyLevel, PermissionAction, PermissionPolicy};
18use crate::registry::ToolDef;
19
20/// Tools denied when a Quarantined skill is active.
21///
22/// Re-exported from `zeph_common::quarantine::QUARANTINE_DENIED` — the canonical definition
23/// lives there so both `zeph-skills` and `zeph-tools` can reference it without a dependency
24/// cycle.
25pub use zeph_common::quarantine::QUARANTINE_DENIED;
26
27fn is_quarantine_denied(tool_id: &str) -> bool {
28    QUARANTINE_DENIED
29        .iter()
30        .any(|denied| tool_id == *denied || tool_id.ends_with(&format!("_{denied}")))
31}
32
33fn trust_to_u8(level: SkillTrustLevel) -> u8 {
34    match level {
35        SkillTrustLevel::Trusted => 0,
36        SkillTrustLevel::Verified => 1,
37        SkillTrustLevel::Quarantined => 2,
38        SkillTrustLevel::Blocked => 3,
39    }
40}
41
42fn u8_to_trust(v: u8) -> SkillTrustLevel {
43    match v {
44        0 => SkillTrustLevel::Trusted,
45        1 => SkillTrustLevel::Verified,
46        2 => SkillTrustLevel::Quarantined,
47        _ => SkillTrustLevel::Blocked,
48    }
49}
50
51/// Wraps an inner `ToolExecutor` and applies trust-level permission overlays.
52pub struct TrustGateExecutor<T: ToolExecutor> {
53    inner: T,
54    policy: PermissionPolicy,
55    effective_trust: AtomicU8,
56    /// Sanitized IDs of all registered MCP tools. When a Quarantined skill is
57    /// active, any tool whose ID appears in this set is denied — regardless of
58    /// whether its name matches `QUARANTINE_DENIED`. Populated at startup by
59    /// calling `set_mcp_tool_ids` after MCP servers connect.
60    mcp_tool_ids: Arc<RwLock<HashSet<String>>>,
61}
62
63impl<T: ToolExecutor + std::fmt::Debug> std::fmt::Debug for TrustGateExecutor<T> {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.debug_struct("TrustGateExecutor")
66            .field("inner", &self.inner)
67            .field("policy", &self.policy)
68            .field("effective_trust", &self.effective_trust())
69            .field("mcp_tool_ids", &self.mcp_tool_ids)
70            .finish()
71    }
72}
73
74impl<T: ToolExecutor> TrustGateExecutor<T> {
75    #[must_use]
76    pub fn new(inner: T, policy: PermissionPolicy) -> Self {
77        Self {
78            inner,
79            policy,
80            effective_trust: AtomicU8::new(trust_to_u8(SkillTrustLevel::Trusted)),
81            mcp_tool_ids: Arc::new(RwLock::new(HashSet::new())),
82        }
83    }
84
85    /// Returns the shared MCP tool ID set so the caller can populate it after
86    /// MCP servers have connected (and after `TrustGateExecutor` has been wrapped
87    /// in a `DynExecutor`).
88    #[must_use]
89    pub fn mcp_tool_ids_handle(&self) -> Arc<RwLock<HashSet<String>>> {
90        Arc::clone(&self.mcp_tool_ids)
91    }
92
93    pub fn set_effective_trust(&self, level: SkillTrustLevel) {
94        self.effective_trust
95            .store(trust_to_u8(level), Ordering::Relaxed);
96    }
97
98    #[must_use]
99    pub fn effective_trust(&self) -> SkillTrustLevel {
100        u8_to_trust(self.effective_trust.load(Ordering::Relaxed))
101    }
102
103    fn is_mcp_tool(&self, tool_id: &str) -> bool {
104        self.mcp_tool_ids.read().contains(tool_id)
105    }
106
107    fn check_trust(&self, tool_id: &str, input: &str) -> Result<(), ToolError> {
108        match self.effective_trust() {
109            SkillTrustLevel::Blocked => {
110                return Err(ToolError::Blocked {
111                    command: "all tools blocked (trust=blocked)".to_owned(),
112                });
113            }
114            SkillTrustLevel::Quarantined => {
115                if is_quarantine_denied(tool_id) || self.is_mcp_tool(tool_id) {
116                    return Err(ToolError::Blocked {
117                        command: format!("{tool_id} denied (trust=quarantined)"),
118                    });
119                }
120            }
121            SkillTrustLevel::Trusted | SkillTrustLevel::Verified => {}
122        }
123
124        // PermissionPolicy was designed for the bash tool. In Supervised mode, tools
125        // without explicit rules default to Ask, which incorrectly blocks MCP/LSP tools.
126        // Skip the policy check for such tools — trust-level enforcement above is sufficient.
127        // ReadOnly mode is excluded: its allowlist is enforced inside policy.check().
128        if self.policy.autonomy_level() == AutonomyLevel::Supervised
129            && self.policy.rules().get(tool_id).is_none()
130        {
131            return Ok(());
132        }
133
134        match self.policy.check(tool_id, input) {
135            PermissionAction::Allow => Ok(()),
136            PermissionAction::Ask => Err(ToolError::ConfirmationRequired {
137                command: input.to_owned(),
138            }),
139            PermissionAction::Deny => Err(ToolError::Blocked {
140                command: input.to_owned(),
141            }),
142        }
143    }
144}
145
146impl<T: ToolExecutor> ToolExecutor for TrustGateExecutor<T> {
147    async fn execute(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
148        // The legacy fenced-block path does not provide a tool_id, so QUARANTINE_DENIED
149        // cannot be applied selectively. Block entirely for Quarantined to match the
150        // conservative posture: unknown tool identity = deny.
151        match self.effective_trust() {
152            SkillTrustLevel::Blocked | SkillTrustLevel::Quarantined => {
153                return Err(ToolError::Blocked {
154                    command: format!(
155                        "tool execution denied (trust={})",
156                        format!("{:?}", self.effective_trust()).to_lowercase()
157                    ),
158                });
159            }
160            SkillTrustLevel::Trusted | SkillTrustLevel::Verified => {}
161        }
162        self.inner.execute(response).await
163    }
164
165    async fn execute_confirmed(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
166        // Same rationale as execute(): no tool_id available for QUARANTINE_DENIED check.
167        match self.effective_trust() {
168            SkillTrustLevel::Blocked | SkillTrustLevel::Quarantined => {
169                return Err(ToolError::Blocked {
170                    command: format!(
171                        "tool execution denied (trust={})",
172                        format!("{:?}", self.effective_trust()).to_lowercase()
173                    ),
174                });
175            }
176            SkillTrustLevel::Trusted | SkillTrustLevel::Verified => {}
177        }
178        self.inner.execute_confirmed(response).await
179    }
180
181    fn tool_definitions(&self) -> Vec<ToolDef> {
182        self.inner.tool_definitions()
183    }
184
185    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
186        let input = call
187            .params
188            .get("command")
189            .or_else(|| call.params.get("file_path"))
190            .or_else(|| call.params.get("query"))
191            .or_else(|| call.params.get("url"))
192            .or_else(|| call.params.get("uri"))
193            .and_then(|v| v.as_str())
194            .unwrap_or("");
195        self.check_trust(call.tool_id.as_str(), input)?;
196        self.inner.execute_tool_call(call).await
197    }
198
199    async fn execute_tool_call_confirmed(
200        &self,
201        call: &ToolCall,
202    ) -> Result<Option<ToolOutput>, ToolError> {
203        // Bypass check_trust: caller already obtained user approval.
204        // Still enforce Blocked/Quarantined trust level constraints.
205        match self.effective_trust() {
206            SkillTrustLevel::Blocked => {
207                return Err(ToolError::Blocked {
208                    command: "all tools blocked (trust=blocked)".to_owned(),
209                });
210            }
211            SkillTrustLevel::Quarantined => {
212                if is_quarantine_denied(call.tool_id.as_str())
213                    || self.is_mcp_tool(call.tool_id.as_str())
214                {
215                    return Err(ToolError::Blocked {
216                        command: format!("{} denied (trust=quarantined)", call.tool_id),
217                    });
218                }
219            }
220            SkillTrustLevel::Trusted | SkillTrustLevel::Verified => {}
221        }
222        self.inner.execute_tool_call_confirmed(call).await
223    }
224
225    fn set_skill_env(&self, env: Option<std::collections::HashMap<String, String>>) {
226        self.inner.set_skill_env(env);
227    }
228
229    fn is_tool_retryable(&self, tool_id: &str) -> bool {
230        self.inner.is_tool_retryable(tool_id)
231    }
232
233    fn set_effective_trust(&self, level: crate::SkillTrustLevel) {
234        self.effective_trust
235            .store(trust_to_u8(level), Ordering::Relaxed);
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242
243    #[derive(Debug)]
244    struct MockExecutor;
245    impl ToolExecutor for MockExecutor {
246        async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
247            Ok(None)
248        }
249        async fn execute_tool_call(
250            &self,
251            call: &ToolCall,
252        ) -> Result<Option<ToolOutput>, ToolError> {
253            Ok(Some(ToolOutput {
254                tool_name: call.tool_id.clone(),
255                summary: "ok".into(),
256                blocks_executed: 1,
257                filter_stats: None,
258                diff: None,
259                streamed: false,
260                terminal_id: None,
261                locations: None,
262                raw_response: None,
263                claim_source: None,
264            }))
265        }
266    }
267
268    fn make_call(tool_id: &str) -> ToolCall {
269        ToolCall {
270            tool_id: tool_id.into(),
271            params: serde_json::Map::new(),
272            caller_id: None,
273        }
274    }
275
276    fn make_call_with_cmd(tool_id: &str, cmd: &str) -> ToolCall {
277        let mut params = serde_json::Map::new();
278        params.insert("command".into(), serde_json::Value::String(cmd.into()));
279        ToolCall {
280            tool_id: tool_id.into(),
281            params,
282            caller_id: None,
283        }
284    }
285
286    #[tokio::test]
287    async fn trusted_allows_all() {
288        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
289        gate.set_effective_trust(SkillTrustLevel::Trusted);
290
291        let result = gate.execute_tool_call(&make_call("bash")).await;
292        // Default policy has no rules for bash => skip policy check => Ok
293        assert!(result.is_ok());
294    }
295
296    #[tokio::test]
297    async fn quarantined_denies_bash() {
298        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
299        gate.set_effective_trust(SkillTrustLevel::Quarantined);
300
301        let result = gate.execute_tool_call(&make_call("bash")).await;
302        assert!(matches!(result, Err(ToolError::Blocked { .. })));
303    }
304
305    #[tokio::test]
306    async fn quarantined_denies_write() {
307        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
308        gate.set_effective_trust(SkillTrustLevel::Quarantined);
309
310        let result = gate.execute_tool_call(&make_call("write")).await;
311        assert!(matches!(result, Err(ToolError::Blocked { .. })));
312    }
313
314    #[tokio::test]
315    async fn quarantined_denies_edit() {
316        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
317        gate.set_effective_trust(SkillTrustLevel::Quarantined);
318
319        let result = gate.execute_tool_call(&make_call("edit")).await;
320        assert!(matches!(result, Err(ToolError::Blocked { .. })));
321    }
322
323    #[tokio::test]
324    async fn quarantined_denies_delete_path() {
325        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
326        gate.set_effective_trust(SkillTrustLevel::Quarantined);
327
328        let result = gate.execute_tool_call(&make_call("delete_path")).await;
329        assert!(matches!(result, Err(ToolError::Blocked { .. })));
330    }
331
332    #[tokio::test]
333    async fn quarantined_denies_fetch() {
334        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
335        gate.set_effective_trust(SkillTrustLevel::Quarantined);
336
337        let result = gate.execute_tool_call(&make_call("fetch")).await;
338        assert!(matches!(result, Err(ToolError::Blocked { .. })));
339    }
340
341    #[tokio::test]
342    async fn quarantined_denies_memory_save() {
343        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
344        gate.set_effective_trust(SkillTrustLevel::Quarantined);
345
346        let result = gate.execute_tool_call(&make_call("memory_save")).await;
347        assert!(matches!(result, Err(ToolError::Blocked { .. })));
348    }
349
350    #[tokio::test]
351    async fn quarantined_allows_read() {
352        let policy = crate::permissions::PermissionPolicy::from_legacy(&[], &[]);
353        let gate = TrustGateExecutor::new(MockExecutor, policy);
354        gate.set_effective_trust(SkillTrustLevel::Quarantined);
355
356        // "read" (file read) is not in QUARANTINE_DENIED — should be allowed
357        let result = gate.execute_tool_call(&make_call("read")).await;
358        assert!(result.is_ok());
359    }
360
361    #[tokio::test]
362    async fn quarantined_allows_file_read() {
363        let policy = crate::permissions::PermissionPolicy::from_legacy(&[], &[]);
364        let gate = TrustGateExecutor::new(MockExecutor, policy);
365        gate.set_effective_trust(SkillTrustLevel::Quarantined);
366
367        let result = gate.execute_tool_call(&make_call("file_read")).await;
368        // file_read is not in quarantine denied list, and policy has no rules for file_read => Ok
369        assert!(result.is_ok());
370    }
371
372    #[tokio::test]
373    async fn blocked_denies_everything() {
374        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
375        gate.set_effective_trust(SkillTrustLevel::Blocked);
376
377        let result = gate.execute_tool_call(&make_call("file_read")).await;
378        assert!(matches!(result, Err(ToolError::Blocked { .. })));
379    }
380
381    #[tokio::test]
382    async fn policy_deny_overrides_trust() {
383        let policy = crate::permissions::PermissionPolicy::from_legacy(&["sudo".into()], &[]);
384        let gate = TrustGateExecutor::new(MockExecutor, policy);
385        gate.set_effective_trust(SkillTrustLevel::Trusted);
386
387        let result = gate
388            .execute_tool_call(&make_call_with_cmd("bash", "sudo rm"))
389            .await;
390        assert!(matches!(result, Err(ToolError::Blocked { .. })));
391    }
392
393    #[tokio::test]
394    async fn blocked_denies_execute() {
395        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
396        gate.set_effective_trust(SkillTrustLevel::Blocked);
397
398        let result = gate.execute("some response").await;
399        assert!(matches!(result, Err(ToolError::Blocked { .. })));
400    }
401
402    #[tokio::test]
403    async fn blocked_denies_execute_confirmed() {
404        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
405        gate.set_effective_trust(SkillTrustLevel::Blocked);
406
407        let result = gate.execute_confirmed("some response").await;
408        assert!(matches!(result, Err(ToolError::Blocked { .. })));
409    }
410
411    #[tokio::test]
412    async fn trusted_allows_execute() {
413        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
414        gate.set_effective_trust(SkillTrustLevel::Trusted);
415
416        let result = gate.execute("some response").await;
417        assert!(result.is_ok());
418    }
419
420    #[tokio::test]
421    async fn verified_with_allow_policy_succeeds() {
422        let policy = crate::permissions::PermissionPolicy::from_legacy(&[], &[]);
423        let gate = TrustGateExecutor::new(MockExecutor, policy);
424        gate.set_effective_trust(SkillTrustLevel::Verified);
425
426        let result = gate
427            .execute_tool_call(&make_call_with_cmd("bash", "echo hi"))
428            .await
429            .unwrap();
430        assert!(result.is_some());
431    }
432
433    #[tokio::test]
434    async fn quarantined_denies_web_scrape() {
435        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
436        gate.set_effective_trust(SkillTrustLevel::Quarantined);
437
438        let result = gate.execute_tool_call(&make_call("web_scrape")).await;
439        assert!(matches!(result, Err(ToolError::Blocked { .. })));
440    }
441
442    #[derive(Debug)]
443    struct EnvCapture {
444        captured: std::sync::Mutex<Option<std::collections::HashMap<String, String>>>,
445    }
446    impl EnvCapture {
447        fn new() -> Self {
448            Self {
449                captured: std::sync::Mutex::new(None),
450            }
451        }
452    }
453    impl ToolExecutor for EnvCapture {
454        async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
455            Ok(None)
456        }
457        async fn execute_tool_call(&self, _: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
458            Ok(None)
459        }
460        fn set_skill_env(&self, env: Option<std::collections::HashMap<String, String>>) {
461            *self.captured.lock().unwrap() = env;
462        }
463    }
464
465    #[test]
466    fn is_tool_retryable_delegated_to_inner() {
467        #[derive(Debug)]
468        struct RetryableExecutor;
469        impl ToolExecutor for RetryableExecutor {
470            async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
471                Ok(None)
472            }
473            async fn execute_tool_call(
474                &self,
475                _: &ToolCall,
476            ) -> Result<Option<ToolOutput>, ToolError> {
477                Ok(None)
478            }
479            fn is_tool_retryable(&self, tool_id: &str) -> bool {
480                tool_id == "fetch"
481            }
482        }
483        let gate = TrustGateExecutor::new(RetryableExecutor, PermissionPolicy::default());
484        assert!(gate.is_tool_retryable("fetch"));
485        assert!(!gate.is_tool_retryable("bash"));
486    }
487
488    #[test]
489    fn set_skill_env_forwarded_to_inner() {
490        let inner = EnvCapture::new();
491        let gate = TrustGateExecutor::new(inner, PermissionPolicy::default());
492
493        let mut env = std::collections::HashMap::new();
494        env.insert("MY_VAR".to_owned(), "42".to_owned());
495        gate.set_skill_env(Some(env.clone()));
496
497        let captured = gate.inner.captured.lock().unwrap();
498        assert_eq!(*captured, Some(env));
499    }
500
501    #[tokio::test]
502    async fn mcp_tool_supervised_no_rules_allows() {
503        // MCP tool with Supervised mode + from_legacy policy (no rules for MCP tool) => Ok
504        let policy = crate::permissions::PermissionPolicy::from_legacy(&[], &[]);
505        let gate = TrustGateExecutor::new(MockExecutor, policy);
506        gate.set_effective_trust(SkillTrustLevel::Trusted);
507
508        let mut params = serde_json::Map::new();
509        params.insert(
510            "file_path".into(),
511            serde_json::Value::String("/tmp/test.txt".into()),
512        );
513        let call = ToolCall {
514            tool_id: "mcp_filesystem__read_file".into(),
515            params,
516            caller_id: None,
517        };
518        let result = gate.execute_tool_call(&call).await;
519        assert!(
520            result.is_ok(),
521            "MCP tool should be allowed when no rules exist"
522        );
523    }
524
525    #[tokio::test]
526    async fn bash_with_explicit_deny_rule_blocked() {
527        // Bash with explicit Deny rule => Err(ToolCallBlocked)
528        let policy = crate::permissions::PermissionPolicy::from_legacy(&["sudo".into()], &[]);
529        let gate = TrustGateExecutor::new(MockExecutor, policy);
530        gate.set_effective_trust(SkillTrustLevel::Trusted);
531
532        let result = gate
533            .execute_tool_call(&make_call_with_cmd("bash", "sudo apt install vim"))
534            .await;
535        assert!(
536            matches!(result, Err(ToolError::Blocked { .. })),
537            "bash with explicit deny rule should be blocked"
538        );
539    }
540
541    #[tokio::test]
542    async fn bash_with_explicit_allow_rule_succeeds() {
543        // Tool with explicit Allow rules => Ok
544        let policy = crate::permissions::PermissionPolicy::from_legacy(&[], &[]);
545        let gate = TrustGateExecutor::new(MockExecutor, policy);
546        gate.set_effective_trust(SkillTrustLevel::Trusted);
547
548        let result = gate
549            .execute_tool_call(&make_call_with_cmd("bash", "echo hello"))
550            .await;
551        assert!(
552            result.is_ok(),
553            "bash with explicit allow rule should succeed"
554        );
555    }
556
557    #[tokio::test]
558    async fn readonly_denies_mcp_tool_not_in_allowlist() {
559        // ReadOnly mode must deny tools not in READONLY_TOOLS, even MCP ones.
560        let policy =
561            crate::permissions::PermissionPolicy::default().with_autonomy(AutonomyLevel::ReadOnly);
562        let gate = TrustGateExecutor::new(MockExecutor, policy);
563        gate.set_effective_trust(SkillTrustLevel::Trusted);
564
565        let result = gate
566            .execute_tool_call(&make_call("mcpls_get_diagnostics"))
567            .await;
568        assert!(
569            matches!(result, Err(ToolError::Blocked { .. })),
570            "ReadOnly mode must deny non-allowlisted tools"
571        );
572    }
573
574    #[test]
575    fn set_effective_trust_interior_mutability() {
576        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
577        assert_eq!(gate.effective_trust(), SkillTrustLevel::Trusted);
578
579        gate.set_effective_trust(SkillTrustLevel::Quarantined);
580        assert_eq!(gate.effective_trust(), SkillTrustLevel::Quarantined);
581
582        gate.set_effective_trust(SkillTrustLevel::Blocked);
583        assert_eq!(gate.effective_trust(), SkillTrustLevel::Blocked);
584
585        gate.set_effective_trust(SkillTrustLevel::Trusted);
586        assert_eq!(gate.effective_trust(), SkillTrustLevel::Trusted);
587    }
588
589    // is_quarantine_denied unit tests
590
591    #[test]
592    fn is_quarantine_denied_exact_match() {
593        assert!(is_quarantine_denied("bash"));
594        assert!(is_quarantine_denied("write"));
595        assert!(is_quarantine_denied("fetch"));
596        assert!(is_quarantine_denied("memory_save"));
597        assert!(is_quarantine_denied("delete_path"));
598        assert!(is_quarantine_denied("create_directory"));
599    }
600
601    #[test]
602    fn is_quarantine_denied_suffix_match_mcp_write() {
603        // "filesystem_write" ends with "_write" -> denied
604        assert!(is_quarantine_denied("filesystem_write"));
605        // "filesystem_write_file" ends with "_file", not "_write" -> NOT denied
606        assert!(!is_quarantine_denied("filesystem_write_file"));
607    }
608
609    #[test]
610    fn is_quarantine_denied_suffix_mcp_bash() {
611        assert!(is_quarantine_denied("shell_bash"));
612        assert!(is_quarantine_denied("mcp_shell_bash"));
613    }
614
615    #[test]
616    fn is_quarantine_denied_suffix_mcp_fetch() {
617        assert!(is_quarantine_denied("http_fetch"));
618        // "server_prefetch" ends with "_prefetch", not "_fetch"
619        assert!(!is_quarantine_denied("server_prefetch"));
620    }
621
622    #[test]
623    fn is_quarantine_denied_suffix_mcp_memory_save() {
624        assert!(is_quarantine_denied("server_memory_save"));
625        // "_save" alone does NOT match the multi-word entry "memory_save"
626        assert!(!is_quarantine_denied("server_save"));
627    }
628
629    #[test]
630    fn is_quarantine_denied_suffix_mcp_delete_path() {
631        assert!(is_quarantine_denied("fs_delete_path"));
632        // "fs_not_delete_path" ends with "_delete_path" as well — suffix check is correct
633        assert!(is_quarantine_denied("fs_not_delete_path"));
634    }
635
636    #[test]
637    fn is_quarantine_denied_substring_not_suffix() {
638        // "write_log" ends with "_log", NOT "_write" — must NOT be denied
639        assert!(!is_quarantine_denied("write_log"));
640    }
641
642    #[test]
643    fn is_quarantine_denied_read_only_tools_allowed() {
644        assert!(!is_quarantine_denied("filesystem_read_file"));
645        assert!(!is_quarantine_denied("filesystem_list_dir"));
646        assert!(!is_quarantine_denied("read"));
647        assert!(!is_quarantine_denied("file_read"));
648    }
649
650    #[tokio::test]
651    async fn quarantined_denies_mcp_write_tool() {
652        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
653        gate.set_effective_trust(SkillTrustLevel::Quarantined);
654
655        let result = gate.execute_tool_call(&make_call("filesystem_write")).await;
656        assert!(matches!(result, Err(ToolError::Blocked { .. })));
657    }
658
659    #[tokio::test]
660    async fn quarantined_allows_mcp_read_file() {
661        let policy = crate::permissions::PermissionPolicy::from_legacy(&[], &[]);
662        let gate = TrustGateExecutor::new(MockExecutor, policy);
663        gate.set_effective_trust(SkillTrustLevel::Quarantined);
664
665        let result = gate
666            .execute_tool_call(&make_call("filesystem_read_file"))
667            .await;
668        assert!(result.is_ok());
669    }
670
671    #[tokio::test]
672    async fn quarantined_denies_mcp_bash_tool() {
673        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
674        gate.set_effective_trust(SkillTrustLevel::Quarantined);
675
676        let result = gate.execute_tool_call(&make_call("shell_bash")).await;
677        assert!(matches!(result, Err(ToolError::Blocked { .. })));
678    }
679
680    #[tokio::test]
681    async fn quarantined_denies_mcp_memory_save() {
682        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
683        gate.set_effective_trust(SkillTrustLevel::Quarantined);
684
685        let result = gate
686            .execute_tool_call(&make_call("server_memory_save"))
687            .await;
688        assert!(matches!(result, Err(ToolError::Blocked { .. })));
689    }
690
691    #[tokio::test]
692    async fn quarantined_denies_mcp_confirmed_path() {
693        // execute_tool_call_confirmed also enforces quarantine via is_quarantine_denied
694        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
695        gate.set_effective_trust(SkillTrustLevel::Quarantined);
696
697        let result = gate
698            .execute_tool_call_confirmed(&make_call("filesystem_write"))
699            .await;
700        assert!(matches!(result, Err(ToolError::Blocked { .. })));
701    }
702
703    // mcp_tool_ids registry tests
704
705    fn gate_with_mcp_ids(ids: &[&str]) -> TrustGateExecutor<MockExecutor> {
706        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
707        let handle = gate.mcp_tool_ids_handle();
708        let set: std::collections::HashSet<String> = ids.iter().map(ToString::to_string).collect();
709        *handle.write() = set;
710        gate
711    }
712
713    #[tokio::test]
714    async fn quarantined_denies_registered_mcp_tool_novel_name() {
715        // "github_run_command" has no QUARANTINE_DENIED suffix match, but is registered as MCP.
716        let gate = gate_with_mcp_ids(&["github_run_command"]);
717        gate.set_effective_trust(SkillTrustLevel::Quarantined);
718
719        let result = gate
720            .execute_tool_call(&make_call("github_run_command"))
721            .await;
722        assert!(matches!(result, Err(ToolError::Blocked { .. })));
723    }
724
725    #[tokio::test]
726    async fn quarantined_denies_registered_mcp_tool_execute() {
727        // "shell_execute" — no suffix match on "execute", but registered as MCP.
728        let gate = gate_with_mcp_ids(&["shell_execute"]);
729        gate.set_effective_trust(SkillTrustLevel::Quarantined);
730
731        let result = gate.execute_tool_call(&make_call("shell_execute")).await;
732        assert!(matches!(result, Err(ToolError::Blocked { .. })));
733    }
734
735    #[tokio::test]
736    async fn quarantined_allows_unregistered_tool_not_in_denied_list() {
737        // Tool not in MCP set and not in QUARANTINE_DENIED — allowed.
738        let gate = gate_with_mcp_ids(&["other_tool"]);
739        gate.set_effective_trust(SkillTrustLevel::Quarantined);
740
741        let result = gate.execute_tool_call(&make_call("read")).await;
742        assert!(result.is_ok());
743    }
744
745    #[tokio::test]
746    async fn trusted_allows_registered_mcp_tool() {
747        // At Trusted level, MCP registry check must NOT fire.
748        let gate = gate_with_mcp_ids(&["github_run_command"]);
749        gate.set_effective_trust(SkillTrustLevel::Trusted);
750
751        let result = gate
752            .execute_tool_call(&make_call("github_run_command"))
753            .await;
754        assert!(result.is_ok());
755    }
756
757    #[tokio::test]
758    async fn quarantined_denies_mcp_tool_via_confirmed_path() {
759        // execute_tool_call_confirmed must also check the MCP registry.
760        let gate = gate_with_mcp_ids(&["docker_container_exec"]);
761        gate.set_effective_trust(SkillTrustLevel::Quarantined);
762
763        let result = gate
764            .execute_tool_call_confirmed(&make_call("docker_container_exec"))
765            .await;
766        assert!(matches!(result, Err(ToolError::Blocked { .. })));
767    }
768
769    #[test]
770    fn mcp_tool_ids_handle_shared_arc() {
771        let gate = TrustGateExecutor::new(MockExecutor, PermissionPolicy::default());
772        let handle = gate.mcp_tool_ids_handle();
773        handle.write().insert("test_tool".to_owned());
774        assert!(gate.is_mcp_tool("test_tool"));
775        assert!(!gate.is_mcp_tool("other_tool"));
776    }
777}