use std::sync::Arc;
use adk_core::{
ActingContext, AgentPrincipal, CredentialBroker, CredentialSecret, RevocationScope,
ScopedToken, Url, async_trait,
};
use chrono::{DateTime, Utc};
use super::exchange::{REQUEST_TIMEOUT, TokenCache, oauth_token};
use super::{AgentTokenSource, CloudProvider, FederationError};
const ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntraAccessToken {
pub secret: CredentialSecret,
pub expires_at: DateTime<Utc>,
pub scope: String,
}
#[derive(Debug)]
pub struct EntraAgentIdentity {
authority: String,
tenant_id: String,
blueprint_app_id: String,
agent_identity_id: String,
tokens: Arc<dyn AgentTokenSource>,
client: reqwest::Client,
cache: TokenCache,
}
impl EntraAgentIdentity {
pub const ASSERTION_AUDIENCE: &'static str = "api://AzureADTokenExchange";
pub fn new(
tenant_id: impl Into<String>,
blueprint_app_id: impl Into<String>,
agent_identity_id: impl Into<String>,
tokens: Arc<dyn AgentTokenSource>,
) -> Self {
Self {
authority: "https://login.microsoftonline.com".to_string(),
tenant_id: tenant_id.into(),
blueprint_app_id: blueprint_app_id.into(),
agent_identity_id: agent_identity_id.into(),
tokens,
client: crate::http::client(REQUEST_TIMEOUT),
cache: TokenCache::default(),
}
}
#[must_use]
pub fn with_authority(mut self, authority: impl Into<String>) -> Self {
self.authority = authority.into().trim_end_matches('/').to_string();
self
}
#[must_use]
pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
self.client = client;
self
}
pub async fn access_token(
&self,
agent: &AgentPrincipal,
resource: &str,
) -> Result<EntraAccessToken, FederationError> {
const PROVIDER: CloudProvider = CloudProvider::Entra;
let endpoint = format!("{}/{}/oauth2/v2.0/token", self.authority, self.tenant_id);
let assertion = self.tokens.agent_token(agent, Self::ASSERTION_AUDIENCE).await?;
let blueprint = [
("client_id", self.blueprint_app_id.as_str()),
("scope", "api://AzureADTokenExchange/.default"),
("grant_type", "client_credentials"),
("fmi_path", self.agent_identity_id.as_str()),
("client_assertion_type", ASSERTION_TYPE),
("client_assertion", assertion.secret.expose()),
];
let (blueprint_token, _) =
oauth_token(PROVIDER, &self.client, &endpoint, &blueprint).await?;
let scope = format!("{resource}/.default");
let identity = [
("client_id", self.agent_identity_id.as_str()),
("scope", scope.as_str()),
("grant_type", "client_credentials"),
("client_assertion_type", ASSERTION_TYPE),
("client_assertion", blueprint_token.expose()),
];
let (secret, expires_at) =
oauth_token(PROVIDER, &self.client, &endpoint, &identity).await?;
tracing::debug!(
agent.id = %agent.id,
entra.agent_identity = %self.agent_identity_id,
token.scope = %scope,
"entra agent identity token issued"
);
Ok(EntraAccessToken { secret, expires_at, scope })
}
}
#[async_trait]
impl CredentialBroker for EntraAgentIdentity {
async fn token_for(
&self,
acting: &ActingContext,
resource: &Url,
scopes: &[String],
) -> adk_core::Result<ScopedToken> {
if !scopes.is_empty() {
return Err(FederationError::UnsupportedRequest {
provider: CloudProvider::Entra,
resource: resource.to_string(),
reason: "an agent identity's application token covers the resource's `.default` \
scope only; request the token with no scopes"
.into(),
}
.into());
}
let key = (acting.agent.id.clone(), resource.clone(), Vec::new());
if let Some(cached) = self.cache.live(&key).await {
return Ok(cached);
}
let issued =
self.access_token(&acting.agent, resource.as_str().trim_end_matches('/')).await?;
let token = ScopedToken::new(
acting.agent.id.clone(),
issued.secret.expose(),
resource.clone(),
vec![issued.scope],
)
.expires_at(issued.expires_at);
self.cache.store(key, token.clone()).await;
Ok(token)
}
async fn revoke(&self, scope: &RevocationScope) -> adk_core::Result<u64> {
Ok(self.cache.revoke(scope).await)
}
}