Skip to main content

rustango_cms/
signing.rs

1//! Minimal HMAC-SHA256 used across the CMS for short signed tokens
2//! (view-restriction grants, signed rendition URLs).
3//!
4//! The framework's CSRF module has an `hmac_sha256` but it's
5//! `pub(crate)`; rather than pull the `hmac` + `sha2` crates twice, we
6//! implement HMAC over the `sha2` crate the workspace already depends
7//! on. One shared impl so the two call sites can't drift.
8
9use sha2::{Digest, Sha256};
10
11/// Process-wide CMS secret used to sign short-lived tokens: preview
12/// tokens, view-restriction grants, password-reset links and the admin's
13/// flash cookie (the last two through [`derived_key`]).
14static SECRET: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();
15
16/// Where the CMS keeps the key it generates when `RCMS_SECRET_KEY` is not
17/// set, relative to the working directory. Several replicas need either
18/// the env var or this file on shared storage, so they sign alike.
19pub const GENERATED_KEY_PATH: &str = "./var/.rustango_cms_signing.key";
20
21/// Set the CMS signing secret. Call once at startup, before anything is
22/// served; the key must be stable across restarts. Sourced from the
23/// `RCMS_SECRET_KEY` env var, then [`GENERATED_KEY_PATH`], when this
24/// isn't called.
25///
26/// The first read fixes the secret for the life of the process, so a call
27/// after it — or a second call with another key — cannot take effect, and
28/// is logged as an error rather than dropped.
29pub fn set_secret(key: impl Into<Vec<u8>>) {
30    let key = key.into();
31    if let Err(rejected) = SECRET.set(key) {
32        if SECRET.get() != Some(&rejected) {
33            tracing::error!(
34                target: "rustango_cms::signing",
35                "set_secret called after the secret was already fixed (set earlier, or read \
36                 from RCMS_SECRET_KEY); this call has no effect — set it before serving"
37            );
38        }
39    }
40}
41
42/// The CMS signing secret: [`set_secret`]'s key, else `RCMS_SECRET_KEY`,
43/// else a 32-byte key generated once and kept at [`GENERATED_KEY_PATH`],
44/// so every signed feature works without configuration.
45#[must_use]
46pub fn secret() -> &'static [u8] {
47    SECRET.get_or_init(|| {
48        crate::config::var("SECRET_KEY")
49            .map(String::into_bytes)
50            .unwrap_or_else(|| load_or_generate(std::path::Path::new(GENERATED_KEY_PATH)))
51    })
52}
53
54/// A key for one purpose, derived from [`secret`], so a value signed for
55/// one feature never verifies in another.
56#[must_use]
57pub fn derived_key(purpose: &str) -> Vec<u8> {
58    hmac_sha256(secret(), purpose.as_bytes()).to_vec()
59}
60
61/// Read the key at `path`, or generate 32 bytes from the OS CSPRNG and
62/// persist them atomically, so signatures survive restarts. If the file
63/// can't be written the key lives for this process only.
64fn load_or_generate(path: &std::path::Path) -> Vec<u8> {
65    if let Ok(bytes) = std::fs::read(path) {
66        if bytes.len() >= 32 {
67            return bytes;
68        }
69    }
70    let mut buf = [0u8; 32];
71    getrandom::fill(&mut buf).expect("OS CSPRNG unavailable");
72    let buf = buf.to_vec();
73    if let Some(parent) = path.parent() {
74        let _ = std::fs::create_dir_all(parent);
75    }
76    let tmp = path.with_extension("tmp");
77    if std::fs::write(&tmp, &buf).is_ok() && std::fs::rename(&tmp, path).is_ok() {
78        tracing::info!(
79            target: "rustango_cms::signing",
80            path = %path.display(),
81            "generated the CMS signing key (set RCMS_SECRET_KEY to choose your own)"
82        );
83    } else {
84        tracing::warn!(
85            target: "rustango_cms::signing",
86            path = %path.display(),
87            "could not persist the generated CMS signing key; signed links \
88             (previews, password resets) stop working at the next restart, and \
89             signed image URLs in cached pages fall back to the unsigned image limit"
90        );
91    }
92    buf
93}
94
95/// HMAC-SHA256(`key`, `msg`) as lowercase hex (64 chars). Callers that
96/// want a shorter token truncate the result (a prefix of a hex HMAC is
97/// itself a valid MAC at reduced bit-strength).
98#[must_use]
99pub fn hmac_sha256_hex(key: &[u8], msg: &[u8]) -> String {
100    let bytes = hmac_sha256(key, msg);
101    let mut out = String::with_capacity(bytes.len() * 2);
102    for b in bytes {
103        out.push_str(&format!("{b:02x}"));
104    }
105    out
106}
107
108/// Constant-time comparison of two byte slices — use when checking a
109/// supplied MAC against the expected one so timing doesn't leak how
110/// many leading bytes matched.
111#[must_use]
112pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
113    if a.len() != b.len() {
114        return false;
115    }
116    let mut diff = 0u8;
117    for (x, y) in a.iter().zip(b.iter()) {
118        diff |= x ^ y;
119    }
120    diff == 0
121}
122
123fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
124    const BLOCK_SIZE: usize = 64;
125    let mut key_block = [0u8; BLOCK_SIZE];
126    if key.len() > BLOCK_SIZE {
127        let hash = Sha256::digest(key);
128        key_block[..32].copy_from_slice(&hash);
129    } else {
130        key_block[..key.len()].copy_from_slice(key);
131    }
132    let mut ipad = [0u8; BLOCK_SIZE];
133    let mut opad = [0u8; BLOCK_SIZE];
134    for i in 0..BLOCK_SIZE {
135        ipad[i] = key_block[i] ^ 0x36;
136        opad[i] = key_block[i] ^ 0x5c;
137    }
138    let mut inner = Sha256::new();
139    inner.update(ipad);
140    inner.update(data);
141    let inner_digest = inner.finalize();
142    let mut outer = Sha256::new();
143    outer.update(opad);
144    outer.update(inner_digest);
145    outer.finalize().into()
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn hmac_matches_known_vector() {
154        // RFC 4231 test case 1: key = 0x0b*20, data = "Hi There".
155        let key = [0x0b_u8; 20];
156        let out = hmac_sha256_hex(&key, b"Hi There");
157        assert_eq!(
158            out,
159            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
160        );
161    }
162
163    #[test]
164    fn different_key_or_msg_changes_mac() {
165        assert_ne!(hmac_sha256_hex(b"k1", b"m"), hmac_sha256_hex(b"k2", b"m"));
166        assert_ne!(hmac_sha256_hex(b"k", b"m1"), hmac_sha256_hex(b"k", b"m2"));
167    }
168
169    #[test]
170    fn constant_time_eq_behaves_like_eq() {
171        assert!(constant_time_eq(b"abc", b"abc"));
172        assert!(!constant_time_eq(b"abc", b"abd"));
173        assert!(!constant_time_eq(b"abc", b"ab"));
174    }
175
176    /// With no `RCMS_SECRET_KEY`, the generated key is kept on disk, so a
177    /// restart — or a second replica reading the same file — signs alike.
178    #[test]
179    fn a_generated_key_is_persisted_and_read_back() {
180        let dir = std::env::temp_dir().join(format!("rcms-signing-{}", std::process::id()));
181        let path = dir.join("var").join("key");
182        let first = load_or_generate(&path);
183        assert_eq!(first.len(), 32);
184        assert_eq!(load_or_generate(&path), first, "a second read returns the stored key");
185        let _ = std::fs::remove_dir_all(&dir);
186    }
187
188    #[test]
189    fn derived_keys_differ_per_purpose() {
190        set_secret(b"test-secret".to_vec());
191        assert_ne!(derived_key("rcms:flash"), derived_key("rcms:password-reset"));
192        assert_ne!(derived_key("rcms:flash"), secret().to_vec());
193    }
194}