Skip to main content

useceleris_server/
signer.rs

1use 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/// Configures a [`Signer`].
17///
18/// The options hold the signing secret, so `Debug` shows them as redacted.
19#[derive(Clone)]
20pub struct SignerOptions {
21    /// Your application's client id. It must not be empty and must not
22    /// contain a colon, CR or LF.
23    pub client_id: String,
24
25    /// Your application's signing secret. It must not be empty. Keep it on
26    /// trusted servers only.
27    pub signing_secret: String,
28
29    /// Gives the time at which credentials are signed. `None` uses
30    /// [`SystemTime::now`].
31    pub clock: Option<Arc<dyn Fn() -> SystemTime + Send + Sync>>,
32} // end struct SignerOptions
33
34impl fmt::Debug for SignerOptions {
35    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
36        formatter.write_str("SignerOptions { redacted }")
37    } // end method fmt
38} // end impl Debug for SignerOptions
39
40/// Signs credentials on a trusted server.
41///
42/// The signer keeps the signing secret only inside its HMAC state, and `Debug`
43/// shows the signer as redacted. It is cheap to clone and safe to share
44/// between threads.
45#[derive(Clone)]
46pub struct Signer {
47    client_id: String,
48    keyed_hash: Hmac<Sha512>,
49    clock: Arc<dyn Fn() -> SystemTime + Send + Sync>,
50} // end struct Signer
51
52impl Signer {
53    /// Validates the options and makes a signer. It fails with
54    /// [`CelerisError::Configuration`], which names each field and rule that
55    /// failed, but never a value.
56    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    } // end fn new
74
75    /// Signs credentials for `claims`, with the current time as the
76    /// timestamp. Sign again for every connection attempt. Never cache,
77    /// reuse or backdate credentials (D-001).
78    ///
79    /// It fails with [`CelerisError::Configuration`] for invalid claims, and
80    /// names each field and rule that failed. It also fails when the clock
81    /// gives a time outside 1 to 253402300799999 milliseconds after the Unix
82    /// epoch.
83    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(&timestamp) {
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        // The digest covers the encoded payload text, as the server checks it.
101        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    } // end method sign
109} // end impl Signer
110
111impl fmt::Debug for Signer {
112    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
113        formatter.write_str("Signer { redacted }")
114    } // end method fmt
115} // end impl Debug for Signer
116
117/// Writes bytes as lowercase hexadecimal.
118pub(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} // end fn hexadecimal