use std::collections::BTreeMap;
use std::sync::Arc;
use adk_awp::v2::capability::CapabilityRegistry;
use adk_awp::v2::store::{ConsentReceiptStore, has_live_receipt};
use adk_core::{PolicyCall, PolicyDecision, ToolPolicy, ToolPolicyRequest};
use async_trait::async_trait;
use awp_types::TrustTier;
use chrono::Utc;
use uuid::Uuid;
pub const ATTR_TIER: &str = "awp.tier";
pub const ATTR_CONSENT: &str = "awp.consent";
pub struct CapabilityPolicy {
registry: Arc<CapabilityRegistry>,
consent: Arc<dyn ConsentReceiptStore>,
origin: String,
}
impl std::fmt::Debug for CapabilityPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CapabilityPolicy").field("origin", &self.origin).finish_non_exhaustive()
}
}
impl CapabilityPolicy {
pub fn new(registry: Arc<CapabilityRegistry>, consent: Arc<dyn ConsentReceiptStore>) -> Self {
let origin = adk_awp::v2::capability::CapabilityTool::origin_for(registry.domain());
Self { registry, consent, origin }
}
}
#[async_trait]
impl ToolPolicy for CapabilityPolicy {
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 Some(tool) = self.registry.get(&request.tool_name) else {
return PolicyDecision::deny(format!(
"'{}' is not a capability this site declares",
request.tool_name
));
};
if let Some(origin) = call.origin
&& origin.source != self.origin
{
return PolicyDecision::deny(format!(
"'{}' is declared by {}, not by {}",
request.tool_name, self.origin, origin.source
));
}
let attributes = request.acting.as_ref().map(|acting| &acting.agent.attributes);
let tier = attributes
.and_then(|attributes| attributes.get(ATTR_TIER))
.and_then(|tier| serde_json::from_value(serde_json::Value::String(tier.clone())).ok())
.unwrap_or(TrustTier::Public);
let declaration = tool.declaration();
if !declaration.visible_to(tier) {
return PolicyDecision::deny(format!(
"'{}' needs tier {} or above",
declaration.name, declaration.min_trust
));
}
if let Some(requirement) = &declaration.consent {
let receipts: Vec<Uuid> = attributes
.and_then(|attributes| attributes.get(ATTR_CONSENT))
.map(|ids| ids.split(',').filter_map(|id| id.trim().parse().ok()).collect())
.unwrap_or_default();
match has_live_receipt(self.consent.as_ref(), &receipts, requirement, Utc::now()).await
{
Ok(true) => {}
Ok(false) => {
return PolicyDecision::deny(format!(
"'{}' needs a live consent receipt for {}",
declaration.name, requirement.scope
));
}
Err(error) => {
return PolicyDecision::deny(format!("consent could not be checked: {error}"));
}
}
}
if declaration.approval.holds(tool.amount(&request.args).await) {
return PolicyDecision::RequireApproval {
reason: format!("the owner decides calls to '{}'", declaration.name),
};
}
PolicyDecision::Allow
}
fn policy_ref(&self) -> Option<String> {
Some("awp.capability_manifest".to_owned())
}
}
#[derive(Debug, Clone)]
pub struct PublicPartitionPolicy {
allowed: BTreeMap<String, String>,
}
impl PublicPartitionPolicy {
pub fn new<N: Into<String>, O: Into<String>>(
allowed: impl IntoIterator<Item = (N, O)>,
) -> Self {
Self {
allowed: allowed
.into_iter()
.map(|(name, origin)| (name.into(), origin.into()))
.collect(),
}
}
pub fn allowed(&self) -> impl Iterator<Item = &str> {
self.allowed.keys().map(String::as_str)
}
}
#[async_trait]
impl ToolPolicy for PublicPartitionPolicy {
async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
self.evaluate_call(request, &PolicyCall::new()).await
}
async fn evaluate_call(
&self,
request: &ToolPolicyRequest,
call: &PolicyCall<'_>,
) -> PolicyDecision {
match (self.allowed.get(&request.tool_name), call.origin) {
(Some(origin), Some(called)) if called.source == *origin => PolicyDecision::Allow,
_ => {
tracing::info!(
tool.name = %request.tool_name,
"public partition refused a tool outside its fixed set"
);
PolicyDecision::deny(format!(
"'{}' is not available to the site's public agents, which hold only the \
site's declared capabilities, search_site, reply_in_thread and emit_signal",
request.tool_name
))
}
}
}
fn policy_ref(&self) -> Option<String> {
Some("awp.public_partition".to_owned())
}
}