use std::future::Future;
use std::pin::Pin;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::Deserialize;
use crate::error::{EmbedError, ErrorKind};
use crate::limits;
use crate::rfc3339;
use crate::secret::Secret;
use crate::types::{TokenReason, UpdateAvailable};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
#[derive(Debug, Clone)]
pub struct IssuedToken {
pub token: Secret,
pub expires_at: Option<String>,
pub expires_in_secs: Option<u32>,
pub update_available: Option<UpdateAvailable>,
}
pub trait EmbedTokenSource: Send + Sync + 'static {
fn fetch(&self, reason: TokenReason) -> BoxFuture<'_, Result<IssuedToken, EmbedError>>;
}
#[derive(Deserialize)]
struct Handoff {
token: String,
expires_at: String,
#[serde(default, deserialize_with = "crate::types::update::lenient")]
update_available: Option<UpdateAvailable>,
}
impl IssuedToken {
pub fn from_handoff_json(body: &[u8]) -> Result<Self, EmbedError> {
let handoff: Handoff = serde_json::from_slice(body)
.map_err(|_| EmbedError::new(ErrorKind::TokenUnavailable, "the token endpoint's answer is not {token, expires_at}"))?;
Ok(Self { token: Secret::new(handoff.token), expires_at: Some(handoff.expires_at), expires_in_secs: None, update_available: handoff.update_available })
}
}
pub(crate) fn check_embed_token(token: &Secret) -> Result<(), EmbedError> {
if token.expose_secret().starts_with(limits::EMBED_TOKEN_PREFIX) {
return Ok(());
}
Err(EmbedError::invalid("only an embed token (lgr_et_…) may be used on a player's device; a client-credentials token belongs on the integrator's server"))
}
pub fn stale_after(lifetime: Duration) -> Duration {
lifetime - Duration::from_secs(limits::STALE_MARGIN_SECS).min(lifetime / 2)
}
pub(crate) struct Lifetime {
pub duration: Duration,
pub clamped: Option<String>,
}
fn clamp(secs: i64, said: &str) -> Lifetime {
if secs <= 0 || secs > limits::MAX_TRUSTED_LIFETIME_SECS as i64 {
let message = format!("a token lifetime of {said} is outside (0 s, 1 h] on this device; treating it as {} s", limits::CLAMPED_LIFETIME_SECS);
return Lifetime { duration: Duration::from_secs(limits::CLAMPED_LIFETIME_SECS), clamped: Some(message) };
}
Lifetime { duration: Duration::from_secs(secs.unsigned_abs()), clamped: None }
}
pub(crate) fn lifetime(issued: &IssuedToken, now: SystemTime) -> Result<Lifetime, EmbedError> {
if let Some(secs) = issued.expires_in_secs {
return Ok(clamp(i64::from(secs), &format!("{secs} s")));
}
let Some(at) = issued.expires_at.as_deref() else {
return Err(EmbedError::invalid("a token needs expires_at or expires_in_secs"));
};
let Some(at_secs) = rfc3339::to_unix(at) else {
return Err(EmbedError::invalid("expires_at is not an RFC 3339 timestamp"));
};
let now_secs = now.duration_since(UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
Ok(clamp(at_secs - now_secs, &format!("expires_at {at} − now {}", rfc3339::from_unix(now_secs))))
}