Skip to main content

adk_guardrail/
tool.rs

1//! Guardrails for tool calls.
2//!
3//! [`Guardrail`] validates [`Content`](adk_core::Content) — a user message or a
4//! model response. It never sees a tool call, so it cannot express "this tool may run, but not
5//! with these arguments." That left argument-level policy with nowhere to live:
6//! [`ToolConfirmationPolicy`](adk_core::ToolConfirmationPolicy) decides per *tool name*, and a
7//! plugin short-circuit is a general-purpose hook rather than a stated policy.
8//!
9//! [`ToolGuardrail`] closes that gap. It runs before a tool executes, sees the tool name and the
10//! arguments, and can allow, deny, or revise. After the tool runs, it sees the result too
11//! ([`ToolGuardrail::validate_result`]) and can deliver, rewrite, or withhold it before the model
12//! and the session see it.
13
14use std::collections::VecDeque;
15use std::path::{Component, Path, PathBuf};
16use std::sync::Arc;
17
18use async_trait::async_trait;
19use regex::Regex;
20use serde_json::Value;
21
22use crate::{Guardrail, GuardrailResult, Severity};
23
24/// Outcome of validating a tool call.
25#[derive(Debug, Clone)]
26pub enum ToolGuardrailResult {
27    /// The call may proceed unchanged.
28    Allow,
29    /// The call is refused. The tool does not run.
30    Deny {
31        /// Why the call was refused. Surfaced to the model so it can adjust.
32        reason: String,
33        /// How serious the violation is.
34        severity: Severity,
35    },
36    /// The call may proceed, with these arguments instead.
37    ///
38    /// Use for narrowing rather than broadening — clamping a limit, forcing a dry-run flag,
39    /// dropping a field the caller should not set.
40    ReviseArgs {
41        /// Arguments the tool is invoked with.
42        args: Value,
43        /// Why the arguments were changed.
44        reason: String,
45    },
46}
47
48impl ToolGuardrailResult {
49    /// Refuses the call.
50    pub fn deny(reason: impl Into<String>, severity: Severity) -> Self {
51        Self::Deny { reason: reason.into(), severity }
52    }
53
54    /// Allows the call with replaced arguments.
55    pub fn revise(args: Value, reason: impl Into<String>) -> Self {
56        Self::ReviseArgs { args, reason: reason.into() }
57    }
58
59    /// Whether the call may proceed.
60    pub fn is_allowed(&self) -> bool {
61        !matches!(self, Self::Deny { .. })
62    }
63}
64
65/// Outcome of validating a tool's result.
66#[derive(Debug, Clone)]
67pub enum ToolResultGuardrailResult {
68    /// The result is delivered unchanged.
69    Allow,
70    /// The result is withheld. The model is told the tool ran and why its result is withheld.
71    Withhold {
72        /// Why the result was withheld. Surfaced to the model, so it must not quote the result.
73        reason: String,
74        /// How serious the violation is.
75        severity: Severity,
76    },
77    /// The result is delivered as `result` instead, such as with personal data redacted.
78    Revise {
79        /// The result the model and the session see.
80        result: Value,
81        /// Why the result was changed.
82        reason: String,
83    },
84}
85
86impl ToolResultGuardrailResult {
87    /// Withholds the result.
88    pub fn withhold(reason: impl Into<String>, severity: Severity) -> Self {
89        Self::Withhold { reason: reason.into(), severity }
90    }
91
92    /// Delivers `result` in place of the tool's result.
93    pub fn revise(result: Value, reason: impl Into<String>) -> Self {
94        Self::Revise { result, reason: reason.into() }
95    }
96}
97
98/// Validates a tool call before it executes.
99///
100/// # Example
101///
102/// ```rust
103/// use adk_guardrail::{Severity, ToolGuardrail, ToolGuardrailResult};
104/// use async_trait::async_trait;
105/// use serde_json::Value;
106///
107/// /// Refuses a recursive delete regardless of which tool is asked to perform it.
108/// struct NoRecursiveDelete;
109///
110/// #[async_trait]
111/// impl ToolGuardrail for NoRecursiveDelete {
112///     fn name(&self) -> &str {
113///         "no-recursive-delete"
114///     }
115///
116///     async fn validate_call(&self, _tool: &str, args: &Value) -> ToolGuardrailResult {
117///         if args.to_string().contains("-rf") {
118///             return ToolGuardrailResult::deny("recursive delete is not permitted", Severity::Critical);
119///         }
120///         ToolGuardrailResult::Allow
121///     }
122/// }
123/// ```
124#[async_trait]
125pub trait ToolGuardrail: Send + Sync {
126    /// Unique name, used in denial messages and logs.
127    fn name(&self) -> &str;
128
129    /// Validates a call to `tool_name` with `args`. Defaults to allowing every call, for a
130    /// guardrail that screens only results.
131    async fn validate_call(&self, _tool_name: &str, _args: &Value) -> ToolGuardrailResult {
132        ToolGuardrailResult::Allow
133    }
134
135    /// Validates the result of a call to `tool_name` with `args`, before the model and the
136    /// session see it. Defaults to delivering every result.
137    ///
138    /// The agent runs it on the result it is about to send, after its after-tool callbacks and
139    /// plugins, and on a tool's error response too. `args` are the arguments the model sent.
140    ///
141    /// # Example
142    ///
143    /// ```rust
144    /// use adk_guardrail::{Severity, ToolGuardrail, ToolResultGuardrailResult};
145    /// use async_trait::async_trait;
146    /// use serde_json::Value;
147    ///
148    /// /// Withholds any result that carries a card number field.
149    /// struct NoCardNumbers;
150    ///
151    /// #[async_trait]
152    /// impl ToolGuardrail for NoCardNumbers {
153    ///     fn name(&self) -> &str {
154    ///         "no-card-numbers"
155    ///     }
156    ///
157    ///     async fn validate_result(
158    ///         &self,
159    ///         _tool: &str,
160    ///         _args: &Value,
161    ///         result: &Value,
162    ///     ) -> ToolResultGuardrailResult {
163    ///         if result.get("card_number").is_some() {
164    ///             return ToolResultGuardrailResult::withhold("the result carries a card number", Severity::High);
165    ///         }
166    ///         ToolResultGuardrailResult::Allow
167    ///     }
168    /// }
169    /// ```
170    async fn validate_result(
171        &self,
172        _tool_name: &str,
173        _args: &Value,
174        _result: &Value,
175    ) -> ToolResultGuardrailResult {
176        ToolResultGuardrailResult::Allow
177    }
178
179    /// Whether this guardrail applies to `tool_name`. Defaults to every tool.
180    ///
181    /// Prefer this over an early `Allow` inside
182    /// [`validate_call`](Self::validate_call) — a guardrail that declares its scope can be skipped
183    /// without being run.
184    fn applies_to(&self, _tool_name: &str) -> bool {
185        true
186    }
187}
188
189/// What a [`ToolGuardrailSet`] decided about a call.
190#[derive(Debug, Clone)]
191pub enum ToolCallDecision {
192    /// The call may proceed with these arguments, which may have been revised.
193    Allow {
194        /// Arguments to invoke the tool with.
195        args: Value,
196    },
197    /// The call is refused.
198    Deny {
199        /// Guardrail that refused it.
200        guardrail: String,
201        /// Why.
202        reason: String,
203        /// How serious.
204        severity: Severity,
205    },
206}
207
208impl ToolCallDecision {
209    /// Whether the call may proceed.
210    pub fn is_allowed(&self) -> bool {
211        matches!(self, Self::Allow { .. })
212    }
213}
214
215/// What a [`ToolGuardrailSet`] decided about a tool's result.
216#[derive(Debug, Clone, PartialEq)]
217pub enum ToolResultDecision {
218    /// The result to deliver, which may have been revised.
219    Deliver {
220        /// The result the model and the session see.
221        result: Value,
222    },
223    /// The result is withheld.
224    Withhold {
225        /// Guardrail that withheld it.
226        guardrail: String,
227        /// Why.
228        reason: String,
229        /// How serious.
230        severity: Severity,
231    },
232}
233
234/// A collection of [`ToolGuardrail`]s evaluated together.
235///
236/// # Example
237///
238/// ```rust
239/// use adk_guardrail::{PathAllowList, Severity, ToolGuardrailSet};
240///
241/// let guardrails = ToolGuardrailSet::new().with(
242///     PathAllowList::new("plist-paths", ["path"], ["/Users/me/Library/LaunchAgents"])
243///         .on_tools(["plist_write"]),
244/// );
245///
246/// assert_eq!(guardrails.guardrails().len(), 1);
247/// ```
248#[derive(Default)]
249pub struct ToolGuardrailSet {
250    guardrails: Vec<Arc<dyn ToolGuardrail>>,
251}
252
253impl ToolGuardrailSet {
254    /// Creates an empty set.
255    pub fn new() -> Self {
256        Self { guardrails: Vec::new() }
257    }
258
259    /// Adds a guardrail.
260    pub fn with(mut self, guardrail: impl ToolGuardrail + 'static) -> Self {
261        self.guardrails.push(Arc::new(guardrail));
262        self
263    }
264
265    /// Adds a pre-wrapped guardrail.
266    pub fn with_arc(mut self, guardrail: Arc<dyn ToolGuardrail>) -> Self {
267        self.guardrails.push(guardrail);
268        self
269    }
270
271    /// The registered guardrails.
272    pub fn guardrails(&self) -> &[Arc<dyn ToolGuardrail>] {
273        &self.guardrails
274    }
275
276    /// Whether no guardrails have been added.
277    pub fn is_empty(&self) -> bool {
278        self.guardrails.is_empty()
279    }
280
281    /// Evaluates a call against every applicable guardrail.
282    ///
283    /// Guardrails run in order and revisions compose: a later guardrail sees the arguments an
284    /// earlier one produced. Evaluation is sequential rather than parallel because a revision has
285    /// to be visible to whatever runs next — parallel evaluation would make the outcome depend on
286    /// completion order. The first denial stops evaluation, so a denied call is never revised and
287    /// never reaches a later guardrail.
288    pub async fn evaluate(&self, tool_name: &str, args: &Value) -> ToolCallDecision {
289        let mut current = args.clone();
290
291        for guardrail in &self.guardrails {
292            if !guardrail.applies_to(tool_name) {
293                continue;
294            }
295
296            match guardrail.validate_call(tool_name, &current).await {
297                ToolGuardrailResult::Allow => {}
298                ToolGuardrailResult::Deny { reason, severity } => {
299                    // A reason can quote the arguments, such as a refused path, so it is
300                    // returned to the caller but not logged.
301                    tracing::warn!(
302                        guardrail = guardrail.name(),
303                        tool = tool_name,
304                        ?severity,
305                        "tool call denied by guardrail"
306                    );
307                    return ToolCallDecision::Deny {
308                        guardrail: guardrail.name().to_string(),
309                        reason,
310                        severity,
311                    };
312                }
313                ToolGuardrailResult::ReviseArgs { args: revised, reason: _ } => {
314                    tracing::debug!(
315                        guardrail = guardrail.name(),
316                        tool = tool_name,
317                        "tool call arguments revised by guardrail"
318                    );
319                    current = revised;
320                }
321            }
322        }
323
324        ToolCallDecision::Allow { args: current }
325    }
326
327    /// Evaluates a tool's result against every applicable guardrail.
328    ///
329    /// Guardrails run in order and revisions compose, as in [`evaluate`](Self::evaluate). The
330    /// first guardrail to withhold the result stops evaluation.
331    ///
332    /// # Example
333    ///
334    /// ```rust
335    /// use adk_guardrail::{PiiRedactor, ResultTextGuardrail, ToolGuardrailSet, ToolResultDecision};
336    /// use serde_json::json;
337    ///
338    /// # futures::executor::block_on(async {
339    /// let guardrails = ToolGuardrailSet::new().with(ResultTextGuardrail::new(PiiRedactor::new()));
340    /// let decision = guardrails
341    ///     .evaluate_result("lookup", &json!({}), &json!({"ssn": "123-45-6789"}))
342    ///     .await;
343    /// assert_eq!(
344    ///     decision,
345    ///     ToolResultDecision::Deliver { result: json!({"ssn": "[SSN REDACTED]"}) }
346    /// );
347    /// # });
348    /// ```
349    pub async fn evaluate_result(
350        &self,
351        tool_name: &str,
352        args: &Value,
353        result: &Value,
354    ) -> ToolResultDecision {
355        let mut current = result.clone();
356
357        for guardrail in &self.guardrails {
358            if !guardrail.applies_to(tool_name) {
359                continue;
360            }
361
362            match guardrail.validate_result(tool_name, args, &current).await {
363                ToolResultGuardrailResult::Allow => {}
364                ToolResultGuardrailResult::Withhold { reason, severity } => {
365                    // The reason is returned to the caller, which sends it to the model, but
366                    // is not logged.
367                    tracing::warn!(
368                        guardrail = guardrail.name(),
369                        tool = tool_name,
370                        ?severity,
371                        "tool result withheld by guardrail"
372                    );
373                    return ToolResultDecision::Withhold {
374                        guardrail: guardrail.name().to_string(),
375                        reason,
376                        severity,
377                    };
378                }
379                // A reason can quote the result it replaced, so it is not logged.
380                ToolResultGuardrailResult::Revise { result: revised, reason: _ } => {
381                    tracing::debug!(
382                        guardrail = guardrail.name(),
383                        tool = tool_name,
384                        "tool result revised by guardrail"
385                    );
386                    current = revised;
387                }
388            }
389        }
390
391        ToolResultDecision::Deliver { result: current }
392    }
393}
394
395/// Screens results with [`ToolGuardrailSet::evaluate_result`], so a set can be handed to any
396/// agent that accepts a [`ToolResultScreen`](adk_core::ToolResultScreen).
397#[async_trait]
398impl adk_core::ToolResultScreen for ToolGuardrailSet {
399    async fn screen_result(
400        &self,
401        tool_name: &str,
402        args: &Value,
403        result: &Value,
404    ) -> std::result::Result<Value, String> {
405        match self.evaluate_result(tool_name, args, result).await {
406            ToolResultDecision::Deliver { result } => Ok(result),
407            ToolResultDecision::Withhold { guardrail, reason, severity } => {
408                Err(format!("tool guardrail '{guardrail}' ({severity:?}): {reason}"))
409            }
410        }
411    }
412}
413
414/// Applies a content [`Guardrail`] to every text value of a tool's result.
415///
416/// Each string in the result JSON, at any depth, is validated as one text part: a transform
417/// replaces the string, so [`PiiRedactor`](crate::PiiRedactor) redacts a result field by field
418/// and the result keeps its shape, and a failure above [`Severity::Low`] withholds the whole
419/// result. Object keys are not screened.
420///
421/// # Example
422///
423/// ```rust
424/// use adk_guardrail::{ContentFilter, PiiRedactor, ResultTextGuardrail, ToolGuardrailSet};
425///
426/// # fn main() -> Result<(), adk_guardrail::GuardrailError> {
427/// let guardrails = ToolGuardrailSet::new()
428///     .with(ResultTextGuardrail::new(PiiRedactor::new()))
429///     .with(
430///         ResultTextGuardrail::new(ContentFilter::blocked_keywords(vec!["internal only".into()])?)
431///             .on_tools(["search_wiki"]),
432///     );
433/// # Ok(())
434/// # }
435/// ```
436pub struct ResultTextGuardrail<G> {
437    guardrail: G,
438    tools: Option<Vec<String>>,
439}
440
441impl<G: Guardrail> ResultTextGuardrail<G> {
442    /// Applies `guardrail` to the text of every tool's result.
443    pub fn new(guardrail: G) -> Self {
444        Self { guardrail, tools: None }
445    }
446
447    /// Restricts this guardrail to the named tools. Without this it applies to every tool.
448    pub fn on_tools<I, S>(mut self, tools: I) -> Self
449    where
450        I: IntoIterator<Item = S>,
451        S: Into<String>,
452    {
453        self.tools = Some(tools.into_iter().map(Into::into).collect());
454        self
455    }
456
457    /// Screens every string in `value`, returning the failure that withholds the result.
458    async fn screen(&self, value: &mut Value) -> std::result::Result<bool, (String, Severity)> {
459        let mut changed = false;
460        let mut pending = vec![value];
461        while let Some(value) = pending.pop() {
462            match value {
463                Value::String(text) => {
464                    let content = adk_core::Content::new("tool").with_text(text.as_str());
465                    match self.guardrail.validate(&content).await {
466                        GuardrailResult::Pass => {}
467                        GuardrailResult::Fail { severity: Severity::Low, .. } => {
468                            tracing::warn!(
469                                guardrail.name = self.guardrail.name(),
470                                "guardrail flagged a tool result at low severity; the result passes"
471                            );
472                        }
473                        GuardrailResult::Fail { reason, severity } => {
474                            return Err((reason, severity));
475                        }
476                        GuardrailResult::Transform { new_content, .. } => {
477                            let screened: String =
478                                new_content.parts.iter().filter_map(adk_core::Part::text).collect();
479                            if screened != *text {
480                                *text = screened;
481                                changed = true;
482                            }
483                        }
484                    }
485                }
486                Value::Array(items) => pending.extend(items.iter_mut()),
487                Value::Object(fields) => pending.extend(fields.values_mut()),
488                Value::Null | Value::Bool(_) | Value::Number(_) => {}
489            }
490        }
491        Ok(changed)
492    }
493}
494
495#[async_trait]
496impl<G: Guardrail> ToolGuardrail for ResultTextGuardrail<G> {
497    fn name(&self) -> &str {
498        self.guardrail.name()
499    }
500
501    fn applies_to(&self, tool_name: &str) -> bool {
502        match &self.tools {
503            Some(tools) => tools.iter().any(|t| t == tool_name),
504            None => true,
505        }
506    }
507
508    async fn validate_result(
509        &self,
510        _tool_name: &str,
511        _args: &Value,
512        result: &Value,
513    ) -> ToolResultGuardrailResult {
514        let mut screened = result.clone();
515        match self.screen(&mut screened).await {
516            Ok(false) => ToolResultGuardrailResult::Allow,
517            Ok(true) => ToolResultGuardrailResult::revise(
518                screened,
519                format!("{} rewrote the result's text", self.guardrail.name()),
520            ),
521            Err((reason, severity)) => ToolResultGuardrailResult::withhold(reason, severity),
522        }
523    }
524}
525
526/// Denies a call whose serialized arguments match a pattern.
527///
528/// The pattern is matched against the JSON encoding of the whole argument object, so it catches a
529/// value wherever it appears rather than requiring the field to be named up front.
530///
531/// # Example
532///
533/// ```rust
534/// use adk_guardrail::{DeniedArgumentPattern, Severity};
535///
536/// # fn main() -> Result<(), regex::Error> {
537/// let guardrail = DeniedArgumentPattern::new("no-force-push", r"--force\b", Severity::High)?
538///     .on_tools(["run_command"]);
539/// # Ok(())
540/// # }
541/// ```
542pub struct DeniedArgumentPattern {
543    name: String,
544    pattern: Regex,
545    severity: Severity,
546    tools: Option<Vec<String>>,
547}
548
549impl DeniedArgumentPattern {
550    /// Creates a guardrail denying calls whose arguments match `pattern`.
551    ///
552    /// # Errors
553    ///
554    /// Returns an error if `pattern` is not a valid regular expression.
555    pub fn new(
556        name: impl Into<String>,
557        pattern: &str,
558        severity: Severity,
559    ) -> std::result::Result<Self, regex::Error> {
560        Ok(Self { name: name.into(), pattern: Regex::new(pattern)?, severity, tools: None })
561    }
562
563    /// Restricts this guardrail to the named tools. Without this it applies to every tool.
564    pub fn on_tools<I, S>(mut self, tools: I) -> Self
565    where
566        I: IntoIterator<Item = S>,
567        S: Into<String>,
568    {
569        self.tools = Some(tools.into_iter().map(Into::into).collect());
570        self
571    }
572}
573
574#[async_trait]
575impl ToolGuardrail for DeniedArgumentPattern {
576    fn name(&self) -> &str {
577        &self.name
578    }
579
580    fn applies_to(&self, tool_name: &str) -> bool {
581        match &self.tools {
582            Some(tools) => tools.iter().any(|t| t == tool_name),
583            None => true,
584        }
585    }
586
587    async fn validate_call(&self, tool_name: &str, args: &Value) -> ToolGuardrailResult {
588        if self.pattern.is_match(&args.to_string()) {
589            return ToolGuardrailResult::deny(
590                format!(
591                    "arguments to `{tool_name}` match the denied pattern `{}`",
592                    self.pattern.as_str()
593                ),
594                self.severity,
595            );
596        }
597        ToolGuardrailResult::Allow
598    }
599}
600
601/// Denies a call whose path-valued arguments fall outside a set of allowed roots.
602///
603/// Checks every key named in `arg_names` at any depth of the arguments: at the top level, in a
604/// nested object, and in an object held in an array. The call is denied when any occurrence is not
605/// an absolute path contained by one of the allowed roots, so a permitted path in one place does
606/// not vouch for another elsewhere.
607///
608/// The value under a named key must be a path string or an array of path strings. Any other value
609/// — a number, a boolean, `null`, an object, or an array holding one of them — is denied, because
610/// it cannot be checked; an empty array holds no path. Every key of a configured name is checked
611/// as a path, including one that holds something else, such as a URL path, so scope the guardrail
612/// to the tools that take filesystem paths. A path inside a string value, such as embedded JSON or
613/// a command line, is not examined; [`DeniedArgumentPattern`] matches the serialized arguments.
614///
615/// A call in which no path is found under one of the names, at any depth, is denied, because the
616/// guardrail cannot vouch for a path it was not shown; [`allow_missing`](Self::allow_missing)
617/// permits such calls. Without [`on_tools`](Self::on_tools) the guardrail applies to every tool, so
618/// a tool that takes no path is denied too — scope it to the tools that take paths. Containment is
619/// compared by path component and after resolving the allowed root and every existing candidate
620/// component, so string-prefix, dangling-symlink, and resolved-symlink escapes are refused. Any
621/// path containing a `..` component is denied outright.
622///
623/// # Time of check and time of use
624///
625/// This is a preflight check: it resolves the path when the call is screened, and the tool opens
626/// it afterwards. A process that replaces a path component in between — a directory swapped for a
627/// symlink — redirects the open outside the root after the check passed. A tool that opens files
628/// where another process can write must open each path relative to a trusted directory handle and
629/// refuse symlinks, as the `adk-devtools` file tools do: `openat2` with `RESOLVE_BENEATH` on Linux,
630/// an `O_NOFOLLOW` walk from the root's descriptor on other Unix systems, and a check of the opened
631/// handle's final path on Windows.
632///
633/// # Example
634///
635/// ```rust
636/// use adk_guardrail::{PathAllowList, ToolGuardrail};
637/// use serde_json::json;
638///
639/// let guardrail = PathAllowList::new(
640///     "launch-agents-only",
641///     ["path"],
642///     ["/Users/me/Library/LaunchAgents"],
643/// )
644/// .on_tools(["plist_write", "plist_read"]);
645///
646/// // A `path` nested under another key is checked like a top-level one.
647/// let nested = json!({ "options": { "path": "/etc/hosts" } });
648/// let decision = futures::executor::block_on(guardrail.validate_call("plist_read", &nested));
649/// assert!(!decision.is_allowed());
650/// ```
651pub struct PathAllowList {
652    name: String,
653    arg_names: Vec<String>,
654    allowed_roots: Vec<PathBuf>,
655    severity: Severity,
656    tools: Option<Vec<String>>,
657    allow_missing: bool,
658}
659
660impl PathAllowList {
661    /// Creates a guardrail confining every key named in `arg_names`, at any depth of a call's
662    /// arguments, to `allowed_roots`.
663    pub fn new<A, S, R, P>(name: impl Into<String>, arg_names: A, allowed_roots: R) -> Self
664    where
665        A: IntoIterator<Item = S>,
666        S: Into<String>,
667        R: IntoIterator<Item = P>,
668        P: Into<PathBuf>,
669    {
670        Self {
671            name: name.into(),
672            arg_names: arg_names.into_iter().map(Into::into).collect(),
673            allowed_roots: allowed_roots.into_iter().map(Into::into).collect(),
674            severity: Severity::Critical,
675            tools: None,
676            allow_missing: false,
677        }
678    }
679
680    /// Sets the severity reported on denial. Defaults to [`Severity::Critical`].
681    pub fn with_severity(mut self, severity: Severity) -> Self {
682        self.severity = severity;
683        self
684    }
685
686    /// Restricts this guardrail to the named tools. Without this it applies to every tool.
687    ///
688    /// A tool not named here is not checked: its calls pass this guardrail whatever their
689    /// arguments. List every tool that takes one of the configured path arguments.
690    pub fn on_tools<I, S>(mut self, tools: I) -> Self
691    where
692        I: IntoIterator<Item = S>,
693        S: Into<String>,
694    {
695        self.tools = Some(tools.into_iter().map(Into::into).collect());
696        self
697    }
698
699    /// Permits a call in which no path is found under a configured name, at any depth.
700    ///
701    /// By default such a call is denied. Use this when the guardrail names arguments that only
702    /// some of its tools take, such as `source` and `destination` beside `path`; every occurrence
703    /// that is present is still checked.
704    ///
705    /// # Example
706    ///
707    /// ```rust
708    /// use adk_guardrail::PathAllowList;
709    ///
710    /// let guardrail = PathAllowList::new("workspace", ["path", "source", "destination"], ["/srv"])
711    ///     .on_tools(["read_file", "move_file"])
712    ///     .allow_missing();
713    /// ```
714    pub fn allow_missing(mut self) -> Self {
715        self.allow_missing = true;
716        self
717    }
718
719    /// Whether `candidate` is an absolute, traversal-free path inside an allowed root.
720    fn is_permitted(&self, candidate: &str) -> bool {
721        let path = Path::new(candidate);
722
723        if !path.is_absolute() {
724            return false;
725        }
726
727        // A `..` cannot be resolved for a path that may not exist, so it is refused rather than
728        // normalized.
729        if path.components().any(|c| matches!(c, Component::ParentDir)) {
730            return false;
731        }
732
733        self.allowed_roots.iter().any(|root| {
734            if !root.is_absolute()
735                || root.components().any(|component| matches!(component, Component::ParentDir))
736                || !path.starts_with(root)
737            {
738                return false;
739            }
740
741            let Ok(canonical_root) = std::fs::canonicalize(root) else {
742                // An unresolved policy root cannot establish a trustworthy boundary.
743                return false;
744            };
745
746            let Ok(relative) = path.strip_prefix(root) else {
747                return false;
748            };
749            let mut current = root.clone();
750            for component in relative.components() {
751                current.push(component);
752                match std::fs::symlink_metadata(&current) {
753                    Ok(_) => {
754                        let Ok(canonical) = std::fs::canonicalize(&current) else {
755                            // Includes dangling symlinks, whose eventual target cannot be trusted.
756                            return false;
757                        };
758                        if !canonical.starts_with(&canonical_root) {
759                            return false;
760                        }
761                    }
762                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
763                        // Once a component is absent, every remaining component is new and cannot
764                        // currently hide a symlink. The tool may create this suffix.
765                        break;
766                    }
767                    Err(_) => return false,
768                }
769            }
770
771            true
772        })
773    }
774}
775
776#[async_trait]
777impl ToolGuardrail for PathAllowList {
778    fn name(&self) -> &str {
779        &self.name
780    }
781
782    fn applies_to(&self, tool_name: &str) -> bool {
783        match &self.tools {
784            Some(tools) => tools.iter().any(|t| t == tool_name),
785            None => true,
786        }
787    }
788
789    async fn validate_call(&self, tool_name: &str, args: &Value) -> ToolGuardrailResult {
790        let deny = |reason: String| ToolGuardrailResult::deny(reason, self.severity);
791        // How many paths were checked under each configured name.
792        let mut found = vec![0_usize; self.arg_names.len()];
793        // Breadth first, so a top-level argument is reported before a nested one; a queue rather
794        // than recursion, so deeply nested arguments cannot exhaust the stack. Each entry carries
795        // its JSON pointer for the denial reason.
796        let mut pending = VecDeque::from([(String::new(), args)]);
797
798        while let Some((pointer, value)) = pending.pop_front() {
799            match value {
800                Value::Object(map) => {
801                    for (key, child) in map {
802                        let at = format!("{pointer}/{}", key.replace('~', "~0").replace('/', "~1"));
803                        let Some(index) = self.arg_names.iter().position(|name| name == key) else {
804                            pending.push_back((at, child));
805                            continue;
806                        };
807                        let candidates: Vec<(String, &Value)> = match child {
808                            Value::Array(items) => items
809                                .iter()
810                                .enumerate()
811                                .map(|(position, item)| (format!("{at}/{position}"), item))
812                                .collect(),
813                            Value::Null
814                            | Value::Bool(_)
815                            | Value::Number(_)
816                            | Value::String(_)
817                            | Value::Object(_) => vec![(at, child)],
818                        };
819                        for (at, candidate) in candidates {
820                            let kind = match candidate {
821                                Value::String(path) => {
822                                    if !self.is_permitted(path) {
823                                        let roots: Vec<_> = self
824                                            .allowed_roots
825                                            .iter()
826                                            .map(|root| root.display().to_string())
827                                            .collect();
828                                        return deny(format!(
829                                            "argument `{key}` of `{tool_name}` at `{at}` is \
830                                             {path:?}, which is not an absolute path inside an \
831                                             allowed root ({})",
832                                            roots.join(", ")
833                                        ));
834                                    }
835                                    found[index] += 1;
836                                    continue;
837                                }
838                                Value::Array(_) => "an array".to_string(),
839                                Value::Object(_) => "an object".to_string(),
840                                Value::Null | Value::Bool(_) | Value::Number(_) => {
841                                    candidate.to_string()
842                                }
843                            };
844                            return deny(format!(
845                                "argument `{key}` of `{tool_name}` at `{at}` must be a path string \
846                                 or an array of path strings, got {kind}"
847                            ));
848                        }
849                    }
850                }
851                Value::Array(items) => {
852                    for (position, item) in items.iter().enumerate() {
853                        pending.push_back((format!("{pointer}/{position}"), item));
854                    }
855                }
856                Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
857            }
858        }
859
860        if !self.allow_missing
861            && let Some((arg_name, _)) =
862                self.arg_names.iter().zip(&found).find(|(_, count)| **count == 0)
863        {
864            return deny(format!(
865                "argument `{arg_name}` of `{tool_name}` holds no path at any depth, so it cannot \
866                 be checked; configure the guardrail with allow_missing() to permit calls without \
867                 it"
868            ));
869        }
870
871        ToolGuardrailResult::Allow
872    }
873}
874
875#[cfg(test)]
876mod tests {
877    use super::*;
878    use crate::{ContentFilter, PiiRedactor};
879    use adk_core::ToolResultScreen;
880    use serde_json::json;
881
882    #[tokio::test]
883    async fn result_text_guardrail_redacts_every_string_and_keeps_the_shape() {
884        let guardrails = ToolGuardrailSet::new().with(ResultTextGuardrail::new(PiiRedactor::new()));
885        let result = json!({
886            "order": 42,
887            "customer": {"email": "jane@example.com", "notes": ["ssn 123-45-6789", true]},
888        });
889        assert_eq!(
890            guardrails.evaluate_result("lookup", &json!({}), &result).await,
891            ToolResultDecision::Deliver {
892                result: json!({
893                    "order": 42,
894                    "customer": {"email": "[EMAIL REDACTED]", "notes": ["ssn [SSN REDACTED]", true]},
895                }),
896            }
897        );
898    }
899
900    #[tokio::test]
901    async fn a_failing_text_check_withholds_the_result() {
902        let filter = ContentFilter::blocked_keywords(vec!["internal only".into()]).unwrap();
903        let guardrails = ToolGuardrailSet::new().with(ResultTextGuardrail::new(filter));
904        let decision = guardrails
905            .evaluate_result("wiki", &json!({}), &json!({"page": ["INTERNAL ONLY: roadmap"]}))
906            .await;
907        assert!(matches!(
908            decision,
909            ToolResultDecision::Withhold { ref guardrail, severity: Severity::High, .. }
910                if guardrail == "blocked_keywords"
911        ));
912        let screened =
913            guardrails.screen_result("wiki", &json!({}), &json!({"page": "internal only"})).await;
914        assert!(screened.unwrap_err().starts_with("tool guardrail 'blocked_keywords' (High)"));
915    }
916
917    #[tokio::test]
918    async fn result_guardrails_are_scoped_and_compose() {
919        let guardrails = ToolGuardrailSet::new()
920            .with(ResultTextGuardrail::new(PiiRedactor::new()).on_tools(["lookup"]))
921            .with(ResultTextGuardrail::new(
922                ContentFilter::blocked_keywords(vec!["redacted".into()]).unwrap(),
923            ));
924        let other =
925            guardrails.evaluate_result("search", &json!({}), &json!("mail jane@example.com")).await;
926        assert_eq!(other, ToolResultDecision::Deliver { result: json!("mail jane@example.com") });
927        // The second guardrail sees what the first produced.
928        let lookup =
929            guardrails.evaluate_result("lookup", &json!({}), &json!("mail jane@example.com")).await;
930        assert!(matches!(lookup, ToolResultDecision::Withhold { .. }));
931    }
932
933    #[tokio::test]
934    async fn call_guardrails_deliver_results_unchanged() {
935        let guardrails = ToolGuardrailSet::new().with(ForceDryRun);
936        let result = json!({"ok": true});
937        assert_eq!(
938            guardrails.evaluate_result("run", &json!({}), &result).await,
939            ToolResultDecision::Deliver { result }
940        );
941    }
942
943    /// Revises rather than denies, so composition can be observed.
944    struct ForceDryRun;
945
946    #[async_trait]
947    impl ToolGuardrail for ForceDryRun {
948        fn name(&self) -> &str {
949            "force-dry-run"
950        }
951        async fn validate_call(&self, _tool: &str, args: &Value) -> ToolGuardrailResult {
952            let mut revised = args.clone();
953            if let Some(object) = revised.as_object_mut() {
954                object.insert("dry_run".to_string(), json!(true));
955            }
956            ToolGuardrailResult::revise(revised, "dry-run is mandatory here")
957        }
958    }
959
960    struct DenyAll;
961
962    #[async_trait]
963    impl ToolGuardrail for DenyAll {
964        fn name(&self) -> &str {
965            "deny-all"
966        }
967        async fn validate_call(&self, _tool: &str, _args: &Value) -> ToolGuardrailResult {
968            ToolGuardrailResult::deny("nothing is permitted", Severity::Critical)
969        }
970    }
971
972    #[tokio::test]
973    async fn an_empty_set_allows_the_call_unchanged() {
974        let decision = ToolGuardrailSet::new().evaluate("any", &json!({ "a": 1 })).await;
975
976        match decision {
977            ToolCallDecision::Allow { args } => assert_eq!(args, json!({ "a": 1 })),
978            other => panic!("expected Allow, got {other:?}"),
979        }
980    }
981
982    #[tokio::test]
983    async fn a_revision_is_returned_to_the_caller() {
984        let set = ToolGuardrailSet::new().with(ForceDryRun);
985
986        match set.evaluate("delete", &json!({ "path": "/tmp/x" })).await {
987            ToolCallDecision::Allow { args } => {
988                assert_eq!(args, json!({ "path": "/tmp/x", "dry_run": true }));
989            }
990            other => panic!("expected Allow, got {other:?}"),
991        }
992    }
993
994    #[tokio::test]
995    async fn a_denial_names_the_guardrail_that_refused() {
996        let set = ToolGuardrailSet::new().with(DenyAll);
997
998        match set.evaluate("delete", &json!({})).await {
999            ToolCallDecision::Deny { guardrail, severity, .. } => {
1000                assert_eq!(guardrail, "deny-all");
1001                assert_eq!(severity, Severity::Critical);
1002            }
1003            other => panic!("expected Deny, got {other:?}"),
1004        }
1005    }
1006
1007    #[tokio::test]
1008    async fn a_denial_stops_evaluation_so_a_denied_call_is_never_revised() {
1009        let set = ToolGuardrailSet::new().with(DenyAll).with(ForceDryRun);
1010
1011        assert!(!set.evaluate("delete", &json!({})).await.is_allowed());
1012    }
1013
1014    #[tokio::test]
1015    async fn a_later_guardrail_sees_an_earlier_revision() {
1016        /// Denies unless a previous guardrail already set `dry_run`.
1017        struct RequireDryRun;
1018
1019        #[async_trait]
1020        impl ToolGuardrail for RequireDryRun {
1021            fn name(&self) -> &str {
1022                "require-dry-run"
1023            }
1024            async fn validate_call(&self, _tool: &str, args: &Value) -> ToolGuardrailResult {
1025                if args.get("dry_run") == Some(&json!(true)) {
1026                    ToolGuardrailResult::Allow
1027                } else {
1028                    ToolGuardrailResult::deny("dry_run was not set", Severity::High)
1029                }
1030            }
1031        }
1032
1033        let set = ToolGuardrailSet::new().with(ForceDryRun).with(RequireDryRun);
1034        assert!(
1035            set.evaluate("delete", &json!({})).await.is_allowed(),
1036            "revisions must compose in order"
1037        );
1038
1039        let reversed = ToolGuardrailSet::new().with(RequireDryRun).with(ForceDryRun);
1040        assert!(
1041            !reversed.evaluate("delete", &json!({})).await.is_allowed(),
1042            "order is meaningful and must not be silently reordered"
1043        );
1044    }
1045
1046    #[tokio::test]
1047    async fn applies_to_skips_an_unrelated_tool() {
1048        let set = ToolGuardrailSet::new().with(
1049            DeniedArgumentPattern::new("no-rf", r"-rf", Severity::Critical)
1050                .expect("valid pattern")
1051                .on_tools(["run_command"]),
1052        );
1053
1054        assert!(set.evaluate("read_file", &json!({ "flags": "-rf" })).await.is_allowed());
1055        assert!(!set.evaluate("run_command", &json!({ "flags": "-rf" })).await.is_allowed());
1056    }
1057
1058    #[tokio::test]
1059    async fn a_denied_pattern_matches_anywhere_in_the_arguments() {
1060        let guardrail = DeniedArgumentPattern::new("no-rf", r"-rf\b", Severity::Critical)
1061            .expect("valid pattern");
1062
1063        for args in [
1064            json!({ "cmd": "rm -rf /" }),
1065            json!({ "nested": { "cmd": "rm -rf ." } }),
1066            json!({ "argv": ["rm", "-rf", "/tmp"] }),
1067        ] {
1068            assert!(
1069                !guardrail.validate_call("run_command", &args).await.is_allowed(),
1070                "should deny {args}"
1071            );
1072        }
1073
1074        assert!(
1075            guardrail.validate_call("run_command", &json!({ "cmd": "ls -l" })).await.is_allowed()
1076        );
1077    }
1078
1079    #[test]
1080    fn an_invalid_pattern_is_reported() {
1081        assert!(DeniedArgumentPattern::new("bad", "([unclosed", Severity::Low).is_err());
1082    }
1083
1084    #[tokio::test]
1085    async fn a_path_inside_an_allowed_root_is_permitted() {
1086        let root = tempfile::tempdir().expect("allowed root");
1087        let guardrail = PathAllowList::new("agents", ["path"], [root.path()]);
1088        let candidate = root.path().join("x.plist");
1089
1090        assert!(
1091            guardrail
1092                .validate_call("plist_write", &json!({ "path": candidate }))
1093                .await
1094                .is_allowed()
1095        );
1096    }
1097
1098    #[tokio::test]
1099    async fn traversal_and_escape_attempts_are_denied() {
1100        let guardrail = PathAllowList::new("agents", ["path"], ["/Users/me/Library/LaunchAgents"]);
1101
1102        for candidate in [
1103            "/Users/me/Library/LaunchAgents/../../../etc/passwd",
1104            "/etc/passwd",
1105            "relative/path.plist",
1106            "/Users/me/Library/LaunchAgentsEvil/x.plist",
1107        ] {
1108            assert!(
1109                !guardrail
1110                    .validate_call("plist_write", &json!({ "path": candidate }))
1111                    .await
1112                    .is_allowed(),
1113                "should deny {candidate:?}"
1114            );
1115        }
1116    }
1117
1118    #[tokio::test]
1119    async fn a_sibling_root_is_not_admitted_by_string_prefix() {
1120        // `/etc/passwd-backup` shares a string prefix with `/etc/passwd` but is a different file.
1121        let guardrail = PathAllowList::new("etc", ["path"], ["/etc/passwd"]);
1122
1123        assert!(
1124            !guardrail
1125                .validate_call("read", &json!({ "path": "/etc/passwd-backup" }))
1126                .await
1127                .is_allowed()
1128        );
1129    }
1130
1131    #[tokio::test]
1132    async fn a_non_string_path_argument_is_denied() {
1133        let guardrail = PathAllowList::new("agents", ["path"], ["/tmp"]);
1134
1135        assert!(
1136            !guardrail.validate_call("write", &json!({ "path": 42 })).await.is_allowed(),
1137            "a non-string path cannot be checked and must not be waved through"
1138        );
1139    }
1140
1141    #[cfg(unix)]
1142    #[tokio::test]
1143    async fn a_symlink_inside_the_root_cannot_escape_it() {
1144        let root = tempfile::tempdir().expect("allowed root");
1145        let outside = tempfile::tempdir().expect("outside root");
1146        std::os::unix::fs::symlink(outside.path(), root.path().join("escape"))
1147            .expect("create symlink");
1148        let guardrail = PathAllowList::new("root", ["path"], [root.path()]);
1149        let candidate = root.path().join("escape/secret.txt");
1150
1151        assert!(
1152            !guardrail.validate_call("write", &json!({ "path": candidate })).await.is_allowed(),
1153            "a lexical child resolving outside the allowed root must be denied"
1154        );
1155    }
1156
1157    #[cfg(unix)]
1158    #[tokio::test]
1159    async fn a_dangling_symlink_inside_the_root_is_denied() {
1160        let root = tempfile::tempdir().expect("allowed root");
1161        let outside = tempfile::tempdir().expect("outside root");
1162        let missing_target = outside.path().join("not-created");
1163        std::os::unix::fs::symlink(&missing_target, root.path().join("escape"))
1164            .expect("create dangling symlink");
1165        let guardrail = PathAllowList::new("root", ["path"], [root.path()]);
1166
1167        assert!(
1168            !guardrail
1169                .validate_call("write", &json!({ "path": root.path().join("escape/secret.txt") }))
1170                .await
1171                .is_allowed()
1172        );
1173    }
1174
1175    #[tokio::test]
1176    async fn an_unresolvable_allowed_root_is_fail_closed() {
1177        let root = tempfile::tempdir().expect("root");
1178        let missing = root.path().join("not-created");
1179        let guardrail = PathAllowList::new("missing", ["path"], [&missing]);
1180
1181        assert!(
1182            !guardrail
1183                .validate_call("write", &json!({ "path": missing.join("file.txt") }))
1184                .await
1185                .is_allowed()
1186        );
1187    }
1188
1189    #[tokio::test]
1190    async fn an_absent_path_argument_is_denied() {
1191        let guardrail = PathAllowList::new("agents", ["path"], ["/tmp"]);
1192
1193        for args in [json!({ "other": 1 }), json!({ "Path": "/etc/passwd" }), json!("/etc/passwd")]
1194        {
1195            assert!(
1196                !guardrail.validate_call("write", &args).await.is_allowed(),
1197                "a call without `path` cannot be shown to stay inside the roots: {args}"
1198            );
1199        }
1200    }
1201
1202    #[tokio::test]
1203    async fn allow_missing_permits_an_absent_argument_but_checks_a_present_one() {
1204        let root = tempfile::tempdir().expect("allowed root");
1205        let guardrail =
1206            PathAllowList::new("moves", ["source", "destination"], [root.path()]).allow_missing();
1207        let inside = root.path().join("a.txt");
1208
1209        assert!(guardrail.validate_call("rm", &json!({ "source": inside })).await.is_allowed());
1210        assert!(
1211            !guardrail
1212                .validate_call("mv", &json!({ "source": inside, "destination": "/etc/x" }))
1213                .await
1214                .is_allowed()
1215        );
1216    }
1217
1218    #[tokio::test]
1219    async fn a_nested_path_outside_the_roots_is_denied() {
1220        let root = tempfile::tempdir().expect("allowed root");
1221        let inside = root.path().join("notes.txt");
1222        let strict = PathAllowList::new("root", ["path"], [root.path()]);
1223        let lenient = PathAllowList::new("root", ["path"], [root.path()]).allow_missing();
1224
1225        for args in [
1226            json!({ "config": { "path": "/etc/shadow" } }),
1227            json!({ "request": { "target": { "path": "/etc/shadow" } } }),
1228        ] {
1229            assert!(!strict.validate_call("read", &args).await.is_allowed(), "should deny {args}");
1230            assert!(!lenient.validate_call("read", &args).await.is_allowed(), "should deny {args}");
1231        }
1232        let beside_a_permitted_one = json!({ "path": inside, "backup": { "path": "/etc/shadow" } });
1233        assert!(
1234            !strict.validate_call("read", &beside_a_permitted_one).await.is_allowed(),
1235            "a permitted top-level path must not vouch for a nested one"
1236        );
1237    }
1238
1239    #[tokio::test]
1240    async fn an_array_held_path_outside_the_roots_is_denied() {
1241        let root = tempfile::tempdir().expect("allowed root");
1242        let inside = root.path().join("notes.txt");
1243        let guardrail = PathAllowList::new("root", ["path"], [root.path()]).allow_missing();
1244
1245        for args in [
1246            json!({ "files": [{ "path": inside }, { "path": "/etc/shadow" }] }),
1247            json!({ "batches": [[{ "path": "/etc/shadow" }]] }),
1248            json!({ "path": [inside, "/etc/shadow"] }),
1249        ] {
1250            assert!(
1251                !guardrail.validate_call("read", &args).await.is_allowed(),
1252                "should deny {args}"
1253            );
1254        }
1255    }
1256
1257    #[tokio::test]
1258    async fn a_nested_path_inside_the_roots_is_permitted() {
1259        let root = tempfile::tempdir().expect("allowed root");
1260        let first = root.path().join("a.txt");
1261        let second = root.path().join("b.txt");
1262        // Without allow_missing: a path found at any depth satisfies the presence check.
1263        let guardrail = PathAllowList::new("root", ["path"], [root.path()]);
1264
1265        for args in [
1266            json!({ "source": { "path": first } }),
1267            json!({ "files": [{ "path": first }, { "path": second }] }),
1268            json!({ "path": [first, second] }),
1269            json!({ "path": first, "backup": { "path": second } }),
1270        ] {
1271            assert!(
1272                guardrail.validate_call("read", &args).await.is_allowed(),
1273                "should allow {args}"
1274            );
1275        }
1276    }
1277
1278    #[tokio::test]
1279    async fn a_value_under_the_name_that_is_not_a_path_is_denied_at_any_depth() {
1280        let root = tempfile::tempdir().expect("allowed root");
1281        let inside = root.path().join("a.txt");
1282        let guardrail = PathAllowList::new("root", ["path"], [root.path()]).allow_missing();
1283
1284        for args in [
1285            json!({ "config": { "path": 42 } }),
1286            json!({ "config": { "path": null } }),
1287            json!({ "config": { "path": { "dir": inside } } }),
1288            json!({ "items": [{ "path": true }] }),
1289            json!({ "path": [inside, 7] }),
1290            json!({ "path": [[inside]] }),
1291        ] {
1292            assert!(
1293                !guardrail.validate_call("read", &args).await.is_allowed(),
1294                "a value that is not a path string cannot be checked: {args}"
1295            );
1296        }
1297    }
1298
1299    #[tokio::test]
1300    async fn an_empty_path_array_holds_no_path() {
1301        let root = tempfile::tempdir().expect("allowed root");
1302        let args = json!({ "options": { "path": [] } });
1303
1304        assert!(
1305            !PathAllowList::new("root", ["path"], [root.path()])
1306                .validate_call("read", &args)
1307                .await
1308                .is_allowed(),
1309            "an empty array shows no path, so it is denied as missing"
1310        );
1311        assert!(
1312            PathAllowList::new("root", ["path"], [root.path()])
1313                .allow_missing()
1314                .validate_call("read", &args)
1315                .await
1316                .is_allowed()
1317        );
1318    }
1319
1320    #[tokio::test]
1321    async fn a_denial_names_where_the_path_was_found() {
1322        let root = tempfile::tempdir().expect("allowed root");
1323        let guardrail = PathAllowList::new("root", ["path"], [root.path()]).allow_missing();
1324
1325        let decision =
1326            guardrail.validate_call("read", &json!({ "a/b": [{ "path": "/etc/shadow" }] })).await;
1327
1328        match decision {
1329            ToolGuardrailResult::Deny { reason, severity } => {
1330                assert_eq!(severity, Severity::Critical);
1331                assert!(reason.contains("at `/a~1b/0/path`"), "got {reason}");
1332                assert!(reason.contains("not an absolute path inside an allowed root"), "{reason}");
1333            }
1334            other => panic!("expected Deny, got {other:?}"),
1335        }
1336    }
1337
1338    #[tokio::test]
1339    async fn a_tool_outside_on_tools_is_not_checked() {
1340        let set = ToolGuardrailSet::new()
1341            .with(PathAllowList::new("writes", ["path"], ["/srv"]).on_tools(["write_file"]));
1342
1343        assert!(set.evaluate("read_file", &json!({ "path": "/etc/passwd" })).await.is_allowed());
1344        assert!(!set.evaluate("write_file", &json!({ "path": "/etc/passwd" })).await.is_allowed());
1345        assert!(!set.evaluate("write_file", &json!({})).await.is_allowed());
1346    }
1347}