1use std::time::Duration;
5
6use jiff::Timestamp;
7use topcoat::{context::Cx, session::Token};
8
9use super::{
10 infrastructure_failure,
11 mail::{AuthLetter, AuthMail},
12 session::token_key,
13};
14use crate::{
15 auth::realm::{current_realm, panel_prefix},
16 error::TabloError,
17 toasty_compat::IsolationLevel,
18};
19
20#[derive(Debug, Clone, toasty::Model)]
24pub struct AuthToken {
25 #[key]
27 pub token_hash: String,
28 pub purpose: TokenPurpose,
30 #[index]
32 pub user_id: String,
33 pub panel: String,
35 pub email: Option<String>,
37 #[index]
38 pub expires_at: Timestamp,
39 pub created_at: Timestamp,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, toasty::Embed)]
45#[column(type = text)]
46#[non_exhaustive]
47pub enum TokenPurpose {
48 PasswordReset,
50 EmailVerification,
52 EmailChange,
54 EmailChangeCancel,
56 TwoFactorChallenge,
58 TwoFactorEmailCode,
60}
61
62pub(super) async fn issue(
66 cx: &Cx,
67 ex: &mut dyn toasty::Executor,
68 purpose: TokenPurpose,
69 user_id: &str,
70 email: Option<String>,
71 lifetime: Duration,
72) -> topcoat::Result<Token> {
73 let token = Token::random();
74 record(
75 cx,
76 ex,
77 purpose,
78 user_id,
79 email,
80 lifetime,
81 token_key(&token.hash()),
82 )
83 .await?;
84 Ok(token)
85}
86
87pub(super) async fn record(
90 cx: &Cx,
91 ex: &mut dyn toasty::Executor,
92 purpose: TokenPurpose,
93 user_id: &str,
94 email: Option<String>,
95 lifetime: Duration,
96 token_hash: String,
97) -> topcoat::Result<()> {
98 let now = Timestamp::now();
99 let expires_at = Timestamp::try_from(std::time::SystemTime::now() + lifetime)
100 .map_err(topcoat::Error::from)?;
101 let panel = panel_prefix(cx);
102 AuthToken::filter(
103 AuthToken::fields()
104 .user_id()
105 .eq(user_id.to_string())
106 .and(AuthToken::fields().panel().eq(panel.clone()))
107 .and(AuthToken::fields().purpose().eq(purpose)),
108 )
109 .delete()
110 .exec(&mut *ex)
111 .await
112 .map_err(infrastructure_failure)?;
113 toasty::create!(AuthToken {
114 token_hash,
115 purpose,
116 user_id: user_id.to_string(),
117 panel,
118 email,
119 expires_at,
120 created_at: now,
121 })
122 .exec(ex)
123 .await
124 .map_err(infrastructure_failure)?;
125 Ok(())
126}
127
128pub(super) async fn live(
131 cx: &Cx,
132 ex: &mut dyn toasty::Executor,
133 purpose: TokenPurpose,
134 encoded: &str,
135) -> topcoat::Result<Option<AuthToken>> {
136 let Ok(token) = Token::decode(encoded) else {
137 return Ok(None);
138 };
139 recorded(cx, ex, purpose, token_key(&token.hash())).await
140}
141
142pub(super) async fn recorded(
144 cx: &Cx,
145 ex: &mut dyn toasty::Executor,
146 purpose: TokenPurpose,
147 token_hash: String,
148) -> topcoat::Result<Option<AuthToken>> {
149 let row = AuthToken::filter(AuthToken::fields().token_hash().eq(token_hash))
150 .first()
151 .exec(ex)
152 .await
153 .map_err(infrastructure_failure)?;
154 let prefix = panel_prefix(cx);
155 Ok(row.filter(|row| {
156 row.purpose == purpose && row.panel == prefix && row.expires_at > Timestamp::now()
157 }))
158}
159
160pub(super) async fn spend(ex: &mut dyn toasty::Executor, row: &AuthToken) -> topcoat::Result<()> {
162 AuthToken::filter(AuthToken::fields().token_hash().eq(row.token_hash.clone()))
163 .delete()
164 .exec(ex)
165 .await
166 .map_err(infrastructure_failure)
167}
168
169pub(super) const CREDENTIALS: &[TokenPurpose] = &[
172 TokenPurpose::PasswordReset,
173 TokenPurpose::TwoFactorChallenge,
174 TokenPurpose::TwoFactorEmailCode,
175];
176
177pub(super) const REVOCATION: &[TokenPurpose] = &[
180 TokenPurpose::PasswordReset,
181 TokenPurpose::TwoFactorChallenge,
182 TokenPurpose::TwoFactorEmailCode,
183 TokenPurpose::EmailChange,
184];
185
186pub(super) async fn end_all(
189 ex: &mut dyn toasty::Executor,
190 user_id: &str,
191 prefixes: Option<Vec<String>>,
192 purposes: &[TokenPurpose],
193) -> topcoat::Result<()> {
194 let user = AuthToken::fields()
195 .user_id()
196 .eq(user_id.to_string())
197 .and(AuthToken::fields().purpose().in_list(purposes.to_vec()));
198 match prefixes {
199 Some(prefixes) => {
200 AuthToken::filter(user.and(AuthToken::fields().panel().in_list(prefixes)))
201 }
202 None => AuthToken::filter(user),
203 }
204 .delete()
205 .exec(ex)
206 .await
207 .map_err(infrastructure_failure)
208}
209
210pub(super) const TOKEN_SWEEP_BATCH: usize = 500;
213
214pub(super) async fn sweep_expired(cx: &Cx) -> topcoat::Result<()> {
217 if current_realm(cx).is_some_and(|panel| panel.auth.issues_tokens()) {
219 sweep(&mut crate::db::db(cx)?).await?;
220 }
221 Ok(())
222}
223
224pub(super) async fn sweep(db: &mut toasty::Db) -> topcoat::Result<()> {
226 let now = Timestamp::now();
227 let expired: Vec<String> = AuthToken::filter(AuthToken::fields().expires_at().le(now))
228 .limit(TOKEN_SWEEP_BATCH)
229 .exec(&mut *db)
230 .await
231 .map_err(infrastructure_failure)?
232 .into_iter()
233 .map(|row| row.token_hash)
234 .collect();
235 if expired.is_empty() {
236 return Ok(());
237 }
238 AuthToken::filter(
240 AuthToken::fields()
241 .token_hash()
242 .in_list(expired)
243 .and(AuthToken::fields().expires_at().le(now)),
244 )
245 .delete()
246 .exec(db)
247 .await
248 .map_err(infrastructure_failure)
249}
250
251pub(super) async fn serializable(db: &mut toasty::Db) -> topcoat::Result<toasty::Transaction<'_>> {
254 db.transaction_builder()
255 .isolation(IsolationLevel::Serializable)
256 .begin()
257 .await
258 .map_err(infrastructure_failure)
259}
260
261const ATTEMPTS: u32 = 10;
267
268macro_rules! run_serializable {
278 ($cx:expr, |$tx:ident| $body:expr) => {{
279 let mut db = crate::db::db($cx)?;
280 let mut attempt = 1;
281 loop {
282 let run = async {
283 let mut tx = crate::auth::token::serializable(&mut db).await?;
284 let answer = {
285 let $tx = &mut tx;
286 crate::auth::token::answering($body).await?
287 };
288 tx.commit()
289 .await
290 .map_err(crate::auth::infrastructure_failure)?;
291 topcoat::Result::Ok(answer)
292 }
293 .await;
294 let Err(error) = run else { break run };
295 if !crate::auth::token::waited_to_retry(&mut attempt, &error).await {
296 break Err(error);
297 }
298 }
299 }};
300}
301pub(super) use run_serializable;
302
303pub(super) fn answering<T>(
306 body: impl Future<Output = topcoat::Result<T>>,
307) -> impl Future<Output = topcoat::Result<T>> {
308 body
309}
310
311pub(super) async fn waited_to_retry(attempt: &mut u32, error: &topcoat::Error) -> bool {
314 if *attempt >= ATTEMPTS || !TabloError::is_conflict(error) {
315 return false;
316 }
317 tokio::time::sleep(backoff(*attempt)).await;
318 *attempt += 1;
319 true
320}
321
322pub(super) async fn issue_mailed(
327 cx: &Cx,
328 mail: &AuthMail,
329 purpose: TokenPurpose,
330 user_id: &str,
331 email: Option<String>,
332 lifetime: Duration,
333 write: impl Fn(&Token) -> topcoat::Result<AuthLetter> + Send + Sync,
334) -> topcoat::Result<()> {
335 let pending = run_serializable!(cx, |tx| async {
336 let token = issue(cx, &mut *tx, purpose, user_id, email.clone(), lifetime).await?;
337 mail.hand(cx, tx, write(&token)?).await
338 })?;
339 if let Some(letter) = pending {
340 super::mail::send(cx, letter).await?;
341 }
342 Ok(())
343}
344
345fn backoff(attempt: u32) -> Duration {
348 let ceiling = 20u64 << attempt.min(6);
349 let jitter = getrandom::u64().map_or(ceiling / 2, |random| random % ceiling);
350 Duration::from_millis(jitter)
351}