auth_framework/protocols/
macaroons.rs1use crate::errors::{AuthError, Result};
11use crate::security::secure_utils::SecureComparison;
12use ring::hmac;
13use serde::{Deserialize, Serialize};
14
15#[derive(Clone, Serialize, Deserialize)]
19pub struct Macaroon {
20 pub location: String,
22 pub identifier: String,
24 pub caveats: Vec<Caveat>,
26 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#[derive(Debug, Clone, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct Caveat {
51 pub cid: String,
53}
54
55impl Caveat {
56 pub fn first_party(predicate: &str) -> Self {
58 Self {
59 cid: predicate.to_string(),
60 }
61 }
62}
63
64pub struct MacaroonManager {
66 root_key: Vec<u8>,
67}
68
69impl MacaroonManager {
70 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 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 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 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 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
138fn 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 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}