1use std::sync::Arc;
14
15use async_trait::async_trait;
16use serde_json::Value;
17
18use crate::{ToolEffect, ToolOrigin};
19
20#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum PolicyDecision {
32 Allow,
34 Deny {
36 reason: String,
38 },
39 RequireApproval {
41 reason: String,
43 },
44}
45
46impl PolicyDecision {
47 pub fn deny(reason: impl Into<String>) -> Self {
49 Self::Deny { reason: reason.into() }
50 }
51
52 pub fn require_approval(reason: impl Into<String>) -> Self {
54 Self::RequireApproval { reason: reason.into() }
55 }
56
57 #[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#[derive(Debug, Clone, PartialEq)]
95pub struct ToolPolicyRequest {
96 pub tool_name: String,
98 pub args: Value,
100 pub effect: ToolEffect,
102 pub agent_name: String,
104 pub app_name: String,
106 pub user_id: String,
108 pub session_id: String,
110 pub invocation_id: String,
112 pub acting: Option<crate::ActingContext>,
116}
117
118impl ToolPolicyRequest {
119 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 pub fn agent_id(&self) -> Option<&crate::AgentId> {
136 self.acting.as_ref().map(|acting| &acting.agent.id)
137 }
138
139 #[must_use]
152 pub fn with_acting_context(mut self, acting: crate::ActingContext) -> Self {
153 self.acting = Some(acting);
154 self
155 }
156
157 pub fn is_read_only(&self) -> bool {
159 self.effect == ToolEffect::ReadOnly
160 }
161
162 #[must_use]
164 pub fn with_effect(mut self, effect: ToolEffect) -> Self {
165 self.effect = effect;
166 self
167 }
168
169 #[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 #[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 #[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 #[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#[non_exhaustive]
229#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
230pub struct PolicyCall<'a> {
231 pub origin: Option<&'a ToolOrigin>,
234 pub function_call_id: Option<&'a str>,
236 pub durable_run_id: Option<&'a str>,
243}
244
245impl<'a> PolicyCall<'a> {
246 pub fn new() -> Self {
248 Self::default()
249 }
250
251 #[must_use]
253 pub fn with_origin(mut self, origin: &'a ToolOrigin) -> Self {
254 self.origin = Some(origin);
255 self
256 }
257
258 #[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 #[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#[async_trait]
309pub trait ToolPolicy: std::fmt::Debug + Send + Sync {
310 async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision;
312
313 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 fn policy_ref(&self) -> Option<String> {
373 None
374 }
375}
376
377#[derive(Debug, Clone, PartialEq)]
399pub enum ArgPredicate {
400 Equals {
402 pointer: String,
404 value: Value,
406 },
407 InSet {
409 pointer: String,
411 values: Vec<Value>,
413 },
414 AtMost {
416 pointer: String,
418 max: f64,
420 },
421 StartsWith {
426 pointer: String,
428 prefix: String,
430 },
431 DomainIn {
439 pointer: String,
441 domains: Vec<String>,
443 },
444}
445
446impl ArgPredicate {
447 pub fn equals(pointer: impl Into<String>, value: Value) -> Self {
449 Self::Equals { pointer: pointer.into(), value }
450 }
451
452 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 pub fn at_most(pointer: impl Into<String>, max: f64) -> Self {
459 Self::AtMost { pointer: pointer.into(), max }
460 }
461
462 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 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 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
501fn 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
535fn 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#[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 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 pub fn allow(tool_pattern: impl Into<String>) -> Self {
602 Self::new(tool_pattern, PolicyDecision::Allow)
603 }
604
605 pub fn deny(tool_pattern: impl Into<String>, reason: impl Into<String>) -> Self {
607 Self::new(tool_pattern, PolicyDecision::deny(reason))
608 }
609
610 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 #[must_use]
617 pub fn when(mut self, predicate: ArgPredicate) -> Self {
618 self.predicates.push(predicate);
619 self
620 }
621
622 #[must_use]
624 pub fn read_only_tools(self) -> Self {
625 self.with_effect(ToolEffect::ReadOnly)
626 }
627
628 #[must_use]
644 pub fn with_effect(mut self, effect: ToolEffect) -> Self {
645 self.effect = Some(effect);
646 self
647 }
648
649 #[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 #[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 #[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 pub fn decision(&self) -> &PolicyDecision {
691 &self.decision
692 }
693
694 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#[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 pub fn builder() -> DeclarativePolicyBuilder {
749 DeclarativePolicyBuilder::default()
750 }
751
752 pub fn rules(&self) -> &[PolicyRule] {
754 &self.rules
755 }
756
757 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#[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 #[must_use]
793 pub fn rule(mut self, rule: PolicyRule) -> Self {
794 self.rules.push(rule);
795 self
796 }
797
798 #[must_use]
800 pub fn allow(self, tool_pattern: impl Into<String>) -> Self {
801 self.rule(PolicyRule::allow(tool_pattern))
802 }
803
804 #[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 #[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 #[must_use]
825 pub fn allow_read_only(self) -> Self {
826 self.rule(PolicyRule::allow("*").read_only_tools())
827 }
828
829 #[must_use]
831 pub fn default_decision(mut self, decision: PolicyDecision) -> Self {
832 self.default_decision = Some(decision);
833 self
834 }
835
836 #[must_use]
839 pub fn name(mut self, name: impl Into<String>) -> Self {
840 self.name = Some(name.into());
841 self
842 }
843
844 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#[derive(Debug, Clone, Default)]
914pub struct StrictestPolicy {
915 layers: Vec<Arc<dyn ToolPolicy>>,
916}
917
918impl StrictestPolicy {
919 pub fn new(layers: Vec<Arc<dyn ToolPolicy>>) -> Self {
921 Self { layers }
922 }
923
924 #[must_use]
926 pub fn layer(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
927 self.layers.push(policy);
928 self
929 }
930
931 pub fn layers(&self) -> &[Arc<dyn ToolPolicy>] {
933 &self.layers
934 }
935
936 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
959const 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 for layer in &self.layers {
976 decision = decision.stricter(layer.evaluate_call(request, call).await);
977 }
978 decision
979 }
980
981 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 #[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 #[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 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 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}