fraiseql-auth 2.16.0

Authentication, authorization, and session management for FraiseQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! One-time password (`OTP`) authentication — email magic links and 6-digit codes.
//!
//! Provides:
//! - [`OtpStore`] — stores and validates `OTP` codes.
//! - [`InMemoryOtpStore`] — thread-safe in-memory backend for single-node and testing.
//! - [`EmailDelivery`] — delivers `OTP` emails.
//! - [`NoopEmailDelivery`] — logs only (no real email sent); for testing and dev.
//! - Axum handlers: `POST /auth/v1/otp` and `POST /auth/v1/verify`.
//!
//! # Security
//!
//! - Codes are 6 random decimal digits (10⁶ space, ~20 bits).
//! - Each code is **single-use**: consumed on first successful verify.
//! - `TTL` is 10 minutes.
//! - Verification attempts are rate-limited to **3 per 15 minutes** per email.
//! - Codes are compared with constant-time equality to prevent timing attacks.

use std::sync::Arc;

use async_trait::async_trait;
use axum::{
    Json,
    extract::State,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use dashmap::DashMap;
use rand::Rng;
use serde::{Deserialize, Serialize};

use crate::{
    audit::logger::{AuditEventType, SecretType, get_audit_logger},
    error::{AuthError, Result},
    session::{SessionStore, unix_now},
};

// ─── Constants ────────────────────────────────────────────────────────────────

/// `OTP` validity window in seconds (10 minutes).
pub(super) const OTP_TTL_SECS: u64 = 600;

/// Maximum verification attempts per code before it is invalidated.
pub(super) const MAX_VERIFY_ATTEMPTS: u32 = 3;

/// Rate-limit window for `OTP` send requests (15 minutes).
pub(super) const OTP_RATE_WINDOW_SECS: u64 = 900;

/// Maximum `OTP` send requests in the rate-limit window.
pub(super) const OTP_RATE_MAX: u32 = 3;

/// Account-store provider key for email-`OTP` identities (#367).
///
/// Distinct from a social provider: no third party asserted the address —
/// receiving the code *is* the proof of control.
pub const OTP_PROVIDER: &str = "otp";

pub mod postgres;

// ─── OTP record ───────────────────────────────────────────────────────────────

/// Internal record for a pending `OTP` code.
#[derive(Debug, Clone)]
struct OtpRecord {
    /// The 6-digit code.
    code:     String,
    /// Unix timestamp when this code expires.
    expires:  u64,
    /// How many verification attempts have been made against this code.
    attempts: u32,
}

impl OtpRecord {
    fn is_expired(&self) -> bool {
        // Fail-closed: a clock failure treats the code as expired, never valid.
        Self::is_expired_at(self.expires, unix_now().ok())
    }

    /// Pure expiry decision against an optional clock reading. `None` (clock failure)
    /// fails closed → expired.
    fn is_expired_at(expires: u64, now: Option<u64>) -> bool {
        now.is_none_or(|now| now >= expires)
    }
}

// ─── Rate-limit record ────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
struct RateRecord {
    /// Number of `OTP` sends in the current window.
    count:        u32,
    /// Unix timestamp when the window started.
    window_start: u64,
}

// ─── OtpStore trait ───────────────────────────────────────────────────────────

/// `OTP` storage and validation backend.
// Reason: used as dyn Trait (Arc<dyn OtpStore>); async_trait ensures Send bounds and
// dyn-compatibility async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
#[async_trait]
pub trait OtpStore: Send + Sync {
    /// Delete expired codes and stale send-budget rows. Returns the number removed.
    ///
    /// Required rather than defaulted, for the reason [`crate::MfaStore::sweep_expired`]
    /// gives. `tb_otp_send_budget` is the sharper case: it holds one row per address that
    /// has ever requested a code and nothing removed them (#950).
    ///
    /// # Errors
    ///
    /// Returns [`AuthError::DatabaseError`] if the store fails.
    async fn sweep_expired(&self) -> Result<u64>;

    /// Generate and store a new `OTP` for the given email.
    ///
    /// # Returns
    ///
    /// The generated 6-digit code (to be delivered to the user).
    ///
    /// # Errors
    ///
    /// Returns [`AuthError::RateLimited`] if the per-email send rate is exceeded.
    /// Returns [`AuthError::DatabaseError`] if the backing store fails.
    async fn create_otp(&self, email: &str) -> Result<String>;

    /// Verify a code for the given email and consume it on success.
    ///
    /// # Returns
    ///
    /// `Ok(())` if the code is correct, not expired, and within attempt limits.
    ///
    /// # Errors
    ///
    /// Returns [`AuthError::InvalidToken`] if the code is wrong or expired.
    /// Returns [`AuthError::RateLimited`] if the attempt count is exceeded.
    async fn verify_otp(&self, email: &str, code: &str) -> Result<()>;
}

// ─── In-memory OTP store ──────────────────────────────────────────────────────

/// Thread-safe in-memory `OTP` store.
///
/// Suitable for single-node deployments and testing.  For distributed deployments
/// use a Redis-backed store (not provided here).
pub struct InMemoryOtpStore {
    /// email → pending OTP record
    codes:       DashMap<String, OtpRecord>,
    /// email → rate-limit record
    rate_limits: DashMap<String, RateRecord>,
}

impl InMemoryOtpStore {
    /// Create a new empty `OTP` store.
    #[must_use]
    pub fn new() -> Self {
        Self {
            codes:       DashMap::new(),
            rate_limits: DashMap::new(),
        }
    }

    /// Return the number of pending `OTP` codes (useful for tests).
    #[must_use]
    pub fn pending_count(&self) -> usize {
        self.codes.len()
    }
}

impl Default for InMemoryOtpStore {
    fn default() -> Self {
        Self::new()
    }
}

// Reason: async_trait required for dyn-compatibility; remove when RTN + Send is stable
#[async_trait]
impl OtpStore for InMemoryOtpStore {
    async fn sweep_expired(&self) -> Result<u64> {
        let now = unix_now()?;
        let before = self.codes.len() + self.rate_limits.len();
        self.codes.retain(|_, r| r.expires > now);
        // A budget row whose window has closed is dead weight: the next send for that
        // address opens a fresh window regardless of what this row says.
        self.rate_limits.retain(|_, r| now < r.window_start + OTP_RATE_WINDOW_SECS);
        Ok((before - (self.codes.len() + self.rate_limits.len())) as u64)
    }

    async fn create_otp(&self, email: &str) -> Result<String> {
        let now = unix_now()?;

        // Per-email rate limiting: max OTP_RATE_MAX sends per OTP_RATE_WINDOW_SECS.
        {
            let mut entry = self.rate_limits.entry(email.to_string()).or_insert(RateRecord {
                count:        0,
                window_start: now,
            });
            // Reset window if it has expired.
            if now >= entry.window_start + OTP_RATE_WINDOW_SECS {
                entry.count = 0;
                entry.window_start = now;
            }
            if entry.count >= OTP_RATE_MAX {
                return Err(AuthError::RateLimited {
                    retry_after_secs: (entry.window_start + OTP_RATE_WINDOW_SECS)
                        .saturating_sub(now),
                });
            }
            entry.count += 1;
        }

        // Generate a 6-digit code using OS-level entropy.
        // SECURITY: rand::rng() uses OS-level entropy; gen_range is unbiased.
        let code = format!("{:06}", rand::rng().random_range(0u32..1_000_000));
        let expires = now + OTP_TTL_SECS;

        self.codes.insert(
            email.to_string(),
            OtpRecord {
                code: code.clone(),
                expires,
                attempts: 0,
            },
        );

        Ok(code)
    }

    async fn verify_otp(&self, email: &str, code: &str) -> Result<()> {
        let mut entry = self.codes.get_mut(email).ok_or_else(|| AuthError::InvalidToken {
            reason: "no pending OTP for email".into(),
        })?;

        if entry.is_expired() {
            drop(entry);
            self.codes.remove(email);
            return Err(AuthError::InvalidToken {
                reason: "OTP has expired".into(),
            });
        }

        entry.attempts += 1;
        if entry.attempts > MAX_VERIFY_ATTEMPTS {
            drop(entry);
            self.codes.remove(email);
            return Err(AuthError::RateLimited {
                retry_after_secs: OTP_RATE_WINDOW_SECS,
            });
        }

        // Constant-time comparison (#788): a data-dependent `!=` on the code leaks
        // how many leading digits matched via its return time. The 3-attempt cap is
        // the primary mitigation, but honouring the module's own "constant-time"
        // doc claim costs nothing here.
        if !crate::constant_time::ConstantTimeOps::compare_str(&entry.code, code) {
            return Err(AuthError::InvalidToken {
                reason: "invalid OTP code".into(),
            });
        }

        // Code is correct — consume it (single-use).
        drop(entry);
        self.codes.remove(email);
        Ok(())
    }
}

// ─── Email delivery ───────────────────────────────────────────────────────────

/// Abstract email delivery backend.
// Reason: used as dyn Trait (Arc<dyn EmailDelivery>); async_trait ensures Send bounds and
// dyn-compatibility async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
#[async_trait]
pub trait EmailDelivery: Send + Sync {
    /// Send an `OTP` code to the given email address.
    ///
    /// Returns a message identifier that can be returned to the caller for
    /// tracking / idempotency (may be empty for noop implementations).
    ///
    /// # Errors
    ///
    /// Returns [`AuthError::Internal`] if delivery fails.
    async fn send_otp(&self, email: &str, code: &str) -> Result<String>;
}

/// No-op email delivery — logs the `OTP` via `tracing` instead of sending real email.
///
/// Suitable for development and testing.
pub struct NoopEmailDelivery;

// Reason: async_trait required for dyn-compatibility; remove when RTN + Send is stable
#[async_trait]
impl EmailDelivery for NoopEmailDelivery {
    async fn send_otp(&self, email: &str, code: &str) -> Result<String> {
        tracing::info!(email, code, "NoopEmailDelivery: OTP code (NOT sent via real email)");
        // Return a deterministic fake message_id for test assertions.
        Ok(format!("noop-{email}-{code}"))
    }
}

// ─── Route state ─────────────────────────────────────────────────────────────

/// Axum state for `OTP` routes.
#[derive(Clone)]
pub struct OtpRouteState {
    /// `OTP` code store.
    pub otp_store:      Arc<dyn OtpStore>,
    /// Email delivery backend.
    pub email_delivery: Arc<dyn EmailDelivery>,
    /// Session store (to create sessions after successful verify).
    pub session_store:  Arc<dyn SessionStore>,
    /// Account store resolving the verified email to a stable local user (#367).
    ///
    /// `None` mints the legacy `otp:<email>` pseudo-identity, which is **not a
    /// real account**: it never links to the same person's social or
    /// local-password sign-in, so the same human ends up with as many
    /// identities as sign-in methods. The server always supplies one; the
    /// option exists for library callers with their own identity model.
    pub account_store:  Option<Arc<dyn crate::account_linking::AccountStore>>,
}

// ─── Request / Response types ─────────────────────────────────────────────────

/// Request body for `POST /auth/v1/otp`.
#[derive(Debug, Deserialize)]
pub struct OtpRequest {
    /// Destination email address.
    pub email: String,
}

/// Response body for `POST /auth/v1/otp`.
#[derive(Debug, Serialize)]
pub struct OtpResponse {
    /// Delivery message identifier (opaque; useful for debugging / idempotency).
    pub message_id: String,
}

/// Request body for `POST /auth/v1/verify`.
#[derive(Debug, Deserialize)]
pub struct VerifyRequest {
    /// Email address the `OTP` was sent to.
    pub email: String,
    /// The 6-digit code.
    pub code:  String,
}

// ─── Handlers ─────────────────────────────────────────────────────────────────

/// `POST /auth/v1/otp`
///
/// Generates a 6-digit `OTP`, stores it, and delivers it via the configured
/// email backend. Returns 200 with a `message_id` on success.
///
/// Returns 429 if the per-email send rate limit is exceeded.
///
/// # Errors
///
/// Returns 422 Unprocessable Entity if the email is blank.
/// Returns 429 Too Many Requests if the rate limit is exceeded.
/// Returns 500 Internal Server Error if delivery fails.
pub async fn otp_send(
    State(state): State<Arc<OtpRouteState>>,
    Json(req): Json<OtpRequest>,
) -> Response {
    let email = req.email.trim().to_lowercase();
    if email.is_empty() {
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(serde_json::json!({
                "error": "invalid_email",
                "message": "email must not be blank"
            })),
        )
            .into_response();
    }

    let code = match state.otp_store.create_otp(&email).await {
        Ok(c) => c,
        Err(AuthError::RateLimited { retry_after_secs }) => {
            return (
                StatusCode::TOO_MANY_REQUESTS,
                Json(serde_json::json!({
                    "error":             "rate_limited",
                    "retry_after_secs": retry_after_secs
                })),
            )
                .into_response();
        },
        Err(e) => {
            tracing::error!(error = %e, "OTP store error");
            return (StatusCode::INTERNAL_SERVER_ERROR, "internal error").into_response();
        },
    };

    let message_id = match state.email_delivery.send_otp(&email, &code).await {
        Ok(id) => id,
        Err(e) => {
            tracing::error!(error = %e, "Email delivery failed");
            return (StatusCode::INTERNAL_SERVER_ERROR, "delivery failed").into_response();
        },
    };

    let logger = get_audit_logger();
    logger.log_success(
        AuditEventType::OauthStart,
        SecretType::CsrfToken,
        None,
        &format!("otp_send:{email}"),
    );

    (StatusCode::OK, Json(OtpResponse { message_id })).into_response()
}

