Skip to main content

adk_core/
policy.rs

1//! Tool execution policy.
2//!
3//! A [`ToolPolicy`] decides, for every tool call, whether it may execute, must not
4//! execute, or may execute only after a person approves it. Agents consult the run's
5//! policy ([`RunConfig::tool_policy`](crate::RunConfig::tool_policy)) on the final
6//! arguments of each call, after every plugin and callback rewrite and immediately
7//! before the tool runs.
8//!
9//! [`DeclarativePolicy`] is a rule list matched in order on the tool name and the
10//! call's arguments. Its default decision is **deny**: a tool that no rule permits
11//! does not run.
12
13use std::sync::Arc;
14
15use async_trait::async_trait;
16use serde_json::Value;
17
18use crate::{ToolEffect, ToolOrigin};
19
20/// The outcome of evaluating a [`ToolPolicy`] for one tool call.
21///
22/// # Example
23///
24/// ```rust
25/// use adk_core::PolicyDecision;
26///
27/// let strict = PolicyDecision::Allow.stricter(PolicyDecision::require_approval("large"));
28/// assert_eq!(strict, PolicyDecision::require_approval("large"));
29/// ```
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum PolicyDecision {
32    /// The call may execute.
33    Allow,
34    /// The call must not execute. `reason` is reported to the model as the call's error.
35    Deny {
36        /// Why the call was refused.
37        reason: String,
38    },
39    /// The call may execute only after a person approves it.
40    RequireApproval {
41        /// Why approval is needed, shown with the confirmation request.
42        reason: String,
43    },
44}
45
46impl PolicyDecision {
47    /// A [`PolicyDecision::Deny`] with `reason`.
48    pub fn deny(reason: impl Into<String>) -> Self {
49        Self::Deny { reason: reason.into() }
50    }
51
52    /// A [`PolicyDecision::RequireApproval`] with `reason`.
53    pub fn require_approval(reason: impl Into<String>) -> Self {
54        Self::RequireApproval { reason: reason.into() }
55    }
56
57    /// Returns the stricter of `self` and `other`.
58    ///
59    /// `Deny` is stricter than `RequireApproval`, which is stricter than `Allow`. On a
60    /// tie, `self` is kept.
61    #[must_use]
62    pub fn stricter(self, other: Self) -> Self {
63        if other.severity() > self.severity() { other } else { self }
64    }
65
66    fn severity(&self) -> u8 {
67        match self {
68            Self::Allow => 0,
69            Self::RequireApproval { .. } => 1,
70            Self::Deny { .. } => 2,
71        }
72    }
73}
74
75/// The facts a [`ToolPolicy`] decides on for one tool call.
76///
77/// Every field is set by the framework at the call site from the call it is about to
78/// execute; the arguments are the final ones, after plugin and callback rewrites.
79///
80/// # Example
81///
82/// ```rust
83/// use adk_core::{ToolEffect, ToolPolicyRequest};
84/// use serde_json::json;
85///
86/// let request = ToolPolicyRequest::new("transfer", json!({ "amount": 25 }))
87///     .with_agent_name("treasurer")
88///     .with_identity("payments", "user-1", "session-1")
89///     .with_invocation_id("inv-1");
90/// assert_eq!(request.tool_name, "transfer");
91/// assert_eq!(request.effect, ToolEffect::NonIdempotent);
92/// assert!(!request.is_read_only());
93/// ```
94#[derive(Debug, Clone, PartialEq)]
95pub struct ToolPolicyRequest {
96    /// Name of the tool the model called.
97    pub tool_name: String,
98    /// Final arguments the tool would execute with.
99    pub args: Value,
100    /// What the tool declares about repeating a call ([`Tool::effect`](crate::Tool::effect)).
101    pub effect: ToolEffect,
102    /// The agent making the call.
103    pub agent_name: String,
104    /// Application the run belongs to.
105    pub app_name: String,
106    /// User the run belongs to.
107    pub user_id: String,
108    /// Session the run belongs to.
109    pub session_id: String,
110    /// Invocation the call happened in.
111    pub invocation_id: String,
112    /// The calling agent's principal, the subject it acts for, and its delegation chain.
113    ///
114    /// The governed path always sets it; `None` only on a request built by hand.
115    pub acting: Option<crate::ActingContext>,
116}
117
118impl ToolPolicyRequest {
119    /// Creates a request for a call to `tool_name` with `args` and no identity attached.
120    pub fn new(tool_name: impl Into<String>, args: Value) -> Self {
121        Self {
122            tool_name: tool_name.into(),
123            args,
124            effect: ToolEffect::NonIdempotent,
125            agent_name: String::new(),
126            app_name: String::new(),
127            user_id: String::new(),
128            session_id: String::new(),
129            invocation_id: String::new(),
130            acting: None,
131        }
132    }
133
134    /// The calling agent's id, when the request carries an acting context.
135    pub fn agent_id(&self) -> Option<&crate::AgentId> {
136        self.acting.as_ref().map(|acting| &acting.agent.id)
137    }
138
139    /// Attaches the calling agent's acting context.
140    ///
141    /// # Example
142    ///
143    /// ```rust
144    /// use adk_core::{ActingContext, SubjectKind, ToolPolicyRequest};
145    /// use serde_json::json;
146    ///
147    /// let request = ToolPolicyRequest::new("search", json!({}))
148    ///     .with_acting_context(ActingContext::derived("app", "researcher", "alice", SubjectKind::Human));
149    /// assert_eq!(request.agent_id().unwrap().as_str(), "urn:adk:agent:app/researcher");
150    /// ```
151    #[must_use]
152    pub fn with_acting_context(mut self, acting: crate::ActingContext) -> Self {
153        self.acting = Some(acting);
154        self
155    }
156
157    /// Whether the called tool declares [`ToolEffect::ReadOnly`].
158    pub fn is_read_only(&self) -> bool {
159        self.effect == ToolEffect::ReadOnly
160    }
161
162    /// Sets the effect the called tool declares.
163    #[must_use]
164    pub fn with_effect(mut self, effect: ToolEffect) -> Self {
165        self.effect = effect;
166        self
167    }
168
169    /// Marks the called tool as read-only, or as having side effects
170    /// ([`ToolEffect::NonIdempotent`]).
171    #[must_use]
172    pub fn with_read_only(self, read_only: bool) -> Self {
173        self.with_effect(if read_only { ToolEffect::ReadOnly } else { ToolEffect::NonIdempotent })
174    }
175
176    /// Attaches the calling agent's name.
177    #[must_use]
178    pub fn with_agent_name(mut self, agent_name: impl Into<String>) -> Self {
179        self.agent_name = agent_name.into();
180        self
181    }
182
183    /// Attaches the run's identity.
184    #[must_use]
185    pub fn with_identity(
186        mut self,
187        app_name: impl Into<String>,
188        user_id: impl Into<String>,
189        session_id: impl Into<String>,
190    ) -> Self {
191        self.app_name = app_name.into();
192        self.user_id = user_id.into();
193        self.session_id = session_id.into();
194        self
195    }
196
197    /// Attaches the invocation the call happened in.
198    #[must_use]
199    pub fn with_invocation_id(mut self, invocation_id: impl Into<String>) -> Self {
200        self.invocation_id = invocation_id.into();
201        self
202    }
203}
204
205/// Facts about one governed call that are not part of the [`ToolPolicyRequest`]: who
206/// publishes the called tool and the model's ID for the call.
207///
208/// The governed path ([`authorize_tool_call`](crate::authorize_tool_call)) passes one to
209/// [`ToolPolicy::evaluate_call`] for every call it evaluates, including arguments an
210/// approver edited. A policy reads [`origin`](Self::origin) to bind a decision to the tool's
211/// publisher and declaration, so a tool of the same name on another MCP server, or a tool
212/// redefined since, is not the tool the decision was made for.
213///
214/// Spec 3.1 §10, C1.
215///
216/// # Example
217///
218/// ```rust
219/// use adk_core::{PolicyCall, ToolOrigin};
220/// use serde_json::json;
221///
222/// let origin = ToolOrigin::new("mcp:github", &json!({ "name": "create_issue" }), None);
223/// let call = PolicyCall::new().with_origin(&origin).with_function_call_id("call-1");
224/// assert_eq!(call.origin.map(|origin| origin.source.as_str()), Some("mcp:github"));
225/// assert_eq!(call.function_call_id, Some("call-1"));
226/// assert_eq!(PolicyCall::new().origin, None);
227/// ```
228#[non_exhaustive]
229#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
230pub struct PolicyCall<'a> {
231    /// Who publishes the called tool and the digest of what it declares. `None` when the
232    /// governed path saw the call without its tool.
233    pub origin: Option<&'a ToolOrigin>,
234    /// The model's ID for the call, as the function response that answers it carries.
235    pub function_call_id: Option<&'a str>,
236    /// The [`DurableRunStore`](crate::DurableRunStore) run the call belongs to
237    /// ([`RunConfig::durable_run_id`](crate::RunConfig::durable_run_id)), so a policy can scope
238    /// a decision to one run across the invocations that resume it. `None` outside a durable
239    /// run, where the invocation is the run.
240    ///
241    /// Spec 3.2 §7.8 (a partition crossing approved for the rest of one run).
242    pub durable_run_id: Option<&'a str>,
243}
244
245impl<'a> PolicyCall<'a> {
246    /// A call with no origin and no call ID.
247    pub fn new() -> Self {
248        Self::default()
249    }
250
251    /// Sets the origin of the called tool.
252    #[must_use]
253    pub fn with_origin(mut self, origin: &'a ToolOrigin) -> Self {
254        self.origin = Some(origin);
255        self
256    }
257
258    /// Sets the model's ID for the call.
259    #[must_use]
260    pub fn with_function_call_id(mut self, function_call_id: &'a str) -> Self {
261        self.function_call_id = Some(function_call_id);
262        self
263    }
264
265    /// Sets the durable run the call belongs to (spec 3.2 §7.8).
266    ///
267    /// # Example
268    ///
269    /// ```rust
270    /// use adk_core::PolicyCall;
271    ///
272    /// let call = PolicyCall::new().with_durable_run_id("run-1");
273    /// assert_eq!(call.durable_run_id, Some("run-1"));
274    /// assert_eq!(PolicyCall::new().durable_run_id, None);
275    /// ```
276    #[must_use]
277    pub fn with_durable_run_id(mut self, durable_run_id: &'a str) -> Self {
278        self.durable_run_id = Some(durable_run_id);
279        self
280    }
281}
282
283/// Decides whether a tool call may execute.
284///
285/// Set one on a run with [`RunConfigBuilder::tool_policy`](crate::RunConfigBuilder::tool_policy)
286/// or on a runner with its builder's `tool_policy`. The policy travels with the run's
287/// [`RunConfig`](crate::RunConfig), so transfer targets and agents behind an agent tool
288/// are governed by it too.
289///
290/// # Example
291///
292/// ```rust
293/// use adk_core::{PolicyDecision, ToolPolicy, ToolPolicyRequest, async_trait};
294///
295/// /// Refuses everything outside business hours.
296/// #[derive(Debug)]
297/// struct OfficeHours {
298///     open: bool,
299/// }
300///
301/// #[async_trait]
302/// impl ToolPolicy for OfficeHours {
303///     async fn evaluate(&self, _request: &ToolPolicyRequest) -> PolicyDecision {
304///         if self.open { PolicyDecision::Allow } else { PolicyDecision::deny("closed") }
305///     }
306/// }
307/// ```
308#[async_trait]
309pub trait ToolPolicy: std::fmt::Debug + Send + Sync {
310    /// Decides one call.
311    async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision;
312
313    /// Decides one call, given its [`PolicyCall`] facts as well as the request.
314    ///
315    /// The governed path calls this method, not [`evaluate`](Self::evaluate). The default
316    /// ignores `call` and returns `self.evaluate(request)`, so a policy that does not
317    /// override it decides exactly as before. Override it to decide on the tool's
318    /// [`ToolOrigin`] or the call's ID.
319    ///
320    /// Spec 3.1 §10, C1.
321    ///
322    /// # Example
323    ///
324    /// ```rust
325    /// use adk_core::{PolicyCall, PolicyDecision, ToolOrigin, ToolPolicy, ToolPolicyRequest, async_trait};
326    /// use serde_json::json;
327    ///
328    /// /// Refuses every tool one MCP server publishes.
329    /// #[derive(Debug)]
330    /// struct BlockServer(&'static str);
331    ///
332    /// #[async_trait]
333    /// impl ToolPolicy for BlockServer {
334    ///     async fn evaluate(&self, _request: &ToolPolicyRequest) -> PolicyDecision {
335    ///         PolicyDecision::Allow
336    ///     }
337    ///
338    ///     async fn evaluate_call(
339    ///         &self,
340    ///         request: &ToolPolicyRequest,
341    ///         call: &PolicyCall<'_>,
342    ///     ) -> PolicyDecision {
343    ///         match call.origin {
344    ///             Some(origin) if origin.source == self.0 => {
345    ///                 PolicyDecision::deny(format!("tools from '{}' are blocked", origin.source))
346    ///             }
347    ///             _ => self.evaluate(request).await,
348    ///         }
349    ///     }
350    /// }
351    ///
352    /// # futures::executor::block_on(async {
353    /// let policy = BlockServer("mcp:evil");
354    /// let request = ToolPolicyRequest::new("search", json!({}));
355    /// let evil = ToolOrigin::new("mcp:evil", &json!({ "name": "search" }), None);
356    /// let call = PolicyCall::new().with_origin(&evil);
357    /// assert!(matches!(policy.evaluate_call(&request, &call).await, PolicyDecision::Deny { .. }));
358    /// assert_eq!(policy.evaluate_call(&request, &PolicyCall::new()).await, PolicyDecision::Allow);
359    /// # });
360    /// ```
361    async fn evaluate_call(
362        &self,
363        request: &ToolPolicyRequest,
364        call: &PolicyCall<'_>,
365    ) -> PolicyDecision {
366        let _ = call;
367        self.evaluate(request).await
368    }
369
370    /// A name or version for audit records, which cite the policy as
371    /// `tool_policy:<name>`. The default is `None`, cited as `tool_policy`.
372    fn policy_ref(&self) -> Option<String> {
373        None
374    }
375}
376
377/// A predicate over one argument, addressed by a JSON pointer (RFC 6901).
378///
379/// A predicate whose pointer does not resolve, or resolves to a value of the wrong
380/// type, does not hold, so the rule it belongs to does not match.
381///
382/// # Example
383///
384/// ```rust
385/// use adk_core::ArgPredicate;
386/// use serde_json::json;
387///
388/// let small = ArgPredicate::at_most("/amount", 100.0);
389/// assert!(small.holds(&json!({ "amount": 99.5 })));
390/// assert!(!small.holds(&json!({ "amount": 101 })));
391/// assert!(!small.holds(&json!({ "amount": "99" })));
392///
393/// let docs = ArgPredicate::domain_in("/url", ["docs.rs", "*.example.com"]);
394/// assert!(docs.holds(&json!({ "url": "https://docs.rs/serde" })));
395/// assert!(docs.holds(&json!({ "url": "https://api.example.com/v1" })));
396/// assert!(!docs.holds(&json!({ "url": "https://docs.rs@evil.test/" })));
397/// ```
398#[derive(Debug, Clone, PartialEq)]
399pub enum ArgPredicate {
400    /// The argument equals `value`.
401    Equals {
402        /// JSON pointer to the argument.
403        pointer: String,
404        /// The required value.
405        value: Value,
406    },
407    /// The argument equals one of `values`.
408    InSet {
409        /// JSON pointer to the argument.
410        pointer: String,
411        /// The permitted values.
412        values: Vec<Value>,
413    },
414    /// The argument is a JSON number no greater than `max`.
415    AtMost {
416        /// JSON pointer to the argument.
417        pointer: String,
418        /// The largest permitted value.
419        max: f64,
420    },
421    /// The argument is a string starting with `prefix`.
422    ///
423    /// The comparison is lexical. For filesystem paths, where `..` segments defeat a
424    /// prefix, screen the call with a path guardrail as well.
425    StartsWith {
426        /// JSON pointer to the argument.
427        pointer: String,
428        /// The required prefix.
429        prefix: String,
430    },
431    /// The argument is an `http` or `https` URL whose host is in `domains`.
432    ///
433    /// An entry matches its host exactly; an entry written `*.example.com` matches any
434    /// subdomain of `example.com` but not `example.com` itself. A URL with user
435    /// information, a backslash, percent-encoding, or any character outside
436    /// `[a-z0-9.-]` in its host does not match, so a URL that parsers could read two
437    /// ways is refused.
438    DomainIn {
439        /// JSON pointer to the argument.
440        pointer: String,
441        /// The permitted hosts.
442        domains: Vec<String>,
443    },
444}
445
446impl ArgPredicate {
447    /// The argument at `pointer` equals `value`.
448    pub fn equals(pointer: impl Into<String>, value: Value) -> Self {
449        Self::Equals { pointer: pointer.into(), value }
450    }
451
452    /// The argument at `pointer` equals one of `values`.
453    pub fn in_set(pointer: impl Into<String>, values: impl IntoIterator<Item = Value>) -> Self {
454        Self::InSet { pointer: pointer.into(), values: values.into_iter().collect() }
455    }
456
457    /// The argument at `pointer` is a number no greater than `max`.
458    pub fn at_most(pointer: impl Into<String>, max: f64) -> Self {
459        Self::AtMost { pointer: pointer.into(), max }
460    }
461
462    /// The argument at `pointer` is a string starting with `prefix`.
463    pub fn starts_with(pointer: impl Into<String>, prefix: impl Into<String>) -> Self {
464        Self::StartsWith { pointer: pointer.into(), prefix: prefix.into() }
465    }
466
467    /// The argument at `pointer` is an `http(s)` URL whose host is in `domains`.
468    pub fn domain_in(
469        pointer: impl Into<String>,
470        domains: impl IntoIterator<Item = impl Into<String>>,
471    ) -> Self {
472        Self::DomainIn {
473            pointer: pointer.into(),
474            domains: domains.into_iter().map(|d| d.into().to_ascii_lowercase()).collect(),
475        }
476    }
477
478    /// Whether the predicate holds for `args`.
479    pub fn holds(&self, args: &Value) -> bool {
480        match self {
481            Self::Equals { pointer, value } => args.pointer(pointer) == Some(value),
482            Self::InSet { pointer, values } => {
483                args.pointer(pointer).is_some_and(|actual| values.contains(actual))
484            }
485            Self::AtMost { pointer, max } => {
486                args.pointer(pointer).and_then(Value::as_f64).is_some_and(|actual| actual <= *max)
487            }
488            Self::StartsWith { pointer, prefix } => args
489                .pointer(pointer)
490                .and_then(Value::as_str)
491                .is_some_and(|actual| actual.starts_with(prefix.as_str())),
492            Self::DomainIn { pointer, domains } => args
493                .pointer(pointer)
494                .and_then(Value::as_str)
495                .and_then(url_host)
496                .is_some_and(|host| domains.iter().any(|domain| domain_matches(domain, &host))),
497        }
498    }
499}
500
501/// Extracts the host of an `http` or `https` URL, refusing anything ambiguous.
502///
503/// Parsers disagree about backslashes, user information, percent-encoded hosts, and
504/// embedded whitespace, so any of those yields `None` rather than a host that a client
505/// might resolve differently.
506fn url_host(url: &str) -> Option<String> {
507    let lower = url.to_ascii_lowercase();
508    let rest = lower.strip_prefix("https://").or_else(|| lower.strip_prefix("http://"))?;
509    let end = rest.find(['/', '?', '#', '\\']).unwrap_or(rest.len());
510    if rest[end..].starts_with('\\') {
511        return None;
512    }
513    let authority = &rest[..end];
514    let host = match authority.rsplit_once(':') {
515        Some((host, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => host,
516        Some(_) => return None,
517        None => authority,
518    };
519    let host = host.strip_suffix('.').unwrap_or(host);
520    let valid = !host.is_empty()
521        && host
522            .bytes()
523            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-')
524        && !host.split('.').any(str::is_empty);
525    valid.then(|| host.to_string())
526}
527
528fn domain_matches(domain: &str, host: &str) -> bool {
529    match domain.strip_prefix("*.") {
530        Some(parent) => host.strip_suffix(parent).is_some_and(|sub| sub.ends_with('.')),
531        None => domain == host,
532    }
533}
534
535/// Matches `name` against a glob where `*` matches any run of characters and `?`
536/// matches exactly one.
537fn glob_matches(pattern: &str, name: &str) -> bool {
538    let pattern: Vec<char> = pattern.chars().collect();
539    let name: Vec<char> = name.chars().collect();
540    let (mut p, mut n) = (0, 0);
541    let mut backtrack: Option<(usize, usize)> = None;
542    while n < name.len() {
543        if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
544            p += 1;
545            n += 1;
546        } else if p < pattern.len() && pattern[p] == '*' {
547            backtrack = Some((p, n));
548            p += 1;
549        } else if let Some((star, matched)) = backtrack {
550            p = star + 1;
551            n = matched + 1;
552            backtrack = Some((star, matched + 1));
553        } else {
554            return false;
555        }
556    }
557    pattern[p..].iter().all(|c| *c == '*')
558}
559
560/// One rule of a [`DeclarativePolicy`].
561///
562/// A rule matches a call when its tool-name glob matches, its read-only condition (if
563/// any) holds, and every argument predicate holds. The first matching rule decides.
564///
565/// # Example
566///
567/// ```rust
568/// use adk_core::{ArgPredicate, PolicyRule, ToolPolicyRequest};
569/// use serde_json::json;
570///
571/// let rule = PolicyRule::allow("transfer_*").when(ArgPredicate::at_most("/amount", 50.0));
572/// assert!(rule.matches(&ToolPolicyRequest::new("transfer_usd", json!({ "amount": 20 }))));
573/// assert!(!rule.matches(&ToolPolicyRequest::new("transfer_usd", json!({ "amount": 80 }))));
574/// ```
575#[derive(Debug, Clone, PartialEq)]
576pub struct PolicyRule {
577    tool_pattern: String,
578    agent_pattern: Option<String>,
579    tenant: Option<String>,
580    class: Option<String>,
581    effect: Option<ToolEffect>,
582    predicates: Vec<ArgPredicate>,
583    decision: PolicyDecision,
584}
585
586impl PolicyRule {
587    /// A rule that decides `decision` for calls to tools matching `tool_pattern`.
588    pub fn new(tool_pattern: impl Into<String>, decision: PolicyDecision) -> Self {
589        Self {
590            tool_pattern: tool_pattern.into(),
591            agent_pattern: None,
592            tenant: None,
593            class: None,
594            effect: None,
595            predicates: Vec::new(),
596            decision,
597        }
598    }
599
600    /// A rule allowing calls to tools matching `tool_pattern`.
601    pub fn allow(tool_pattern: impl Into<String>) -> Self {
602        Self::new(tool_pattern, PolicyDecision::Allow)
603    }
604
605    /// A rule refusing calls to tools matching `tool_pattern`.
606    pub fn deny(tool_pattern: impl Into<String>, reason: impl Into<String>) -> Self {
607        Self::new(tool_pattern, PolicyDecision::deny(reason))
608    }
609
610    /// A rule requiring approval for calls to tools matching `tool_pattern`.
611    pub fn require_approval(tool_pattern: impl Into<String>, reason: impl Into<String>) -> Self {
612        Self::new(tool_pattern, PolicyDecision::require_approval(reason))
613    }
614
615    /// Adds an argument predicate; every predicate must hold for the rule to match.
616    #[must_use]
617    pub fn when(mut self, predicate: ArgPredicate) -> Self {
618        self.predicates.push(predicate);
619        self
620    }
621
622    /// Restricts the rule to read-only tools.
623    #[must_use]
624    pub fn read_only_tools(self) -> Self {
625        self.with_effect(ToolEffect::ReadOnly)
626    }
627
628    /// Restricts the rule to tools that declare `effect`.
629    ///
630    /// # Example
631    ///
632    /// ```rust
633    /// use adk_core::{PolicyDecision, PolicyRule, ToolEffect, ToolPolicyRequest};
634    /// use serde_json::json;
635    ///
636    /// let rule = PolicyRule::require_approval("*", "side effects")
637    ///     .with_effect(ToolEffect::NonIdempotent);
638    /// let charge = ToolPolicyRequest::new("charge_card", json!({}));
639    /// let lookup = ToolPolicyRequest::new("get_order", json!({})).with_effect(ToolEffect::Idempotent);
640    /// assert!(rule.matches(&charge));
641    /// assert!(!rule.matches(&lookup));
642    /// ```
643    #[must_use]
644    pub fn with_effect(mut self, effect: ToolEffect) -> Self {
645        self.effect = Some(effect);
646        self
647    }
648
649    /// Restricts the rule to agents whose [`AgentId`](crate::AgentId) matches the glob
650    /// `agent_pattern`.
651    ///
652    /// A call with no acting context does not match.
653    ///
654    /// # Example
655    ///
656    /// ```rust
657    /// use adk_core::{ActingContext, PolicyRule, SubjectKind, ToolPolicyRequest};
658    /// use serde_json::json;
659    ///
660    /// let rule = PolicyRule::allow("refund").for_agent("urn:adk:agent:shop/support-*");
661    /// let call = |agent: &str| {
662    ///     ToolPolicyRequest::new("refund", json!({}))
663    ///         .with_acting_context(ActingContext::derived("shop", agent, "u", SubjectKind::Human))
664    /// };
665    /// assert!(rule.matches(&call("support-eu")));
666    /// assert!(!rule.matches(&call("marketing")));
667    /// assert!(!rule.matches(&ToolPolicyRequest::new("refund", json!({}))));
668    /// ```
669    #[must_use]
670    pub fn for_agent(mut self, agent_pattern: impl Into<String>) -> Self {
671        self.agent_pattern = Some(agent_pattern.into());
672        self
673    }
674
675    /// Restricts the rule to agents of `tenant` ([`AgentPrincipal::tenant`](crate::AgentPrincipal::tenant)).
676    #[must_use]
677    pub fn for_tenant(mut self, tenant: impl Into<String>) -> Self {
678        self.tenant = Some(tenant.into());
679        self
680    }
681
682    /// Restricts the rule to agents of `class` ([`AgentPrincipal::class`](crate::AgentPrincipal::class)).
683    #[must_use]
684    pub fn for_class(mut self, class: impl Into<String>) -> Self {
685        self.class = Some(class.into());
686        self
687    }
688
689    /// The decision the rule makes when it matches.
690    pub fn decision(&self) -> &PolicyDecision {
691        &self.decision
692    }
693
694    /// Whether the rule matches `request`.
695    pub fn matches(&self, request: &ToolPolicyRequest) -> bool {
696        let principal = request.acting.as_ref().map(|acting| &acting.agent);
697        let identity_matches =
698            |required: &Option<String>, actual: fn(&crate::AgentPrincipal) -> Option<&str>| {
699                required
700                    .as_deref()
701                    .is_none_or(|required| principal.and_then(actual) == Some(required))
702            };
703        glob_matches(&self.tool_pattern, &request.tool_name)
704            && self.agent_pattern.as_deref().is_none_or(|pattern| {
705                principal.is_some_and(|principal| glob_matches(pattern, principal.id.as_str()))
706            })
707            && identity_matches(&self.tenant, |principal| principal.tenant.as_deref())
708            && identity_matches(&self.class, |principal| principal.class.as_deref())
709            && self.effect.is_none_or(|effect| effect == request.effect)
710            && self.predicates.iter().all(|predicate| predicate.holds(&request.args))
711    }
712}
713
714/// A rule list matched in order, with a default decision for calls no rule matches.
715///
716/// The default decision is **deny**, so a tool that no rule permits does not run.
717/// Build one with [`DeclarativePolicy::builder`].
718///
719/// # Example
720///
721/// ```rust
722/// use adk_core::{ArgPredicate, DeclarativePolicy, PolicyDecision, PolicyRule, ToolPolicyRequest};
723/// use serde_json::json;
724///
725/// let policy = DeclarativePolicy::builder()
726///     .allow_read_only()
727///     .rule(PolicyRule::allow("transfer").when(ArgPredicate::at_most("/amount", 100.0)))
728///     .rule(PolicyRule::require_approval("transfer", "transfers over 100 need approval"))
729///     .build();
730///
731/// let small = ToolPolicyRequest::new("transfer", json!({ "amount": 40 }));
732/// let large = ToolPolicyRequest::new("transfer", json!({ "amount": 4000 }));
733/// let unlisted = ToolPolicyRequest::new("delete_account", json!({}));
734///
735/// assert_eq!(policy.decide(&small), PolicyDecision::Allow);
736/// assert!(matches!(policy.decide(&large), PolicyDecision::RequireApproval { .. }));
737/// assert!(matches!(policy.decide(&unlisted), PolicyDecision::Deny { .. }));
738/// ```
739#[derive(Debug, Clone, PartialEq)]
740pub struct DeclarativePolicy {
741    rules: Vec<PolicyRule>,
742    default_decision: Option<PolicyDecision>,
743    name: Option<String>,
744}
745
746impl DeclarativePolicy {
747    /// Starts a policy with no rules and a default decision of deny.
748    pub fn builder() -> DeclarativePolicyBuilder {
749        DeclarativePolicyBuilder::default()
750    }
751
752    /// The rules, in match order.
753    pub fn rules(&self) -> &[PolicyRule] {
754        &self.rules
755    }
756
757    /// Decides one call: the first matching rule's decision, else the default.
758    pub fn decide(&self, request: &ToolPolicyRequest) -> PolicyDecision {
759        if let Some(rule) = self.rules.iter().find(|rule| rule.matches(request)) {
760            return rule.decision.clone();
761        }
762        self.default_decision.clone().unwrap_or_else(|| {
763            PolicyDecision::deny(format!(
764                "no policy rule permits tool '{}'; it is denied by default",
765                request.tool_name
766            ))
767        })
768    }
769}
770
771#[async_trait]
772impl ToolPolicy for DeclarativePolicy {
773    async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
774        self.decide(request)
775    }
776
777    fn policy_ref(&self) -> Option<String> {
778        self.name.clone()
779    }
780}
781
782/// Builder for [`DeclarativePolicy`].
783#[derive(Debug, Clone, Default)]
784pub struct DeclarativePolicyBuilder {
785    rules: Vec<PolicyRule>,
786    default_decision: Option<PolicyDecision>,
787    name: Option<String>,
788}
789
790impl DeclarativePolicyBuilder {
791    /// Appends a rule. Rules are matched in the order they are added.
792    #[must_use]
793    pub fn rule(mut self, rule: PolicyRule) -> Self {
794        self.rules.push(rule);
795        self
796    }
797
798    /// Appends a rule allowing calls to tools matching `tool_pattern`.
799    #[must_use]
800    pub fn allow(self, tool_pattern: impl Into<String>) -> Self {
801        self.rule(PolicyRule::allow(tool_pattern))
802    }
803
804    /// Appends a rule refusing calls to tools matching `tool_pattern`.
805    #[must_use]
806    pub fn deny(self, tool_pattern: impl Into<String>, reason: impl Into<String>) -> Self {
807        self.rule(PolicyRule::deny(tool_pattern, reason))
808    }
809
810    /// Appends a rule requiring approval for calls to tools matching `tool_pattern`.
811    #[must_use]
812    pub fn require_approval(
813        self,
814        tool_pattern: impl Into<String>,
815        reason: impl Into<String>,
816    ) -> Self {
817        self.rule(PolicyRule::require_approval(tool_pattern, reason))
818    }
819
820    /// Appends a rule allowing every read-only tool.
821    ///
822    /// Rules added before it still take precedence, so a read-only tool can be denied
823    /// by name ahead of this rule.
824    #[must_use]
825    pub fn allow_read_only(self) -> Self {
826        self.rule(PolicyRule::allow("*").read_only_tools())
827    }
828
829    /// Sets the decision for calls no rule matches. The default is deny.
830    #[must_use]
831    pub fn default_decision(mut self, decision: PolicyDecision) -> Self {
832        self.default_decision = Some(decision);
833        self
834    }
835
836    /// Names the policy, such as `payments-v3`, so audit records cite it as
837    /// `tool_policy:payments-v3`.
838    #[must_use]
839    pub fn name(mut self, name: impl Into<String>) -> Self {
840        self.name = Some(name.into());
841        self
842    }
843
844    /// Builds the policy.
845    pub fn build(self) -> DeclarativePolicy {
846        DeclarativePolicy {
847            rules: self.rules,
848            default_decision: self.default_decision,
849            name: self.name,
850        }
851    }
852}
853
854/// Several policies applied together: every layer decides each call, and the strictest
855/// decision wins.
856///
857/// `Deny` is stricter than `RequireApproval`, which is stricter than `Allow`
858/// ([`PolicyDecision::stricter`]); between equally strict decisions the earlier layer's
859/// reason is kept. Each layer is asked through [`ToolPolicy::evaluate_call`] with the
860/// call's [`PolicyCall`] facts. With no layers every call is allowed, as with no policy.
861///
862/// Use it to add a policy to a run that already has one without replacing it: an
863/// [`Agent::configure_run`](crate::Agent::configure_run) hook runs on every run, on
864/// transfer and for delegates, so it checks [`contains_ref`](Self::contains_ref) before
865/// adding its layer and never nests it twice.
866///
867/// Spec 3.1 §10, C2.
868///
869/// # Example
870///
871/// ```rust
872/// use adk_core::{
873///     DeclarativePolicy, PolicyDecision, RunConfig, StrictestPolicy, ToolPolicy,
874///     ToolPolicyRequest,
875/// };
876/// use serde_json::json;
877/// use std::sync::Arc;
878///
879/// let operator = DeclarativePolicy::builder().name("ops-v3").allow("*").build();
880/// let harness = DeclarativePolicy::builder()
881///     .name("adk-harness")
882///     .require_approval("bash", "shell commands need a person")
883///     .allow("*")
884///     .build();
885///
886/// /// Adds the harness layer to whatever policy the run already has, once.
887/// fn add_layer(config: &mut RunConfig, layer: Arc<dyn ToolPolicy>) {
888///     let Some(existing) = config.tool_policy.take() else {
889///         config.tool_policy = Some(layer);
890///         return;
891///     };
892///     let composed = StrictestPolicy::new(vec![existing.clone()]);
893///     config.tool_policy = Some(if composed.contains_ref("adk-harness") {
894///         existing
895///     } else {
896///         Arc::new(composed.layer(layer))
897///     });
898/// }
899///
900/// let mut config = RunConfig::builder().tool_policy(Arc::new(operator)).build();
901/// let harness: Arc<dyn ToolPolicy> = Arc::new(harness);
902/// for _ in 0..3 {
903///     add_layer(&mut config, harness.clone());
904/// }
905/// let policy = config.tool_policy.unwrap();
906/// assert_eq!(policy.policy_ref().as_deref(), Some("ops-v3+adk-harness"));
907///
908/// # futures::executor::block_on(async {
909/// let bash = ToolPolicyRequest::new("bash", json!({ "command": "ls" }));
910/// assert!(matches!(policy.evaluate(&bash).await, PolicyDecision::RequireApproval { .. }));
911/// # });
912/// ```
913#[derive(Debug, Clone, Default)]
914pub struct StrictestPolicy {
915    layers: Vec<Arc<dyn ToolPolicy>>,
916}
917
918impl StrictestPolicy {
919    /// A policy over `layers`, asked in order.
920    pub fn new(layers: Vec<Arc<dyn ToolPolicy>>) -> Self {
921        Self { layers }
922    }
923
924    /// Appends `policy` as the last layer.
925    #[must_use]
926    pub fn layer(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
927        self.layers.push(policy);
928        self
929    }
930
931    /// The layers, in the order they are asked.
932    pub fn layers(&self) -> &[Arc<dyn ToolPolicy>] {
933        &self.layers
934    }
935
936    /// Whether a layer, or a layer of a nested `StrictestPolicy`, names itself
937    /// `policy_ref`.
938    ///
939    /// # Example
940    ///
941    /// ```rust
942    /// use adk_core::{DeclarativePolicy, StrictestPolicy};
943    /// use std::sync::Arc;
944    ///
945    /// let named = |name: &str| Arc::new(DeclarativePolicy::builder().name(name).build());
946    /// let inner = StrictestPolicy::new(vec![named("ops-v3"), named("adk-harness")]);
947    /// let outer = StrictestPolicy::new(vec![Arc::new(inner), named("tenant")]);
948    /// assert!(outer.contains_ref("adk-harness"));
949    /// assert!(!outer.contains_ref("adk"));
950    /// ```
951    pub fn contains_ref(&self, policy_ref: &str) -> bool {
952        self.layers.iter().filter_map(|layer| layer.policy_ref()).any(|layer_ref| {
953            layer_ref == policy_ref
954                || layer_ref.split(STRICTEST_REF_SEPARATOR).any(|part| part == policy_ref)
955        })
956    }
957}
958
959/// Joins the layer names in [`StrictestPolicy::policy_ref`].
960const STRICTEST_REF_SEPARATOR: char = '+';
961
962#[async_trait]
963impl ToolPolicy for StrictestPolicy {
964    async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
965        self.evaluate_call(request, &PolicyCall::new()).await
966    }
967
968    async fn evaluate_call(
969        &self,
970        request: &ToolPolicyRequest,
971        call: &PolicyCall<'_>,
972    ) -> PolicyDecision {
973        let mut decision = PolicyDecision::Allow;
974        // Every layer is asked, so each one observes (and can audit) every call.
975        for layer in &self.layers {
976            decision = decision.stricter(layer.evaluate_call(request, call).await);
977        }
978        decision
979    }
980
981    /// The named layers' references joined with `+`, such as `ops-v3+adk-harness`;
982    /// unnamed layers are left out, and `None` when no layer is named.
983    fn policy_ref(&self) -> Option<String> {
984        let names: Vec<String> =
985            self.layers.iter().filter_map(|layer| layer.policy_ref()).collect();
986        (!names.is_empty()).then(|| names.join(&STRICTEST_REF_SEPARATOR.to_string()))
987    }
988}
989
990#[cfg(test)]
991mod tests {
992    use super::*;
993    use serde_json::json;
994
995    #[test]
996    fn glob_matching() {
997        assert!(glob_matches("*", "anything"));
998        assert!(glob_matches("send_*", "send_email"));
999        assert!(!glob_matches("send_*", "resend_email"));
1000        assert!(glob_matches("*_file", "delete_file"));
1001        assert!(glob_matches("get_?", "get_x"));
1002        assert!(!glob_matches("get_?", "get_xy"));
1003        assert!(glob_matches("a*b*c", "aXXbYYc"));
1004        assert!(!glob_matches("a*b*c", "aXXbYY"));
1005        assert!(glob_matches("exact", "exact"));
1006        assert!(!glob_matches("exact", "exactly"));
1007    }
1008
1009    #[test]
1010    fn url_hosts_refuse_ambiguous_forms() {
1011        assert_eq!(url_host("https://Docs.RS/serde").as_deref(), Some("docs.rs"));
1012        assert_eq!(url_host("http://example.com:8080/x").as_deref(), Some("example.com"));
1013        assert_eq!(url_host("https://example.com.").as_deref(), Some("example.com"));
1014        assert_eq!(url_host("https://example.com?q=1").as_deref(), Some("example.com"));
1015        assert_eq!(url_host("https://example.com#frag").as_deref(), Some("example.com"));
1016        for ambiguous in [
1017            "https://allowed.com@evil.test/",
1018            "https://evil.test\\@allowed.com",
1019            "https://allowed.com\\.evil.test",
1020            "https://%61llowed.com/",
1021            "https://[::1]/",
1022            "https://allowed.com:/",
1023            "https://allowed.com:80x/",
1024            "https://allowed.com\t.evil.test",
1025            "https://allowed..com",
1026            "https:///path",
1027            "ftp://allowed.com/",
1028            "allowed.com/path",
1029            " https://allowed.com",
1030        ] {
1031            assert_eq!(url_host(ambiguous), None, "{ambiguous}");
1032        }
1033    }
1034
1035    #[test]
1036    fn domain_patterns() {
1037        assert!(domain_matches("example.com", "example.com"));
1038        assert!(!domain_matches("example.com", "api.example.com"));
1039        assert!(domain_matches("*.example.com", "api.example.com"));
1040        assert!(!domain_matches("*.example.com", "example.com"));
1041        assert!(!domain_matches("*.example.com", "badexample.com"));
1042    }
1043
1044    #[test]
1045    fn predicates_fail_closed_on_missing_or_mistyped_arguments() {
1046        let args = json!({ "amount": "5", "nested": { "region": "eu" } });
1047        assert!(!ArgPredicate::at_most("/amount", 10.0).holds(&args));
1048        assert!(!ArgPredicate::at_most("/missing", 10.0).holds(&args));
1049        assert!(ArgPredicate::equals("/nested/region", json!("eu")).holds(&args));
1050        assert!(ArgPredicate::in_set("/nested/region", [json!("us"), json!("eu")]).holds(&args));
1051        assert!(!ArgPredicate::in_set("/nested/region", [json!("us")]).holds(&args));
1052        assert!(!ArgPredicate::starts_with("/amount", "6").holds(&args));
1053        assert!(!ArgPredicate::domain_in("/nested", ["eu"]).holds(&args));
1054    }
1055
1056    #[test]
1057    fn rules_match_in_order_and_unlisted_tools_are_denied() {
1058        let policy = DeclarativePolicy::builder()
1059            .deny("lookup_secret", "secrets are off limits")
1060            .allow_read_only()
1061            .rule(PolicyRule::allow("fetch").when(ArgPredicate::domain_in("/url", ["docs.rs"])))
1062            .build();
1063
1064        let read = |name: &str| ToolPolicyRequest::new(name, json!({})).with_read_only(true);
1065        assert_eq!(policy.decide(&read("search")), PolicyDecision::Allow);
1066        assert_eq!(
1067            policy.decide(&read("lookup_secret")),
1068            PolicyDecision::deny("secrets are off limits")
1069        );
1070        assert_eq!(
1071            policy.decide(&ToolPolicyRequest::new("fetch", json!({ "url": "https://docs.rs" }))),
1072            PolicyDecision::Allow
1073        );
1074        assert!(matches!(
1075            policy.decide(&ToolPolicyRequest::new("fetch", json!({ "url": "https://evil.test" }))),
1076            PolicyDecision::Deny { .. }
1077        ));
1078        assert!(matches!(
1079            policy.decide(&ToolPolicyRequest::new("delete", json!({}))),
1080            PolicyDecision::Deny { .. }
1081        ));
1082    }
1083
1084    #[test]
1085    fn rules_can_match_on_the_declared_effect() {
1086        let policy = DeclarativePolicy::builder()
1087            .rule(PolicyRule::allow("*").with_effect(ToolEffect::Idempotent))
1088            .require_approval("*", "may repeat a side effect")
1089            .build();
1090
1091        let idempotent =
1092            ToolPolicyRequest::new("put_record", json!({})).with_effect(ToolEffect::Idempotent);
1093        assert_eq!(policy.decide(&idempotent), PolicyDecision::Allow);
1094        assert_eq!(
1095            policy.decide(&ToolPolicyRequest::new("charge_card", json!({}))),
1096            PolicyDecision::require_approval("may repeat a side effect")
1097        );
1098        assert!(!idempotent.is_read_only());
1099        assert!(ToolPolicyRequest::new("search", json!({})).with_read_only(true).is_read_only());
1100    }
1101
1102    #[test]
1103    fn rules_can_match_on_the_acting_agent() {
1104        use crate::{ActingContext, AgentId, AgentPrincipal};
1105        let principal = |id: &str| AgentPrincipal::new(AgentId::new(id).unwrap());
1106        let policy = DeclarativePolicy::builder()
1107            .rule(PolicyRule::deny("*", "quarantined").for_agent("urn:adk:agent:ops/rogue"))
1108            .rule(PolicyRule::allow("deploy").for_tenant("acme").for_class("release-bot"))
1109            .rule(PolicyRule::allow("search").for_agent("urn:adk:agent:ops/*"))
1110            .build();
1111        let call = |tool: &str, principal: AgentPrincipal| {
1112            ToolPolicyRequest::new(tool, json!({}))
1113                .with_acting_context(ActingContext::new(principal))
1114        };
1115
1116        assert_eq!(
1117            policy.decide(&call("search", principal("urn:adk:agent:ops/rogue"))),
1118            PolicyDecision::deny("quarantined")
1119        );
1120        assert_eq!(
1121            policy.decide(&call("search", principal("urn:adk:agent:ops/scout"))),
1122            PolicyDecision::Allow
1123        );
1124        assert!(matches!(
1125            policy.decide(&call("search", principal("urn:adk:agent:dev/scout"))),
1126            PolicyDecision::Deny { .. }
1127        ));
1128        let release =
1129            principal("spiffe://acme/release").with_tenant("acme").with_class("release-bot");
1130        assert_eq!(policy.decide(&call("deploy", release.clone())), PolicyDecision::Allow);
1131        assert!(matches!(
1132            policy.decide(&call("deploy", release.with_tenant("globex"))),
1133            PolicyDecision::Deny { .. }
1134        ));
1135        assert!(matches!(
1136            policy.decide(&ToolPolicyRequest::new("deploy", json!({}))),
1137            PolicyDecision::Deny { .. }
1138        ));
1139    }
1140
1141    #[test]
1142    fn the_default_decision_can_be_replaced() {
1143        let policy = DeclarativePolicy::builder()
1144            .default_decision(PolicyDecision::require_approval("unlisted"))
1145            .build();
1146        assert_eq!(
1147            policy.decide(&ToolPolicyRequest::new("anything", json!({}))),
1148            PolicyDecision::require_approval("unlisted")
1149        );
1150    }
1151
1152    #[test]
1153    fn stricter_orders_decisions() {
1154        let allow = PolicyDecision::Allow;
1155        let approve = PolicyDecision::require_approval("a");
1156        let deny = PolicyDecision::deny("d");
1157        assert_eq!(allow.clone().stricter(approve.clone()), approve);
1158        assert_eq!(approve.clone().stricter(deny.clone()), deny);
1159        assert_eq!(deny.clone().stricter(allow), deny);
1160    }
1161
1162    /// A policy with a fixed decision that counts how often it is asked.
1163    #[derive(Debug)]
1164    struct Fixed {
1165        name: Option<&'static str>,
1166        decision: PolicyDecision,
1167        asked: std::sync::atomic::AtomicUsize,
1168    }
1169
1170    fn fixed(name: Option<&'static str>, decision: PolicyDecision) -> Arc<Fixed> {
1171        Arc::new(Fixed { name, decision, asked: std::sync::atomic::AtomicUsize::new(0) })
1172    }
1173
1174    #[async_trait]
1175    impl ToolPolicy for Fixed {
1176        async fn evaluate(&self, _request: &ToolPolicyRequest) -> PolicyDecision {
1177            self.asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1178            self.decision.clone()
1179        }
1180
1181        fn policy_ref(&self) -> Option<String> {
1182            self.name.map(str::to_string)
1183        }
1184    }
1185
1186    /// Denies the tools one publisher serves, and allows everything else.
1187    #[derive(Debug)]
1188    struct BlockSource(&'static str);
1189
1190    #[async_trait]
1191    impl ToolPolicy for BlockSource {
1192        async fn evaluate(&self, _request: &ToolPolicyRequest) -> PolicyDecision {
1193            PolicyDecision::Allow
1194        }
1195
1196        async fn evaluate_call(
1197            &self,
1198            _request: &ToolPolicyRequest,
1199            call: &PolicyCall<'_>,
1200        ) -> PolicyDecision {
1201            match call.origin {
1202                Some(origin) if origin.source == self.0 => PolicyDecision::deny("blocked source"),
1203                _ => PolicyDecision::Allow,
1204            }
1205        }
1206    }
1207
1208    fn request() -> ToolPolicyRequest {
1209        ToolPolicyRequest::new("search", json!({ "q": "rust" }))
1210    }
1211
1212    async fn strictest(layers: Vec<Arc<dyn ToolPolicy>>) -> PolicyDecision {
1213        StrictestPolicy::new(layers).evaluate_call(&request(), &PolicyCall::new()).await
1214    }
1215
1216    #[tokio::test]
1217    async fn evaluate_call_defaults_to_evaluate() {
1218        let origin = ToolOrigin::new("mcp:any", &json!({ "name": "search" }), None);
1219        let call = PolicyCall::new().with_origin(&origin).with_function_call_id("c1");
1220        let policy = DeclarativePolicy::builder().allow("search").build();
1221        assert_eq!(policy.evaluate_call(&request(), &call).await, PolicyDecision::Allow);
1222        let unlisted = ToolPolicyRequest::new("delete", json!({}));
1223        assert_eq!(policy.evaluate_call(&unlisted, &call).await, policy.evaluate(&unlisted).await);
1224    }
1225
1226    #[tokio::test]
1227    async fn the_strictest_layer_decides() {
1228        let allow = || fixed(None, PolicyDecision::Allow) as Arc<dyn ToolPolicy>;
1229        let approve =
1230            || fixed(None, PolicyDecision::require_approval("ask")) as Arc<dyn ToolPolicy>;
1231        let deny = || fixed(None, PolicyDecision::deny("no")) as Arc<dyn ToolPolicy>;
1232
1233        assert_eq!(strictest(vec![allow(), deny()]).await, PolicyDecision::deny("no"));
1234        assert_eq!(strictest(vec![deny(), allow()]).await, PolicyDecision::deny("no"));
1235        assert_eq!(
1236            strictest(vec![allow(), approve()]).await,
1237            PolicyDecision::require_approval("ask")
1238        );
1239        assert_eq!(
1240            strictest(vec![approve(), allow()]).await,
1241            PolicyDecision::require_approval("ask")
1242        );
1243        assert_eq!(strictest(vec![approve(), deny()]).await, PolicyDecision::deny("no"));
1244        assert_eq!(strictest(vec![allow(), allow()]).await, PolicyDecision::Allow);
1245        assert_eq!(strictest(vec![]).await, PolicyDecision::Allow);
1246
1247        // Between equally strict layers the earlier reason is kept.
1248        let first = fixed(None, PolicyDecision::deny("first"));
1249        let second = fixed(None, PolicyDecision::deny("second"));
1250        assert_eq!(strictest(vec![first, second]).await, PolicyDecision::deny("first"));
1251    }
1252
1253    #[tokio::test]
1254    async fn every_layer_is_asked_even_after_a_denial() {
1255        let deny = fixed(None, PolicyDecision::deny("no"));
1256        let allow = fixed(None, PolicyDecision::Allow);
1257        let policy = StrictestPolicy::new(vec![deny.clone()]).layer(allow.clone());
1258        assert_eq!(policy.evaluate(&request()).await, PolicyDecision::deny("no"));
1259        assert_eq!(deny.asked.load(std::sync::atomic::Ordering::SeqCst), 1);
1260        assert_eq!(allow.asked.load(std::sync::atomic::Ordering::SeqCst), 1);
1261        assert_eq!(policy.layers().len(), 2);
1262    }
1263
1264    #[tokio::test]
1265    async fn layers_receive_the_calls_facts() {
1266        let evil = ToolOrigin::new("mcp:evil", &json!({ "name": "search" }), None);
1267        let good = ToolOrigin::new("mcp:good", &json!({ "name": "search" }), None);
1268        let policy = StrictestPolicy::new(vec![
1269            fixed(Some("operator"), PolicyDecision::Allow) as Arc<dyn ToolPolicy>,
1270            Arc::new(BlockSource("mcp:evil")),
1271        ]);
1272        let decide = |origin| {
1273            let policy = &policy;
1274            async move { policy.evaluate_call(&request(), &PolicyCall::new().with_origin(origin)).await }
1275        };
1276        assert_eq!(decide(&evil).await, PolicyDecision::deny("blocked source"));
1277        assert_eq!(decide(&good).await, PolicyDecision::Allow);
1278        // Without the facts, the origin-aware layer cannot tell the call apart.
1279        assert_eq!(policy.evaluate(&request()).await, PolicyDecision::Allow);
1280    }
1281
1282    #[test]
1283    fn policy_ref_joins_the_named_layers() {
1284        let named = |name| fixed(Some(name), PolicyDecision::Allow) as Arc<dyn ToolPolicy>;
1285        let unnamed = || fixed(None, PolicyDecision::Allow) as Arc<dyn ToolPolicy>;
1286        let policy = StrictestPolicy::new(vec![named("ops-v3"), unnamed(), named("adk-harness")]);
1287        assert_eq!(policy.policy_ref().as_deref(), Some("ops-v3+adk-harness"));
1288        assert_eq!(StrictestPolicy::new(vec![unnamed()]).policy_ref(), None);
1289        assert_eq!(StrictestPolicy::default().policy_ref(), None);
1290
1291        let nested = StrictestPolicy::new(vec![Arc::new(policy), named("tenant")]);
1292        assert_eq!(nested.policy_ref().as_deref(), Some("ops-v3+adk-harness+tenant"));
1293        assert!(nested.contains_ref("adk-harness"));
1294        assert!(nested.contains_ref("tenant"));
1295        assert!(!nested.contains_ref("adk"));
1296        assert!(!nested.contains_ref("ops-v3+adk"));
1297    }
1298
1299    #[tokio::test]
1300    async fn layering_guarded_by_contains_ref_is_idempotent() {
1301        let harness: Arc<dyn ToolPolicy> =
1302            fixed(Some("adk-harness"), PolicyDecision::require_approval("harness"));
1303        let add_layer = |existing: Option<Arc<dyn ToolPolicy>>| -> Arc<dyn ToolPolicy> {
1304            let Some(existing) = existing else {
1305                return harness.clone();
1306            };
1307            let composed = StrictestPolicy::new(vec![existing.clone()]);
1308            if composed.contains_ref("adk-harness") {
1309                existing
1310            } else {
1311                Arc::new(composed.layer(harness.clone()))
1312            }
1313        };
1314
1315        let operator: Arc<dyn ToolPolicy> = fixed(Some("ops-v3"), PolicyDecision::Allow);
1316        let once = add_layer(Some(operator));
1317        let thrice = add_layer(Some(add_layer(Some(once.clone()))));
1318        assert!(Arc::ptr_eq(&once, &thrice), "the layer is added once");
1319        assert_eq!(thrice.policy_ref().as_deref(), Some("ops-v3+adk-harness"));
1320        assert_eq!(thrice.evaluate(&request()).await, PolicyDecision::require_approval("harness"));
1321
1322        let alone = add_layer(None);
1323        assert!(Arc::ptr_eq(&alone, &add_layer(Some(alone.clone()))));
1324    }
1325}