adk_server/awp/policy.rs
1//! Tool policies the edge compiles (spec 3.5 §7.4, §7.10, A-I2).
2//!
3//! | Policy | Governs | Decides |
4//! |---|---|---|
5//! | [`CapabilityPolicy`] | Every capability call, from every binding | Denies undeclared tools, tools of another origin and calls above the caller's tier or without a live consent receipt; holds calls the approval hint names; allows the rest |
6//! | [`PublicPartitionPolicy`] | The tools of agents hosted at the edge | Allows only declared capabilities, `search_site`, `reply_in_thread` and `emit_signal`, each from the edge's own origin; denies everything else, web access included |
7
8use std::collections::BTreeMap;
9use std::sync::Arc;
10
11use adk_awp::v2::capability::CapabilityRegistry;
12use adk_awp::v2::store::{ConsentReceiptStore, has_live_receipt};
13use adk_core::{PolicyCall, PolicyDecision, ToolPolicy, ToolPolicyRequest};
14use async_trait::async_trait;
15use awp_types::TrustTier;
16use chrono::Utc;
17use uuid::Uuid;
18
19/// Principal attribute carrying the caller's tier on the edge's acting context.
20pub const ATTR_TIER: &str = "awp.tier";
21/// Principal attribute carrying the consent receipt ids a call references, comma-separated.
22pub const ATTR_CONSENT: &str = "awp.consent";
23
24/// The governed path's policy for capability calls, compiled from the capability manifest:
25/// tiers, consent requirements and approval hints (spec 3.5 §7.4, D-4).
26///
27/// The edge sets the caller's tier and consent references as attributes of the site's acting
28/// principal ([`ATTR_TIER`], [`ATTR_CONSENT`]); the call's tool origin must be the site's,
29/// `awp:{domain}`.
30///
31/// # Example
32///
33/// ```rust
34/// use std::sync::Arc;
35///
36/// use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler, CapabilityRegistry};
37/// use adk_awp::v2::store::InMemoryConsentReceiptStore;
38/// use adk_core::{PolicyCall, PolicyDecision, ToolPolicy, ToolPolicyRequest};
39/// use adk_server::awp::policy::CapabilityPolicy;
40/// use awp_types::{ApprovalHint, CapabilityEffect, CapabilityV2};
41/// use serde_json::{Value, json};
42///
43/// struct Noop;
44/// #[async_trait::async_trait]
45/// impl CapabilityHandler for Noop {
46/// async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> { Ok(call.input) }
47/// }
48///
49/// # futures::executor::block_on(async {
50/// let mut registry = CapabilityRegistry::new("example.com");
51/// registry
52/// .declare(
53/// CapabilityV2::new("book", "Book", CapabilityEffect::NonIdempotent)
54/// .with_approval(ApprovalHint::AboveAmount(50_000)),
55/// Arc::new(Noop),
56/// )
57/// .unwrap();
58/// let policy = CapabilityPolicy::new(Arc::new(registry), Arc::new(InMemoryConsentReceiptStore::default()));
59/// let small = ToolPolicyRequest::new("book", json!({ "amount": 10_000 }));
60/// assert_eq!(policy.evaluate_call(&small, &PolicyCall::new()).await, PolicyDecision::Allow);
61/// let large = ToolPolicyRequest::new("book", json!({ "amount": 90_000 }));
62/// assert!(matches!(policy.evaluate_call(&large, &PolicyCall::new()).await, PolicyDecision::RequireApproval { .. }));
63/// let other = ToolPolicyRequest::new("publish_page", json!({}));
64/// assert!(matches!(policy.evaluate(&other).await, PolicyDecision::Deny { .. }));
65/// # });
66/// ```
67pub struct CapabilityPolicy {
68 registry: Arc<CapabilityRegistry>,
69 consent: Arc<dyn ConsentReceiptStore>,
70 origin: String,
71}
72
73impl std::fmt::Debug for CapabilityPolicy {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 f.debug_struct("CapabilityPolicy").field("origin", &self.origin).finish_non_exhaustive()
76 }
77}
78
79impl CapabilityPolicy {
80 /// The policy of `registry`'s capabilities, checking consent receipts in `consent`.
81 pub fn new(registry: Arc<CapabilityRegistry>, consent: Arc<dyn ConsentReceiptStore>) -> Self {
82 let origin = adk_awp::v2::capability::CapabilityTool::origin_for(registry.domain());
83 Self { registry, consent, origin }
84 }
85}
86
87#[async_trait]
88impl ToolPolicy for CapabilityPolicy {
89 async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
90 self.evaluate_call(request, &PolicyCall::new()).await
91 }
92
93 async fn evaluate_call(
94 &self,
95 request: &ToolPolicyRequest,
96 call: &PolicyCall<'_>,
97 ) -> PolicyDecision {
98 let Some(tool) = self.registry.get(&request.tool_name) else {
99 return PolicyDecision::deny(format!(
100 "'{}' is not a capability this site declares",
101 request.tool_name
102 ));
103 };
104 if let Some(origin) = call.origin
105 && origin.source != self.origin
106 {
107 return PolicyDecision::deny(format!(
108 "'{}' is declared by {}, not by {}",
109 request.tool_name, self.origin, origin.source
110 ));
111 }
112 let attributes = request.acting.as_ref().map(|acting| &acting.agent.attributes);
113 let tier = attributes
114 .and_then(|attributes| attributes.get(ATTR_TIER))
115 .and_then(|tier| serde_json::from_value(serde_json::Value::String(tier.clone())).ok())
116 .unwrap_or(TrustTier::Public);
117 let declaration = tool.declaration();
118 if !declaration.visible_to(tier) {
119 return PolicyDecision::deny(format!(
120 "'{}' needs tier {} or above",
121 declaration.name, declaration.min_trust
122 ));
123 }
124 if let Some(requirement) = &declaration.consent {
125 let receipts: Vec<Uuid> = attributes
126 .and_then(|attributes| attributes.get(ATTR_CONSENT))
127 .map(|ids| ids.split(',').filter_map(|id| id.trim().parse().ok()).collect())
128 .unwrap_or_default();
129 match has_live_receipt(self.consent.as_ref(), &receipts, requirement, Utc::now()).await
130 {
131 Ok(true) => {}
132 Ok(false) => {
133 return PolicyDecision::deny(format!(
134 "'{}' needs a live consent receipt for {}",
135 declaration.name, requirement.scope
136 ));
137 }
138 Err(error) => {
139 return PolicyDecision::deny(format!("consent could not be checked: {error}"));
140 }
141 }
142 }
143 if declaration.approval.holds(tool.amount(&request.args).await) {
144 return PolicyDecision::RequireApproval {
145 reason: format!("the owner decides calls to '{}'", declaration.name),
146 };
147 }
148 PolicyDecision::Allow
149 }
150
151 fn policy_ref(&self) -> Option<String> {
152 Some("awp.capability_manifest".to_owned())
153 }
154}
155
156/// The fixed policy of the public partition: its agents hold only declared capabilities,
157/// `search_site`, `reply_in_thread` and `emit_signal` (spec 3.5 §7.10, A-I2).
158///
159/// A tool is allowed only by its name and its origin together, so a tool another toolset
160/// publishes under an allowed name is denied, and so is every tool that publishes, deploys,
161/// changes DNS, spends, sends in bulk, fetches the web or reads the owner's memory.
162///
163/// # Example
164///
165/// ```rust
166/// use adk_core::{PolicyCall, PolicyDecision, ToolOrigin, ToolPolicy, ToolPolicyRequest};
167/// use adk_server::awp::policy::PublicPartitionPolicy;
168/// use serde_json::json;
169///
170/// # futures::executor::block_on(async {
171/// let policy = PublicPartitionPolicy::new([("search_site", "awp-edge:example.com")]);
172/// let search = ToolOrigin::new("awp-edge:example.com", &json!({ "name": "search_site" }), None);
173/// let request = ToolPolicyRequest::new("search_site", json!({ "query": "hours" }));
174/// assert_eq!(policy.evaluate_call(&request, &PolicyCall::new().with_origin(&search)).await, PolicyDecision::Allow);
175/// let fetch = ToolPolicyRequest::new("web_fetch", json!({ "url": "https://evil.example" }));
176/// assert!(matches!(policy.evaluate_call(&fetch, &PolicyCall::new()).await, PolicyDecision::Deny { .. }));
177/// # });
178/// ```
179#[derive(Debug, Clone)]
180pub struct PublicPartitionPolicy {
181 allowed: BTreeMap<String, String>,
182}
183
184impl PublicPartitionPolicy {
185 /// Allows each `(tool name, origin)` pair and nothing else.
186 pub fn new<N: Into<String>, O: Into<String>>(
187 allowed: impl IntoIterator<Item = (N, O)>,
188 ) -> Self {
189 Self {
190 allowed: allowed
191 .into_iter()
192 .map(|(name, origin)| (name.into(), origin.into()))
193 .collect(),
194 }
195 }
196
197 /// The allowed tool names.
198 pub fn allowed(&self) -> impl Iterator<Item = &str> {
199 self.allowed.keys().map(String::as_str)
200 }
201}
202
203#[async_trait]
204impl ToolPolicy for PublicPartitionPolicy {
205 async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
206 self.evaluate_call(request, &PolicyCall::new()).await
207 }
208
209 async fn evaluate_call(
210 &self,
211 request: &ToolPolicyRequest,
212 call: &PolicyCall<'_>,
213 ) -> PolicyDecision {
214 match (self.allowed.get(&request.tool_name), call.origin) {
215 (Some(origin), Some(called)) if called.source == *origin => PolicyDecision::Allow,
216 _ => {
217 tracing::info!(
218 tool.name = %request.tool_name,
219 "public partition refused a tool outside its fixed set"
220 );
221 PolicyDecision::deny(format!(
222 "'{}' is not available to the site's public agents, which hold only the \
223 site's declared capabilities, search_site, reply_in_thread and emit_signal",
224 request.tool_name
225 ))
226 }
227 }
228 }
229
230 fn policy_ref(&self) -> Option<String> {
231 Some("awp.public_partition".to_owned())
232 }
233}