1use sha2::{Digest, Sha256};
10
11static SECRET: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();
15
16pub const GENERATED_KEY_PATH: &str = "./var/.rustango_cms_signing.key";
20
21pub 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#[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#[must_use]
57pub fn derived_key(purpose: &str) -> Vec<u8> {
58 hmac_sha256(secret(), purpose.as_bytes()).to_vec()
59}
60
61fn 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#[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#[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 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 #[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}