use std::sync::{Arc, Mutex};
use jiff::{SignedDuration, Timestamp};
use jsonwebtoken::{Algorithm, EncodingKey, Header};
use serde::Serialize;
const LIFETIME: SignedDuration = SignedDuration::from_hours(1);
const RENEWAL_MARGIN: SignedDuration = SignedDuration::from_mins(5);
#[derive(Clone)]
pub struct Signer(Arc<Inner>);
struct Inner {
application_id: String,
key: EncodingKey,
cached: Mutex<Option<(String, Timestamp)>>,
}
#[derive(Debug, thiserror::Error)]
pub enum SignError {
#[error("the private key is not a PEM-encoded RSA key: {0}")]
Key(#[source] jsonwebtoken::errors::Error),
#[error("signing the token failed: {0}")]
Signing(#[source] jsonwebtoken::errors::Error),
}
#[derive(Serialize)]
struct Claims<'a> {
iss: &'a str,
aud: &'a str,
iat: i64,
exp: i64,
}
impl Signer {
pub fn new(
application_id: impl Into<String>,
private_key_pem: &[u8],
) -> Result<Self, SignError> {
Ok(Self(Arc::new(Inner {
application_id: application_id.into(),
key: EncodingKey::from_rsa_pem(private_key_pem).map_err(SignError::Key)?,
cached: Mutex::new(None),
})))
}
pub fn token(&self) -> Result<String, SignError> {
self.token_at(Timestamp::now())
}
fn token_at(&self, now: Timestamp) -> Result<String, SignError> {
if let Some(token) = self.cached_until(now + RENEWAL_MARGIN) {
return Ok(token);
}
let expires = now + LIFETIME;
let mut header = Header::new(Algorithm::RS256);
header.kid = Some(self.0.application_id.clone());
let claims = Claims {
iss: "enablebanking.com",
aud: "api.enablebanking.com",
iat: now.as_second(),
exp: expires.as_second(),
};
let token =
jsonwebtoken::encode(&header, &claims, &self.0.key).map_err(SignError::Signing)?;
*self.cache() = Some((token.clone(), expires));
Ok(token)
}
fn cached_until(&self, instant: Timestamp) -> Option<String> {
self.cache()
.as_ref()
.filter(|(_, expires)| instant < *expires)
.map(|(token, _)| token.clone())
}
fn cache(&self) -> std::sync::MutexGuard<'_, Option<(String, Timestamp)>> {
self.0
.cached
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
impl std::fmt::Debug for Signer {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Signer")
.field("application_id", &self.0.application_id)
.finish_non_exhaustive()
}
}
#[cfg(test)]
#[expect(clippy::unwrap_used, reason = "a test panics on any unexpected value")]
mod tests {
use jiff::{SignedDuration, Timestamp};
use super::{LIFETIME, RENEWAL_MARGIN, Signer};
const KEY: &[u8] = include_bytes!("../tests/fixtures/test-key.pem");
#[test]
fn a_token_is_reused_until_its_renewal_margin_then_replaced() {
let signer = Signer::new("app", KEY).unwrap();
let start = Timestamp::from_second(1_800_000_000).unwrap();
let first = signer.token_at(start).unwrap();
let last_reuse = start + LIFETIME - RENEWAL_MARGIN - SignedDuration::from_secs(1);
assert_eq!(signer.token_at(last_reuse).unwrap(), first);
let renewal = start + LIFETIME - RENEWAL_MARGIN;
assert_ne!(signer.token_at(renewal).unwrap(), first);
}
}