use std::collections::BTreeMap;
use std::fmt;
use async_trait::async_trait;
use crate::principal::{
ActingContext, AgentId, AgentPrincipal, MAX_AGENT_ID_LEN, PrincipalError, SubjectKind,
SubjectRef,
};
use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
pub const SUBJECT_MISMATCH_CODE: &str = "identity.subject_mismatch";
pub const PRINCIPAL_NOT_ALLOWED_CODE: &str = "identity.principal_not_allowed";
impl From<PrincipalError> for AdkError {
fn from(error: PrincipalError) -> Self {
AdkError::new(
ErrorComponent::Auth,
ErrorCategory::InvalidInput,
"identity.agent_id.invalid",
error.to_string(),
)
}
}
impl fmt::Display for SubjectKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Human => "human",
Self::Service => "service",
Self::Agent => "agent",
Self::Visitor => "visitor",
})
}
}
impl fmt::Display for SubjectRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.kind, self.id)
}
}
impl AgentPrincipal {
pub fn derived(app_name: &str, agent_name: &str) -> Self {
let encode = |value: &str| -> String {
if value.is_empty() {
return "_".to_string();
}
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
out.push(byte as char);
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
};
let mut id = format!("urn:adk:agent:{}/{}", encode(app_name), encode(agent_name));
id.truncate(MAX_AGENT_ID_LEN);
Self::new(AgentId::new(id).expect("a percent-encoded URN is a valid agent id"))
}
}
impl ActingContext {
pub fn derived(app_name: &str, agent_name: &str, user_id: &str, kind: SubjectKind) -> Self {
let acting = Self::new(AgentPrincipal::derived(app_name, agent_name));
if user_id.is_empty() {
acting
} else {
acting.on_behalf_of(SubjectRef::new(kind, user_id))
}
}
#[must_use]
pub fn delegate(&self, delegate: AgentPrincipal) -> Self {
let mut delegated = Self::new(delegate);
delegated.on_behalf_of = self.on_behalf_of.clone();
delegated.delegation_chain = self.delegation_chain.clone();
delegated.delegated_by(SubjectRef::agent(&self.agent.id))
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ActingConfig {
pub principals: BTreeMap<String, AgentPrincipal>,
pub on_behalf_of: Option<SubjectRef>,
pub subject_kind: SubjectKind,
pub delegation_chain: Vec<SubjectRef>,
}
impl ActingConfig {
#[must_use]
pub fn with_principal(
mut self,
agent_name: impl Into<String>,
principal: AgentPrincipal,
) -> Self {
self.principals.insert(agent_name.into(), principal);
self
}
#[must_use]
pub fn with_on_behalf_of(mut self, subject: SubjectRef) -> Self {
self.on_behalf_of = Some(subject);
self
}
#[must_use]
pub fn with_subject_kind(mut self, kind: SubjectKind) -> Self {
self.subject_kind = kind;
self
}
pub fn principal_for(&self, app_name: &str, agent_name: &str) -> AgentPrincipal {
self.principals
.get(agent_name)
.cloned()
.unwrap_or_else(|| AgentPrincipal::derived(app_name, agent_name))
}
pub fn session_subject(&self, user_id: &str) -> Option<SubjectRef> {
(!user_id.is_empty()).then(|| SubjectRef::new(self.subject_kind, user_id))
}
pub fn acting_context_for(
&self,
app_name: &str,
agent_name: &str,
user_id: &str,
) -> ActingContext {
ActingContext {
agent: self.principal_for(app_name, agent_name),
on_behalf_of: self.on_behalf_of.clone().or_else(|| self.session_subject(user_id)),
delegation_chain: self.delegation_chain.clone(),
}
}
pub async fn admit_subject(
&mut self,
app_name: &str,
user_id: &str,
agent: &AgentPrincipal,
policy: Option<&dyn SubjectDelegationPolicy>,
) -> Result<()> {
let Some(session) = self.session_subject(user_id) else {
return Ok(());
};
let Some(requested) = &self.on_behalf_of else {
self.on_behalf_of = Some(session);
return Ok(());
};
if *requested == session {
return Ok(());
}
let allowed = match policy {
Some(policy) => {
policy
.may_act_for(&SubjectDelegationRequest {
app_name: app_name.to_string(),
agent: agent.clone(),
session_subject: session.clone(),
requested: requested.clone(),
})
.await?
}
None => false,
};
if !allowed {
return Err(subject_mismatch_error(&session, requested));
}
if self.delegation_chain.first() != Some(&session) {
self.delegation_chain.insert(0, session);
}
Ok(())
}
}
pub fn subject_mismatch_error(session: &SubjectRef, requested: &SubjectRef) -> AdkError {
AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Forbidden,
SUBJECT_MISMATCH_CODE,
format!(
"the run acts for {requested} but its session belongs to {session}; a run acts for \
its session's user unless a SubjectDelegationPolicy on the runner allows the \
delegation"
),
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SubjectDelegationRequest {
pub app_name: String,
pub agent: AgentPrincipal,
pub session_subject: SubjectRef,
pub requested: SubjectRef,
}
#[async_trait]
pub trait SubjectDelegationPolicy: fmt::Debug + Send + Sync {
async fn may_act_for(&self, request: &SubjectDelegationRequest) -> Result<bool>;
}
#[derive(Debug, Clone, Default)]
pub struct StaticSubjectDelegation {
rules: Vec<(SubjectRef, Option<SubjectRef>)>,
}
impl StaticSubjectDelegation {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn allow_any(mut self, session_subject: SubjectRef) -> Self {
self.rules.push((session_subject, None));
self
}
#[must_use]
pub fn allow(mut self, session_subject: SubjectRef, requested: SubjectRef) -> Self {
self.rules.push((session_subject, Some(requested)));
self
}
}
#[async_trait]
impl SubjectDelegationPolicy for StaticSubjectDelegation {
async fn may_act_for(&self, request: &SubjectDelegationRequest) -> Result<bool> {
Ok(self.rules.iter().any(|(session, requested)| {
*session == request.session_subject
&& requested.as_ref().is_none_or(|requested| *requested == request.requested)
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn derived_ids_are_stable_and_always_valid() {
assert_eq!(AgentPrincipal::derived("a", "b"), AgentPrincipal::derived("a", "b"));
assert_eq!(AgentPrincipal::derived("", "").id.as_str(), "urn:adk:agent:_/_");
assert_eq!(AgentPrincipal::derived("a/b", "c:d").id.as_str(), "urn:adk:agent:a%2Fb/c%3Ad");
let long = AgentPrincipal::derived(&"\n".repeat(400), "agent");
assert!(AgentId::new(long.id.as_str()).is_ok());
}
#[test]
fn delegation_extends_the_chain_and_keeps_the_subject() {
let acting = ActingContext::derived("app", "agent", "alice", SubjectKind::Human)
.delegate(AgentPrincipal::derived("app", "helper").with_tenant("acme"));
let json = serde_json::to_value(&acting).unwrap();
assert_eq!(
json,
serde_json::json!({
"agent": { "id": "urn:adk:agent:app/helper", "tenant": "acme" },
"onBehalfOf": { "kind": "human", "id": "alice" },
"delegationChain": [{ "kind": "agent", "id": "urn:adk:agent:app/agent" }],
})
);
}
#[test]
fn principal_errors_convert_with_a_structured_code() {
let error: AdkError = AgentId::new("").unwrap_err().into();
assert_eq!(error.code, "identity.agent_id.invalid");
}
#[test]
fn the_subject_kind_comes_from_the_config() {
let service = ActingConfig::default().with_subject_kind(SubjectKind::Service);
assert_eq!(
service.acting_context_for("ops", "reporter", "nightly"),
ActingContext::derived("ops", "reporter", "nightly", SubjectKind::Service)
);
assert_eq!(
ActingConfig::default().acting_context_for("ops", "reporter", "alice").on_behalf_of,
Some(SubjectRef::human("alice"))
);
assert_eq!(ActingConfig::default().acting_context_for("ops", "r", "").on_behalf_of, None);
}
#[test]
fn principals_resolve_per_agent() {
let billing = AgentPrincipal::new(AgentId::new("spiffe://acme/billing").unwrap());
let config = ActingConfig::default().with_principal("billing", billing.clone());
assert_eq!(config.principal_for("shop", "billing"), billing);
assert_eq!(config.principal_for("shop", "audit"), AgentPrincipal::derived("shop", "audit"));
}
#[tokio::test]
async fn a_mismatched_subject_is_refused_without_a_policy() {
let agent = AgentPrincipal::derived("bank", "teller");
let mut acting = ActingConfig::default().with_on_behalf_of(SubjectRef::human("bob"));
let error = acting.admit_subject("bank", "alice", &agent, None).await.unwrap_err();
assert_eq!(error.code, SUBJECT_MISMATCH_CODE);
assert_eq!(error.category, ErrorCategory::Forbidden);
assert!(error.message.contains("human:bob"), "{}", error.message);
assert!(error.message.contains("human:alice"), "{}", error.message);
let mut acting = ActingConfig::default().with_on_behalf_of(SubjectRef::service("alice"));
let error = acting.admit_subject("bank", "alice", &agent, None).await.unwrap_err();
assert_eq!(error.code, SUBJECT_MISMATCH_CODE);
}
#[tokio::test]
async fn the_session_subject_is_pinned_or_matched() {
let agent = AgentPrincipal::derived("bank", "teller");
let mut acting = ActingConfig::default();
acting.admit_subject("bank", "alice", &agent, None).await.unwrap();
assert_eq!(acting.on_behalf_of, Some(SubjectRef::human("alice")));
let mut acting = ActingConfig::default()
.with_subject_kind(SubjectKind::Service)
.with_on_behalf_of(SubjectRef::service("cron"));
acting.admit_subject("bank", "cron", &agent, None).await.unwrap();
assert_eq!(acting.on_behalf_of, Some(SubjectRef::service("cron")));
assert!(acting.delegation_chain.is_empty());
}
#[tokio::test]
async fn a_delegation_rule_allows_another_subject() {
let agent = AgentPrincipal::derived("crm", "sync");
let policy = StaticSubjectDelegation::new().allow_any(SubjectRef::service("crm-sync"));
let mut acting = ActingConfig::default()
.with_subject_kind(SubjectKind::Service)
.with_on_behalf_of(SubjectRef::human("bob"));
acting.admit_subject("crm", "crm-sync", &agent, Some(&policy)).await.unwrap();
assert_eq!(acting.on_behalf_of, Some(SubjectRef::human("bob")));
assert_eq!(acting.delegation_chain, vec![SubjectRef::service("crm-sync")]);
let mut other = ActingConfig::default()
.with_subject_kind(SubjectKind::Service)
.with_on_behalf_of(SubjectRef::human("bob"));
let error = other.admit_subject("crm", "billing", &agent, Some(&policy)).await.unwrap_err();
assert_eq!(error.code, SUBJECT_MISMATCH_CODE);
let pair = StaticSubjectDelegation::new()
.allow(SubjectRef::human("assistant"), SubjectRef::human("bob"));
let mut for_bob = ActingConfig::default().with_on_behalf_of(SubjectRef::human("bob"));
for_bob.admit_subject("crm", "assistant", &agent, Some(&pair)).await.unwrap();
let mut for_carol = ActingConfig::default().with_on_behalf_of(SubjectRef::human("carol"));
assert!(for_carol.admit_subject("crm", "assistant", &agent, Some(&pair)).await.is_err());
}
}