use std::fmt;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
ActingContext, AdkError, AgentId, AgentPrincipal, ErrorCategory, ErrorComponent, Result,
};
#[derive(Clone, PartialEq, Eq)]
pub struct CredentialSecret(String);
impl CredentialSecret {
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
pub fn expose(&self) -> &str {
&self.0
}
}
impl fmt::Debug for CredentialSecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("CredentialSecret([redacted])")
}
}
impl fmt::Display for CredentialSecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum CredentialKind {
JwtSvid,
X509,
Opaque,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentCredential {
pub subject: AgentId,
pub kind: CredentialKind,
pub secret: CredentialSecret,
pub expires_at: Option<DateTime<Utc>>,
pub audience: Vec<String>,
}
impl AgentCredential {
pub fn new(subject: AgentId, kind: CredentialKind, secret: impl Into<String>) -> Self {
Self {
subject,
kind,
secret: CredentialSecret::new(secret),
expires_at: None,
audience: Vec::new(),
}
}
#[must_use]
pub fn expires_at(mut self, at: DateTime<Utc>) -> Self {
self.expires_at = Some(at);
self
}
#[must_use]
pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
self.audience.push(audience.into());
self
}
pub fn is_live(&self, now: DateTime<Utc>) -> bool {
self.expires_at.is_none_or(|at| at > now)
}
}
#[async_trait]
pub trait IdentitySource: fmt::Debug + Send + Sync {
async fn current(&self) -> Result<AgentPrincipal>;
async fn principal_for(&self, agent_name: &str) -> Result<Option<AgentPrincipal>> {
let _ = agent_name;
Ok(None)
}
async fn credential(&self) -> Result<AgentCredential> {
Err(AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Unsupported,
"identity.credential.unavailable",
"this identity source issues no credential; configure one that does, such as \
StaticIdentitySource::with_credential or a SPIFFE Workload API source",
))
}
}
#[derive(Debug, Clone)]
pub struct StaticIdentitySource {
principal: AgentPrincipal,
agents: std::collections::BTreeMap<String, AgentPrincipal>,
credential: Option<AgentCredential>,
}
impl StaticIdentitySource {
pub fn new(principal: AgentPrincipal) -> Self {
Self { principal, agents: std::collections::BTreeMap::new(), credential: None }
}
#[must_use]
pub fn with_agent(mut self, agent_name: impl Into<String>, principal: AgentPrincipal) -> Self {
self.agents.insert(agent_name.into(), principal);
self
}
#[must_use]
pub fn with_credential(mut self, credential: AgentCredential) -> Self {
self.credential = Some(credential);
self
}
}
#[async_trait]
impl IdentitySource for StaticIdentitySource {
async fn current(&self) -> Result<AgentPrincipal> {
Ok(self.principal.clone())
}
async fn principal_for(&self, agent_name: &str) -> Result<Option<AgentPrincipal>> {
Ok(self.agents.get(agent_name).cloned())
}
async fn credential(&self) -> Result<AgentCredential> {
let Some(credential) = &self.credential else {
return Err(AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Unsupported,
"identity.credential.unavailable",
"StaticIdentitySource has no credential; set one with with_credential",
));
};
if credential.subject != self.principal.id {
return Err(AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Internal,
"identity.credential.subject_mismatch",
format!(
"the configured credential identifies '{}' but the principal is '{}'; \
issue the credential for the principal's agent id",
credential.subject, self.principal.id
),
));
}
if !credential.is_live(Utc::now()) {
return Err(AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Unauthorized,
"identity.credential.expired",
"the configured credential has expired; rotate it",
));
}
Ok(credential.clone())
}
}
pub fn resource_indicator(resource: &str) -> Result<Url> {
let invalid = |why: &str| {
AdkError::new(
ErrorComponent::Auth,
ErrorCategory::InvalidInput,
"credential.resource.invalid",
format!(
"'{resource}' is not a resource indicator: {why}; pass an absolute https URL \
such as 'https://api.example.com/mcp' (RFC 8707)"
),
)
};
let url = Url::parse(resource).map_err(|error| invalid(&error.to_string()))?;
if !matches!(url.scheme(), "https" | "http") {
return Err(invalid("the scheme must be http or https"));
}
if url.fragment().is_some() {
return Err(invalid("it must not carry a fragment"));
}
if !url.username().is_empty() || url.password().is_some() {
return Err(invalid("it must not carry user information"));
}
if url.host_str().is_none() {
return Err(invalid("it must name a host"));
}
Ok(url)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopedToken {
pub agent: AgentId,
pub secret: CredentialSecret,
pub audience: Url,
pub scopes: Vec<String>,
pub expires_at: Option<DateTime<Utc>>,
}
impl ScopedToken {
pub fn new(
agent: AgentId,
secret: impl Into<String>,
audience: Url,
scopes: Vec<String>,
) -> Self {
Self { agent, secret: CredentialSecret::new(secret), audience, scopes, expires_at: None }
}
#[must_use]
pub fn expires_at(mut self, at: DateTime<Utc>) -> Self {
self.expires_at = Some(at);
self
}
pub fn is_live(&self, now: DateTime<Utc>) -> bool {
self.expires_at.is_none_or(|at| at > now)
}
pub fn covers(&self, request: &Url) -> bool {
let audience = &self.audience;
if request.scheme() != audience.scheme()
|| request.host_str().map(str::to_ascii_lowercase)
!= audience.host_str().map(str::to_ascii_lowercase)
|| request.port_or_known_default() != audience.port_or_known_default()
|| !request.username().is_empty()
|| request.password().is_some()
{
return false;
}
let base = audience.path().trim_end_matches('/');
let path = request.path();
base.is_empty()
|| path == base
|| path.strip_prefix(base).is_some_and(|rest| rest.starts_with('/'))
}
pub fn authorize_for(&self, request: &Url) -> Result<&CredentialSecret> {
if !self.covers(request) {
tracing::warn!(
agent.id = %self.agent,
token.audience = %self.audience,
request.url = %request,
"token refused for a resource outside its audience"
);
return Err(AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Forbidden,
"credential.audience_mismatch",
format!(
"a token minted for '{}' must not be sent to '{request}'; request a token \
for that resource from the credential broker",
self.audience
),
));
}
if !self.is_live(Utc::now()) {
return Err(AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Unauthorized,
"credential.expired",
format!("the token for '{}' has expired; request a new one", self.audience),
));
}
Ok(&self.secret)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RevocationScope {
All,
Agent(AgentId),
Resource(Url),
AgentResource {
agent: AgentId,
resource: Url,
},
}
impl RevocationScope {
pub fn covers(&self, agent: &AgentId, resource: &Url) -> bool {
match self {
Self::All => true,
Self::Agent(scope) => scope == agent,
Self::Resource(scope) => scope == resource,
Self::AgentResource { agent: scope_agent, resource: scope_resource } => {
scope_agent == agent && scope_resource == resource
}
}
}
}
#[async_trait]
pub trait CredentialBroker: fmt::Debug + Send + Sync {
async fn token_for(
&self,
acting: &ActingContext,
resource: &Url,
scopes: &[String],
) -> Result<ScopedToken>;
async fn revoke(&self, scope: &RevocationScope) -> Result<u64>;
}
#[cfg(test)]
mod tests {
use super::*;
fn token(audience: &str) -> ScopedToken {
ScopedToken::new(
AgentId::new("urn:adk:agent:t").unwrap(),
"secret",
resource_indicator(audience).unwrap(),
vec![],
)
}
#[test]
fn audience_matching_is_strict() {
let mcp = token("https://a.example.com/mcp");
let url = |s: &str| Url::parse(s).unwrap();
assert!(mcp.covers(&url("https://a.example.com/mcp")));
assert!(mcp.covers(&url("https://A.example.com:443/mcp/tools?x=1")));
assert!(!mcp.covers(&url("https://a.example.com/mcpx")));
assert!(!mcp.covers(&url("https://a.example.com/other")));
assert!(!mcp.covers(&url("http://a.example.com/mcp")));
assert!(!mcp.covers(&url("https://a.example.com:8443/mcp")));
assert!(!mcp.covers(&url("https://b.example.com/mcp")));
assert!(!mcp.covers(&url("https://a.example.com.evil.test/mcp")));
assert!(!mcp.covers(&url("https://x@a.example.com/mcp")));
let root = token("https://a.example.com/");
assert!(root.covers(&url("https://a.example.com/anything")));
assert!(!root.covers(&url("https://b.example.com/anything")));
}
#[test]
fn expired_tokens_are_refused() {
let expired =
token("https://a.example.com/").expires_at(Utc::now() - chrono::Duration::seconds(1));
let error =
expired.authorize_for(&Url::parse("https://a.example.com/").unwrap()).unwrap_err();
assert_eq!(error.code, "credential.expired");
}
#[test]
fn secrets_never_print() {
let credential = AgentCredential::new(
AgentId::new("urn:adk:agent:t").unwrap(),
CredentialKind::Opaque,
"hunter2",
);
assert!(!format!("{credential:?}").contains("hunter2"));
assert!(!format!("{:?}", token("https://a.example.com/")).contains("secret\""));
}
#[tokio::test]
async fn static_source_refuses_a_credential_for_another_agent() {
let principal = AgentPrincipal::new(AgentId::new("urn:adk:agent:a").unwrap());
let other = AgentCredential::new(
AgentId::new("urn:adk:agent:b").unwrap(),
CredentialKind::JwtSvid,
"jwt",
);
let source = StaticIdentitySource::new(principal).with_credential(other);
assert_eq!(
source.credential().await.unwrap_err().code,
"identity.credential.subject_mismatch"
);
}
}