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 GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
const TOKEN_TYPE_ACCESS: &str = "urn:ietf:params:oauth:token-type:access_token";
const TOKEN_TYPE_JWT: &str = "urn:ietf:params:oauth:token-type:jwt";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GoogleAccessToken {
pub secret: CredentialSecret,
pub expires_at: DateTime<Utc>,
pub scopes: Vec<String>,
}
#[derive(Debug)]
pub struct GoogleWorkloadIdentity {
audience: String,
endpoint: String,
tokens: Arc<dyn AgentTokenSource>,
client: reqwest::Client,
cache: TokenCache,
}
impl GoogleWorkloadIdentity {
pub const DEFAULT_SCOPE: &'static str = "https://www.googleapis.com/auth/cloud-platform";
pub fn new(
project_number: impl AsRef<str>,
pool_id: impl AsRef<str>,
provider_id: impl AsRef<str>,
tokens: Arc<dyn AgentTokenSource>,
) -> Self {
Self {
audience: format!(
"//iam.googleapis.com/projects/{}/locations/global/workloadIdentityPools/{}/providers/{}",
project_number.as_ref(),
pool_id.as_ref(),
provider_id.as_ref()
),
endpoint: "https://sts.googleapis.com/v1/token".to_string(),
tokens,
client: crate::http::client(REQUEST_TIMEOUT),
cache: TokenCache::default(),
}
}
#[must_use]
pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = endpoint.into();
self
}
#[must_use]
pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
self.client = client;
self
}
pub fn audience(&self) -> &str {
&self.audience
}
pub fn token_audience(&self) -> String {
format!("https:{}", self.audience)
}
pub async fn access_token(
&self,
agent: &AgentPrincipal,
) -> Result<GoogleAccessToken, FederationError> {
self.exchange(agent, &[Self::DEFAULT_SCOPE.to_string()]).await
}
async fn exchange(
&self,
agent: &AgentPrincipal,
scopes: &[String],
) -> Result<GoogleAccessToken, FederationError> {
let token = self.tokens.agent_token(agent, &self.token_audience()).await?;
let scope = scopes.join(" ");
let form = [
("grant_type", GRANT_TYPE),
("audience", self.audience.as_str()),
("scope", scope.as_str()),
("requested_token_type", TOKEN_TYPE_ACCESS),
("subject_token_type", TOKEN_TYPE_JWT),
("subject_token", token.secret.expose()),
];
let (secret, expires_at) =
oauth_token(CloudProvider::Google, &self.client, &self.endpoint, &form).await?;
tracing::debug!(agent.id = %agent.id, "google federated access token issued");
Ok(GoogleAccessToken { secret, expires_at, scopes: scopes.to_vec() })
}
}
#[async_trait]
impl CredentialBroker for GoogleWorkloadIdentity {
async fn token_for(
&self,
acting: &ActingContext,
resource: &Url,
scopes: &[String],
) -> adk_core::Result<ScopedToken> {
let google_api = resource.scheme() == "https"
&& resource
.host_str()
.is_some_and(|host| host == "googleapis.com" || host.ends_with(".googleapis.com"));
if !google_api {
return Err(FederationError::UnsupportedRequest {
provider: CloudProvider::Google,
resource: resource.to_string(),
reason: "a Google access token is sent only to an https URL on googleapis.com; \
use another broker for this resource"
.into(),
}
.into());
}
let mut scopes = scopes.to_vec();
if scopes.is_empty() {
scopes.push(Self::DEFAULT_SCOPE.to_string());
}
scopes.sort();
scopes.dedup();
let key = (acting.agent.id.clone(), resource.clone(), scopes);
if let Some(cached) = self.cache.live(&key).await {
return Ok(cached);
}
let issued = self.exchange(&acting.agent, &key.2).await?;
let token = ScopedToken::new(
acting.agent.id.clone(),
issued.secret.expose(),
resource.clone(),
issued.scopes,
)
.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)
}
}