Skip to main content

capsule_runtime/
mac_token.rs

1//! One opaque token grammar, and the memory-only key that seals it.
2//!
3//! ```text
4//! <tag> "." base64url-nopad(payload JSON) "." base64url-nopad(HMAC-SHA256)
5//! ```
6//!
7//! Two authorities mint tokens in this shape: the peer file handles in [`crate::peer_handoff`],
8//! and the spawn credentials and approvals `mur-roost` issues. The parts that must not vary live
9//! here — the constant-time comparison, the unambiguous MAC input, and a key that never leaves the
10//! process it was generated in.
11//!
12//! **A token is bound to its family by two values a caller cannot influence**: the version tag,
13//! compared before the MAC, and the MAC domain, mixed into the MAC. Distinct pairs mean a token of
14//! one family can never verify as another, so an authority that mints several families cannot be
15//! made to accept one in another's place.
16//!
17//! **Verification order is fixed**: shape → MAC → payload. Nothing downstream of the MAC is
18//! evaluated before it passes, so a caller that fails it learns nothing about which field to
19//! change next. For the same reason [`MacTokenError`] carries two variants and not five.
20//!
21//! A value passed as `bound_to` is covered by the MAC without being carried in the token. That is
22//! what makes a token non-bearer: holding it is not enough, the holder must also assert the exact
23//! value it was sealed against.
24
25use base64::Engine as _;
26use hmac::{Hmac, Mac};
27use sha2::Sha256;
28use std::sync::atomic::Ordering;
29
30/// Nonce width in bytes, for a payload field that has to distinguish two otherwise identical
31/// tokens.
32pub const NONCE_BYTES: usize = 16;
33
34/// Width of a [`token_id`], in lowercase hex characters.
35const TOKEN_ID_HEX_CHARS: usize = 16;
36
37/// Separator between the MAC input's fields. ASCII unit separator: it cannot occur in base64url,
38/// so no pair of distinct inputs can produce the same MAC input by moving a boundary between them.
39const MAC_FIELD_SEPARATOR: u8 = 0x1f;
40
41/// The base64 alphabet used for both token segments: URL-safe and unpadded, so a whole token is
42/// safe in a header value or a request path and has no `=` for a transport to mangle.
43pub const B64: base64::engine::general_purpose::GeneralPurpose =
44    base64::engine::general_purpose::URL_SAFE_NO_PAD;
45
46type HmacSha256 = Hmac<Sha256>;
47
48/// The 32-byte HMAC key one authority mints and verifies with.
49///
50/// Never written to disk, never placed in an environment variable, and never copied out of this
51/// type: a key that reaches durable storage outlives the process whose lifetime is the only
52/// revocation mechanism there is. Dropping it makes every outstanding token unverifiable at once
53/// — revoke-all with no revocation list.
54pub struct MintKey([u8; 32]);
55
56impl MintKey {
57    /// 32 bytes from the operating system's CSPRNG.
58    pub fn generate() -> Result<Self, String> {
59        let mut bytes = [0u8; 32];
60        getrandom::fill(&mut bytes)
61            .map_err(|error| format!("failed to generate a mint key: {error}"))?;
62        Ok(Self(bytes))
63    }
64
65    /// Builds a fresh MAC context. Private: the key bytes never leave this module.
66    fn mac(&self) -> HmacSha256 {
67        HmacSha256::new_from_slice(&self.0).expect("HMAC-SHA256 accepts a key of any length")
68    }
69
70    /// Overwrites the key bytes with volatile writes.
71    ///
72    /// Volatile so the compiler cannot elide a write whose result is provably never read — which
73    /// is the whole of what the write is for.
74    #[allow(unsafe_code)]
75    fn zeroize(&mut self) {
76        for byte in self.0.iter_mut() {
77            // SAFETY: `byte` is a valid, aligned, exclusively-borrowed `u8` inside an array this
78            // value owns. `write_volatile` of a `u8` through such a reference is always defined.
79            unsafe { std::ptr::write_volatile(byte, 0) };
80        }
81        std::sync::atomic::compiler_fence(Ordering::SeqCst);
82    }
83}
84
85impl Drop for MintKey {
86    fn drop(&mut self) {
87        self.zeroize();
88    }
89}
90
91impl std::fmt::Debug for MintKey {
92    /// Prints no key material. A key that can reach a log line is a key on disk by another route.
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.write_str("MintKey(<redacted>)")
95    }
96}
97
98/// Why a token's shape or MAC was not accepted.
99///
100/// Two variants and not more: a caller that cannot tell a tampered payload from a token minted by
101/// a different key cannot use the endpoint as an oracle. Whatever an authority checks *after*
102/// [`open`] returns is its own to distinguish.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum MacTokenError {
105    /// Not `<tag>.<base64url>.<base64url>`, or a segment that is not base64url, or empty.
106    Malformed,
107    /// MAC verification failed, for any reason at all.
108    NotValid,
109}
110
111/// The stable identifier a mint and a redemption are correlated by: the first
112/// [`TOKEN_ID_HEX_CHARS`] lowercase hex characters of `sha256(token)`.
113///
114/// This — never the token — is what may appear in a trace, a log line or an error body.
115pub fn token_id(token: &str) -> String {
116    murmur_artifact::sha256_hex(token.as_bytes())[..TOKEN_ID_HEX_CHARS].to_string()
117}
118
119/// `bytes` random bytes as lowercase hex.
120pub fn random_hex(bytes: usize) -> Result<String, String> {
121    let mut buffer = vec![0u8; bytes];
122    getrandom::fill(&mut buffer).map_err(|error| format!("failed to generate a nonce: {error}"))?;
123    Ok(buffer
124        .iter()
125        .map(|byte| format!("{byte:02x}"))
126        .collect::<String>())
127}
128
129/// Mints one token over `payload_json`, for the family named by `tag` and `domain`.
130///
131/// Each value in `bound_to` is covered by the MAC and left out of the token, so redemption
132/// requires asserting it.
133pub fn seal(
134    key: &MintKey,
135    tag: &str,
136    domain: &[u8],
137    payload_json: &[u8],
138    bound_to: &[&str],
139) -> String {
140    let payload_b64 = B64.encode(payload_json);
141    let mut mac = key.mac();
142    mac.update(&mac_input(domain, &payload_b64, bound_to));
143    let signature = B64.encode(mac.finalize().into_bytes());
144    format!("{tag}.{payload_b64}.{signature}")
145}
146
147/// Verifies one token of the family named by `tag` and `domain` and returns its payload bytes.
148///
149/// The MAC comparison is `verify_slice`, which is constant-time; comparing decoded bytes with `==`
150/// would leak the signature one byte at a time.
151pub fn open(
152    key: &MintKey,
153    tag: &str,
154    domain: &[u8],
155    token: &str,
156    bound_to: &[&str],
157) -> Result<Vec<u8>, MacTokenError> {
158    let (payload_b64, payload, signature) = split_token(tag, token)?;
159    let mut mac = key.mac();
160    mac.update(&mac_input(domain, payload_b64, bound_to));
161    mac.verify_slice(&signature)
162        .map_err(|_| MacTokenError::NotValid)?;
163    Ok(payload)
164}
165
166/// The payload bytes of a token whose MAC has *not* been checked, for the family named by `tag`.
167///
168/// The value is caller-controlled and must never decide anything. Two uses are legitimate:
169/// rejecting a string that is not a token of this family before asking for anything else, and
170/// naming a local artefact after a token this process could not have minted.
171pub fn payload_segment(tag: &str, token: &str) -> Result<Vec<u8>, MacTokenError> {
172    split_token(tag, token).map(|(_, payload, _)| payload)
173}
174
175/// The bytes a token's MAC is taken over: `<domain> ‖ 0x1f ‖ <payload base64url>`, then `0x1f` and
176/// each bound value in turn.
177fn mac_input(domain: &[u8], payload_b64: &str, bound_to: &[&str]) -> Vec<u8> {
178    let mut input = Vec::with_capacity(domain.len() + payload_b64.len() + 1);
179    input.extend_from_slice(domain);
180    input.push(MAC_FIELD_SEPARATOR);
181    input.extend_from_slice(payload_b64.as_bytes());
182    for bound in bound_to {
183        input.push(MAC_FIELD_SEPARATOR);
184        input.extend_from_slice(bound.as_bytes());
185    }
186    input
187}
188
189/// The token's three segments, checked for shape alone. Nothing here looks at what the payload
190/// *says*. The payload segment is returned both as base64 text, which is what the MAC covers, and
191/// decoded.
192fn split_token<'a>(
193    expected_tag: &str,
194    token: &'a str,
195) -> Result<(&'a str, Vec<u8>, Vec<u8>), MacTokenError> {
196    let mut segments = token.split('.');
197    let tag = segments.next().ok_or(MacTokenError::Malformed)?;
198    let payload_b64 = segments.next().ok_or(MacTokenError::Malformed)?;
199    let signature_b64 = segments.next().ok_or(MacTokenError::Malformed)?;
200    if segments.next().is_some() || tag != expected_tag {
201        return Err(MacTokenError::Malformed);
202    }
203    let payload = B64
204        .decode(payload_b64)
205        .map_err(|_| MacTokenError::Malformed)?;
206    let signature = B64
207        .decode(signature_b64)
208        .map_err(|_| MacTokenError::Malformed)?;
209    if payload.is_empty() || signature.is_empty() {
210        return Err(MacTokenError::Malformed);
211    }
212    Ok((payload_b64, payload, signature))
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    const TAG: &str = "tst1";
220    const DOMAIN: &[u8] = b"murmur-mac-token-test";
221
222    /// `Drop` is `zeroize` and nothing else, so testing the helper tests the teardown guarantee
223    /// without reading memory the value has already released.
224    #[test]
225    fn zeroizing_clears_every_key_byte() {
226        let mut key = MintKey([0xAB; 32]);
227        assert_ne!(key.0, [0u8; 32]);
228        key.zeroize();
229        assert_eq!(key.0, [0u8; 32]);
230    }
231
232    /// A generated key is not the all-zero array a zeroized one becomes, and two are distinct —
233    /// enough to catch a `generate` that stopped reaching the OS CSPRNG.
234    #[test]
235    fn a_generated_key_is_random() {
236        let one = MintKey::generate().unwrap();
237        let two = MintKey::generate().unwrap();
238        assert_ne!(one.0, [0u8; 32]);
239        assert_ne!(one.0, two.0);
240    }
241
242    #[test]
243    fn a_key_prints_no_material() {
244        assert_eq!(format!("{:?}", MintKey([0xAB; 32])), "MintKey(<redacted>)");
245    }
246
247    #[test]
248    fn a_sealed_token_opens_with_the_key_that_sealed_it() {
249        let key = MintKey::generate().unwrap();
250        let token = seal(&key, TAG, DOMAIN, b"{\"a\":1}", &[]);
251        assert!(token.starts_with("tst1."));
252        assert_eq!(open(&key, TAG, DOMAIN, &token, &[]).unwrap(), b"{\"a\":1}");
253    }
254
255    #[test]
256    fn another_key_does_not_open_it() {
257        let token = seal(&MintKey::generate().unwrap(), TAG, DOMAIN, b"{}", &[]);
258        assert_eq!(
259            open(&MintKey::generate().unwrap(), TAG, DOMAIN, &token, &[]),
260            Err(MacTokenError::NotValid)
261        );
262    }
263
264    /// The tag is compared before the MAC and the domain is mixed into it, so neither a token of
265    /// another family nor the same payload under another domain verifies.
266    #[test]
267    fn a_token_of_another_family_does_not_open() {
268        let key = MintKey::generate().unwrap();
269        let token = seal(&key, TAG, DOMAIN, b"{}", &[]);
270        assert_eq!(
271            open(&key, "oth1", DOMAIN, &token, &[]),
272            Err(MacTokenError::Malformed)
273        );
274        assert_eq!(
275            open(&key, TAG, b"murmur-other-domain", &token, &[]),
276            Err(MacTokenError::NotValid)
277        );
278    }
279
280    /// A bound value is covered by the MAC and absent from the token, so asserting the wrong one
281    /// fails and the right one is not recoverable from the token itself.
282    #[test]
283    fn a_bound_value_is_required_but_not_carried() {
284        let key = MintKey::generate().unwrap();
285        let token = seal(&key, TAG, DOMAIN, b"{}", &["reporter@localhost:1"]);
286        assert!(!token.contains("reporter"));
287        assert!(open(&key, TAG, DOMAIN, &token, &["reporter@localhost:1"]).is_ok());
288        assert_eq!(
289            open(&key, TAG, DOMAIN, &token, &["reporter@localhost:2"]),
290            Err(MacTokenError::NotValid)
291        );
292        assert_eq!(
293            open(&key, TAG, DOMAIN, &token, &[]),
294            Err(MacTokenError::NotValid)
295        );
296    }
297
298    #[test]
299    fn a_token_that_is_not_three_base64_segments_is_malformed() {
300        let key = MintKey::generate().unwrap();
301        for token in [
302            "",
303            "tst1",
304            "tst1.abc",
305            "tst1.abc.def.ghi",
306            "tst1..def",
307            "tst1.abc.",
308            "tst1.not base64!.def",
309        ] {
310            assert_eq!(
311                open(&key, TAG, DOMAIN, token, &[]),
312                Err(MacTokenError::Malformed),
313                "{token}"
314            );
315        }
316    }
317
318    #[test]
319    fn a_payload_segment_reads_without_the_key() {
320        let token = seal(
321            &MintKey::generate().unwrap(),
322            TAG,
323            DOMAIN,
324            b"{\"a\":1}",
325            &[],
326        );
327        assert_eq!(payload_segment(TAG, &token).unwrap(), b"{\"a\":1}");
328        assert_eq!(
329            payload_segment("oth1", &token),
330            Err(MacTokenError::Malformed)
331        );
332    }
333
334    #[test]
335    fn a_token_id_is_stable_and_distinguishing() {
336        let id = token_id("tst1.abc.def");
337        assert_eq!(id.len(), TOKEN_ID_HEX_CHARS);
338        assert_eq!(id, token_id("tst1.abc.def"));
339        assert_ne!(id, token_id("tst1.abc.deg"));
340    }
341
342    #[test]
343    fn a_nonce_is_hex_of_the_requested_width() {
344        let nonce = random_hex(NONCE_BYTES).unwrap();
345        assert_eq!(nonce.len(), NONCE_BYTES * 2);
346        assert!(nonce.chars().all(|c| c.is_ascii_hexdigit()));
347        assert_ne!(nonce, random_hex(NONCE_BYTES).unwrap());
348    }
349}