Skip to main content

adk_core/
acting.rs

1//! How a run's agents act: the identity ADK-Rust derives when none is configured, the
2//! run-level [`ActingConfig`], delegation, and the [`SubjectDelegationPolicy`] that lets a
3//! run act for a subject other than its session's user.
4//!
5//! # Identity model
6//!
7//! | Type | Answers | Source |
8//! |------|---------|--------|
9//! | [`AdkIdentity`](crate::AdkIdentity) | Whose data: app, user, session | The session the run continues |
10//! | [`ExecutionIdentity`](crate::ExecutionIdentity) | Which execution: invocation, branch, agent name | The runner, per invocation |
11//! | [`ActingContext`] | Who acts, for whom, through whom | The run's [`ActingConfig`], resolved per agent |
12//!
13//! The invariants the runtime keeps:
14//!
15//! 1. **The session user is the subject.** An agent acts on behalf of the run's
16//!    `user_id`, as the run's [`SubjectKind`]. A run configured to act for anyone else is
17//!    refused at its start with [`SUBJECT_MISMATCH_CODE`] unless a
18//!    [`SubjectDelegationPolicy`] allows it; the session's subject then heads the
19//!    delegation chain.
20//! 2. **Each agent acts as itself.** The principal is resolved for the agent that is
21//!    executing — root, transfer target, or workflow sub-agent — from
22//!    [`ActingConfig::principals`], falling back to [`AgentPrincipal::derived`].
23//! 3. **One invocation id.** [`ActingContext`] holds none; the invocation is the
24//!    execution identity's.
25
26use 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
37/// The error code of a run refused because it asks to act for a subject other than its
38/// session's user, with no [`SubjectDelegationPolicy`] allowing it.
39pub const SUBJECT_MISMATCH_CODE: &str = "identity.subject_mismatch";
40
41/// The error code of a durable run refused because its stored principal names an agent
42/// the worker may not act as.
43pub 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    /// Formats as `kind:id`, for example `human:alice`.
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        write!(f, "{}:{}", self.kind, self.id)
71    }
72}
73
74impl AgentPrincipal {
75    /// The principal ADK-Rust derives when none is configured:
76    /// `urn:adk:agent:{app_name}/{agent_name}`.
77    ///
78    /// Characters outside `[A-Za-z0-9-._~]` are percent-encoded, so every app and agent
79    /// name yields a valid [`AgentId`], and the same names always yield the same id.
80    ///
81    /// # Example
82    ///
83    /// ```rust
84    /// use adk_core::AgentPrincipal;
85    ///
86    /// let principal = AgentPrincipal::derived("billing app", "invoicer");
87    /// assert_eq!(principal.id.as_str(), "urn:adk:agent:billing%20app/invoicer");
88    /// ```
89    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        // Percent-encoding at most triples a name, so only absurd names reach the cap;
106        // the encoded id is ASCII, so truncation stays on a character boundary.
107        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    /// The acting context ADK-Rust derives when none is configured.
114    ///
115    /// The principal is [`AgentPrincipal::derived`] from `app_name` and `agent_name`,
116    /// and the agent acts for `user_id` as a subject of `kind` when `user_id` is
117    /// non-empty.
118    ///
119    /// # Example
120    ///
121    /// ```rust
122    /// use adk_core::{ActingContext, SubjectKind, SubjectRef};
123    ///
124    /// let acting = ActingContext::derived("shop", "cashier", "alice", SubjectKind::Human);
125    /// assert_eq!(acting.agent.id.as_str(), "urn:adk:agent:shop/cashier");
126    /// assert_eq!(acting.on_behalf_of, Some(SubjectRef::human("alice")));
127    /// ```
128    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    /// The context `delegate` acts in when this agent hands it a task.
138    ///
139    /// The delegate acts for the same subject, and the chain gains this agent.
140    ///
141    /// # Example
142    ///
143    /// ```rust
144    /// use adk_core::{ActingContext, AgentPrincipal, SubjectKind, SubjectRef};
145    ///
146    /// let planner = ActingContext::derived("ops", "planner", "alice", SubjectKind::Human);
147    /// let researcher = planner.delegate(AgentPrincipal::derived("ops", "researcher"));
148    /// assert_eq!(researcher.delegation_chain, vec![SubjectRef::agent(&planner.agent.id)]);
149    /// assert_eq!(researcher.on_behalf_of, planner.on_behalf_of);
150    /// ```
151    #[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/// Who a run's agents act as, and for whom.
161///
162/// Carried on [`RunConfig::acting`](crate::RunConfig::acting). The runner fills
163/// [`principals`](Self::principals) from its [`IdentitySource`](crate::IdentitySource)
164/// and checks [`on_behalf_of`](Self::on_behalf_of) against the session's user at the
165/// start of each run ([`admit_subject`](Self::admit_subject)).
166///
167/// # Example
168///
169/// ```rust
170/// use adk_core::{ActingConfig, AgentId, AgentPrincipal, SubjectKind, SubjectRef};
171///
172/// let acting = ActingConfig::default()
173///     .with_principal("billing", AgentPrincipal::new(AgentId::new("spiffe://acme/billing")?))
174///     .with_subject_kind(SubjectKind::Service);
175///
176/// let billing = acting.acting_context_for("shop", "billing", "nightly-close");
177/// assert_eq!(billing.agent.id.as_str(), "spiffe://acme/billing");
178/// assert_eq!(billing.on_behalf_of, Some(SubjectRef::service("nightly-close")));
179///
180/// // An agent with no configured principal acts as its derived id.
181/// let auditor = acting.acting_context_for("shop", "auditor", "nightly-close");
182/// assert_eq!(auditor.agent.id.as_str(), "urn:adk:agent:shop/auditor");
183/// # Ok::<(), adk_core::AdkError>(())
184/// ```
185#[derive(Debug, Clone, Default, PartialEq, Eq)]
186pub struct ActingConfig {
187    /// The principal each named agent acts as. An agent with no entry acts as
188    /// [`AgentPrincipal::derived`] from the app and its name.
189    pub principals: BTreeMap<String, AgentPrincipal>,
190    /// The subject the run's agents act for. `None` acts for the session's user as
191    /// [`subject_kind`](Self::subject_kind); any other subject needs a
192    /// [`SubjectDelegationPolicy`] on the runner.
193    pub on_behalf_of: Option<SubjectRef>,
194    /// What kind of subject the session's user is. [`SubjectKind::Human`] by default;
195    /// runs created by a scheduler, a webhook, or a queue are
196    /// [`SubjectKind::Service`].
197    pub subject_kind: SubjectKind,
198    /// The subjects that delegated the run's work, outermost first.
199    pub delegation_chain: Vec<SubjectRef>,
200}
201
202impl ActingConfig {
203    /// Sets the principal the agent named `agent_name` acts as.
204    #[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    /// Sets the subject the run's agents act for.
215    #[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    /// Sets what kind of subject the session's user is.
222    #[must_use]
223    pub fn with_subject_kind(mut self, kind: SubjectKind) -> Self {
224        self.subject_kind = kind;
225        self
226    }
227
228    /// The principal the agent named `agent_name` of `app_name` acts as.
229    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    /// The subject a session of `user_id` names: `user_id` as
237    /// [`subject_kind`](Self::subject_kind), or `None` for an empty user.
238    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    /// The acting context of the agent named `agent_name` running for `user_id`.
243    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    /// Checks the subject the run acts for against the session's user and pins it.
257    ///
258    /// | `on_behalf_of` | Result |
259    /// |----------------|--------|
260    /// | `None` | Set to the session's subject |
261    /// | The session's subject | Unchanged |
262    /// | Another subject, allowed by `policy` | Unchanged; the session's subject heads the delegation chain |
263    /// | Another subject, otherwise | Refused |
264    ///
265    /// `agent` is the principal of the run's root agent, for the policy to decide on.
266    ///
267    /// # Errors
268    ///
269    /// Returns [`SUBJECT_MISMATCH_CODE`] (`Forbidden`) when the run asks to act for a
270    /// subject other than the session's user and no policy allows it, or the policy's
271    /// own error.
272    ///
273    /// # Example
274    ///
275    /// ```rust
276    /// use adk_core::{ActingConfig, AgentPrincipal, SUBJECT_MISMATCH_CODE, SubjectRef};
277    ///
278    /// # futures::executor::block_on(async {
279    /// let agent = AgentPrincipal::derived("bank", "teller");
280    /// let mut acting = ActingConfig::default().with_on_behalf_of(SubjectRef::human("bob"));
281    /// let error = acting.admit_subject("bank", "alice", &agent, None).await.unwrap_err();
282    /// assert_eq!(error.code, SUBJECT_MISMATCH_CODE);
283    /// # });
284    /// ```
285    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
325/// The [`SUBJECT_MISMATCH_CODE`] error for a run of `session` asking to act for `requested`.
326pub 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/// A request to act for a subject other than the session's user.
340#[derive(Debug, Clone, PartialEq, Eq)]
341#[non_exhaustive]
342pub struct SubjectDelegationRequest {
343    /// The application the run belongs to.
344    pub app_name: String,
345    /// The principal of the run's root agent.
346    pub agent: AgentPrincipal,
347    /// The session's user, as the run's subject kind.
348    pub session_subject: SubjectRef,
349    /// The subject the run asks to act for.
350    pub requested: SubjectRef,
351}
352
353/// Decides whether a run may act for a subject other than its session's user.
354///
355/// Installed with `Runner::builder().subject_delegation(...)`. Without one, every such run
356/// is refused with [`SUBJECT_MISMATCH_CODE`]. Implement it over a token-exchange or
357/// directory lookup to decide per request; [`StaticSubjectDelegation`] covers fixed
358/// rules.
359#[async_trait]
360pub trait SubjectDelegationPolicy: fmt::Debug + Send + Sync {
361    /// Whether the run described by `request` may act for `request.requested`.
362    ///
363    /// # Errors
364    ///
365    /// An error refuses the run with that error.
366    async fn may_act_for(&self, request: &SubjectDelegationRequest) -> Result<bool>;
367}
368
369/// A [`SubjectDelegationPolicy`] with fixed rules: sessions of a subject may act for any
370/// subject, or for listed subjects.
371///
372/// # Example
373///
374/// ```rust
375/// use adk_core::{
376///     AgentPrincipal, StaticSubjectDelegation, SubjectDelegationPolicy,
377///     SubjectDelegationRequest, SubjectRef,
378/// };
379///
380/// let policy = StaticSubjectDelegation::new()
381///     .allow_any(SubjectRef::service("crm-sync"))
382///     .allow(SubjectRef::human("assistant-of-bob"), SubjectRef::human("bob"));
383/// # let _ = policy;
384/// ```
385#[derive(Debug, Clone, Default)]
386pub struct StaticSubjectDelegation {
387    rules: Vec<(SubjectRef, Option<SubjectRef>)>,
388}
389
390impl StaticSubjectDelegation {
391    /// A policy that allows nothing.
392    pub fn new() -> Self {
393        Self::default()
394    }
395
396    /// Sessions of `session_subject` may act for any subject.
397    #[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    /// Sessions of `session_subject` may act for `requested`.
404    #[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        // The same id as another kind is a different subject.
488        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        // The rule names the session subject, so another service is still refused.
520        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}