Skip to main content

auth_framework/protocols/
macaroons.rs

1//! Macaroons authorization credential support.
2//!
3//! Implements Macaroons — a flexible authorization credential mechanism using
4//! chained HMAC-based caveats for decentralized attenuation.
5//!
6//! # References
7//!
8//! - [Macaroons: Cookies with Contextual Caveats](https://research.google/pubs/pub41892/)
9
10use crate::errors::{AuthError, Result};
11use crate::security::secure_utils::SecureComparison;
12use ring::hmac;
13use serde::{Deserialize, Serialize};
14
15/// A Macaroon authorization token with chained HMAC caveats.
16///
17/// The signature is the bearer secret, so `Debug` prints it redacted.
18#[derive(Clone, Serialize, Deserialize)]
19pub struct Macaroon {
20    /// Location hint (not cryptographically bound).
21    pub location: String,
22    /// Opaque identifier for this macaroon.
23    pub identifier: String,
24    /// First-party caveats.
25    pub caveats: Vec<Caveat>,
26    /// HMAC signature (hex-encoded).
27    pub signature: String,
28}
29
30impl std::fmt::Debug for Macaroon {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.debug_struct("Macaroon")
33            .field("location", &self.location)
34            .field("identifier", &self.identifier)
35            .field("caveats", &self.caveats)
36            .field(
37                "signature",
38                &crate::utils::redact::redacted(&self.signature),
39            )
40            .finish()
41    }
42}
43
44/// A first-party caveat restricting the macaroon's authority.
45///
46/// Unknown fields are rejected on deserialization, so a credential that carries
47/// anything other than a plain predicate is refused instead of being read as one.
48#[derive(Debug, Clone, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct Caveat {
51    /// Caveat identifier (e.g. "account = 3735928559").
52    pub cid: String,
53}
54
55impl Caveat {
56    /// Create a new first-party caveat.
57    pub fn first_party(predicate: &str) -> Self {
58        Self {
59            cid: predicate.to_string(),
60        }
61    }
62}
63
64/// Macaroon minting and verification.
65pub struct MacaroonManager {
66    root_key: Vec<u8>,
67}
68
69impl MacaroonManager {
70    /// Create a manager from a root key.
71    ///
72    /// The root key should be at least 32 bytes of cryptographically random data.
73    pub fn new(root_key: &[u8]) -> Result<Self> {
74        if root_key.len() < 16 {
75            return Err(AuthError::validation("Root key must be at least 16 bytes"));
76        }
77        Ok(Self {
78            root_key: root_key.to_vec(),
79        })
80    }
81
82    /// Mint a new macaroon with the given identifier.
83    pub fn create(&self, location: &str, identifier: &str) -> Macaroon {
84        let sig = hmac_hex(&self.root_key, identifier.as_bytes());
85        Macaroon {
86            location: location.to_string(),
87            identifier: identifier.to_string(),
88            caveats: Vec::new(),
89            signature: sig,
90        }
91    }
92
93    /// Add a first-party caveat, updating the signature chain.
94    pub fn add_first_party_caveat(&self, macaroon: &mut Macaroon, predicate: &str) {
95        let sig_bytes = hex::decode(&macaroon.signature).unwrap_or_default();
96        let new_sig = hmac_hex(&sig_bytes, predicate.as_bytes());
97        macaroon.caveats.push(Caveat::first_party(predicate));
98        macaroon.signature = new_sig;
99    }
100
101    /// Verify a macaroon by replaying the HMAC chain and checking caveats.
102    ///
103    /// `verifier` is called for each caveat predicate and must return `true`
104    /// if the caveat is satisfied.
105    pub fn verify<F>(&self, macaroon: &Macaroon, verifier: F) -> Result<()>
106    where
107        F: Fn(&str) -> bool,
108    {
109        let mut sig = hmac_hex(&self.root_key, macaroon.identifier.as_bytes());
110
111        for caveat in &macaroon.caveats {
112            let sig_bytes = hex::decode(&sig).unwrap_or_default();
113            sig = hmac_hex(&sig_bytes, caveat.cid.as_bytes());
114            if !verifier(&caveat.cid) {
115                return Err(AuthError::validation(format!(
116                    "Caveat not satisfied: {}",
117                    caveat.cid
118                )));
119            }
120        }
121
122        if !SecureComparison::constant_time_eq(&sig, &macaroon.signature) {
123            return Err(AuthError::validation("Macaroon signature mismatch"));
124        }
125        Ok(())
126    }
127
128    /// Attenuate (create a restricted copy of) a macaroon with additional caveats.
129    pub fn attenuate(&self, macaroon: &Macaroon, predicates: &[&str]) -> Macaroon {
130        let mut attenuated = macaroon.clone();
131        for p in predicates {
132            self.add_first_party_caveat(&mut attenuated, p);
133        }
134        attenuated
135    }
136}
137
138/// Compute HMAC-SHA256 and return the result as a hex string.
139fn hmac_hex(key: &[u8], data: &[u8]) -> String {
140    let hmac_key = hmac::Key::new(hmac::HMAC_SHA256, key);
141    let tag = hmac::sign(&hmac_key, data);
142    hex::encode(tag.as_ref())
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    fn test_key() -> Vec<u8> {
150        vec![0xABu8; 32]
151    }
152
153    #[test]
154    fn test_create_macaroon() {
155        let mgr = MacaroonManager::new(&test_key()).unwrap();
156        let m = mgr.create("https://example.com", "user-token-1");
157        assert_eq!(m.identifier, "user-token-1");
158        assert_eq!(m.location, "https://example.com");
159        assert!(m.caveats.is_empty());
160        assert!(!m.signature.is_empty());
161    }
162
163    #[test]
164    fn test_short_key_rejected() {
165        assert!(MacaroonManager::new(&[1; 8]).is_err());
166    }
167
168    #[test]
169    fn test_verify_no_caveats() {
170        let mgr = MacaroonManager::new(&test_key()).unwrap();
171        let m = mgr.create("https://example.com", "token-1");
172        mgr.verify(&m, |_| true).unwrap();
173    }
174
175    #[test]
176    fn test_verify_with_caveats() {
177        let mgr = MacaroonManager::new(&test_key()).unwrap();
178        let mut m = mgr.create("https://example.com", "token-1");
179        mgr.add_first_party_caveat(&mut m, "account = 12345");
180        mgr.add_first_party_caveat(&mut m, "time < 2099-01-01");
181
182        mgr.verify(&m, |caveat| {
183            caveat == "account = 12345" || caveat.starts_with("time < ")
184        })
185        .unwrap();
186    }
187
188    #[test]
189    fn test_verify_fails_unsatisfied_caveat() {
190        let mgr = MacaroonManager::new(&test_key()).unwrap();
191        let mut m = mgr.create("https://example.com", "token-1");
192        mgr.add_first_party_caveat(&mut m, "admin = true");
193
194        assert!(mgr.verify(&m, |_| false).is_err());
195    }
196
197    #[test]
198    fn test_verify_fails_tampered_signature() {
199        let mgr = MacaroonManager::new(&test_key()).unwrap();
200        let mut m = mgr.create("https://example.com", "token-1");
201        m.signature =
202            "0000000000000000000000000000000000000000000000000000000000000000".to_string();
203        assert!(mgr.verify(&m, |_| true).is_err());
204    }
205
206    #[test]
207    fn test_different_keys_fail() {
208        let mgr1 = MacaroonManager::new(&[0xAA; 32]).unwrap();
209        let mgr2 = MacaroonManager::new(&[0xBB; 32]).unwrap();
210        let m = mgr1.create("https://example.com", "token-1");
211        assert!(mgr2.verify(&m, |_| true).is_err());
212    }
213
214    #[test]
215    fn test_attenuate() {
216        let mgr = MacaroonManager::new(&test_key()).unwrap();
217        let m = mgr.create("https://example.com", "token-1");
218        let attenuated = mgr.attenuate(&m, &["op = read", "ip = 10.0.0.1"]);
219        assert_eq!(attenuated.caveats.len(), 2);
220        mgr.verify(&attenuated, |c| c == "op = read" || c == "ip = 10.0.0.1")
221            .unwrap();
222    }
223
224    #[test]
225    fn test_signature_deterministic() {
226        let mgr = MacaroonManager::new(&test_key()).unwrap();
227        let m1 = mgr.create("loc", "id-1");
228        let m2 = mgr.create("loc", "id-1");
229        assert_eq!(m1.signature, m2.signature);
230    }
231
232    #[test]
233    fn test_credential_carrying_a_third_party_caveat_is_refused() {
234        // Shape of a credential minted by releases that had third-party caveats.
235        let json = r#"{"location":"l","identifier":"token-1","caveats":[{"cid":"tp","vid":"00","cl":"https://auth.third-party.com"}],"signature":"00"}"#;
236        assert!(serde_json::from_str::<Macaroon>(json).is_err());
237    }
238
239    #[test]
240    fn test_tampered_caveat_list_is_rejected() {
241        let mgr = MacaroonManager::new(&test_key()).unwrap();
242        let mut m = mgr.create("https://example.com", "token-1");
243        mgr.add_first_party_caveat(&mut m, "op = read");
244        m.caveats[0] = Caveat::first_party("op = write");
245        assert!(mgr.verify(&m, |_| true).is_err());
246    }
247
248    #[test]
249    fn test_debug_output_does_not_contain_the_signature() {
250        let mgr = MacaroonManager::new(&test_key()).unwrap();
251        let m = mgr.create("https://example.com", "token-1");
252        let shown = format!("{m:?}");
253        assert!(!shown.contains(&m.signature), "{shown}");
254        assert!(shown.contains("token-1"));
255    }
256}