1use std::collections::HashMap;
5use std::fmt;
6use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
7
8use id_effect::{Effect, UtcDateTime, fail, succeed, suspend};
9use sha2::{Digest, Sha256};
10use subtle::ConstantTimeEq;
11
12use super::AccountError;
13use crate::apikey::random_hex;
14
15const ID_BYTES: usize = 8;
17const SECRET_BYTES: usize = 32;
19
20fn hex(bytes: &[u8]) -> String {
21 bytes.iter().map(|b| format!("{b:02x}")).collect()
22}
23
24fn is_hex(s: &str, len: usize) -> bool {
25 s.len() == len
26 && s
27 .bytes()
28 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
29}
30
31fn digest(secret: &str) -> [u8; 32] {
32 Sha256::digest(secret.as_bytes()).into()
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum TokenKind {
38 VerifyEmail,
40 ResetPassword,
42}
43
44impl TokenKind {
45 pub fn as_str(self) -> &'static str {
47 match self {
48 Self::VerifyEmail => "verify_email",
49 Self::ResetPassword => "reset_password",
50 }
51 }
52
53 pub fn parse(s: &str) -> Option<Self> {
55 match s {
56 "verify_email" => Some(Self::VerifyEmail),
57 "reset_password" => Some(Self::ResetPassword),
58 _ => None,
59 }
60 }
61}
62
63impl fmt::Display for TokenKind {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 f.write_str(self.as_str())
66 }
67}
68
69#[derive(Clone, PartialEq, Eq)]
73pub struct AccountToken(String);
74
75impl AccountToken {
76 pub fn generate(
83 kind: TokenKind,
84 account_id: impl Into<String>,
85 expires_at: UtcDateTime,
86 ) -> Result<(Self, TokenRecord), AccountError> {
87 let random = |len| random_hex(len).map_err(|e| AccountError::Random(e.to_string()));
88 let id = random(ID_BYTES)?;
89 let secret = random(SECRET_BYTES)?;
90 let record = TokenRecord {
91 id: id.clone(),
92 kind,
93 account_id: account_id.into(),
94 digest: digest(&secret),
95 expires_at,
96 };
97 Ok((Self(format!("{id}_{secret}")), record))
98 }
99
100 #[inline]
102 pub fn expose(&self) -> &str {
103 &self.0
104 }
105
106 pub(crate) fn split(presented: &str) -> Option<(&str, &str)> {
109 let (id, secret) = presented.split_once('_')?;
110 (is_hex(id, ID_BYTES * 2) && is_hex(secret, SECRET_BYTES * 2)).then_some((id, secret))
111 }
112}
113
114impl fmt::Debug for AccountToken {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 let id = self.0.split_once('_').map_or("", |(id, _)| id);
117 write!(f, "AccountToken({id}_…)")
118 }
119}
120
121#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct TokenRecord {
125 id: String,
126 kind: TokenKind,
127 account_id: String,
128 digest: [u8; 32],
129 expires_at: UtcDateTime,
130}
131
132impl TokenRecord {
133 pub fn from_parts(
140 id: impl Into<String>,
141 kind: TokenKind,
142 account_id: impl Into<String>,
143 digest_hex: &str,
144 expires_at: UtcDateTime,
145 ) -> Result<Self, AccountError> {
146 let id = id.into();
147 let malformed = || AccountError::Storage("malformed account token record".into());
148 if !is_hex(&id, ID_BYTES * 2) || !is_hex(digest_hex, 64) {
149 return Err(malformed());
150 }
151 let mut digest = [0_u8; 32];
152 for (i, byte) in digest.iter_mut().enumerate() {
153 *byte = u8::from_str_radix(&digest_hex[i * 2..i * 2 + 2], 16).map_err(|_| malformed())?;
154 }
155 Ok(Self {
156 id,
157 kind,
158 account_id: account_id.into(),
159 digest,
160 expires_at,
161 })
162 }
163
164 #[inline]
166 pub fn id(&self) -> &str {
167 &self.id
168 }
169
170 #[inline]
172 pub fn kind(&self) -> TokenKind {
173 self.kind
174 }
175
176 #[inline]
178 pub fn account_id(&self) -> &str {
179 &self.account_id
180 }
181
182 pub fn digest_hex(&self) -> String {
184 hex(&self.digest)
185 }
186
187 #[inline]
189 pub fn expires_at(&self) -> UtcDateTime {
190 self.expires_at
191 }
192
193 pub(crate) fn matches(&self, secret: &str) -> bool {
195 bool::from(digest(secret).ct_eq(&self.digest))
196 }
197}
198
199pub trait AccountTokenStore: Send + Sync + 'static {
206 fn insert(&self, record: TokenRecord) -> Effect<(), AccountError>;
208
209 fn find(&self, id: &str) -> Effect<Option<TokenRecord>, AccountError>;
211
212 fn consume(&self, id: &str) -> Effect<bool, AccountError>;
214
215 fn remove_account(&self, account_id: &str, kind: TokenKind) -> Effect<u64, AccountError>;
217
218 fn purge_expired(&self, now: UtcDateTime) -> Effect<u64, AccountError>;
220}
221
222#[derive(Default)]
223struct MemoryTokensState {
224 records: HashMap<String, TokenRecord>,
225 fail: Option<String>,
226}
227
228#[derive(Clone, Default)]
231pub struct MemoryAccountTokenStore {
232 inner: Arc<Mutex<MemoryTokensState>>,
233}
234
235impl fmt::Debug for MemoryAccountTokenStore {
236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237 f.debug_struct("MemoryAccountTokenStore")
238 .field("len", &self.len())
239 .finish()
240 }
241}
242
243impl MemoryAccountTokenStore {
244 #[inline]
246 pub fn new() -> Self {
247 Self::default()
248 }
249
250 fn state(&self) -> MutexGuard<'_, MemoryTokensState> {
251 self.inner.lock().unwrap_or_else(PoisonError::into_inner)
252 }
253
254 pub fn len(&self) -> usize {
256 self.state().records.len()
257 }
258
259 pub fn is_empty(&self) -> bool {
261 self.len() == 0
262 }
263
264 pub fn records(&self) -> Vec<TokenRecord> {
266 self.state().records.values().cloned().collect()
267 }
268
269 pub fn fail_with(&self, message: Option<&str>) {
272 self.state().fail = message.map(str::to_owned);
273 }
274
275 fn with<A: Send + 'static>(
277 &self,
278 f: impl FnOnce(&mut HashMap<String, TokenRecord>) -> A + Send + 'static,
279 ) -> Effect<A, AccountError> {
280 let this = self.clone();
281 suspend(move || {
282 let mut st = this.state();
283 match st.fail.clone() {
284 Some(m) => fail(AccountError::Storage(m)),
285 None => succeed(f(&mut st.records)),
286 }
287 })
288 }
289}
290
291fn count(n: usize) -> u64 {
292 u64::try_from(n).unwrap_or(u64::MAX)
293}
294
295impl AccountTokenStore for MemoryAccountTokenStore {
296 fn insert(&self, record: TokenRecord) -> Effect<(), AccountError> {
297 self.with(move |records| {
298 records.insert(record.id.clone(), record);
299 })
300 }
301
302 fn find(&self, id: &str) -> Effect<Option<TokenRecord>, AccountError> {
303 let id = id.to_owned();
304 self.with(move |records| records.get(&id).cloned())
305 }
306
307 fn consume(&self, id: &str) -> Effect<bool, AccountError> {
308 let id = id.to_owned();
309 self.with(move |records| records.remove(&id).is_some())
310 }
311
312 fn remove_account(&self, account_id: &str, kind: TokenKind) -> Effect<u64, AccountError> {
313 let account_id = account_id.to_owned();
314 self.with(move |records| {
315 let before = records.len();
316 records.retain(|_, r| !(r.account_id == account_id && r.kind == kind));
317 count(before - records.len())
318 })
319 }
320
321 fn purge_expired(&self, now: UtcDateTime) -> Effect<u64, AccountError> {
322 self.with(move |records| {
323 let before = records.len();
324 records.retain(|_, r| r.expires_at > now);
325 count(before - records.len())
326 })
327 }
328}
329
330#[cfg(test)]
331mod tests {
332 use id_effect::{Cause, Exit};
333
334 use super::*;
335
336 fn at(secs: i64) -> UtcDateTime {
337 UtcDateTime::unsafe_make(secs * 1000)
338 }
339
340 fn run<A: Send + 'static>(eff: Effect<A, AccountError>) -> Result<A, AccountError> {
341 match eff.block_on() {
342 Exit::Success(a) => Ok(a),
343 Exit::Failure(Cause::Fail(e)) => Err(e),
344 Exit::Failure(c) => panic!("unexpected cause: {c:?}"),
345 }
346 }
347
348 #[test]
349 fn generated_tokens_split_and_match_only_their_record() {
350 let (token, record) = AccountToken::generate(TokenKind::ResetPassword, "a1", at(9)).unwrap();
351 let (id, secret) = AccountToken::split(token.expose()).expect("well formed");
352 assert_eq!(id, record.id());
353 assert!(record.matches(secret));
354 assert!(!record.matches(&"0".repeat(64)));
355 assert_eq!(record.kind(), TokenKind::ResetPassword);
356 assert_eq!(record.account_id(), "a1");
357 assert_eq!(record.expires_at(), at(9));
358 assert!(!record.digest_hex().contains(secret));
359 assert_eq!(format!("{token:?}"), format!("AccountToken({id}_…)"));
360 let (other, _) = AccountToken::generate(TokenKind::ResetPassword, "a1", at(9)).unwrap();
361 assert_ne!(token, other);
362 }
363
364 #[test]
365 fn malformed_tokens_and_records_are_rejected() {
366 for bad in [
367 "",
368 "abc",
369 &format!("{}_{}", "0".repeat(16), "0".repeat(63)),
370 &format!("{}_{}", "G".repeat(16), "0".repeat(64)),
371 &format!("{}{}", "0".repeat(16), "0".repeat(64)),
372 ] {
373 assert_eq!(AccountToken::split(bad), None, "{bad}");
374 }
375 let (_, record) = AccountToken::generate(TokenKind::VerifyEmail, "a", at(1)).unwrap();
376 let back =
377 TokenRecord::from_parts(record.id(), record.kind(), "a", &record.digest_hex(), at(1))
378 .unwrap();
379 assert_eq!(back, record);
380 assert!(TokenRecord::from_parts("x", TokenKind::VerifyEmail, "a", "00", at(1)).is_err());
381 }
382
383 #[test]
384 fn kinds_round_trip_their_names() {
385 for kind in [TokenKind::VerifyEmail, TokenKind::ResetPassword] {
386 assert_eq!(TokenKind::parse(kind.as_str()), Some(kind));
387 assert_eq!(kind.to_string(), kind.as_str());
388 }
389 assert_eq!(TokenKind::parse("other"), None);
390 }
391
392 #[test]
393 fn the_memory_store_consumes_once_and_purges() {
394 let store = MemoryAccountTokenStore::new();
395 let (_, a) = AccountToken::generate(TokenKind::VerifyEmail, "a", at(10)).unwrap();
396 let (_, b) = AccountToken::generate(TokenKind::ResetPassword, "a", at(10)).unwrap();
397 let (_, c) = AccountToken::generate(TokenKind::ResetPassword, "b", at(5)).unwrap();
398 for r in [&a, &b, &c] {
399 run(store.insert(r.clone())).unwrap();
400 }
401 assert_eq!(run(store.find(a.id())), Ok(Some(a.clone())));
402 assert_eq!(run(store.consume(a.id())), Ok(true));
403 assert_eq!(run(store.consume(a.id())), Ok(false));
404 assert_eq!(
405 run(store.remove_account("a", TokenKind::ResetPassword)),
406 Ok(1)
407 );
408 assert_eq!(run(store.purge_expired(at(5))), Ok(1));
409 assert!(store.is_empty());
410 store.fail_with(Some("down"));
411 assert!(matches!(run(store.find("x")), Err(AccountError::Storage(m)) if m == "down"));
412 assert!(format!("{store:?}").contains("len"));
413 }
414}