use std::future::Future;
use std::sync::Arc;
use tonic::Code;
use tonic::service::interceptor::InterceptedService;
use tonic::transport::Channel;
use uuid::Uuid;
use crate::grpc::client::{RefreshFn, status_to_axiam_error};
use crate::grpc::r#gen::token_service_client::TokenServiceClient;
use crate::grpc::r#gen::{
CnfClaim as WireCnfClaim, IntrospectTokenRequest,
IntrospectTokenResponse as WireIntrospectTokenResponse, RptPermission as WireRptPermission,
ValidateTokenRequest, ValidateTokenResponse as WireValidateTokenResponse,
};
use crate::grpc::interceptor::AuthInterceptor;
use crate::token::{CnfClaim, PresentedProofs, TokenManager};
use crate::{AxiamError, Sensitive};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TokenStatus {
Inactive,
Bearer,
SenderConstrained,
Unverifiable,
}
fn status_of(valid: bool, cnf: Option<&CnfClaim>) -> TokenStatus {
match (valid, cnf) {
(false, _) => TokenStatus::Inactive,
(true, None) => TokenStatus::Bearer,
(true, Some(c)) if c.names_nothing_checkable() => TokenStatus::Unverifiable,
(true, Some(_)) => TokenStatus::SenderConstrained,
}
}
fn verify_possession_of(
valid: bool,
cnf: Option<&CnfClaim>,
proofs: PresentedProofs<'_>,
) -> Result<(), AxiamError> {
if !valid {
return Err(AxiamError::auth(
"the token is not valid (expired, revoked, badly signed, or of another tenant)",
));
}
match cnf {
None => Ok(()),
Some(cnf) => cnf.verify(proofs),
}
}
fn cnf_from_wire(wire: Option<WireCnfClaim>) -> Option<CnfClaim> {
wire.map(|c| CnfClaim {
x5t_s256: non_empty(c.x5t_s256),
jkt: non_empty(c.jkt),
})
}
fn non_empty(value: String) -> Option<String> {
if value.is_empty() { None } else { Some(value) }
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TokenValidation {
pub valid: bool,
pub subject_id: String,
pub tenant_id: String,
pub org_id: String,
pub exp: i64,
pub cnf: Option<CnfClaim>,
pub token_type: String,
}
impl TokenValidation {
#[must_use]
pub fn status(&self) -> TokenStatus {
status_of(self.valid, self.cnf.as_ref())
}
pub fn verify_possession(&self, proofs: PresentedProofs<'_>) -> Result<(), AxiamError> {
verify_possession_of(self.valid, self.cnf.as_ref(), proofs)
}
}
impl From<WireValidateTokenResponse> for TokenValidation {
fn from(wire: WireValidateTokenResponse) -> Self {
Self {
valid: wire.valid,
subject_id: wire.subject_id,
tenant_id: wire.tenant_id,
org_id: wire.org_id,
exp: wire.exp,
cnf: cnf_from_wire(wire.cnf),
token_type: wire.token_type,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RptPermission {
pub resource_id: String,
pub resource_scopes: Vec<String>,
pub exp: i64,
}
impl From<WireRptPermission> for RptPermission {
fn from(wire: WireRptPermission) -> Self {
Self {
resource_id: wire.resource_id,
resource_scopes: wire.resource_scopes,
exp: wire.exp,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TokenIntrospection {
pub active: bool,
pub sub: String,
pub tenant_id: String,
pub org_id: String,
pub iss: String,
pub iat: i64,
pub exp: i64,
pub jti: String,
pub scope: Option<String>,
pub client_id: Option<String>,
pub token_type: String,
pub cnf: Option<CnfClaim>,
pub permissions: Vec<RptPermission>,
pub ext_exchange_iss: Option<String>,
}
impl TokenIntrospection {
#[must_use]
pub fn status(&self) -> TokenStatus {
status_of(self.active, self.cnf.as_ref())
}
pub fn verify_possession(&self, proofs: PresentedProofs<'_>) -> Result<(), AxiamError> {
verify_possession_of(self.active, self.cnf.as_ref(), proofs)
}
}
impl From<WireIntrospectTokenResponse> for TokenIntrospection {
fn from(wire: WireIntrospectTokenResponse) -> Self {
Self {
active: wire.active,
sub: wire.sub,
tenant_id: wire.tenant_id,
org_id: wire.org_id,
iss: wire.iss,
iat: wire.iat,
exp: wire.exp,
jti: wire.jti,
scope: non_empty(wire.scope),
client_id: non_empty(wire.client_id),
token_type: wire.token_type,
cnf: cnf_from_wire(wire.cnf),
permissions: wire.permissions.into_iter().map(Into::into).collect(),
ext_exchange_iss: non_empty(wire.ext_exchange_iss),
}
}
}
type InnerClient = TokenServiceClient<InterceptedService<Channel, AuthInterceptor>>;
#[derive(Clone)]
pub struct TokenGrpcClient {
inner: InnerClient,
token_manager: Arc<TokenManager>,
tenant_id: Uuid,
refresh_fn: RefreshFn,
}
impl std::fmt::Debug for TokenGrpcClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TokenGrpcClient")
.field("tenant_id", &self.tenant_id)
.finish_non_exhaustive()
}
}
impl TokenGrpcClient {
pub fn new(
channel: Channel,
token_manager: Arc<TokenManager>,
tenant_id: Uuid,
refresh_fn: RefreshFn,
) -> Self {
let interceptor = AuthInterceptor::new(Arc::clone(&token_manager), tenant_id);
Self {
inner: TokenServiceClient::with_interceptor(channel, interceptor),
token_manager,
tenant_id,
refresh_fn,
}
}
pub fn tenant_id(&self) -> Uuid {
self.tenant_id
}
pub async fn validate_token(
&self,
token: &Sensitive<String>,
) -> Result<TokenValidation, AxiamError> {
self.require_caller_token("validate_token")?;
let request = || ValidateTokenRequest {
access_token: token.expose().clone(),
};
self.call(|| {
let mut client = self.inner.clone();
let request = request();
async move { client.validate_token(request).await }
})
.await
.map(Into::into)
}
pub async fn introspect_token(
&self,
token: &Sensitive<String>,
) -> Result<TokenIntrospection, AxiamError> {
self.require_caller_token("introspect_token")?;
let request = || IntrospectTokenRequest {
access_token: token.expose().clone(),
};
self.call(|| {
let mut client = self.inner.clone();
let request = request();
async move { client.introspect_token(request).await }
})
.await
.map(Into::into)
}
fn require_caller_token(&self, operation: &str) -> Result<(), AxiamError> {
if self.token_manager.cached_access_token().is_none() {
return Err(AxiamError::auth(format!(
"{operation}: no caller token — call login() first (the token being inspected is \
a separate argument and never authenticates the call)"
)));
}
Ok(())
}
async fn call<T, F, Fut>(&self, attempt: F) -> Result<T, AxiamError>
where
F: Fn() -> Fut,
Fut: Future<Output = Result<tonic::Response<T>, tonic::Status>>,
{
match attempt().await {
Ok(response) => Ok(response.into_inner()),
Err(status) if status.code() == Code::Unauthenticated => {
if !self.token_manager.has_refresh_token().await {
return Err(status_to_axiam_error(status));
}
let observed = self
.token_manager
.cached_access_token()
.map(|t| t.expose().clone())
.unwrap_or_default();
let refresh_fn = Arc::clone(&self.refresh_fn);
self.token_manager
.refresh_if_needed(&observed, move |refresh_token| refresh_fn(refresh_token))
.await?;
attempt()
.await
.map(tonic::Response::into_inner)
.map_err(status_to_axiam_error)
}
Err(status) => Err(status_to_axiam_error(status)),
}
}
}