Skip to main content

adk_core/
principal.rs

1//! Agent identity: who an agent is, who sponsors it, and on whose behalf it acts.
2//!
3//! | Type | Identifies |
4//! |------|------------|
5//! | [`AgentId`] | One agent, stable across redeploys and replicas |
6//! | [`SubjectRef`] | A human, a visitor, a service, or an agent, by kind and identifier |
7//! | [`AgentPrincipal`] | An agent with its tenant, class, instance, sponsor, and attributes |
8//! | [`ActingContext`] | An agent acting on behalf of a subject, through a delegation chain |
9//!
10//! Every type serializes with camelCase field names, so a principal recorded by one
11//! process (in a run record, an audit entry, or a governance state) reads back unchanged
12//! in another.
13//!
14//! # Example
15//!
16//! ```rust
17//! use adk_core::principal::{ActingContext, AgentId, AgentPrincipal, SubjectRef};
18//!
19//! let agent = AgentPrincipal::new(AgentId::new("urn:adk:agent:billing")?)
20//!     .with_tenant("acme")
21//!     .with_sponsor(SubjectRef::human("alice@example.com"));
22//! let acting = ActingContext::new(agent)
23//!     .on_behalf_of(SubjectRef::human("bob@example.com"));
24//!
25//! let json = serde_json::to_value(&acting)?;
26//! assert_eq!(json["agent"]["id"], "urn:adk:agent:billing");
27//! assert_eq!(json["onBehalfOf"]["kind"], "human");
28//! # Ok::<(), Box<dyn std::error::Error>>(())
29//! ```
30
31use std::collections::BTreeMap;
32use std::fmt;
33use std::str::FromStr;
34
35use serde::{Deserialize, Serialize};
36use thiserror::Error;
37
38/// Maximum length of an [`AgentId`], in bytes.
39pub const MAX_AGENT_ID_LEN: usize = 512;
40
41/// Error returned when a string is not a valid [`AgentId`].
42///
43/// # Example
44///
45/// ```rust
46/// use adk_core::principal::{AgentId, PrincipalError};
47///
48/// assert_eq!(AgentId::new(""), Err(PrincipalError::Empty));
49/// ```
50#[derive(Debug, Error, Clone, PartialEq, Eq)]
51#[non_exhaustive]
52pub enum PrincipalError {
53    /// The agent identifier was empty.
54    #[error("agent id must not be empty; use a URI such as `urn:adk:agent:<name>`")]
55    Empty,
56    /// The agent identifier exceeded [`MAX_AGENT_ID_LEN`].
57    #[error(
58        "agent id is {len} bytes, more than the {MAX_AGENT_ID_LEN}-byte limit; use a shorter URI"
59    )]
60    TooLong {
61        /// The length of the rejected identifier, in bytes.
62        len: usize,
63    },
64    /// The agent identifier contained a control character.
65    #[error("agent id must not contain control characters (found U+{code_point:04X})")]
66    ContainsControl {
67        /// The first control character found.
68        code_point: u32,
69    },
70}
71
72/// Opaque, stable agent identifier.
73///
74/// A URI such as `spiffe://example.org/agent/billing` or `urn:adk:agent:billing`. It
75/// survives redeploys and is shared by every replica of the agent. Validation requires
76/// a non-empty value of at most [`MAX_AGENT_ID_LEN`] bytes with no control characters;
77/// the URI scheme is not checked, so any identity system's naming fits.
78///
79/// Deserialization applies the same validation.
80///
81/// # Example
82///
83/// ```rust
84/// use adk_core::principal::AgentId;
85///
86/// let id: AgentId = "spiffe://example.org/agent/billing".parse()?;
87/// assert_eq!(id.as_str(), "spiffe://example.org/agent/billing");
88/// assert!(AgentId::new("bad\nid").is_err());
89/// # Ok::<(), adk_core::principal::PrincipalError>(())
90/// ```
91#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
92#[serde(try_from = "String", into = "String")]
93pub struct AgentId(String);
94
95impl AgentId {
96    /// Creates an agent identifier after validating it.
97    ///
98    /// # Errors
99    ///
100    /// Returns [`PrincipalError`] when the value is empty, longer than
101    /// [`MAX_AGENT_ID_LEN`] bytes, or contains a control character.
102    pub fn new(value: impl Into<String>) -> Result<Self, PrincipalError> {
103        let value = value.into();
104        if value.is_empty() {
105            return Err(PrincipalError::Empty);
106        }
107        if value.len() > MAX_AGENT_ID_LEN {
108            return Err(PrincipalError::TooLong { len: value.len() });
109        }
110        if let Some(control) = value.chars().find(|c| c.is_control()) {
111            return Err(PrincipalError::ContainsControl { code_point: control as u32 });
112        }
113        Ok(Self(value))
114    }
115
116    /// Returns the identifier as a string slice.
117    pub fn as_str(&self) -> &str {
118        &self.0
119    }
120}
121
122impl fmt::Display for AgentId {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.write_str(&self.0)
125    }
126}
127
128impl AsRef<str> for AgentId {
129    fn as_ref(&self) -> &str {
130        &self.0
131    }
132}
133
134impl FromStr for AgentId {
135    type Err = PrincipalError;
136
137    fn from_str(s: &str) -> Result<Self, Self::Err> {
138        Self::new(s)
139    }
140}
141
142impl TryFrom<String> for AgentId {
143    type Error = PrincipalError;
144
145    fn try_from(value: String) -> Result<Self, Self::Error> {
146        Self::new(value)
147    }
148}
149
150impl TryFrom<&str> for AgentId {
151    type Error = PrincipalError;
152
153    fn try_from(value: &str) -> Result<Self, Self::Error> {
154        Self::new(value)
155    }
156}
157
158impl From<AgentId> for String {
159    fn from(id: AgentId) -> Self {
160        id.0
161    }
162}
163
164/// What kind of subject a [`SubjectRef`] names.
165///
166/// # Example
167///
168/// ```rust
169/// use adk_core::principal::SubjectKind;
170///
171/// assert_eq!(serde_json::to_value(SubjectKind::Service).unwrap(), "service");
172/// ```
173#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
174#[serde(rename_all = "camelCase")]
175#[non_exhaustive]
176pub enum SubjectKind {
177    /// A person. The default: an interactive run acts for a person.
178    #[default]
179    Human,
180    /// A non-agent workload, such as a backend service or a scheduler.
181    Service,
182    /// An agent; the identifier is an [`AgentId`] string.
183    Agent,
184    /// A person the deployment knows only by an id it issued, such as a website visitor
185    /// who has not signed in; the identifier is a
186    /// [`VisitorId`](crate::subject::VisitorId) string.
187    ///
188    /// The id is pseudonymous, not anonymous: it names one person, so the data held under
189    /// it is that person's. A visitor's run is never authenticated.
190    Visitor,
191}
192
193/// A reference to a human, a visitor, a service, or an agent.
194///
195/// # Example
196///
197/// ```rust
198/// use adk_core::principal::{SubjectKind, SubjectRef};
199///
200/// let alice = SubjectRef::human("alice@example.com");
201/// assert_eq!(alice, SubjectRef { kind: SubjectKind::Human, id: "alice@example.com".into() });
202/// ```
203#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
204#[serde(rename_all = "camelCase")]
205pub struct SubjectRef {
206    /// The kind of subject.
207    pub kind: SubjectKind,
208    /// The subject's identifier in its identity system.
209    pub id: String,
210}
211
212impl SubjectRef {
213    /// Creates a reference to a subject of `kind`.
214    pub fn new(kind: SubjectKind, id: impl Into<String>) -> Self {
215        Self { kind, id: id.into() }
216    }
217
218    /// Creates a reference to a person.
219    pub fn human(id: impl Into<String>) -> Self {
220        Self::new(SubjectKind::Human, id)
221    }
222
223    /// Creates a reference to a non-agent workload.
224    pub fn service(id: impl Into<String>) -> Self {
225        Self::new(SubjectKind::Service, id)
226    }
227
228    /// Creates a reference to an agent.
229    pub fn agent(id: &AgentId) -> Self {
230        Self::new(SubjectKind::Agent, id.as_str())
231    }
232
233    /// Creates a reference to a visitor known by `id`, a
234    /// [`VisitorId`](crate::subject::VisitorId) the deployment issued.
235    ///
236    /// # Example
237    ///
238    /// ```rust
239    /// use adk_core::principal::{SubjectKind, SubjectRef};
240    /// use adk_core::subject::VisitorId;
241    ///
242    /// let visitor = SubjectRef::visitor(VisitorId::generate().as_str());
243    /// assert_eq!(visitor.kind, SubjectKind::Visitor);
244    /// ```
245    pub fn visitor(id: impl Into<String>) -> Self {
246        Self::new(SubjectKind::Visitor, id)
247    }
248}
249
250/// An agent's identity: its stable identifier plus where and for whom it runs.
251///
252/// # Example
253///
254/// ```rust
255/// use adk_core::principal::{AgentId, AgentPrincipal, SubjectRef};
256///
257/// let principal = AgentPrincipal::new(AgentId::new("urn:adk:agent:billing")?)
258///     .with_tenant("acme")
259///     .with_class("billing-v2")
260///     .with_instance("replica-3")
261///     .with_sponsor(SubjectRef::human("alice@example.com"))
262///     .with_attribute("cost-center", "finance");
263/// assert_eq!(principal.attributes["cost-center"], "finance");
264/// # Ok::<(), adk_core::principal::PrincipalError>(())
265/// ```
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "camelCase")]
268pub struct AgentPrincipal {
269    /// The agent's stable identifier.
270    pub id: AgentId,
271    /// The tenant the agent belongs to, in a multi-tenant deployment.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub tenant: Option<String>,
274    /// The template or blueprint the agent was created from.
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub class: Option<String>,
277    /// The deployment or replica running the agent.
278    #[serde(default, skip_serializing_if = "Option::is_none")]
279    pub instance: Option<String>,
280    /// The subject accountable for the agent.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub sponsor: Option<SubjectRef>,
283    /// Further attributes, ordered by key so serialization is deterministic.
284    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
285    pub attributes: BTreeMap<String, String>,
286}
287
288impl AgentPrincipal {
289    /// Creates a principal with only an identifier.
290    pub fn new(id: AgentId) -> Self {
291        Self {
292            id,
293            tenant: None,
294            class: None,
295            instance: None,
296            sponsor: None,
297            attributes: BTreeMap::new(),
298        }
299    }
300
301    /// Sets the tenant.
302    pub fn with_tenant(mut self, tenant: impl Into<String>) -> Self {
303        self.tenant = Some(tenant.into());
304        self
305    }
306
307    /// Sets the class (template or blueprint).
308    pub fn with_class(mut self, class: impl Into<String>) -> Self {
309        self.class = Some(class.into());
310        self
311    }
312
313    /// Sets the instance (deployment or replica).
314    pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
315        self.instance = Some(instance.into());
316        self
317    }
318
319    /// Sets the sponsor.
320    pub fn with_sponsor(mut self, sponsor: SubjectRef) -> Self {
321        self.sponsor = Some(sponsor);
322        self
323    }
324
325    /// Adds or replaces one attribute.
326    pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
327        self.attributes.insert(key.into(), value.into());
328        self
329    }
330}
331
332/// An agent acting for a subject, through a delegation chain.
333///
334/// The context names no invocation: the invocation an agent acts in is the execution
335/// identity's ([`ReadonlyContext::invocation_id`](crate::ReadonlyContext::invocation_id)),
336/// so there is one source for it. Audit records pair the two with
337/// [`AuditActor::new`](crate::audit_log::AuditActor::new).
338///
339/// `delegation_chain` lists the subjects that handed the work down, outermost first:
340/// a human who asked an orchestrator agent, which delegated to this agent, reads
341/// `[human, orchestrator]`.
342///
343/// # Example
344///
345/// ```rust
346/// use adk_core::principal::{ActingContext, AgentId, AgentPrincipal, SubjectRef};
347///
348/// let orchestrator = AgentId::new("urn:adk:agent:orchestrator")?;
349/// let acting = ActingContext::new(AgentPrincipal::new(AgentId::new("urn:adk:agent:billing")?))
350///     .on_behalf_of(SubjectRef::human("bob@example.com"))
351///     .delegated_by(SubjectRef::human("bob@example.com"))
352///     .delegated_by(SubjectRef::agent(&orchestrator));
353/// assert_eq!(acting.delegation_chain.len(), 2);
354/// # Ok::<(), adk_core::principal::PrincipalError>(())
355/// ```
356#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
357#[serde(rename_all = "camelCase")]
358pub struct ActingContext {
359    /// The acting agent.
360    pub agent: AgentPrincipal,
361    /// The subject the agent acts for, when it acts for one.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub on_behalf_of: Option<SubjectRef>,
364    /// The subjects that delegated the work, outermost first.
365    #[serde(default, skip_serializing_if = "Vec::is_empty")]
366    pub delegation_chain: Vec<SubjectRef>,
367}
368
369impl ActingContext {
370    /// Creates a context for `agent` acting for no subject.
371    pub fn new(agent: AgentPrincipal) -> Self {
372        Self { agent, on_behalf_of: None, delegation_chain: Vec::new() }
373    }
374
375    /// Sets the subject the agent acts for.
376    pub fn on_behalf_of(mut self, subject: SubjectRef) -> Self {
377        self.on_behalf_of = Some(subject);
378        self
379    }
380
381    /// Appends a subject to the end of the delegation chain.
382    pub fn delegated_by(mut self, subject: SubjectRef) -> Self {
383        self.delegation_chain.push(subject);
384        self
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391    use serde_json::json;
392
393    #[test]
394    fn agent_id_validation() {
395        assert_eq!(AgentId::new(""), Err(PrincipalError::Empty));
396        assert_eq!(
397            AgentId::new("a".repeat(MAX_AGENT_ID_LEN + 1)),
398            Err(PrincipalError::TooLong { len: MAX_AGENT_ID_LEN + 1 })
399        );
400        assert_eq!(
401            AgentId::new("urn:adk:\u{7f}"),
402            Err(PrincipalError::ContainsControl { code_point: 0x7f })
403        );
404        assert_eq!(AgentId::new("x\0y"), Err(PrincipalError::ContainsControl { code_point: 0 }));
405        assert!(AgentId::new("a".repeat(MAX_AGENT_ID_LEN)).is_ok());
406        assert!(AgentId::new("urn:adk:agent:fakturering/ΓΈ").is_ok());
407    }
408
409    #[test]
410    fn agent_id_deserialization_validates() {
411        let parsed: AgentId = serde_json::from_value(json!("urn:adk:agent:a")).unwrap();
412        assert_eq!(parsed.as_str(), "urn:adk:agent:a");
413        assert!(serde_json::from_value::<AgentId>(json!("")).is_err());
414        assert!(serde_json::from_value::<AgentId>(json!("a\tb")).is_err());
415    }
416
417    #[test]
418    fn acting_context_round_trips_in_camel_case() {
419        let acting = ActingContext::new(
420            AgentPrincipal::new(AgentId::new("spiffe://example.org/agent/billing").unwrap())
421                .with_tenant("acme")
422                .with_class("billing")
423                .with_instance("r1")
424                .with_sponsor(SubjectRef::human("alice"))
425                .with_attribute("tier", "gold"),
426        )
427        .on_behalf_of(SubjectRef::service("crm"))
428        .delegated_by(SubjectRef::human("alice"));
429
430        let value = serde_json::to_value(&acting).unwrap();
431        assert_eq!(
432            value,
433            json!({
434                "agent": {
435                    "id": "spiffe://example.org/agent/billing",
436                    "tenant": "acme",
437                    "class": "billing",
438                    "instance": "r1",
439                    "sponsor": {"kind": "human", "id": "alice"},
440                    "attributes": {"tier": "gold"}
441                },
442                "onBehalfOf": {"kind": "service", "id": "crm"},
443                "delegationChain": [{"kind": "human", "id": "alice"}]
444            })
445        );
446        let back: ActingContext = serde_json::from_value(value).unwrap();
447        assert_eq!(back, acting);
448
449        let minimal =
450            ActingContext::new(AgentPrincipal::new(AgentId::new("urn:adk:agent:a").unwrap()));
451        let back: ActingContext =
452            serde_json::from_value(serde_json::to_value(&minimal).unwrap()).unwrap();
453        assert_eq!(back, minimal);
454    }
455
456    #[test]
457    fn contexts_recorded_with_an_invocation_id_still_read() {
458        // Records written before the invocation id moved to the execution identity.
459        let back: ActingContext = serde_json::from_value(json!({
460            "agent": {"id": "urn:adk:agent:a"},
461            "invocationId": "inv-old"
462        }))
463        .unwrap();
464        assert_eq!(
465            back,
466            ActingContext::new(AgentPrincipal::new(AgentId::new("urn:adk:agent:a").unwrap()))
467        );
468    }
469}