Skip to main content

adk_core/
identity.rs

1//! Typed identity primitives for ADK-Rust.
2//!
3//! This module provides strongly-typed wrappers for the identity values used
4//! throughout the ADK runtime: application names, user identifiers, session
5//! identifiers, and invocation identifiers.
6//!
7//! ## Identity Layers
8//!
9//! ADK distinguishes three identity concerns:
10//!
11//! - **Auth identity** ([`RequestContext`](crate::RequestContext)): who is
12//!   authenticated and what scopes they hold.
13//! - **Session identity** ([`AdkIdentity`]): the stable `(app, user, session)`
14//!   triple that addresses a conversation session.
15//! - **Execution identity** ([`ExecutionIdentity`]): session identity plus the
16//!   per-invocation `invocation_id`, `branch`, and `agent_name`.
17//!
18//! ## Validation Rules
19//!
20//! All leaf identifiers ([`AppName`], [`UserId`], [`SessionId`],
21//! [`InvocationId`]) enforce the same validation:
22//!
23//! - Must not be empty.
24//! - Must not contain null bytes (`\0`).
25//! - Must not exceed [`MAX_ID_LEN`](crate::identity::MAX_ID_LEN) bytes (512).
26//! - Characters like `:`, `|`, `/`, and `@` are allowed — validation does not
27//!   couple to any backend's internal key encoding.
28//!
29//! ## Examples
30//!
31//! ```
32//! use adk_core::identity::{AdkIdentity, AppName, ExecutionIdentity, InvocationId, SessionId, UserId};
33//!
34//! let identity = AdkIdentity::new(
35//!     AppName::try_from("weather-app").unwrap(),
36//!     UserId::try_from("tenant:alice@example.com").unwrap(),
37//!     SessionId::generate(),
38//! );
39//!
40//! let exec = ExecutionIdentity {
41//!     adk: identity,
42//!     invocation_id: InvocationId::generate(),
43//!     branch: String::new(),
44//!     agent_name: "planner".to_string(),
45//! };
46//! ```
47
48use serde::{Deserialize, Serialize};
49use std::borrow::Borrow;
50use std::fmt;
51use std::str::FromStr;
52use thiserror::Error;
53use uuid::Uuid;
54
55/// Maximum allowed length for any identity value, in bytes.
56pub const MAX_ID_LEN: usize = 512;
57
58// ---------------------------------------------------------------------------
59// IdentityError
60// ---------------------------------------------------------------------------
61
62/// Error returned when a raw string cannot be converted into a typed identifier.
63///
64/// # Examples
65///
66/// ```
67/// use adk_core::identity::{AppName, IdentityError};
68///
69/// let err = AppName::try_from("").unwrap_err();
70/// assert!(matches!(err, IdentityError::Empty { .. }));
71/// ```
72#[derive(Debug, Error, Clone, PartialEq, Eq)]
73pub enum IdentityError {
74    /// The input string was empty.
75    #[error("{kind} must not be empty")]
76    Empty {
77        /// Human-readable name of the identifier kind (e.g. `"AppName"`).
78        kind: &'static str,
79    },
80
81    /// The input string exceeded [`MAX_ID_LEN`].
82    #[error("{kind} exceeds maximum length of {max} bytes")]
83    TooLong {
84        /// Human-readable name of the identifier kind.
85        kind: &'static str,
86        /// The maximum allowed length.
87        max: usize,
88    },
89
90    /// The input string contained a null byte.
91    #[error("{kind} must not contain null bytes")]
92    ContainsNull {
93        /// Human-readable name of the identifier kind.
94        kind: &'static str,
95    },
96}
97
98// ---------------------------------------------------------------------------
99// Shared validation
100// ---------------------------------------------------------------------------
101
102fn validate(value: &str, kind: &'static str) -> Result<(), IdentityError> {
103    if value.is_empty() {
104        return Err(IdentityError::Empty { kind });
105    }
106    if value.len() > MAX_ID_LEN {
107        return Err(IdentityError::TooLong { kind, max: MAX_ID_LEN });
108    }
109    if value.contains('\0') {
110        return Err(IdentityError::ContainsNull { kind });
111    }
112    Ok(())
113}
114
115// ---------------------------------------------------------------------------
116// Macro for leaf identifier newtypes
117// ---------------------------------------------------------------------------
118
119macro_rules! define_id {
120    (
121        $(#[$meta:meta])*
122        $name:ident, $kind:literal
123    ) => {
124        $(#[$meta])*
125        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
126        #[serde(transparent)]
127        pub struct $name(String);
128
129        impl $name {
130            /// Returns the inner string slice.
131            pub fn as_str(&self) -> &str {
132                &self.0
133            }
134
135            /// Creates a typed identifier with validation.
136            ///
137            /// Prefer this constructor at trust boundaries where the input may
138            /// come from users, HTTP payloads, or external systems.
139            pub fn new(value: impl Into<String>) -> Result<Self, IdentityError> {
140                let value = value.into();
141                validate(&value, $kind)?;
142                Ok(Self(value))
143            }
144
145            /// Creates a typed identifier from a trusted string without
146            /// validation.
147            ///
148            /// Use this only for values that originate from internal runtime
149            /// paths (e.g. session service, runner) where the string is
150            /// already known to be valid. Prefer [`TryFrom`] or [`FromStr`]
151            /// at trust boundaries.
152            pub fn new_unchecked(value: impl Into<String>) -> Self {
153                Self(value.into())
154            }
155        }
156
157        impl AsRef<str> for $name {
158            fn as_ref(&self) -> &str {
159                &self.0
160            }
161        }
162
163        impl Borrow<str> for $name {
164            fn borrow(&self) -> &str {
165                &self.0
166            }
167        }
168
169        impl fmt::Display for $name {
170            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171                f.write_str(&self.0)
172            }
173        }
174
175        impl FromStr for $name {
176            type Err = IdentityError;
177
178            fn from_str(s: &str) -> Result<Self, Self::Err> {
179                validate(s, $kind)?;
180                Ok(Self(s.to_owned()))
181            }
182        }
183
184        impl TryFrom<&str> for $name {
185            type Error = IdentityError;
186
187            fn try_from(s: &str) -> Result<Self, Self::Error> {
188                validate(s, $kind)?;
189                Ok(Self(s.to_owned()))
190            }
191        }
192
193        impl TryFrom<String> for $name {
194            type Error = IdentityError;
195
196            fn try_from(s: String) -> Result<Self, Self::Error> {
197                validate(&s, $kind)?;
198                Ok(Self(s))
199            }
200        }
201    };
202}
203
204// ---------------------------------------------------------------------------
205// Leaf identifier types
206// ---------------------------------------------------------------------------
207
208define_id! {
209    /// A typed wrapper around the logical application name used in session
210    /// addressing.
211    ///
212    /// # Examples
213    ///
214    /// ```
215    /// use adk_core::identity::AppName;
216    ///
217    /// let app: AppName = "my-app".parse().unwrap();
218    /// assert_eq!(app.as_ref(), "my-app");
219    ///
220    /// // Empty values are rejected
221    /// assert!(AppName::try_from("").is_err());
222    /// ```
223    AppName, "AppName"
224}
225
226define_id! {
227    /// A typed wrapper around a logical user identifier.
228    ///
229    /// # Examples
230    ///
231    /// ```
232    /// use adk_core::identity::UserId;
233    ///
234    /// let uid: UserId = "tenant:alice@example.com".parse().unwrap();
235    /// assert_eq!(uid.as_ref(), "tenant:alice@example.com");
236    /// ```
237    UserId, "UserId"
238}
239
240define_id! {
241    /// A typed wrapper around a logical session identifier.
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// use adk_core::identity::SessionId;
247    ///
248    /// // Parse from a known value
249    /// let sid = SessionId::try_from("session-abc-123").unwrap();
250    /// assert_eq!(sid.as_ref(), "session-abc-123");
251    ///
252    /// // Or generate a new UUID-based session ID
253    /// let generated = SessionId::generate();
254    /// assert!(!generated.as_ref().is_empty());
255    /// ```
256    SessionId, "SessionId"
257}
258
259define_id! {
260    /// A typed wrapper around a single execution or turn identifier.
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// use adk_core::identity::InvocationId;
266    ///
267    /// // Parse from a known value
268    /// let iid = InvocationId::try_from("inv-001").unwrap();
269    /// assert_eq!(iid.as_ref(), "inv-001");
270    ///
271    /// // Or generate a new UUID-based invocation ID
272    /// let generated = InvocationId::generate();
273    /// assert!(!generated.as_ref().is_empty());
274    /// ```
275    InvocationId, "InvocationId"
276}
277
278// ---------------------------------------------------------------------------
279// Generation helpers
280// ---------------------------------------------------------------------------
281
282impl SessionId {
283    /// Generates a new random session identifier using UUID v4.
284    ///
285    /// # Examples
286    ///
287    /// ```
288    /// use adk_core::identity::SessionId;
289    ///
290    /// let a = SessionId::generate();
291    /// let b = SessionId::generate();
292    /// assert_ne!(a, b);
293    /// ```
294    pub fn generate() -> Self {
295        Self(Uuid::new_v4().to_string())
296    }
297}
298
299impl InvocationId {
300    /// Generates a new random invocation identifier using UUID v4.
301    ///
302    /// # Examples
303    ///
304    /// ```
305    /// use adk_core::identity::InvocationId;
306    ///
307    /// let a = InvocationId::generate();
308    /// let b = InvocationId::generate();
309    /// assert_ne!(a, b);
310    /// ```
311    pub fn generate() -> Self {
312        Self(Uuid::new_v4().to_string())
313    }
314}
315
316// ---------------------------------------------------------------------------
317// AdkIdentity
318// ---------------------------------------------------------------------------
319
320/// The stable session-scoped identity triple: application name, user, and
321/// session.
322///
323/// This is the natural addressing key for session-scoped operations. Passing
324/// an `AdkIdentity` instead of three separate strings eliminates parameter
325/// ordering bugs and makes the addressing model explicit.
326///
327/// # Display
328///
329/// The [`Display`](fmt::Display) implementation is diagnostic only and must
330/// not be parsed or used as a storage key.
331///
332/// # Examples
333///
334/// ```
335/// use adk_core::identity::{AdkIdentity, AppName, SessionId, UserId};
336///
337/// let identity = AdkIdentity::new(
338///     AppName::try_from("weather-app").unwrap(),
339///     UserId::try_from("alice").unwrap(),
340///     SessionId::try_from("sess-1").unwrap(),
341/// );
342///
343/// assert_eq!(identity.app_name.as_ref(), "weather-app");
344/// assert_eq!(identity.user_id.as_ref(), "alice");
345/// assert_eq!(identity.session_id.as_ref(), "sess-1");
346/// ```
347#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
348pub struct AdkIdentity {
349    /// The application name.
350    pub app_name: AppName,
351    /// The user identifier.
352    pub user_id: UserId,
353    /// The session identifier.
354    pub session_id: SessionId,
355}
356
357impl AdkIdentity {
358    /// Creates a new `AdkIdentity` from its constituent parts.
359    pub fn new(app_name: AppName, user_id: UserId, session_id: SessionId) -> Self {
360        Self { app_name, user_id, session_id }
361    }
362}
363
364impl fmt::Display for AdkIdentity {
365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366        write!(
367            f,
368            "AdkIdentity(app=\"{}\", user=\"{}\", session=\"{}\")",
369            self.app_name, self.user_id, self.session_id
370        )
371    }
372}
373
374// ---------------------------------------------------------------------------
375// ExecutionIdentity
376// ---------------------------------------------------------------------------
377
378/// The per-invocation execution identity, built from a stable
379/// [`AdkIdentity`] plus invocation-scoped metadata.
380///
381/// This is the runtime's internal identity capsule. It carries everything
382/// needed for event creation, telemetry correlation, and agent transfers
383/// without re-parsing raw strings.
384///
385/// # Examples
386///
387/// ```
388/// use adk_core::identity::{
389///     AdkIdentity, AppName, ExecutionIdentity, InvocationId, SessionId, UserId,
390/// };
391///
392/// let exec = ExecutionIdentity {
393///     adk: AdkIdentity::new(
394///         AppName::try_from("my-app").unwrap(),
395///         UserId::try_from("user-1").unwrap(),
396///         SessionId::try_from("sess-1").unwrap(),
397///     ),
398///     invocation_id: InvocationId::generate(),
399///     branch: String::new(),
400///     agent_name: "root".to_string(),
401/// };
402///
403/// assert_eq!(exec.adk.app_name.as_ref(), "my-app");
404/// ```
405#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
406pub struct ExecutionIdentity {
407    /// The stable session-scoped identity.
408    pub adk: AdkIdentity,
409    /// The invocation identifier for this execution turn.
410    pub invocation_id: InvocationId,
411    /// The branch name. Defaults to an empty string in phase 1.
412    pub branch: String,
413    /// The name of the currently executing agent.
414    pub agent_name: String,
415}
416
417// ---------------------------------------------------------------------------
418// IdentityError -> AdkError conversion
419// ---------------------------------------------------------------------------
420
421/// An identifier that fails validation becomes `session.invalid_identifier`
422/// ([`ErrorCategory::InvalidInput`](crate::ErrorCategory::InvalidInput), HTTP 400) in the
423/// [`Session`](crate::ErrorComponent::Session) component, the error every session backend
424/// and the runner return for an invalid app name, user ID, or session ID.
425///
426/// # Example
427///
428/// ```
429/// use adk_core::identity::UserId;
430/// use adk_core::{AdkError, ErrorCategory};
431///
432/// let error: AdkError = UserId::try_from("").unwrap_err().into();
433/// assert_eq!(error.code, "session.invalid_identifier");
434/// assert_eq!(error.category, ErrorCategory::InvalidInput);
435/// ```
436impl From<IdentityError> for crate::AdkError {
437    fn from(err: IdentityError) -> Self {
438        crate::AdkError::new(
439            crate::ErrorComponent::Session,
440            crate::ErrorCategory::InvalidInput,
441            "session.invalid_identifier",
442            format!(
443                "{err}; identifiers must be non-empty, at most {MAX_ID_LEN} bytes, and free of NUL \
444                 characters"
445            ),
446        )
447    }
448}
449
450// ---------------------------------------------------------------------------
451// Tests
452// ---------------------------------------------------------------------------
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457
458    #[test]
459    fn test_app_name_valid() {
460        let app = AppName::try_from("my-app").unwrap();
461        assert_eq!(app.as_ref(), "my-app");
462        assert_eq!(app.to_string(), "my-app");
463    }
464
465    #[test]
466    fn test_app_name_with_special_chars() {
467        // Colons, slashes, and @ are allowed
468        let app = AppName::try_from("org:team/app@v2").unwrap();
469        assert_eq!(app.as_ref(), "org:team/app@v2");
470    }
471
472    #[test]
473    fn test_empty_rejected() {
474        let err = AppName::try_from("").unwrap_err();
475        assert_eq!(err, IdentityError::Empty { kind: "AppName" });
476    }
477
478    #[test]
479    fn test_null_byte_rejected() {
480        let err = UserId::try_from("user\0id").unwrap_err();
481        assert_eq!(err, IdentityError::ContainsNull { kind: "UserId" });
482    }
483
484    #[test]
485    fn test_too_long_rejected() {
486        let long = "x".repeat(MAX_ID_LEN + 1);
487        let err = SessionId::try_from(long.as_str()).unwrap_err();
488        assert_eq!(err, IdentityError::TooLong { kind: "SessionId", max: MAX_ID_LEN });
489    }
490
491    #[test]
492    fn test_max_length_accepted() {
493        let exact = "a".repeat(MAX_ID_LEN);
494        assert!(SessionId::try_from(exact.as_str()).is_ok());
495    }
496
497    #[test]
498    fn test_from_str() {
499        let app: AppName = "hello".parse().unwrap();
500        assert_eq!(app.as_ref(), "hello");
501    }
502
503    #[test]
504    fn test_try_from_string() {
505        let s = String::from("owned-value");
506        let uid = UserId::try_from(s).unwrap();
507        assert_eq!(uid.as_ref(), "owned-value");
508    }
509
510    #[test]
511    fn test_borrow_str() {
512        let sid = SessionId::try_from("sess-1").unwrap();
513        let borrowed: &str = sid.borrow();
514        assert_eq!(borrowed, "sess-1");
515    }
516
517    #[test]
518    fn test_ord() {
519        let a = AppName::try_from("aaa").unwrap();
520        let b = AppName::try_from("bbb").unwrap();
521        assert!(a < b);
522    }
523
524    #[test]
525    fn test_session_id_generate() {
526        let a = SessionId::generate();
527        let b = SessionId::generate();
528        assert_ne!(a, b);
529        assert!(!a.as_ref().is_empty());
530    }
531
532    #[test]
533    fn test_invocation_id_generate() {
534        let a = InvocationId::generate();
535        let b = InvocationId::generate();
536        assert_ne!(a, b);
537        assert!(!a.as_ref().is_empty());
538    }
539
540    #[test]
541    fn test_adk_identity_new() {
542        let identity = AdkIdentity::new(
543            AppName::try_from("app").unwrap(),
544            UserId::try_from("user").unwrap(),
545            SessionId::try_from("sess").unwrap(),
546        );
547        assert_eq!(identity.app_name.as_ref(), "app");
548        assert_eq!(identity.user_id.as_ref(), "user");
549        assert_eq!(identity.session_id.as_ref(), "sess");
550    }
551
552    #[test]
553    fn test_adk_identity_display() {
554        let identity = AdkIdentity::new(
555            AppName::try_from("weather-app").unwrap(),
556            UserId::try_from("alice").unwrap(),
557            SessionId::try_from("abc-123").unwrap(),
558        );
559        let display = identity.to_string();
560        assert!(display.contains("weather-app"));
561        assert!(display.contains("alice"));
562        assert!(display.contains("abc-123"));
563        assert!(display.starts_with("AdkIdentity("));
564    }
565
566    #[test]
567    fn test_adk_identity_equality() {
568        let a = AdkIdentity::new(
569            AppName::try_from("app").unwrap(),
570            UserId::try_from("user").unwrap(),
571            SessionId::try_from("sess").unwrap(),
572        );
573        let b = a.clone();
574        assert_eq!(a, b);
575
576        let c = AdkIdentity::new(
577            AppName::try_from("app").unwrap(),
578            UserId::try_from("other-user").unwrap(),
579            SessionId::try_from("sess").unwrap(),
580        );
581        assert_ne!(a, c);
582    }
583
584    #[test]
585    fn test_adk_identity_hash() {
586        use std::collections::HashSet;
587        let a = AdkIdentity::new(
588            AppName::try_from("app").unwrap(),
589            UserId::try_from("user").unwrap(),
590            SessionId::try_from("sess").unwrap(),
591        );
592        let b = a.clone();
593        let mut set = HashSet::new();
594        set.insert(a);
595        set.insert(b);
596        assert_eq!(set.len(), 1);
597    }
598
599    #[test]
600    fn test_execution_identity() {
601        let exec = ExecutionIdentity {
602            adk: AdkIdentity::new(
603                AppName::try_from("app").unwrap(),
604                UserId::try_from("user").unwrap(),
605                SessionId::try_from("sess").unwrap(),
606            ),
607            invocation_id: InvocationId::try_from("inv-1").unwrap(),
608            branch: String::new(),
609            agent_name: "root".to_string(),
610        };
611        assert_eq!(exec.adk.app_name.as_ref(), "app");
612        assert_eq!(exec.invocation_id.as_ref(), "inv-1");
613        assert_eq!(exec.branch, "");
614        assert_eq!(exec.agent_name, "root");
615    }
616
617    #[test]
618    fn test_serde_round_trip_leaf() {
619        let app = AppName::try_from("my-app").unwrap();
620        let json = serde_json::to_string(&app).unwrap();
621        assert_eq!(json, "\"my-app\"");
622        let deserialized: AppName = serde_json::from_str(&json).unwrap();
623        assert_eq!(app, deserialized);
624    }
625
626    #[test]
627    fn test_serde_round_trip_adk_identity() {
628        let identity = AdkIdentity::new(
629            AppName::try_from("app").unwrap(),
630            UserId::try_from("user").unwrap(),
631            SessionId::try_from("sess").unwrap(),
632        );
633        let json = serde_json::to_string(&identity).unwrap();
634        let deserialized: AdkIdentity = serde_json::from_str(&json).unwrap();
635        assert_eq!(identity, deserialized);
636    }
637
638    #[test]
639    fn test_serde_round_trip_execution_identity() {
640        let exec = ExecutionIdentity {
641            adk: AdkIdentity::new(
642                AppName::try_from("app").unwrap(),
643                UserId::try_from("user").unwrap(),
644                SessionId::try_from("sess").unwrap(),
645            ),
646            invocation_id: InvocationId::try_from("inv-1").unwrap(),
647            branch: "main".to_string(),
648            agent_name: "agent".to_string(),
649        };
650        let json = serde_json::to_string(&exec).unwrap();
651        let deserialized: ExecutionIdentity = serde_json::from_str(&json).unwrap();
652        assert_eq!(exec, deserialized);
653    }
654
655    #[test]
656    fn test_identity_error_display() {
657        let err = IdentityError::Empty { kind: "AppName" };
658        assert_eq!(err.to_string(), "AppName must not be empty");
659
660        let err = IdentityError::TooLong { kind: "UserId", max: 512 };
661        assert_eq!(err.to_string(), "UserId exceeds maximum length of 512 bytes");
662
663        let err = IdentityError::ContainsNull { kind: "SessionId" };
664        assert_eq!(err.to_string(), "SessionId must not contain null bytes");
665    }
666
667    #[test]
668    fn test_identity_error_to_adk_error() {
669        for err in [
670            IdentityError::Empty { kind: "AppName" },
671            IdentityError::TooLong { kind: "UserId", max: MAX_ID_LEN },
672            IdentityError::ContainsNull { kind: "SessionId" },
673        ] {
674            let message = err.to_string();
675            let adk_err: crate::AdkError = err.into();
676            assert_eq!(
677                (adk_err.component, adk_err.category, adk_err.code),
678                (
679                    crate::ErrorComponent::Session,
680                    crate::ErrorCategory::InvalidInput,
681                    "session.invalid_identifier"
682                )
683            );
684            assert!(adk_err.message.starts_with(&message), "{}", adk_err.message);
685            assert_eq!(adk_err.http_status_code(), 400);
686        }
687    }
688}