use std::sync::Arc;
use async_trait::async_trait;
use serde_json::Value;
use crate::{ToolEffect, ToolOrigin};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PolicyDecision {
Allow,
Deny {
reason: String,
},
RequireApproval {
reason: String,
},
}
impl PolicyDecision {
pub fn deny(reason: impl Into<String>) -> Self {
Self::Deny { reason: reason.into() }
}
pub fn require_approval(reason: impl Into<String>) -> Self {
Self::RequireApproval { reason: reason.into() }
}
#[must_use]
pub fn stricter(self, other: Self) -> Self {
if other.severity() > self.severity() { other } else { self }
}
fn severity(&self) -> u8 {
match self {
Self::Allow => 0,
Self::RequireApproval { .. } => 1,
Self::Deny { .. } => 2,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolPolicyRequest {
pub tool_name: String,
pub args: Value,
pub effect: ToolEffect,
pub agent_name: String,
pub app_name: String,
pub user_id: String,
pub session_id: String,
pub invocation_id: String,
pub acting: Option<crate::ActingContext>,
}
impl ToolPolicyRequest {
pub fn new(tool_name: impl Into<String>, args: Value) -> Self {
Self {
tool_name: tool_name.into(),
args,
effect: ToolEffect::NonIdempotent,
agent_name: String::new(),
app_name: String::new(),
user_id: String::new(),
session_id: String::new(),
invocation_id: String::new(),
acting: None,
}
}
pub fn agent_id(&self) -> Option<&crate::AgentId> {
self.acting.as_ref().map(|acting| &acting.agent.id)
}
#[must_use]
pub fn with_acting_context(mut self, acting: crate::ActingContext) -> Self {
self.acting = Some(acting);
self
}
pub fn is_read_only(&self) -> bool {
self.effect == ToolEffect::ReadOnly
}
#[must_use]
pub fn with_effect(mut self, effect: ToolEffect) -> Self {
self.effect = effect;
self
}
#[must_use]
pub fn with_read_only(self, read_only: bool) -> Self {
self.with_effect(if read_only { ToolEffect::ReadOnly } else { ToolEffect::NonIdempotent })
}
#[must_use]
pub fn with_agent_name(mut self, agent_name: impl Into<String>) -> Self {
self.agent_name = agent_name.into();
self
}
#[must_use]
pub fn with_identity(
mut self,
app_name: impl Into<String>,
user_id: impl Into<String>,
session_id: impl Into<String>,
) -> Self {
self.app_name = app_name.into();
self.user_id = user_id.into();
self.session_id = session_id.into();
self
}
#[must_use]
pub fn with_invocation_id(mut self, invocation_id: impl Into<String>) -> Self {
self.invocation_id = invocation_id.into();
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PolicyCall<'a> {
pub origin: Option<&'a ToolOrigin>,
pub function_call_id: Option<&'a str>,
pub durable_run_id: Option<&'a str>,
}
impl<'a> PolicyCall<'a> {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_origin(mut self, origin: &'a ToolOrigin) -> Self {
self.origin = Some(origin);
self
}
#[must_use]
pub fn with_function_call_id(mut self, function_call_id: &'a str) -> Self {
self.function_call_id = Some(function_call_id);
self
}
#[must_use]
pub fn with_durable_run_id(mut self, durable_run_id: &'a str) -> Self {
self.durable_run_id = Some(durable_run_id);
self
}
}
#[async_trait]
pub trait ToolPolicy: std::fmt::Debug + Send + Sync {
async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision;
async fn evaluate_call(
&self,
request: &ToolPolicyRequest,
call: &PolicyCall<'_>,
) -> PolicyDecision {
let _ = call;
self.evaluate(request).await
}
fn policy_ref(&self) -> Option<String> {
None
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ArgPredicate {
Equals {
pointer: String,
value: Value,
},
InSet {
pointer: String,
values: Vec<Value>,
},
AtMost {
pointer: String,
max: f64,
},
StartsWith {
pointer: String,
prefix: String,
},
DomainIn {
pointer: String,
domains: Vec<String>,
},
}
impl ArgPredicate {
pub fn equals(pointer: impl Into<String>, value: Value) -> Self {
Self::Equals { pointer: pointer.into(), value }
}
pub fn in_set(pointer: impl Into<String>, values: impl IntoIterator<Item = Value>) -> Self {
Self::InSet { pointer: pointer.into(), values: values.into_iter().collect() }
}
pub fn at_most(pointer: impl Into<String>, max: f64) -> Self {
Self::AtMost { pointer: pointer.into(), max }
}
pub fn starts_with(pointer: impl Into<String>, prefix: impl Into<String>) -> Self {
Self::StartsWith { pointer: pointer.into(), prefix: prefix.into() }
}
pub fn domain_in(
pointer: impl Into<String>,
domains: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
Self::DomainIn {
pointer: pointer.into(),
domains: domains.into_iter().map(|d| d.into().to_ascii_lowercase()).collect(),
}
}
pub fn holds(&self, args: &Value) -> bool {
match self {
Self::Equals { pointer, value } => args.pointer(pointer) == Some(value),
Self::InSet { pointer, values } => {
args.pointer(pointer).is_some_and(|actual| values.contains(actual))
}
Self::AtMost { pointer, max } => {
args.pointer(pointer).and_then(Value::as_f64).is_some_and(|actual| actual <= *max)
}
Self::StartsWith { pointer, prefix } => args
.pointer(pointer)
.and_then(Value::as_str)
.is_some_and(|actual| actual.starts_with(prefix.as_str())),
Self::DomainIn { pointer, domains } => args
.pointer(pointer)
.and_then(Value::as_str)
.and_then(url_host)
.is_some_and(|host| domains.iter().any(|domain| domain_matches(domain, &host))),
}
}
}
fn url_host(url: &str) -> Option<String> {
let lower = url.to_ascii_lowercase();
let rest = lower.strip_prefix("https://").or_else(|| lower.strip_prefix("http://"))?;
let end = rest.find(['/', '?', '#', '\\']).unwrap_or(rest.len());
if rest[end..].starts_with('\\') {
return None;
}
let authority = &rest[..end];
let host = match authority.rsplit_once(':') {
Some((host, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => host,
Some(_) => return None,
None => authority,
};
let host = host.strip_suffix('.').unwrap_or(host);
let valid = !host.is_empty()
&& host
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-')
&& !host.split('.').any(str::is_empty);
valid.then(|| host.to_string())
}
fn domain_matches(domain: &str, host: &str) -> bool {
match domain.strip_prefix("*.") {
Some(parent) => host.strip_suffix(parent).is_some_and(|sub| sub.ends_with('.')),
None => domain == host,
}
}
fn glob_matches(pattern: &str, name: &str) -> bool {
let pattern: Vec<char> = pattern.chars().collect();
let name: Vec<char> = name.chars().collect();
let (mut p, mut n) = (0, 0);
let mut backtrack: Option<(usize, usize)> = None;
while n < name.len() {
if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
p += 1;
n += 1;
} else if p < pattern.len() && pattern[p] == '*' {
backtrack = Some((p, n));
p += 1;
} else if let Some((star, matched)) = backtrack {
p = star + 1;
n = matched + 1;
backtrack = Some((star, matched + 1));
} else {
return false;
}
}
pattern[p..].iter().all(|c| *c == '*')
}
#[derive(Debug, Clone, PartialEq)]
pub struct PolicyRule {
tool_pattern: String,
agent_pattern: Option<String>,
tenant: Option<String>,
class: Option<String>,
effect: Option<ToolEffect>,
predicates: Vec<ArgPredicate>,
decision: PolicyDecision,
}
impl PolicyRule {
pub fn new(tool_pattern: impl Into<String>, decision: PolicyDecision) -> Self {
Self {
tool_pattern: tool_pattern.into(),
agent_pattern: None,
tenant: None,
class: None,
effect: None,
predicates: Vec::new(),
decision,
}
}
pub fn allow(tool_pattern: impl Into<String>) -> Self {
Self::new(tool_pattern, PolicyDecision::Allow)
}
pub fn deny(tool_pattern: impl Into<String>, reason: impl Into<String>) -> Self {
Self::new(tool_pattern, PolicyDecision::deny(reason))
}
pub fn require_approval(tool_pattern: impl Into<String>, reason: impl Into<String>) -> Self {
Self::new(tool_pattern, PolicyDecision::require_approval(reason))
}
#[must_use]
pub fn when(mut self, predicate: ArgPredicate) -> Self {
self.predicates.push(predicate);
self
}
#[must_use]
pub fn read_only_tools(self) -> Self {
self.with_effect(ToolEffect::ReadOnly)
}
#[must_use]
pub fn with_effect(mut self, effect: ToolEffect) -> Self {
self.effect = Some(effect);
self
}
#[must_use]
pub fn for_agent(mut self, agent_pattern: impl Into<String>) -> Self {
self.agent_pattern = Some(agent_pattern.into());
self
}
#[must_use]
pub fn for_tenant(mut self, tenant: impl Into<String>) -> Self {
self.tenant = Some(tenant.into());
self
}
#[must_use]
pub fn for_class(mut self, class: impl Into<String>) -> Self {
self.class = Some(class.into());
self
}
pub fn decision(&self) -> &PolicyDecision {
&self.decision
}
pub fn matches(&self, request: &ToolPolicyRequest) -> bool {
let principal = request.acting.as_ref().map(|acting| &acting.agent);
let identity_matches =
|required: &Option<String>, actual: fn(&crate::AgentPrincipal) -> Option<&str>| {
required
.as_deref()
.is_none_or(|required| principal.and_then(actual) == Some(required))
};
glob_matches(&self.tool_pattern, &request.tool_name)
&& self.agent_pattern.as_deref().is_none_or(|pattern| {
principal.is_some_and(|principal| glob_matches(pattern, principal.id.as_str()))
})
&& identity_matches(&self.tenant, |principal| principal.tenant.as_deref())
&& identity_matches(&self.class, |principal| principal.class.as_deref())
&& self.effect.is_none_or(|effect| effect == request.effect)
&& self.predicates.iter().all(|predicate| predicate.holds(&request.args))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct DeclarativePolicy {
rules: Vec<PolicyRule>,
default_decision: Option<PolicyDecision>,
name: Option<String>,
}
impl DeclarativePolicy {
pub fn builder() -> DeclarativePolicyBuilder {
DeclarativePolicyBuilder::default()
}
pub fn rules(&self) -> &[PolicyRule] {
&self.rules
}
pub fn decide(&self, request: &ToolPolicyRequest) -> PolicyDecision {
if let Some(rule) = self.rules.iter().find(|rule| rule.matches(request)) {
return rule.decision.clone();
}
self.default_decision.clone().unwrap_or_else(|| {
PolicyDecision::deny(format!(
"no policy rule permits tool '{}'; it is denied by default",
request.tool_name
))
})
}
}
#[async_trait]
impl ToolPolicy for DeclarativePolicy {
async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
self.decide(request)
}
fn policy_ref(&self) -> Option<String> {
self.name.clone()
}
}
#[derive(Debug, Clone, Default)]
pub struct DeclarativePolicyBuilder {
rules: Vec<PolicyRule>,
default_decision: Option<PolicyDecision>,
name: Option<String>,
}
impl DeclarativePolicyBuilder {
#[must_use]
pub fn rule(mut self, rule: PolicyRule) -> Self {
self.rules.push(rule);
self
}
#[must_use]
pub fn allow(self, tool_pattern: impl Into<String>) -> Self {
self.rule(PolicyRule::allow(tool_pattern))
}
#[must_use]
pub fn deny(self, tool_pattern: impl Into<String>, reason: impl Into<String>) -> Self {
self.rule(PolicyRule::deny(tool_pattern, reason))
}
#[must_use]
pub fn require_approval(
self,
tool_pattern: impl Into<String>,
reason: impl Into<String>,
) -> Self {
self.rule(PolicyRule::require_approval(tool_pattern, reason))
}
#[must_use]
pub fn allow_read_only(self) -> Self {
self.rule(PolicyRule::allow("*").read_only_tools())
}
#[must_use]
pub fn default_decision(mut self, decision: PolicyDecision) -> Self {
self.default_decision = Some(decision);
self
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn build(self) -> DeclarativePolicy {
DeclarativePolicy {
rules: self.rules,
default_decision: self.default_decision,
name: self.name,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct StrictestPolicy {
layers: Vec<Arc<dyn ToolPolicy>>,
}
impl StrictestPolicy {
pub fn new(layers: Vec<Arc<dyn ToolPolicy>>) -> Self {
Self { layers }
}
#[must_use]
pub fn layer(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
self.layers.push(policy);
self
}
pub fn layers(&self) -> &[Arc<dyn ToolPolicy>] {
&self.layers
}
pub fn contains_ref(&self, policy_ref: &str) -> bool {
self.layers.iter().filter_map(|layer| layer.policy_ref()).any(|layer_ref| {
layer_ref == policy_ref
|| layer_ref.split(STRICTEST_REF_SEPARATOR).any(|part| part == policy_ref)
})
}
}
const STRICTEST_REF_SEPARATOR: char = '+';
#[async_trait]
impl ToolPolicy for StrictestPolicy {
async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
self.evaluate_call(request, &PolicyCall::new()).await
}
async fn evaluate_call(
&self,
request: &ToolPolicyRequest,
call: &PolicyCall<'_>,
) -> PolicyDecision {
let mut decision = PolicyDecision::Allow;
for layer in &self.layers {
decision = decision.stricter(layer.evaluate_call(request, call).await);
}
decision
}
fn policy_ref(&self) -> Option<String> {
let names: Vec<String> =
self.layers.iter().filter_map(|layer| layer.policy_ref()).collect();
(!names.is_empty()).then(|| names.join(&STRICTEST_REF_SEPARATOR.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn glob_matching() {
assert!(glob_matches("*", "anything"));
assert!(glob_matches("send_*", "send_email"));
assert!(!glob_matches("send_*", "resend_email"));
assert!(glob_matches("*_file", "delete_file"));
assert!(glob_matches("get_?", "get_x"));
assert!(!glob_matches("get_?", "get_xy"));
assert!(glob_matches("a*b*c", "aXXbYYc"));
assert!(!glob_matches("a*b*c", "aXXbYY"));
assert!(glob_matches("exact", "exact"));
assert!(!glob_matches("exact", "exactly"));
}
#[test]
fn url_hosts_refuse_ambiguous_forms() {
assert_eq!(url_host("https://Docs.RS/serde").as_deref(), Some("docs.rs"));
assert_eq!(url_host("http://example.com:8080/x").as_deref(), Some("example.com"));
assert_eq!(url_host("https://example.com.").as_deref(), Some("example.com"));
assert_eq!(url_host("https://example.com?q=1").as_deref(), Some("example.com"));
assert_eq!(url_host("https://example.com#frag").as_deref(), Some("example.com"));
for ambiguous in [
"https://allowed.com@evil.test/",
"https://evil.test\\@allowed.com",
"https://allowed.com\\.evil.test",
"https://%61llowed.com/",
"https://[::1]/",
"https://allowed.com:/",
"https://allowed.com:80x/",
"https://allowed.com\t.evil.test",
"https://allowed..com",
"https:///path",
"ftp://allowed.com/",
"allowed.com/path",
" https://allowed.com",
] {
assert_eq!(url_host(ambiguous), None, "{ambiguous}");
}
}
#[test]
fn domain_patterns() {
assert!(domain_matches("example.com", "example.com"));
assert!(!domain_matches("example.com", "api.example.com"));
assert!(domain_matches("*.example.com", "api.example.com"));
assert!(!domain_matches("*.example.com", "example.com"));
assert!(!domain_matches("*.example.com", "badexample.com"));
}
#[test]
fn predicates_fail_closed_on_missing_or_mistyped_arguments() {
let args = json!({ "amount": "5", "nested": { "region": "eu" } });
assert!(!ArgPredicate::at_most("/amount", 10.0).holds(&args));
assert!(!ArgPredicate::at_most("/missing", 10.0).holds(&args));
assert!(ArgPredicate::equals("/nested/region", json!("eu")).holds(&args));
assert!(ArgPredicate::in_set("/nested/region", [json!("us"), json!("eu")]).holds(&args));
assert!(!ArgPredicate::in_set("/nested/region", [json!("us")]).holds(&args));
assert!(!ArgPredicate::starts_with("/amount", "6").holds(&args));
assert!(!ArgPredicate::domain_in("/nested", ["eu"]).holds(&args));
}
#[test]
fn rules_match_in_order_and_unlisted_tools_are_denied() {
let policy = DeclarativePolicy::builder()
.deny("lookup_secret", "secrets are off limits")
.allow_read_only()
.rule(PolicyRule::allow("fetch").when(ArgPredicate::domain_in("/url", ["docs.rs"])))
.build();
let read = |name: &str| ToolPolicyRequest::new(name, json!({})).with_read_only(true);
assert_eq!(policy.decide(&read("search")), PolicyDecision::Allow);
assert_eq!(
policy.decide(&read("lookup_secret")),
PolicyDecision::deny("secrets are off limits")
);
assert_eq!(
policy.decide(&ToolPolicyRequest::new("fetch", json!({ "url": "https://docs.rs" }))),
PolicyDecision::Allow
);
assert!(matches!(
policy.decide(&ToolPolicyRequest::new("fetch", json!({ "url": "https://evil.test" }))),
PolicyDecision::Deny { .. }
));
assert!(matches!(
policy.decide(&ToolPolicyRequest::new("delete", json!({}))),
PolicyDecision::Deny { .. }
));
}
#[test]
fn rules_can_match_on_the_declared_effect() {
let policy = DeclarativePolicy::builder()
.rule(PolicyRule::allow("*").with_effect(ToolEffect::Idempotent))
.require_approval("*", "may repeat a side effect")
.build();
let idempotent =
ToolPolicyRequest::new("put_record", json!({})).with_effect(ToolEffect::Idempotent);
assert_eq!(policy.decide(&idempotent), PolicyDecision::Allow);
assert_eq!(
policy.decide(&ToolPolicyRequest::new("charge_card", json!({}))),
PolicyDecision::require_approval("may repeat a side effect")
);
assert!(!idempotent.is_read_only());
assert!(ToolPolicyRequest::new("search", json!({})).with_read_only(true).is_read_only());
}
#[test]
fn rules_can_match_on_the_acting_agent() {
use crate::{ActingContext, AgentId, AgentPrincipal};
let principal = |id: &str| AgentPrincipal::new(AgentId::new(id).unwrap());
let policy = DeclarativePolicy::builder()
.rule(PolicyRule::deny("*", "quarantined").for_agent("urn:adk:agent:ops/rogue"))
.rule(PolicyRule::allow("deploy").for_tenant("acme").for_class("release-bot"))
.rule(PolicyRule::allow("search").for_agent("urn:adk:agent:ops/*"))
.build();
let call = |tool: &str, principal: AgentPrincipal| {
ToolPolicyRequest::new(tool, json!({}))
.with_acting_context(ActingContext::new(principal))
};
assert_eq!(
policy.decide(&call("search", principal("urn:adk:agent:ops/rogue"))),
PolicyDecision::deny("quarantined")
);
assert_eq!(
policy.decide(&call("search", principal("urn:adk:agent:ops/scout"))),
PolicyDecision::Allow
);
assert!(matches!(
policy.decide(&call("search", principal("urn:adk:agent:dev/scout"))),
PolicyDecision::Deny { .. }
));
let release =
principal("spiffe://acme/release").with_tenant("acme").with_class("release-bot");
assert_eq!(policy.decide(&call("deploy", release.clone())), PolicyDecision::Allow);
assert!(matches!(
policy.decide(&call("deploy", release.with_tenant("globex"))),
PolicyDecision::Deny { .. }
));
assert!(matches!(
policy.decide(&ToolPolicyRequest::new("deploy", json!({}))),
PolicyDecision::Deny { .. }
));
}
#[test]
fn the_default_decision_can_be_replaced() {
let policy = DeclarativePolicy::builder()
.default_decision(PolicyDecision::require_approval("unlisted"))
.build();
assert_eq!(
policy.decide(&ToolPolicyRequest::new("anything", json!({}))),
PolicyDecision::require_approval("unlisted")
);
}
#[test]
fn stricter_orders_decisions() {
let allow = PolicyDecision::Allow;
let approve = PolicyDecision::require_approval("a");
let deny = PolicyDecision::deny("d");
assert_eq!(allow.clone().stricter(approve.clone()), approve);
assert_eq!(approve.clone().stricter(deny.clone()), deny);
assert_eq!(deny.clone().stricter(allow), deny);
}
#[derive(Debug)]
struct Fixed {
name: Option<&'static str>,
decision: PolicyDecision,
asked: std::sync::atomic::AtomicUsize,
}
fn fixed(name: Option<&'static str>, decision: PolicyDecision) -> Arc<Fixed> {
Arc::new(Fixed { name, decision, asked: std::sync::atomic::AtomicUsize::new(0) })
}
#[async_trait]
impl ToolPolicy for Fixed {
async fn evaluate(&self, _request: &ToolPolicyRequest) -> PolicyDecision {
self.asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
self.decision.clone()
}
fn policy_ref(&self) -> Option<String> {
self.name.map(str::to_string)
}
}
#[derive(Debug)]
struct BlockSource(&'static str);
#[async_trait]
impl ToolPolicy for BlockSource {
async fn evaluate(&self, _request: &ToolPolicyRequest) -> PolicyDecision {
PolicyDecision::Allow
}
async fn evaluate_call(
&self,
_request: &ToolPolicyRequest,
call: &PolicyCall<'_>,
) -> PolicyDecision {
match call.origin {
Some(origin) if origin.source == self.0 => PolicyDecision::deny("blocked source"),
_ => PolicyDecision::Allow,
}
}
}
fn request() -> ToolPolicyRequest {
ToolPolicyRequest::new("search", json!({ "q": "rust" }))
}
async fn strictest(layers: Vec<Arc<dyn ToolPolicy>>) -> PolicyDecision {
StrictestPolicy::new(layers).evaluate_call(&request(), &PolicyCall::new()).await
}
#[tokio::test]
async fn evaluate_call_defaults_to_evaluate() {
let origin = ToolOrigin::new("mcp:any", &json!({ "name": "search" }), None);
let call = PolicyCall::new().with_origin(&origin).with_function_call_id("c1");
let policy = DeclarativePolicy::builder().allow("search").build();
assert_eq!(policy.evaluate_call(&request(), &call).await, PolicyDecision::Allow);
let unlisted = ToolPolicyRequest::new("delete", json!({}));
assert_eq!(policy.evaluate_call(&unlisted, &call).await, policy.evaluate(&unlisted).await);
}
#[tokio::test]
async fn the_strictest_layer_decides() {
let allow = || fixed(None, PolicyDecision::Allow) as Arc<dyn ToolPolicy>;
let approve =
|| fixed(None, PolicyDecision::require_approval("ask")) as Arc<dyn ToolPolicy>;
let deny = || fixed(None, PolicyDecision::deny("no")) as Arc<dyn ToolPolicy>;
assert_eq!(strictest(vec![allow(), deny()]).await, PolicyDecision::deny("no"));
assert_eq!(strictest(vec![deny(), allow()]).await, PolicyDecision::deny("no"));
assert_eq!(
strictest(vec![allow(), approve()]).await,
PolicyDecision::require_approval("ask")
);
assert_eq!(
strictest(vec![approve(), allow()]).await,
PolicyDecision::require_approval("ask")
);
assert_eq!(strictest(vec![approve(), deny()]).await, PolicyDecision::deny("no"));
assert_eq!(strictest(vec![allow(), allow()]).await, PolicyDecision::Allow);
assert_eq!(strictest(vec![]).await, PolicyDecision::Allow);
let first = fixed(None, PolicyDecision::deny("first"));
let second = fixed(None, PolicyDecision::deny("second"));
assert_eq!(strictest(vec![first, second]).await, PolicyDecision::deny("first"));
}
#[tokio::test]
async fn every_layer_is_asked_even_after_a_denial() {
let deny = fixed(None, PolicyDecision::deny("no"));
let allow = fixed(None, PolicyDecision::Allow);
let policy = StrictestPolicy::new(vec![deny.clone()]).layer(allow.clone());
assert_eq!(policy.evaluate(&request()).await, PolicyDecision::deny("no"));
assert_eq!(deny.asked.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(allow.asked.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(policy.layers().len(), 2);
}
#[tokio::test]
async fn layers_receive_the_calls_facts() {
let evil = ToolOrigin::new("mcp:evil", &json!({ "name": "search" }), None);
let good = ToolOrigin::new("mcp:good", &json!({ "name": "search" }), None);
let policy = StrictestPolicy::new(vec![
fixed(Some("operator"), PolicyDecision::Allow) as Arc<dyn ToolPolicy>,
Arc::new(BlockSource("mcp:evil")),
]);
let decide = |origin| {
let policy = &policy;
async move { policy.evaluate_call(&request(), &PolicyCall::new().with_origin(origin)).await }
};
assert_eq!(decide(&evil).await, PolicyDecision::deny("blocked source"));
assert_eq!(decide(&good).await, PolicyDecision::Allow);
assert_eq!(policy.evaluate(&request()).await, PolicyDecision::Allow);
}
#[test]
fn policy_ref_joins_the_named_layers() {
let named = |name| fixed(Some(name), PolicyDecision::Allow) as Arc<dyn ToolPolicy>;
let unnamed = || fixed(None, PolicyDecision::Allow) as Arc<dyn ToolPolicy>;
let policy = StrictestPolicy::new(vec![named("ops-v3"), unnamed(), named("adk-harness")]);
assert_eq!(policy.policy_ref().as_deref(), Some("ops-v3+adk-harness"));
assert_eq!(StrictestPolicy::new(vec![unnamed()]).policy_ref(), None);
assert_eq!(StrictestPolicy::default().policy_ref(), None);
let nested = StrictestPolicy::new(vec![Arc::new(policy), named("tenant")]);
assert_eq!(nested.policy_ref().as_deref(), Some("ops-v3+adk-harness+tenant"));
assert!(nested.contains_ref("adk-harness"));
assert!(nested.contains_ref("tenant"));
assert!(!nested.contains_ref("adk"));
assert!(!nested.contains_ref("ops-v3+adk"));
}
#[tokio::test]
async fn layering_guarded_by_contains_ref_is_idempotent() {
let harness: Arc<dyn ToolPolicy> =
fixed(Some("adk-harness"), PolicyDecision::require_approval("harness"));
let add_layer = |existing: Option<Arc<dyn ToolPolicy>>| -> Arc<dyn ToolPolicy> {
let Some(existing) = existing else {
return harness.clone();
};
let composed = StrictestPolicy::new(vec![existing.clone()]);
if composed.contains_ref("adk-harness") {
existing
} else {
Arc::new(composed.layer(harness.clone()))
}
};
let operator: Arc<dyn ToolPolicy> = fixed(Some("ops-v3"), PolicyDecision::Allow);
let once = add_layer(Some(operator));
let thrice = add_layer(Some(add_layer(Some(once.clone()))));
assert!(Arc::ptr_eq(&once, &thrice), "the layer is added once");
assert_eq!(thrice.policy_ref().as_deref(), Some("ops-v3+adk-harness"));
assert_eq!(thrice.evaluate(&request()).await, PolicyDecision::require_approval("harness"));
let alone = add_layer(None);
assert!(Arc::ptr_eq(&alone, &add_layer(Some(alone.clone()))));
}
}