Skip to main content

adk_core/
credential.rs

1//! Agent credentials, identity sources, and resource-scoped token brokers.
2//!
3//! | Item | Role |
4//! |------|------|
5//! | [`IdentitySource`] | Says who the running agent is ([`AgentPrincipal`]) and proves it ([`AgentCredential`]) |
6//! | [`StaticIdentitySource`] | A fixed principal and optional credential, for configuration-driven deployments |
7//! | [`CredentialBroker`] | Mints a [`ScopedToken`] for one acting agent, one resource, and a set of scopes |
8//! | [`ScopedToken`] | A secret bound to one audience; [`ScopedToken::authorize_for`] refuses any other resource |
9//!
10//! SPIFFE Workload API and cloud metadata servers are extension points: implement
11//! [`IdentitySource`] over the client of your choice and pass it to the runner.
12
13use std::fmt;
14
15use async_trait::async_trait;
16use chrono::{DateTime, Utc};
17use serde::{Deserialize, Serialize};
18use url::Url;
19
20use crate::{
21    ActingContext, AdkError, AgentId, AgentPrincipal, ErrorCategory, ErrorComponent, Result,
22};
23
24/// A secret value whose `Debug` and `Display` output is redacted.
25///
26/// # Example
27///
28/// ```rust
29/// use adk_core::CredentialSecret;
30///
31/// let secret = CredentialSecret::new("s3cr3t");
32/// assert_eq!(secret.expose(), "s3cr3t");
33/// assert_eq!(format!("{secret:?}"), "CredentialSecret([redacted])");
34/// ```
35#[derive(Clone, PartialEq, Eq)]
36pub struct CredentialSecret(String);
37
38impl CredentialSecret {
39    /// Wraps `value`.
40    pub fn new(value: impl Into<String>) -> Self {
41        Self(value.into())
42    }
43
44    /// The secret value. Pass it only to the party it was issued for.
45    pub fn expose(&self) -> &str {
46        &self.0
47    }
48}
49
50impl fmt::Debug for CredentialSecret {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.write_str("CredentialSecret([redacted])")
53    }
54}
55
56impl fmt::Display for CredentialSecret {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.write_str("[redacted]")
59    }
60}
61
62/// The form of an [`AgentCredential`].
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
64#[serde(rename_all = "camelCase")]
65#[non_exhaustive]
66pub enum CredentialKind {
67    /// A JWT-SVID (SPIFFE JWT identity document) or another signed JWT.
68    JwtSvid,
69    /// A PEM-encoded X.509 certificate chain, such as an X.509-SVID.
70    X509,
71    /// Any other bearer value, such as an API key or a platform-issued token.
72    Opaque,
73}
74
75/// A credential proving an agent's identity to a third party.
76///
77/// # Example
78///
79/// ```rust
80/// use adk_core::{AgentCredential, AgentId, CredentialKind};
81///
82/// let credential = AgentCredential::new(
83///     AgentId::new("spiffe://example.org/agent/billing")?,
84///     CredentialKind::JwtSvid,
85///     "eyJhbGciOi...",
86/// );
87/// assert!(credential.is_live(chrono::Utc::now()));
88/// # Ok::<(), adk_core::AdkError>(())
89/// ```
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct AgentCredential {
92    /// The agent the credential identifies.
93    pub subject: AgentId,
94    /// The credential's form.
95    pub kind: CredentialKind,
96    /// The credential value.
97    pub secret: CredentialSecret,
98    /// When the credential stops being valid, if it expires.
99    pub expires_at: Option<DateTime<Utc>>,
100    /// The audiences the credential was issued for; empty when unrestricted.
101    pub audience: Vec<String>,
102}
103
104impl AgentCredential {
105    /// A credential of `kind` for `subject` with no expiry or audience.
106    pub fn new(subject: AgentId, kind: CredentialKind, secret: impl Into<String>) -> Self {
107        Self {
108            subject,
109            kind,
110            secret: CredentialSecret::new(secret),
111            expires_at: None,
112            audience: Vec::new(),
113        }
114    }
115
116    /// Sets the expiry.
117    #[must_use]
118    pub fn expires_at(mut self, at: DateTime<Utc>) -> Self {
119        self.expires_at = Some(at);
120        self
121    }
122
123    /// Adds an audience.
124    #[must_use]
125    pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
126        self.audience.push(audience.into());
127        self
128    }
129
130    /// Whether the credential is still valid at `now`.
131    pub fn is_live(&self, now: DateTime<Utc>) -> bool {
132        self.expires_at.is_none_or(|at| at > now)
133    }
134}
135
136/// Says who the running agents are, and proves it.
137///
138/// The runner reads the source at the start of every run, so a source backed by a
139/// rotating workload identity (SPIFFE Workload API, a cloud metadata server) is read
140/// fresh each time. The root agent acts as [`principal_for`](Self::principal_for) its
141/// name, falling back to [`current`](Self::current); every other agent in the tree acts
142/// as `principal_for` its name, falling back to
143/// [`AgentPrincipal::derived`](crate::AgentPrincipal::derived). A principal's
144/// [`AgentId`] must stay the same across redeploys; the deployment belongs in
145/// [`AgentPrincipal::instance`].
146///
147/// # Example
148///
149/// ```rust
150/// use adk_core::{AgentId, AgentPrincipal, IdentitySource, StaticIdentitySource};
151///
152/// # futures::executor::block_on(async {
153/// let source = StaticIdentitySource::new(
154///     AgentPrincipal::new(AgentId::new("urn:adk:agent:billing")?).with_tenant("acme"),
155/// );
156/// assert_eq!(source.current().await?.id.as_str(), "urn:adk:agent:billing");
157/// assert!(source.credential().await.is_err());
158/// # Ok::<(), adk_core::AdkError>(())
159/// # }).unwrap();
160/// ```
161#[async_trait]
162pub trait IdentitySource: fmt::Debug + Send + Sync {
163    /// The principal the workload runs as; the root agent's unless
164    /// [`principal_for`](Self::principal_for) maps it.
165    async fn current(&self) -> Result<AgentPrincipal>;
166
167    /// The principal of the agent named `agent_name`, when the source maps it.
168    ///
169    /// The default maps no agent, so only the root agent acts as
170    /// [`current`](Self::current).
171    async fn principal_for(&self, agent_name: &str) -> Result<Option<AgentPrincipal>> {
172        let _ = agent_name;
173        Ok(None)
174    }
175
176    /// A credential proving the principal's identity.
177    ///
178    /// # Errors
179    ///
180    /// The default returns `identity.credential.unavailable`.
181    async fn credential(&self) -> Result<AgentCredential> {
182        Err(AdkError::new(
183            ErrorComponent::Auth,
184            ErrorCategory::Unsupported,
185            "identity.credential.unavailable",
186            "this identity source issues no credential; configure one that does, such as \
187             StaticIdentitySource::with_credential or a SPIFFE Workload API source",
188        ))
189    }
190}
191
192/// An [`IdentitySource`] with a fixed principal, optional fixed principals for named
193/// agents, and, optionally, a fixed credential.
194///
195/// # Example
196///
197/// ```rust
198/// use adk_core::{AgentId, AgentPrincipal, IdentitySource, StaticIdentitySource};
199///
200/// # futures::executor::block_on(async {
201/// let source = StaticIdentitySource::new(AgentPrincipal::new(AgentId::new("spiffe://acme/ops")?))
202///     .with_agent("auditor", AgentPrincipal::new(AgentId::new("spiffe://acme/auditor")?));
203/// assert_eq!(
204///     source.principal_for("auditor").await?.unwrap().id.as_str(),
205///     "spiffe://acme/auditor"
206/// );
207/// assert!(source.principal_for("writer").await?.is_none());
208/// # Ok::<(), adk_core::AdkError>(())
209/// # }).unwrap();
210/// ```
211#[derive(Debug, Clone)]
212pub struct StaticIdentitySource {
213    principal: AgentPrincipal,
214    agents: std::collections::BTreeMap<String, AgentPrincipal>,
215    credential: Option<AgentCredential>,
216}
217
218impl StaticIdentitySource {
219    /// A source whose root agent acts as `principal`.
220    pub fn new(principal: AgentPrincipal) -> Self {
221        Self { principal, agents: std::collections::BTreeMap::new(), credential: None }
222    }
223
224    /// Maps the agent named `agent_name` to `principal`.
225    #[must_use]
226    pub fn with_agent(mut self, agent_name: impl Into<String>, principal: AgentPrincipal) -> Self {
227        self.agents.insert(agent_name.into(), principal);
228        self
229    }
230
231    /// Sets the credential the source hands out.
232    #[must_use]
233    pub fn with_credential(mut self, credential: AgentCredential) -> Self {
234        self.credential = Some(credential);
235        self
236    }
237}
238
239#[async_trait]
240impl IdentitySource for StaticIdentitySource {
241    async fn current(&self) -> Result<AgentPrincipal> {
242        Ok(self.principal.clone())
243    }
244
245    async fn principal_for(&self, agent_name: &str) -> Result<Option<AgentPrincipal>> {
246        Ok(self.agents.get(agent_name).cloned())
247    }
248
249    async fn credential(&self) -> Result<AgentCredential> {
250        let Some(credential) = &self.credential else {
251            return Err(AdkError::new(
252                ErrorComponent::Auth,
253                ErrorCategory::Unsupported,
254                "identity.credential.unavailable",
255                "StaticIdentitySource has no credential; set one with with_credential",
256            ));
257        };
258        if credential.subject != self.principal.id {
259            return Err(AdkError::new(
260                ErrorComponent::Auth,
261                ErrorCategory::Internal,
262                "identity.credential.subject_mismatch",
263                format!(
264                    "the configured credential identifies '{}' but the principal is '{}'; \
265                     issue the credential for the principal's agent id",
266                    credential.subject, self.principal.id
267                ),
268            ));
269        }
270        if !credential.is_live(Utc::now()) {
271            return Err(AdkError::new(
272                ErrorComponent::Auth,
273                ErrorCategory::Unauthorized,
274                "identity.credential.expired",
275                "the configured credential has expired; rotate it",
276            ));
277        }
278        Ok(credential.clone())
279    }
280}
281
282/// Validates `resource` as an RFC 8707 resource indicator: an absolute `http` or
283/// `https` URI without a fragment or user information.
284///
285/// # Errors
286///
287/// Returns `credential.resource.invalid` otherwise.
288///
289/// # Example
290///
291/// ```rust
292/// use adk_core::resource_indicator;
293///
294/// assert!(resource_indicator("https://api.example.com/mcp").is_ok());
295/// assert!(resource_indicator("https://api.example.com/mcp#x").is_err());
296/// assert!(resource_indicator("https://user@api.example.com/").is_err());
297/// ```
298pub fn resource_indicator(resource: &str) -> Result<Url> {
299    let invalid = |why: &str| {
300        AdkError::new(
301            ErrorComponent::Auth,
302            ErrorCategory::InvalidInput,
303            "credential.resource.invalid",
304            format!(
305                "'{resource}' is not a resource indicator: {why}; pass an absolute https URL \
306                 such as 'https://api.example.com/mcp' (RFC 8707)"
307            ),
308        )
309    };
310    let url = Url::parse(resource).map_err(|error| invalid(&error.to_string()))?;
311    if !matches!(url.scheme(), "https" | "http") {
312        return Err(invalid("the scheme must be http or https"));
313    }
314    if url.fragment().is_some() {
315        return Err(invalid("it must not carry a fragment"));
316    }
317    if !url.username().is_empty() || url.password().is_some() {
318        return Err(invalid("it must not carry user information"));
319    }
320    if url.host_str().is_none() {
321        return Err(invalid("it must name a host"));
322    }
323    Ok(url)
324}
325
326/// A secret minted for one agent, one resource (its audience), and a set of scopes.
327///
328/// A token is presented only to its audience: [`authorize_for`](Self::authorize_for)
329/// returns the secret for a request URL under the audience and refuses every other.
330///
331/// # Example
332///
333/// ```rust
334/// use adk_core::{AgentId, ScopedToken, resource_indicator};
335///
336/// let token = ScopedToken::new(
337///     AgentId::new("urn:adk:agent:billing")?,
338///     "tok",
339///     resource_indicator("https://a.example.com/mcp")?,
340///     vec!["tools.read".into()],
341/// );
342/// assert!(token.authorize_for(&resource_indicator("https://a.example.com/mcp/tools")?).is_ok());
343/// let refused = token.authorize_for(&resource_indicator("https://b.example.com/mcp")?);
344/// assert_eq!(refused.unwrap_err().code, "credential.audience_mismatch");
345/// # Ok::<(), adk_core::AdkError>(())
346/// ```
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct ScopedToken {
349    /// The agent the token was minted for.
350    pub agent: AgentId,
351    /// The token value.
352    pub secret: CredentialSecret,
353    /// The resource the token may be presented to (RFC 8707).
354    pub audience: Url,
355    /// The scopes granted.
356    pub scopes: Vec<String>,
357    /// When the token stops being valid, if it expires.
358    pub expires_at: Option<DateTime<Utc>>,
359}
360
361impl ScopedToken {
362    /// A token for `agent` at `audience` with `scopes` and no expiry.
363    pub fn new(
364        agent: AgentId,
365        secret: impl Into<String>,
366        audience: Url,
367        scopes: Vec<String>,
368    ) -> Self {
369        Self { agent, secret: CredentialSecret::new(secret), audience, scopes, expires_at: None }
370    }
371
372    /// Sets the expiry.
373    #[must_use]
374    pub fn expires_at(mut self, at: DateTime<Utc>) -> Self {
375        self.expires_at = Some(at);
376        self
377    }
378
379    /// Whether the token is still valid at `now`.
380    pub fn is_live(&self, now: DateTime<Utc>) -> bool {
381        self.expires_at.is_none_or(|at| at > now)
382    }
383
384    /// Whether `request` falls under the token's audience: same scheme, host, and port,
385    /// and a path equal to the audience path or below it at a segment boundary.
386    pub fn covers(&self, request: &Url) -> bool {
387        let audience = &self.audience;
388        if request.scheme() != audience.scheme()
389            || request.host_str().map(str::to_ascii_lowercase)
390                != audience.host_str().map(str::to_ascii_lowercase)
391            || request.port_or_known_default() != audience.port_or_known_default()
392            || !request.username().is_empty()
393            || request.password().is_some()
394        {
395            return false;
396        }
397        let base = audience.path().trim_end_matches('/');
398        let path = request.path();
399        base.is_empty()
400            || path == base
401            || path.strip_prefix(base).is_some_and(|rest| rest.starts_with('/'))
402    }
403
404    /// The secret, for a request to `request`.
405    ///
406    /// # Errors
407    ///
408    /// Returns `credential.audience_mismatch` when `request` is outside the token's
409    /// audience, and `credential.expired` when the token has expired.
410    pub fn authorize_for(&self, request: &Url) -> Result<&CredentialSecret> {
411        if !self.covers(request) {
412            tracing::warn!(
413                agent.id = %self.agent,
414                token.audience = %self.audience,
415                request.url = %request,
416                "token refused for a resource outside its audience"
417            );
418            return Err(AdkError::new(
419                ErrorComponent::Auth,
420                ErrorCategory::Forbidden,
421                "credential.audience_mismatch",
422                format!(
423                    "a token minted for '{}' must not be sent to '{request}'; request a token \
424                     for that resource from the credential broker",
425                    self.audience
426                ),
427            ));
428        }
429        if !self.is_live(Utc::now()) {
430            return Err(AdkError::new(
431                ErrorComponent::Auth,
432                ErrorCategory::Unauthorized,
433                "credential.expired",
434                format!("the token for '{}' has expired; request a new one", self.audience),
435            ));
436        }
437        Ok(&self.secret)
438    }
439}
440
441/// Which brokered tokens [`CredentialBroker::revoke`] withdraws.
442#[derive(Debug, Clone, PartialEq, Eq)]
443#[non_exhaustive]
444pub enum RevocationScope {
445    /// Every token the broker issued.
446    All,
447    /// Every token issued to one agent.
448    Agent(AgentId),
449    /// Every token issued for one resource.
450    Resource(Url),
451    /// Tokens issued to one agent for one resource.
452    AgentResource {
453        /// The agent.
454        agent: AgentId,
455        /// The resource.
456        resource: Url,
457    },
458}
459
460impl RevocationScope {
461    /// Whether a token for `agent` at `resource` falls in this scope.
462    ///
463    /// # Example
464    ///
465    /// ```rust
466    /// use adk_core::{AgentId, RevocationScope, resource_indicator};
467    ///
468    /// let agent = AgentId::new("urn:adk:agent:a")?;
469    /// let resource = resource_indicator("https://api.example.com/")?;
470    /// assert!(RevocationScope::Agent(agent.clone()).covers(&agent, &resource));
471    /// assert!(!RevocationScope::Agent(AgentId::new("urn:adk:agent:b")?).covers(&agent, &resource));
472    /// # Ok::<(), adk_core::AdkError>(())
473    /// ```
474    pub fn covers(&self, agent: &AgentId, resource: &Url) -> bool {
475        match self {
476            Self::All => true,
477            Self::Agent(scope) => scope == agent,
478            Self::Resource(scope) => scope == resource,
479            Self::AgentResource { agent: scope_agent, resource: scope_resource } => {
480                scope_agent == agent && scope_resource == resource
481            }
482        }
483    }
484}
485
486/// Mints resource-scoped tokens for acting agents.
487///
488/// A broker issues a token for exactly the resource it was asked for (RFC 8707
489/// `resource`, carried as the token's audience) and never returns a token minted for a
490/// different resource. Callers present it with [`ScopedToken::authorize_for`], which
491/// refuses any request outside the audience.
492///
493/// # Example
494///
495/// ```rust
496/// use adk_core::{
497///     ActingContext, CredentialBroker, Result, RevocationScope, ScopedToken, async_trait,
498/// };
499/// use url::Url;
500///
501/// /// Issues a fixed development token.
502/// #[derive(Debug)]
503/// struct DevBroker;
504///
505/// #[async_trait]
506/// impl CredentialBroker for DevBroker {
507///     async fn token_for(
508///         &self,
509///         acting: &ActingContext,
510///         resource: &Url,
511///         scopes: &[String],
512///     ) -> Result<ScopedToken> {
513///         Ok(ScopedToken::new(acting.agent.id.clone(), "dev", resource.clone(), scopes.to_vec()))
514///     }
515///
516///     async fn revoke(&self, _scope: &RevocationScope) -> Result<u64> {
517///         Ok(0)
518///     }
519/// }
520/// ```
521#[async_trait]
522pub trait CredentialBroker: fmt::Debug + Send + Sync {
523    /// A token for `acting`'s agent to present at `resource` with `scopes`.
524    ///
525    /// # Errors
526    ///
527    /// Returns an error when the broker holds no credential for the agent and resource,
528    /// when the requested scopes exceed what it may grant, or when the issuer fails.
529    async fn token_for(
530        &self,
531        acting: &ActingContext,
532        resource: &Url,
533        scopes: &[String],
534    ) -> Result<ScopedToken>;
535
536    /// Withdraws the tokens in `scope`, returning how many were withdrawn.
537    async fn revoke(&self, scope: &RevocationScope) -> Result<u64>;
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543
544    fn token(audience: &str) -> ScopedToken {
545        ScopedToken::new(
546            AgentId::new("urn:adk:agent:t").unwrap(),
547            "secret",
548            resource_indicator(audience).unwrap(),
549            vec![],
550        )
551    }
552
553    #[test]
554    fn audience_matching_is_strict() {
555        let mcp = token("https://a.example.com/mcp");
556        let url = |s: &str| Url::parse(s).unwrap();
557        assert!(mcp.covers(&url("https://a.example.com/mcp")));
558        assert!(mcp.covers(&url("https://A.example.com:443/mcp/tools?x=1")));
559        assert!(!mcp.covers(&url("https://a.example.com/mcpx")));
560        assert!(!mcp.covers(&url("https://a.example.com/other")));
561        assert!(!mcp.covers(&url("http://a.example.com/mcp")));
562        assert!(!mcp.covers(&url("https://a.example.com:8443/mcp")));
563        assert!(!mcp.covers(&url("https://b.example.com/mcp")));
564        assert!(!mcp.covers(&url("https://a.example.com.evil.test/mcp")));
565        assert!(!mcp.covers(&url("https://x@a.example.com/mcp")));
566
567        let root = token("https://a.example.com/");
568        assert!(root.covers(&url("https://a.example.com/anything")));
569        assert!(!root.covers(&url("https://b.example.com/anything")));
570    }
571
572    #[test]
573    fn expired_tokens_are_refused() {
574        let expired =
575            token("https://a.example.com/").expires_at(Utc::now() - chrono::Duration::seconds(1));
576        let error =
577            expired.authorize_for(&Url::parse("https://a.example.com/").unwrap()).unwrap_err();
578        assert_eq!(error.code, "credential.expired");
579    }
580
581    #[test]
582    fn secrets_never_print() {
583        let credential = AgentCredential::new(
584            AgentId::new("urn:adk:agent:t").unwrap(),
585            CredentialKind::Opaque,
586            "hunter2",
587        );
588        assert!(!format!("{credential:?}").contains("hunter2"));
589        assert!(!format!("{:?}", token("https://a.example.com/")).contains("secret\""));
590    }
591
592    #[tokio::test]
593    async fn static_source_refuses_a_credential_for_another_agent() {
594        let principal = AgentPrincipal::new(AgentId::new("urn:adk:agent:a").unwrap());
595        let other = AgentCredential::new(
596            AgentId::new("urn:adk:agent:b").unwrap(),
597            CredentialKind::JwtSvid,
598            "jwt",
599        );
600        let source = StaticIdentitySource::new(principal).with_credential(other);
601        assert_eq!(
602            source.credential().await.unwrap_err().code,
603            "identity.credential.subject_mismatch"
604        );
605    }
606}