use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use adk_core::{
AgentCredential, AgentId, AgentPrincipal, CredentialKind, CredentialSecret, Url, async_trait,
};
use aws_lc_rs::encoding::AsDer;
use aws_lc_rs::rand::SystemRandom;
use aws_lc_rs::rsa::{KeyPair, KeySize};
use aws_lc_rs::signature::{KeyPair as _, RSA_PKCS1_SHA256};
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;
use zeroize::Zeroizing;
use super::FederationError;
pub const TOKEN_ALGORITHM: &str = "RS256";
const NOT_BEFORE_LEEWAY: i64 = 5;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RsaPublicJwk {
pub kty: String,
#[serde(rename = "use")]
pub key_use: String,
pub alg: String,
pub kid: String,
pub n: String,
pub e: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JwkSet {
pub keys: Vec<RsaPublicJwk>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiscoveryDocument {
pub issuer: String,
pub jwks_uri: String,
pub response_types_supported: Vec<String>,
pub subject_types_supported: Vec<String>,
pub id_token_signing_alg_values_supported: Vec<String>,
pub claims_supported: Vec<String>,
}
#[async_trait]
pub trait AgentTokenSigner: fmt::Debug + Send + Sync {
fn kid(&self) -> &str;
fn public_jwk(&self) -> RsaPublicJwk;
async fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, FederationError>;
}
pub struct RsaTokenSigner {
kid: String,
key_pair: KeyPair,
public_jwk: RsaPublicJwk,
}
impl fmt::Debug for RsaTokenSigner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RsaTokenSigner").field("kid", &self.kid).finish_non_exhaustive()
}
}
impl RsaTokenSigner {
pub fn from_pkcs8_der(kid: impl Into<String>, der: &[u8]) -> Result<Self, FederationError> {
let kid = kid.into();
if kid.is_empty() {
return Err(FederationError::InvalidKey { reason: "the key id is empty".into() });
}
let key_pair = KeyPair::from_pkcs8(der)
.map_err(|error| FederationError::InvalidKey { reason: error.to_string() })?;
let public = key_pair.public_key();
let public_jwk = RsaPublicJwk {
kty: "RSA".into(),
key_use: "sig".into(),
alg: TOKEN_ALGORITHM.into(),
kid: kid.clone(),
n: URL_SAFE_NO_PAD.encode(public.modulus().big_endian_without_leading_zero()),
e: URL_SAFE_NO_PAD.encode(public.exponent().big_endian_without_leading_zero()),
};
Ok(Self { kid, key_pair, public_jwk })
}
pub fn from_pkcs8_pem(kid: impl Into<String>, pem: &str) -> Result<Self, FederationError> {
const BEGIN: &str = "-----BEGIN PRIVATE KEY-----";
const END: &str = "-----END PRIVATE KEY-----";
let invalid = |reason: &str| FederationError::InvalidKey { reason: reason.to_string() };
let body = pem
.find(BEGIN)
.map(|start| &pem[start + BEGIN.len()..])
.and_then(|rest| rest.find(END).map(|end| &rest[..end]))
.ok_or_else(|| {
if pem.contains("BEGIN RSA PRIVATE KEY") {
invalid("the PEM holds a PKCS#1 key, not PKCS#8")
} else if pem.contains("BEGIN ENCRYPTED PRIVATE KEY") {
invalid("the PEM holds an encrypted key")
} else {
invalid("the PEM has no `PRIVATE KEY` block")
}
})?;
let encoded: Zeroizing<String> =
Zeroizing::new(body.chars().filter(|c| !c.is_ascii_whitespace()).collect());
let der = Zeroizing::new(
STANDARD
.decode(encoded.as_bytes())
.map_err(|_| invalid("the PEM body is not valid base64"))?,
);
Self::from_pkcs8_der(kid, &der)
}
pub fn generate(kid: impl Into<String>) -> Result<Self, FederationError> {
let invalid = |_| FederationError::InvalidKey { reason: "key generation failed".into() };
let der =
KeyPair::generate(KeySize::Rsa2048).map_err(invalid)?.as_der().map_err(invalid)?;
Self::from_pkcs8_der(kid, der.as_ref())
}
}
#[async_trait]
impl AgentTokenSigner for RsaTokenSigner {
fn kid(&self) -> &str {
&self.kid
}
fn public_jwk(&self) -> RsaPublicJwk {
self.public_jwk.clone()
}
async fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, FederationError> {
let mut signature = vec![0; self.key_pair.public_modulus_len()];
self.key_pair
.sign(&RSA_PKCS1_SHA256, &SystemRandom::new(), signing_input, &mut signature)
.map_err(|error| FederationError::Signing { reason: error.to_string() })?;
Ok(signature)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentToken {
pub subject: AgentId,
pub secret: CredentialSecret,
pub audience: String,
pub expires_at: DateTime<Utc>,
}
impl AgentToken {
pub fn new(
subject: AgentId,
secret: impl Into<String>,
audience: impl Into<String>,
expires_at: DateTime<Utc>,
) -> Self {
Self {
subject,
secret: CredentialSecret::new(secret),
audience: audience.into(),
expires_at,
}
}
}
impl From<AgentToken> for AgentCredential {
fn from(token: AgentToken) -> Self {
AgentCredential::new(token.subject, CredentialKind::JwtSvid, token.secret.expose())
.expires_at(token.expires_at)
.with_audience(token.audience)
}
}
#[async_trait]
pub trait AgentTokenSource: fmt::Debug + Send + Sync {
async fn agent_token(
&self,
agent: &AgentPrincipal,
audience: &str,
) -> Result<AgentToken, FederationError>;
}
#[derive(Debug, Clone)]
pub struct AgentTokenIssuer {
issuer: String,
signer: Arc<dyn AgentTokenSigner>,
token_ttl: Duration,
}
impl AgentTokenIssuer {
pub const DISCOVERY_PATH: &'static str = "/.well-known/openid-configuration";
pub const JWKS_PATH: &'static str = "/jwks.json";
pub const DEFAULT_TOKEN_TTL: Duration = Duration::from_secs(600);
pub const MAX_TOKEN_TTL: Duration = Duration::from_secs(3600);
pub fn new(
issuer_url: impl Into<String>,
signer: Arc<dyn AgentTokenSigner>,
) -> Result<Self, FederationError> {
let issuer = issuer_url.into().trim_end_matches('/').to_string();
let invalid = |why: &str| FederationError::InvalidConfig {
reason: format!(
"issuer URL '{issuer}' {why}; use an https URL such as 'https://agents.example.com'"
),
};
let url =
Url::parse(&issuer).map_err(|error| invalid(&format!("is not a URL ({error})")))?;
let Some(host) = url.host_str() else {
return Err(invalid("names no host"));
};
let loopback = host == "localhost"
|| host
.trim_matches(['[', ']'])
.parse::<std::net::IpAddr>()
.is_ok_and(|address| address.is_loopback());
match url.scheme() {
"https" => {}
"http" if loopback => {}
_ => return Err(invalid("must use https, which every cloud requires of an issuer")),
}
if url.query().is_some() || url.fragment().is_some() {
return Err(invalid("must not carry a query or a fragment"));
}
if !url.username().is_empty() || url.password().is_some() {
return Err(invalid("must not carry user information"));
}
Ok(Self { issuer, signer, token_ttl: Self::DEFAULT_TOKEN_TTL })
}
pub fn from_rsa_pem(
issuer_url: impl Into<String>,
kid: impl Into<String>,
pem: &str,
) -> Result<Self, FederationError> {
Self::new(issuer_url, Arc::new(RsaTokenSigner::from_pkcs8_pem(kid, pem)?))
}
pub fn from_rsa_der(
issuer_url: impl Into<String>,
kid: impl Into<String>,
der: &[u8],
) -> Result<Self, FederationError> {
Self::new(issuer_url, Arc::new(RsaTokenSigner::from_pkcs8_der(kid, der)?))
}
#[must_use]
pub fn with_token_ttl(mut self, ttl: Duration) -> Self {
self.token_ttl = ttl.clamp(Duration::from_secs(1), Self::MAX_TOKEN_TTL);
self
}
pub fn issuer(&self) -> &str {
&self.issuer
}
pub fn token_ttl(&self) -> Duration {
self.token_ttl
}
pub fn discovery_document(&self) -> DiscoveryDocument {
let strings = |values: &[&str]| values.iter().map(ToString::to_string).collect();
DiscoveryDocument {
issuer: self.issuer.clone(),
jwks_uri: format!("{}{}", self.issuer, Self::JWKS_PATH),
response_types_supported: strings(&["id_token"]),
subject_types_supported: strings(&["public"]),
id_token_signing_alg_values_supported: strings(&[TOKEN_ALGORITHM]),
claims_supported: strings(&["iss", "sub", "aud", "exp", "iat", "jti"]),
}
}
pub fn jwks(&self) -> JwkSet {
JwkSet { keys: vec![self.signer.public_jwk()] }
}
pub async fn issue(
&self,
agent: &AgentPrincipal,
audience: &str,
) -> Result<AgentToken, FederationError> {
if audience.is_empty() {
return Err(FederationError::InvalidConfig {
reason: "the token audience is empty; name the party the token is presented to"
.into(),
});
}
let mut random = [0u8; 16];
aws_lc_rs::rand::fill(&mut random)
.map_err(|_| FederationError::Signing { reason: "no secure randomness".into() })?;
random[6] = (random[6] & 0x0f) | 0x40;
random[8] = (random[8] & 0x3f) | 0x80;
let hex = hex::encode(random);
let jti = format!(
"{}-{}-{}-{}-{}",
&hex[..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..]
);
let issued_at = Utc::now();
let expires_at = issued_at + self.token_ttl;
let claims = json!({
"iss": self.issuer,
"sub": agent.id.as_str(),
"aud": audience,
"iat": issued_at.timestamp(),
"nbf": issued_at.timestamp() - NOT_BEFORE_LEEWAY,
"exp": expires_at.timestamp(),
"jti": jti,
});
let jws = self.sign_claims(&claims).await?;
tracing::debug!(
agent.id = %agent.id,
token.audience = audience,
token.jti = %jti,
"agent token issued"
);
Ok(AgentToken::new(agent.id.clone(), jws, audience, expires_at))
}
pub(crate) async fn sign_claims(
&self,
claims: &serde_json::Value,
) -> Result<String, FederationError> {
let header = json!({ "alg": TOKEN_ALGORITHM, "typ": "JWT", "kid": self.signer.kid() });
let signing_input = format!(
"{}.{}",
URL_SAFE_NO_PAD.encode(header.to_string()),
URL_SAFE_NO_PAD.encode(claims.to_string())
);
let signature = self.signer.sign(signing_input.as_bytes()).await?;
Ok(format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(signature)))
}
}
#[async_trait]
impl AgentTokenSource for AgentTokenIssuer {
async fn agent_token(
&self,
agent: &AgentPrincipal,
audience: &str,
) -> Result<AgentToken, FederationError> {
self.issue(agent, audience).await
}
}