/// `POST /auth/v1/verify`
///
/// Validates a 6-digit `OTP` and issues a session token on success.
///
/// Returns 422 if the code is wrong or expired.
/// Returns 429 if the attempt limit is exceeded.
///
/// # Errors
///
/// Returns 422 Unprocessable Entity if the code is invalid or expired.
/// Returns 429 Too Many Requests if the attempt rate limit is exceeded.
pub async fn otp_verify(
    State(state): State<Arc<OtpRouteState>>,
    Json(req): Json<VerifyRequest>,
) -> Response {
    let email = req.email.trim().to_lowercase();
    let logger = get_audit_logger();

    match state.otp_store.verify_otp(&email, &req.code).await {
        Ok(()) => {},
        Err(AuthError::RateLimited { retry_after_secs }) => {
            return (
                StatusCode::TOO_MANY_REQUESTS,
                Json(serde_json::json!({
                    "error":             "rate_limited",
                    "retry_after_secs": retry_after_secs
                })),
            )
                .into_response();
        },
        Err(e) => {
            logger.log_failure(
                AuditEventType::AuthFailure,
                SecretType::CsrfToken,
                None,
                "otp_verify",
                &e.to_string(),
            );
            return (
                StatusCode::UNPROCESSABLE_ENTITY,
                Json(serde_json::json!({
                    "error":   "invalid_otp",
                    "message": "invalid or expired OTP code"
                })),
            )
                .into_response();
        },
    }

    // OTP verified — resolve the local account (#367).
    //
    // Completing the flow proves control of the mailbox, so the email is
    // verified by construction: no provider asserted it, FraiseQL observed it.
    // That is what makes email-keyed linking correct here — the same person
    // signing in later via Google or a local password lands on this account
    // instead of a parallel one.
    let user_id = match &state.account_store {
        Some(accounts) => {
            match accounts
                .link_or_create_user(None, Some(&email), true, OTP_PROVIDER, &email)
                .await
            {
                Ok(result) => result.user_id,
                Err(e) => {
                    tracing::error!(error = %e, "OTP account resolution failed");
                    return (StatusCode::INTERNAL_SERVER_ERROR, "user resolution failed")
                        .into_response();
                },
            }
        },
        None => format!("otp:{email}"),
    };
    let expires_at = match unix_now() {
        Ok(now) => now + 3_600, // 1-hour session
        Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "internal error").into_response(),
    };

    let tokens = match state.session_store.create_session(&user_id, expires_at).await {
        Ok(t) => t,
        Err(e) => {
            tracing::error!(error = %e, "Session creation failed after OTP verify");
            return (StatusCode::INTERNAL_SERVER_ERROR, "session creation failed").into_response();
        },
    };

    logger.log_success(
        AuditEventType::AuthSuccess,
        SecretType::SessionToken,
        Some(user_id),
        "otp_verify",
    );

    (StatusCode::OK, Json(tokens)).into_response()
}

#[cfg(test)]
mod tests;