universal_exports/
factor_seal.rs1use base64::Engine as _;
10use base64::engine::general_purpose::URL_SAFE_NO_PAD;
11use ring::aead::{AES_256_GCM, Aad, LessSafeKey, NONCE_LEN, Nonce, UnboundKey};
12use ring::hkdf::{HKDF_SHA256, KeyType, Salt};
13use ring::rand::{SecureRandom, SystemRandom};
14
15const PREFIX: &str = "aes256gcm1:";
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum SealError {
22 NoKey,
24 Unreadable,
26 Sealing,
28}
29
30impl std::fmt::Display for SealError {
31 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 formatter.write_str(match self {
33 Self::NoKey => "no usable [unex] factor_key seals one-time code secrets",
34 Self::Unreadable => "a one-time code secret cannot be opened with the factor_key",
35 Self::Sealing => "a one-time code secret could not be sealed",
36 })
37 }
38}
39
40impl std::error::Error for SealError {}
41
42struct Key32;
43
44impl KeyType for Key32 {
45 fn len(&self) -> usize {
46 32
47 }
48}
49
50pub struct FactorSealer {
52 key: Option<LessSafeKey>,
53 too_short: Option<(usize, usize)>,
55 random: SystemRandom,
56}
57
58impl std::fmt::Debug for FactorSealer {
59 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 formatter
61 .debug_struct("FactorSealer")
62 .field("ready", &self.key.is_some())
63 .finish()
64 }
65}
66
67impl FactorSealer {
68 pub fn new(secret: Option<&str>, min_bytes: usize) -> Result<Self, String> {
75 let mut too_short = None;
76 let key = match secret {
77 None => None,
78 Some("") => return Err("the one-time code sealing key is empty".to_owned()),
79 Some(secret) if secret.len() < min_bytes => {
80 too_short = Some((secret.len(), min_bytes));
81 None
82 }
83 Some(secret) => {
84 let mut derived = [0u8; 32];
85 Salt::new(HKDF_SHA256, b"ai6 one-time code sealing")
86 .extract(secret.as_bytes())
87 .expand(&[b"aes-256-gcm"], Key32)
88 .and_then(|okm| okm.fill(&mut derived))
89 .map_err(|_| "the one-time code sealing key cannot be used".to_owned())?;
90 let unbound = UnboundKey::new(&AES_256_GCM, &derived)
91 .map_err(|_| "the one-time code sealing key cannot be used".to_owned())?;
92 Some(LessSafeKey::new(unbound))
93 }
94 };
95 Ok(Self {
96 key,
97 too_short,
98 random: SystemRandom::new(),
99 })
100 }
101
102 pub fn ready(&self) -> bool {
104 self.key.is_some()
105 }
106
107 pub fn refusal(&self) -> Option<String> {
109 if self.key.is_some() {
110 return None;
111 }
112 Some(match self.too_short {
113 Some((_, least)) => format!("[unex] factor_key holds fewer than {least} bytes"),
114 None => "no [unex] factor_key is configured".to_owned(),
115 })
116 }
117
118 pub fn seal(&self, context: &str, plain: &str) -> Result<String, SealError> {
124 let key = self.key.as_ref().ok_or(SealError::NoKey)?;
125 let mut nonce = [0u8; NONCE_LEN];
126 self.random
127 .fill(&mut nonce)
128 .map_err(|_| SealError::Sealing)?;
129 let mut sealed = plain.as_bytes().to_vec();
130 key.seal_in_place_append_tag(
131 Nonce::assume_unique_for_key(nonce),
132 Aad::from(context.as_bytes()),
133 &mut sealed,
134 )
135 .map_err(|_| SealError::Sealing)?;
136 let mut text = nonce.to_vec();
137 text.extend_from_slice(&sealed);
138 Ok(format!("{PREFIX}{}", URL_SAFE_NO_PAD.encode(text)))
139 }
140
141 pub fn open(&self, context: &str, sealed: &str) -> Result<String, SealError> {
147 let key = self.key.as_ref().ok_or(SealError::NoKey)?;
148 let bytes = sealed
149 .strip_prefix(PREFIX)
150 .and_then(|body| URL_SAFE_NO_PAD.decode(body).ok())
151 .filter(|bytes| bytes.len() > NONCE_LEN)
152 .ok_or(SealError::Unreadable)?;
153 let (nonce, body) = bytes.split_at(NONCE_LEN);
154 let nonce = Nonce::try_assume_unique_for_key(nonce).map_err(|_| SealError::Unreadable)?;
155 let mut body = body.to_vec();
156 let plain = key
157 .open_in_place(nonce, Aad::from(context.as_bytes()), &mut body)
158 .map_err(|_| SealError::Unreadable)?;
159 String::from_utf8(plain.to_vec()).map_err(|_| SealError::Unreadable)
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 fn sealer(secret: &str) -> FactorSealer {
168 FactorSealer::new(Some(secret), 0).unwrap()
169 }
170
171 #[test]
172 fn a_secret_opens_only_under_its_key_and_its_account() {
173 let sealed = sealer("key one")
174 .seal("totp\0id-alice", "JBSWY3DPEHPK3PXP")
175 .unwrap();
176 assert!(!sealed.contains("JBSWY3DPEHPK3PXP"), "{sealed}");
177 assert_eq!(
178 sealer("key one").open("totp\0id-alice", &sealed).unwrap(),
179 "JBSWY3DPEHPK3PXP"
180 );
181 assert_eq!(
182 sealer("key two").open("totp\0id-alice", &sealed),
183 Err(SealError::Unreadable),
184 "another key"
185 );
186 assert_eq!(
187 sealer("key one").open("totp\0id-bob", &sealed),
188 Err(SealError::Unreadable),
189 "another account"
190 );
191 assert_eq!(
192 sealer("key one").open("totp_enrolling\0id-alice", &sealed),
193 Err(SealError::Unreadable),
194 "another table"
195 );
196 assert_eq!(
197 sealer("key one").open("totp\0id-alice", "JBSWY3DPEHPK3PXP"),
198 Err(SealError::Unreadable),
199 "a secret in the clear is not a sealed one"
200 );
201 }
202
203 #[test]
204 fn every_seal_has_a_fresh_nonce() {
205 let key = sealer("key one");
206 let first = key.seal("totp\0id-alice", "same").unwrap();
207 let second = key.seal("totp\0id-alice", "same").unwrap();
208 assert_ne!(first, second);
209 }
210
211 #[test]
212 fn with_no_key_nothing_is_sealed_or_opened() {
213 let none = FactorSealer::new(None, 32).unwrap();
214 assert!(!none.ready());
215 assert!(none.refusal().unwrap().contains("configured"));
216 assert_eq!(none.seal("c", "secret"), Err(SealError::NoKey));
217 assert_eq!(none.open("c", "aes256gcm1:AAAA"), Err(SealError::NoKey));
218 assert!(FactorSealer::new(Some(""), 32).is_err());
219 }
220
221 #[test]
222 fn a_key_shorter_than_the_floor_seals_nothing_and_says_so() {
223 let short = FactorSealer::new(Some("only a few bytes"), 32).unwrap();
224 assert!(!short.ready());
225 assert_eq!(short.seal("c", "secret"), Err(SealError::NoKey));
226 let reason = short.refusal().unwrap();
227 assert!(
228 reason.contains("32") && !reason.contains("only a few"),
229 "{reason}"
230 );
231 assert!(
232 FactorSealer::new(Some(&"k".repeat(32)), 32)
233 .unwrap()
234 .ready()
235 );
236 }
237}