use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, SystemTime};
use serde::Serialize;
use super::{Expiry, Key, Registered, TokenError, sign};
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct ApiClaims {
pub audience: String,
pub scope: Vec<String>,
pub issuer: String,
pub subject: String,
pub expires_at: Option<SystemTime>,
pub issued_at: Option<SystemTime>,
pub id: String,
}
impl ApiClaims {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn audience(mut self, audience: impl Into<String>) -> Self {
self.audience = audience.into();
self
}
#[must_use]
pub fn scope(mut self, scope: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.scope = scope.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
self.issuer = issuer.into();
self
}
#[must_use]
pub fn subject(mut self, subject: impl Into<String>) -> Self {
self.subject = subject.into();
self
}
#[must_use]
pub fn expires_at(mut self, t: SystemTime) -> Self {
self.expires_at = Some(t);
self
}
#[must_use]
pub fn issued_at(mut self, t: SystemTime) -> Self {
self.issued_at = Some(t);
self
}
#[must_use]
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = id.into();
self
}
}
#[derive(Serialize)]
struct ApiWire<'a> {
#[serde(flatten)]
registered: Registered<'a>,
#[serde(skip_serializing_if = "String::is_empty")]
scope: String,
}
pub fn api(key: &Key, c: &ApiClaims) -> Result<String, TokenError> {
if !key.is_asymmetric() {
return Err(TokenError::new(
"an API token needs an RSA, ECDSA or Ed25519 key: Centrifugo PRO verifies it with the public keys of its JWKS endpoint",
));
}
if key.key_id().is_none() {
return Err(TokenError::new(
"an API token needs a key ID, by which Centrifugo PRO finds the key in its JWKS: set one with with_key_id",
));
}
if c.audience.is_empty() && c.scope.is_empty() {
return Err(TokenError::new(
"set an audience or a scope, required by http_api.jwks, so that client tokens signed with the same keys cannot call the server API",
));
}
let Some(expires_at) = c.expires_at else {
return Err(TokenError::new(
"set expires_at: Centrifugo PRO accepts an API token without one for as long as its key is published",
));
};
if c.scope
.iter()
.any(|s| s.is_empty() || s.contains(char::is_whitespace))
{
return Err(TokenError::new("a scope is empty or has a space"));
}
sign(
key,
&ApiWire {
registered: Registered::new(
&c.subject,
Expiry::At(expires_at),
c.issued_at,
&c.id,
&c.audience,
&c.issuer,
)?,
scope: c.scope.join(" "),
},
)
}
type CurrentKey = dyn Fn() -> Result<Key, TokenError> + Send + Sync;
pub struct ApiTokens {
key: Key,
current_key: Option<Arc<CurrentKey>>,
claims: ApiClaims,
ttl: Duration,
cache: Mutex<Option<(String, SystemTime)>>,
}
impl fmt::Debug for ApiTokens {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ApiTokens")
.field("key", &self.key)
.field("claims", &self.claims)
.field("ttl", &self.ttl)
.finish_non_exhaustive()
}
}
impl ApiTokens {
#[must_use]
pub fn new(key: Key, claims: ApiClaims) -> Self {
Self {
key,
current_key: None,
claims,
ttl: Duration::from_secs(300),
cache: Mutex::new(None),
}
}
#[must_use]
pub fn ttl(mut self, ttl: Duration) -> Self {
self.ttl = ttl;
self
}
#[must_use]
pub fn current_key(
mut self,
f: impl Fn() -> Result<Key, TokenError> + Send + Sync + 'static,
) -> Self {
self.current_key = Some(Arc::new(f));
self
}
pub fn token(&self) -> Result<String, TokenError> {
let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
let now = SystemTime::now();
if let Some((token, refresh_at)) = &*cache {
if now < *refresh_at {
return Ok(token.clone());
}
}
if self.claims.expires_at.is_some() || self.claims.issued_at.is_some() {
return Err(TokenError::new(
"ApiTokens sets expires_at and issued_at itself: leave them unset in its claims, and set its ttl",
));
}
if self.ttl.is_zero() {
return Err(TokenError::new("ApiTokens with a zero ttl"));
}
let key = match &self.current_key {
Some(f) => f()?,
None => self.key.clone(),
};
let mut claims = self.claims.clone();
let Some(expires_at) = now.checked_add(self.ttl) else {
return Err(TokenError::new("ApiTokens with a ttl too far ahead"));
};
claims.issued_at = Some(now);
claims.expires_at = Some(expires_at);
let token = api(&key, &claims)?;
*cache = Some((token.clone(), now + self.ttl / 2)); Ok(token)
}
}
#[cfg(feature = "client")]
impl crate::TokenSource for ApiTokens {
fn token(&self) -> crate::BoxFuture<'_, Result<String, crate::BoxError>> {
let token = ApiTokens::token(self).map_err(Into::into);
Box::pin(async move { token })
}
}