1use std::collections::BTreeMap;
27use std::fmt;
28
29use async_trait::async_trait;
30
31use crate::principal::{
32 ActingContext, AgentId, AgentPrincipal, MAX_AGENT_ID_LEN, PrincipalError, SubjectKind,
33 SubjectRef,
34};
35use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
36
37pub const SUBJECT_MISMATCH_CODE: &str = "identity.subject_mismatch";
40
41pub const PRINCIPAL_NOT_ALLOWED_CODE: &str = "identity.principal_not_allowed";
44
45impl From<PrincipalError> for AdkError {
46 fn from(error: PrincipalError) -> Self {
47 AdkError::new(
48 ErrorComponent::Auth,
49 ErrorCategory::InvalidInput,
50 "identity.agent_id.invalid",
51 error.to_string(),
52 )
53 }
54}
55
56impl fmt::Display for SubjectKind {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 f.write_str(match self {
59 Self::Human => "human",
60 Self::Service => "service",
61 Self::Agent => "agent",
62 Self::Visitor => "visitor",
63 })
64 }
65}
66
67impl fmt::Display for SubjectRef {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 write!(f, "{}:{}", self.kind, self.id)
71 }
72}
73
74impl AgentPrincipal {
75 pub fn derived(app_name: &str, agent_name: &str) -> Self {
90 let encode = |value: &str| -> String {
91 if value.is_empty() {
92 return "_".to_string();
93 }
94 let mut out = String::with_capacity(value.len());
95 for byte in value.bytes() {
96 if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
97 out.push(byte as char);
98 } else {
99 out.push_str(&format!("%{byte:02X}"));
100 }
101 }
102 out
103 };
104 let mut id = format!("urn:adk:agent:{}/{}", encode(app_name), encode(agent_name));
105 id.truncate(MAX_AGENT_ID_LEN);
108 Self::new(AgentId::new(id).expect("a percent-encoded URN is a valid agent id"))
109 }
110}
111
112impl ActingContext {
113 pub fn derived(app_name: &str, agent_name: &str, user_id: &str, kind: SubjectKind) -> Self {
129 let acting = Self::new(AgentPrincipal::derived(app_name, agent_name));
130 if user_id.is_empty() {
131 acting
132 } else {
133 acting.on_behalf_of(SubjectRef::new(kind, user_id))
134 }
135 }
136
137 #[must_use]
152 pub fn delegate(&self, delegate: AgentPrincipal) -> Self {
153 let mut delegated = Self::new(delegate);
154 delegated.on_behalf_of = self.on_behalf_of.clone();
155 delegated.delegation_chain = self.delegation_chain.clone();
156 delegated.delegated_by(SubjectRef::agent(&self.agent.id))
157 }
158}
159
160#[derive(Debug, Clone, Default, PartialEq, Eq)]
186pub struct ActingConfig {
187 pub principals: BTreeMap<String, AgentPrincipal>,
190 pub on_behalf_of: Option<SubjectRef>,
194 pub subject_kind: SubjectKind,
198 pub delegation_chain: Vec<SubjectRef>,
200}
201
202impl ActingConfig {
203 #[must_use]
205 pub fn with_principal(
206 mut self,
207 agent_name: impl Into<String>,
208 principal: AgentPrincipal,
209 ) -> Self {
210 self.principals.insert(agent_name.into(), principal);
211 self
212 }
213
214 #[must_use]
216 pub fn with_on_behalf_of(mut self, subject: SubjectRef) -> Self {
217 self.on_behalf_of = Some(subject);
218 self
219 }
220
221 #[must_use]
223 pub fn with_subject_kind(mut self, kind: SubjectKind) -> Self {
224 self.subject_kind = kind;
225 self
226 }
227
228 pub fn principal_for(&self, app_name: &str, agent_name: &str) -> AgentPrincipal {
230 self.principals
231 .get(agent_name)
232 .cloned()
233 .unwrap_or_else(|| AgentPrincipal::derived(app_name, agent_name))
234 }
235
236 pub fn session_subject(&self, user_id: &str) -> Option<SubjectRef> {
239 (!user_id.is_empty()).then(|| SubjectRef::new(self.subject_kind, user_id))
240 }
241
242 pub fn acting_context_for(
244 &self,
245 app_name: &str,
246 agent_name: &str,
247 user_id: &str,
248 ) -> ActingContext {
249 ActingContext {
250 agent: self.principal_for(app_name, agent_name),
251 on_behalf_of: self.on_behalf_of.clone().or_else(|| self.session_subject(user_id)),
252 delegation_chain: self.delegation_chain.clone(),
253 }
254 }
255
256 pub async fn admit_subject(
286 &mut self,
287 app_name: &str,
288 user_id: &str,
289 agent: &AgentPrincipal,
290 policy: Option<&dyn SubjectDelegationPolicy>,
291 ) -> Result<()> {
292 let Some(session) = self.session_subject(user_id) else {
293 return Ok(());
294 };
295 let Some(requested) = &self.on_behalf_of else {
296 self.on_behalf_of = Some(session);
297 return Ok(());
298 };
299 if *requested == session {
300 return Ok(());
301 }
302 let allowed = match policy {
303 Some(policy) => {
304 policy
305 .may_act_for(&SubjectDelegationRequest {
306 app_name: app_name.to_string(),
307 agent: agent.clone(),
308 session_subject: session.clone(),
309 requested: requested.clone(),
310 })
311 .await?
312 }
313 None => false,
314 };
315 if !allowed {
316 return Err(subject_mismatch_error(&session, requested));
317 }
318 if self.delegation_chain.first() != Some(&session) {
319 self.delegation_chain.insert(0, session);
320 }
321 Ok(())
322 }
323}
324
325pub fn subject_mismatch_error(session: &SubjectRef, requested: &SubjectRef) -> AdkError {
327 AdkError::new(
328 ErrorComponent::Auth,
329 ErrorCategory::Forbidden,
330 SUBJECT_MISMATCH_CODE,
331 format!(
332 "the run acts for {requested} but its session belongs to {session}; a run acts for \
333 its session's user unless a SubjectDelegationPolicy on the runner allows the \
334 delegation"
335 ),
336 )
337}
338
339#[derive(Debug, Clone, PartialEq, Eq)]
341#[non_exhaustive]
342pub struct SubjectDelegationRequest {
343 pub app_name: String,
345 pub agent: AgentPrincipal,
347 pub session_subject: SubjectRef,
349 pub requested: SubjectRef,
351}
352
353#[async_trait]
360pub trait SubjectDelegationPolicy: fmt::Debug + Send + Sync {
361 async fn may_act_for(&self, request: &SubjectDelegationRequest) -> Result<bool>;
367}
368
369#[derive(Debug, Clone, Default)]
386pub struct StaticSubjectDelegation {
387 rules: Vec<(SubjectRef, Option<SubjectRef>)>,
388}
389
390impl StaticSubjectDelegation {
391 pub fn new() -> Self {
393 Self::default()
394 }
395
396 #[must_use]
398 pub fn allow_any(mut self, session_subject: SubjectRef) -> Self {
399 self.rules.push((session_subject, None));
400 self
401 }
402
403 #[must_use]
405 pub fn allow(mut self, session_subject: SubjectRef, requested: SubjectRef) -> Self {
406 self.rules.push((session_subject, Some(requested)));
407 self
408 }
409}
410
411#[async_trait]
412impl SubjectDelegationPolicy for StaticSubjectDelegation {
413 async fn may_act_for(&self, request: &SubjectDelegationRequest) -> Result<bool> {
414 Ok(self.rules.iter().any(|(session, requested)| {
415 *session == request.session_subject
416 && requested.as_ref().is_none_or(|requested| *requested == request.requested)
417 }))
418 }
419}
420
421#[cfg(test)]
422mod tests {
423 use super::*;
424
425 #[test]
426 fn derived_ids_are_stable_and_always_valid() {
427 assert_eq!(AgentPrincipal::derived("a", "b"), AgentPrincipal::derived("a", "b"));
428 assert_eq!(AgentPrincipal::derived("", "").id.as_str(), "urn:adk:agent:_/_");
429 assert_eq!(AgentPrincipal::derived("a/b", "c:d").id.as_str(), "urn:adk:agent:a%2Fb/c%3Ad");
430 let long = AgentPrincipal::derived(&"\n".repeat(400), "agent");
431 assert!(AgentId::new(long.id.as_str()).is_ok());
432 }
433
434 #[test]
435 fn delegation_extends_the_chain_and_keeps_the_subject() {
436 let acting = ActingContext::derived("app", "agent", "alice", SubjectKind::Human)
437 .delegate(AgentPrincipal::derived("app", "helper").with_tenant("acme"));
438 let json = serde_json::to_value(&acting).unwrap();
439 assert_eq!(
440 json,
441 serde_json::json!({
442 "agent": { "id": "urn:adk:agent:app/helper", "tenant": "acme" },
443 "onBehalfOf": { "kind": "human", "id": "alice" },
444 "delegationChain": [{ "kind": "agent", "id": "urn:adk:agent:app/agent" }],
445 })
446 );
447 }
448
449 #[test]
450 fn principal_errors_convert_with_a_structured_code() {
451 let error: AdkError = AgentId::new("").unwrap_err().into();
452 assert_eq!(error.code, "identity.agent_id.invalid");
453 }
454
455 #[test]
456 fn the_subject_kind_comes_from_the_config() {
457 let service = ActingConfig::default().with_subject_kind(SubjectKind::Service);
458 assert_eq!(
459 service.acting_context_for("ops", "reporter", "nightly"),
460 ActingContext::derived("ops", "reporter", "nightly", SubjectKind::Service)
461 );
462 assert_eq!(
463 ActingConfig::default().acting_context_for("ops", "reporter", "alice").on_behalf_of,
464 Some(SubjectRef::human("alice"))
465 );
466 assert_eq!(ActingConfig::default().acting_context_for("ops", "r", "").on_behalf_of, None);
467 }
468
469 #[test]
470 fn principals_resolve_per_agent() {
471 let billing = AgentPrincipal::new(AgentId::new("spiffe://acme/billing").unwrap());
472 let config = ActingConfig::default().with_principal("billing", billing.clone());
473 assert_eq!(config.principal_for("shop", "billing"), billing);
474 assert_eq!(config.principal_for("shop", "audit"), AgentPrincipal::derived("shop", "audit"));
475 }
476
477 #[tokio::test]
478 async fn a_mismatched_subject_is_refused_without_a_policy() {
479 let agent = AgentPrincipal::derived("bank", "teller");
480 let mut acting = ActingConfig::default().with_on_behalf_of(SubjectRef::human("bob"));
481 let error = acting.admit_subject("bank", "alice", &agent, None).await.unwrap_err();
482 assert_eq!(error.code, SUBJECT_MISMATCH_CODE);
483 assert_eq!(error.category, ErrorCategory::Forbidden);
484 assert!(error.message.contains("human:bob"), "{}", error.message);
485 assert!(error.message.contains("human:alice"), "{}", error.message);
486
487 let mut acting = ActingConfig::default().with_on_behalf_of(SubjectRef::service("alice"));
489 let error = acting.admit_subject("bank", "alice", &agent, None).await.unwrap_err();
490 assert_eq!(error.code, SUBJECT_MISMATCH_CODE);
491 }
492
493 #[tokio::test]
494 async fn the_session_subject_is_pinned_or_matched() {
495 let agent = AgentPrincipal::derived("bank", "teller");
496 let mut acting = ActingConfig::default();
497 acting.admit_subject("bank", "alice", &agent, None).await.unwrap();
498 assert_eq!(acting.on_behalf_of, Some(SubjectRef::human("alice")));
499
500 let mut acting = ActingConfig::default()
501 .with_subject_kind(SubjectKind::Service)
502 .with_on_behalf_of(SubjectRef::service("cron"));
503 acting.admit_subject("bank", "cron", &agent, None).await.unwrap();
504 assert_eq!(acting.on_behalf_of, Some(SubjectRef::service("cron")));
505 assert!(acting.delegation_chain.is_empty());
506 }
507
508 #[tokio::test]
509 async fn a_delegation_rule_allows_another_subject() {
510 let agent = AgentPrincipal::derived("crm", "sync");
511 let policy = StaticSubjectDelegation::new().allow_any(SubjectRef::service("crm-sync"));
512 let mut acting = ActingConfig::default()
513 .with_subject_kind(SubjectKind::Service)
514 .with_on_behalf_of(SubjectRef::human("bob"));
515 acting.admit_subject("crm", "crm-sync", &agent, Some(&policy)).await.unwrap();
516 assert_eq!(acting.on_behalf_of, Some(SubjectRef::human("bob")));
517 assert_eq!(acting.delegation_chain, vec![SubjectRef::service("crm-sync")]);
518
519 let mut other = ActingConfig::default()
521 .with_subject_kind(SubjectKind::Service)
522 .with_on_behalf_of(SubjectRef::human("bob"));
523 let error = other.admit_subject("crm", "billing", &agent, Some(&policy)).await.unwrap_err();
524 assert_eq!(error.code, SUBJECT_MISMATCH_CODE);
525
526 let pair = StaticSubjectDelegation::new()
527 .allow(SubjectRef::human("assistant"), SubjectRef::human("bob"));
528 let mut for_bob = ActingConfig::default().with_on_behalf_of(SubjectRef::human("bob"));
529 for_bob.admit_subject("crm", "assistant", &agent, Some(&pair)).await.unwrap();
530 let mut for_carol = ActingConfig::default().with_on_behalf_of(SubjectRef::human("carol"));
531 assert!(for_carol.admit_subject("crm", "assistant", &agent, Some(&pair)).await.is_err());
532 }
533}