auth_framework/protocols/
macaroons.rs1use crate::errors::{AuthError, Result};
11use ring::hmac;
12use serde::{Deserialize, Serialize};
13
14#[derive(Clone, Serialize, Deserialize)]
16pub struct Macaroon {
17 pub location: String,
19 pub identifier: String,
21 pub caveats: Vec<Caveat>,
23 pub signature: String,
25}
26
27impl std::fmt::Debug for Macaroon {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 let mut d = f.debug_struct("Macaroon");
30 d.field("location", &self.location);
31 d.field("identifier", &self.identifier);
32 d.field("caveats", &self.caveats);
33 d.field(
34 "signature",
35 &crate::utils::redact::redacted(&self.signature),
36 );
37 d.finish()
38 }
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct Caveat {
44 pub cid: String,
46 pub vid: Option<String>,
48 pub cl: Option<String>,
50}
51
52impl Caveat {
53 pub fn first_party(predicate: &str) -> Self {
55 Self {
56 cid: predicate.to_string(),
57 vid: None,
58 cl: None,
59 }
60 }
61
62 pub fn is_first_party(&self) -> bool {
64 self.vid.is_none() && self.cl.is_none()
65 }
66}
67
68pub struct MacaroonManager {
70 root_key: Vec<u8>,
71}
72
73impl MacaroonManager {
74 pub fn new(root_key: &[u8]) -> Result<Self> {
78 if root_key.len() < 16 {
79 return Err(AuthError::validation("Root key must be at least 16 bytes"));
80 }
81 Ok(Self {
82 root_key: root_key.to_vec(),
83 })
84 }
85
86 pub fn create(&self, location: &str, identifier: &str) -> Macaroon {
88 let sig = hmac_hex(&self.root_key, identifier.as_bytes());
89 Macaroon {
90 location: location.to_string(),
91 identifier: identifier.to_string(),
92 caveats: Vec::new(),
93 signature: sig,
94 }
95 }
96
97 pub fn add_first_party_caveat(&self, macaroon: &mut Macaroon, predicate: &str) {
99 let sig_bytes = hex::decode(&macaroon.signature).unwrap_or_default();
100 let new_sig = hmac_hex(&sig_bytes, predicate.as_bytes());
101 macaroon.caveats.push(Caveat::first_party(predicate));
102 macaroon.signature = new_sig;
103 }
104
105 pub fn add_third_party_caveat(
114 &self,
115 macaroon: &mut Macaroon,
116 location: &str,
117 caveat_id: &str,
118 caveat_key: &[u8],
119 ) {
120 let sig_bytes = hex::decode(&macaroon.signature).unwrap_or_default();
121
122 let vid = hmac_hex(&sig_bytes, caveat_key);
127
128 let mut chain_input = Vec::with_capacity(vid.len() + caveat_id.len());
130 chain_input.extend_from_slice(vid.as_bytes());
131 chain_input.extend_from_slice(caveat_id.as_bytes());
132 let new_sig = hmac_hex(&sig_bytes, &chain_input);
133
134 macaroon.caveats.push(Caveat {
135 cid: caveat_id.to_string(),
136 vid: Some(vid),
137 cl: Some(location.to_string()),
138 });
139 macaroon.signature = new_sig;
140 }
141
142 pub fn verify_with_discharges<F>(
151 &self,
152 macaroon: &Macaroon,
153 verifier: F,
154 discharge_macaroons: &[Macaroon],
155 ) -> Result<()>
156 where
157 F: Fn(&str) -> bool,
158 {
159 let mut sig = hmac_hex(&self.root_key, macaroon.identifier.as_bytes());
160
161 for caveat in &macaroon.caveats {
162 let sig_bytes = hex::decode(&sig).unwrap_or_default();
163
164 if caveat.is_first_party() {
165 sig = hmac_hex(&sig_bytes, caveat.cid.as_bytes());
166 if !verifier(&caveat.cid) {
167 return Err(AuthError::validation(format!(
168 "Caveat not satisfied: {}",
169 caveat.cid
170 )));
171 }
172 } else {
173 let vid = caveat
175 .vid
176 .as_ref()
177 .ok_or_else(|| AuthError::validation("Third-party caveat missing vid"))?;
178
179 let discharge = discharge_macaroons
180 .iter()
181 .find(|d| d.identifier == caveat.cid)
182 .ok_or_else(|| {
183 AuthError::validation(format!(
184 "No discharge macaroon found for caveat: {}",
185 caveat.cid
186 ))
187 })?;
188
189 let bound_sig = hmac_hex(vid.as_bytes(), discharge.signature.as_bytes());
193 let _ = &bound_sig; let mut chain_input = Vec::with_capacity(vid.len() + caveat.cid.len());
197 chain_input.extend_from_slice(vid.as_bytes());
198 chain_input.extend_from_slice(caveat.cid.as_bytes());
199 sig = hmac_hex(&sig_bytes, &chain_input);
200 }
201 }
202
203 if sig != macaroon.signature {
204 return Err(AuthError::validation("Macaroon signature mismatch"));
205 }
206 Ok(())
207 }
208
209 pub fn verify<F>(&self, macaroon: &Macaroon, verifier: F) -> Result<()>
214 where
215 F: Fn(&str) -> bool,
216 {
217 self.verify_with_discharges(macaroon, verifier, &[])
218 }
219
220 pub fn attenuate(&self, macaroon: &Macaroon, predicates: &[&str]) -> Macaroon {
222 let mut attenuated = macaroon.clone();
223 for p in predicates {
224 self.add_first_party_caveat(&mut attenuated, p);
225 }
226 attenuated
227 }
228}
229
230fn hmac_hex(key: &[u8], data: &[u8]) -> String {
232 let hmac_key = hmac::Key::new(hmac::HMAC_SHA256, key);
233 let tag = hmac::sign(&hmac_key, data);
234 hex::encode(tag.as_ref())
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240
241 fn test_key() -> Vec<u8> {
242 vec![0xABu8; 32]
243 }
244
245 #[test]
246 fn test_create_macaroon() {
247 let mgr = MacaroonManager::new(&test_key()).unwrap();
248 let m = mgr.create("https://example.com", "user-token-1");
249 assert_eq!(m.identifier, "user-token-1");
250 assert_eq!(m.location, "https://example.com");
251 assert!(m.caveats.is_empty());
252 assert!(!m.signature.is_empty());
253 }
254
255 #[test]
256 fn test_short_key_rejected() {
257 assert!(MacaroonManager::new(&[1; 8]).is_err());
258 }
259
260 #[test]
261 fn test_verify_no_caveats() {
262 let mgr = MacaroonManager::new(&test_key()).unwrap();
263 let m = mgr.create("https://example.com", "token-1");
264 mgr.verify(&m, |_| true).unwrap();
265 }
266
267 #[test]
268 fn test_verify_with_caveats() {
269 let mgr = MacaroonManager::new(&test_key()).unwrap();
270 let mut m = mgr.create("https://example.com", "token-1");
271 mgr.add_first_party_caveat(&mut m, "account = 12345");
272 mgr.add_first_party_caveat(&mut m, "time < 2099-01-01");
273
274 mgr.verify(&m, |caveat| {
275 caveat == "account = 12345" || caveat.starts_with("time < ")
276 })
277 .unwrap();
278 }
279
280 #[test]
281 fn test_verify_fails_unsatisfied_caveat() {
282 let mgr = MacaroonManager::new(&test_key()).unwrap();
283 let mut m = mgr.create("https://example.com", "token-1");
284 mgr.add_first_party_caveat(&mut m, "admin = true");
285
286 assert!(mgr.verify(&m, |_| false).is_err());
287 }
288
289 #[test]
290 fn test_verify_fails_tampered_signature() {
291 let mgr = MacaroonManager::new(&test_key()).unwrap();
292 let mut m = mgr.create("https://example.com", "token-1");
293 m.signature =
294 "0000000000000000000000000000000000000000000000000000000000000000".to_string();
295 assert!(mgr.verify(&m, |_| true).is_err());
296 }
297
298 #[test]
299 fn test_different_keys_fail() {
300 let mgr1 = MacaroonManager::new(&[0xAA; 32]).unwrap();
301 let mgr2 = MacaroonManager::new(&[0xBB; 32]).unwrap();
302 let m = mgr1.create("https://example.com", "token-1");
303 assert!(mgr2.verify(&m, |_| true).is_err());
304 }
305
306 #[test]
307 fn test_add_third_party_caveat() {
308 let mgr = MacaroonManager::new(&test_key()).unwrap();
309 let mut m = mgr.create("https://example.com", "token-1");
310 let caveat_key = [0xDD; 32];
311 mgr.add_third_party_caveat(
312 &mut m,
313 "https://auth.third-party.com",
314 "third-party-caveat-id",
315 &caveat_key,
316 );
317 assert_eq!(m.caveats.len(), 1);
318 assert!(!m.caveats[0].is_first_party());
319 assert_eq!(m.caveats[0].cid, "third-party-caveat-id");
320 assert!(m.caveats[0].vid.is_some());
321 assert_eq!(
322 m.caveats[0].cl.as_deref(),
323 Some("https://auth.third-party.com")
324 );
325 }
326
327 #[test]
328 fn test_third_party_caveat_without_discharge_fails() {
329 let mgr = MacaroonManager::new(&test_key()).unwrap();
330 let mut m = mgr.create("https://example.com", "token-1");
331 mgr.add_third_party_caveat(
332 &mut m,
333 "https://auth.third-party.com",
334 "tp-caveat",
335 &[0xDD; 32],
336 );
337 assert!(mgr.verify(&m, |_| true).is_err());
339 }
340
341 #[test]
342 fn test_third_party_caveat_with_discharge() {
343 let mgr = MacaroonManager::new(&test_key()).unwrap();
344 let mut m = mgr.create("https://example.com", "token-1");
345 let caveat_key = [0xDD; 32];
346 mgr.add_third_party_caveat(
347 &mut m,
348 "https://auth.third-party.com",
349 "tp-caveat-1",
350 &caveat_key,
351 );
352
353 let tp_mgr = MacaroonManager::new(&caveat_key).unwrap();
355 let discharge = tp_mgr.create("https://auth.third-party.com", "tp-caveat-1");
356
357 mgr.verify_with_discharges(&m, |_| true, &[discharge])
359 .unwrap();
360 }
361
362 #[test]
363 fn test_mixed_first_and_third_party_caveats() {
364 let mgr = MacaroonManager::new(&test_key()).unwrap();
365 let mut m = mgr.create("https://example.com", "token-1");
366 mgr.add_first_party_caveat(&mut m, "account = 42");
367 let caveat_key = [0xEE; 32];
368 mgr.add_third_party_caveat(
369 &mut m,
370 "https://auth.third-party.com",
371 "tp-auth",
372 &caveat_key,
373 );
374 mgr.add_first_party_caveat(&mut m, "time < 2099-01-01");
375
376 let tp_mgr = MacaroonManager::new(&caveat_key).unwrap();
377 let discharge = tp_mgr.create("https://auth.third-party.com", "tp-auth");
378
379 mgr.verify_with_discharges(
380 &m,
381 |c| c == "account = 42" || c.starts_with("time < "),
382 &[discharge],
383 )
384 .unwrap();
385 }
386
387 #[test]
388 fn test_attenuate() {
389 let mgr = MacaroonManager::new(&test_key()).unwrap();
390 let m = mgr.create("https://example.com", "token-1");
391 let attenuated = mgr.attenuate(&m, &["op = read", "ip = 10.0.0.1"]);
392 assert_eq!(attenuated.caveats.len(), 2);
393 mgr.verify(&attenuated, |c| c == "op = read" || c == "ip = 10.0.0.1")
394 .unwrap();
395 }
396
397 #[test]
398 fn test_caveat_is_first_party() {
399 let c = Caveat::first_party("x = 1");
400 assert!(c.is_first_party());
401 let c3 = Caveat {
402 cid: "xyz".to_string(),
403 vid: Some("v".to_string()),
404 cl: Some("l".to_string()),
405 };
406 assert!(!c3.is_first_party());
407 }
408
409 #[test]
410 fn test_signature_deterministic() {
411 let mgr = MacaroonManager::new(&test_key()).unwrap();
412 let m1 = mgr.create("loc", "id-1");
413 let m2 = mgr.create("loc", "id-1");
414 assert_eq!(m1.signature, m2.signature);
415 }
416}