useceleris_server/
signer.rs1use std::fmt;
2use std::sync::Arc;
3use std::time::{SystemTime, UNIX_EPOCH};
4
5use base64::Engine;
6use base64::engine::general_purpose::STANDARD;
7use hmac::{Hmac, KeyInit, Mac};
8use sha2::Sha512;
9use useceleris_client::{CelerisError, Credentials};
10
11use crate::claims::Claims;
12use crate::constants::MAXIMUM_TIMESTAMP;
13use crate::token_payload::token_payload;
14use crate::validation::{validate_claims, validate_signer_options};
15
16#[derive(Clone)]
20pub struct SignerOptions {
21 pub client_id: String,
24
25 pub signing_secret: String,
28
29 pub clock: Option<Arc<dyn Fn() -> SystemTime + Send + Sync>>,
32} impl fmt::Debug for SignerOptions {
35 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
36 formatter.write_str("SignerOptions { redacted }")
37 } } #[derive(Clone)]
46pub struct Signer {
47 client_id: String,
48 keyed_hash: Hmac<Sha512>,
49 clock: Arc<dyn Fn() -> SystemTime + Send + Sync>,
50} impl Signer {
53 pub fn new(options: SignerOptions) -> Result<Signer, CelerisError> {
57 validate_signer_options(&options.client_id, &options.signing_secret)?;
58
59 let keyed_hash = Hmac::<Sha512>::new_from_slice(options.signing_secret.as_bytes())
60 .map_err(|_| {
61 CelerisError::Configuration(
62 "Invalid signer options. signing_secret: Must be a usable HMAC key.".to_owned(),
63 )
64 })?;
65
66 let clock = options.clock.unwrap_or_else(|| Arc::new(SystemTime::now));
67
68 Ok(Signer {
69 client_id: options.client_id,
70 keyed_hash,
71 clock,
72 })
73 } pub fn sign(&self, claims: &Claims) -> Result<Credentials, CelerisError> {
84 validate_claims(claims)?;
85
86 let timestamp = (self.clock)()
87 .duration_since(UNIX_EPOCH)
88 .map(|elapsed| elapsed.as_millis())
89 .unwrap_or(0);
90
91 if !(1..=MAXIMUM_TIMESTAMP).contains(×tamp) {
92 return Err(CelerisError::Configuration(
93 "Invalid timestamp from clock. Must be between 1 and 253402300799999 milliseconds."
94 .to_owned(),
95 ));
96 }
97
98 let payload = STANDARD.encode(token_payload(timestamp, claims));
99
100 let mut keyed_hash = self.keyed_hash.clone();
102 keyed_hash.update(payload.as_bytes());
103
104 let digest = hexadecimal(&keyed_hash.finalize().into_bytes());
105 let signature = STANDARD.encode(format!("{}:{digest}", self.client_id));
106
107 Ok(Credentials { payload, signature })
108 } } impl fmt::Debug for Signer {
112 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
113 formatter.write_str("Signer { redacted }")
114 } } pub(crate) fn hexadecimal(bytes: &[u8]) -> String {
119 const DIGITS: &[u8; 16] = b"0123456789abcdef";
120
121 let mut text = String::with_capacity(bytes.len() * 2);
122
123 for byte in bytes {
124 text.push(DIGITS[usize::from(byte >> 4)] as char);
125 text.push(DIGITS[usize::from(byte & 0x0f)] as char);
126 }
127
128 text
129}