Skip to main content

auth_framework/api/
email_verification.rs

1//! Email Verification API Endpoints
2//!
3//! Handles email address verification through token-based confirmation.
4//!
5//! ## Storage keys
6//! - `email_verify:{token}` — user_id bytes, TTL 24 hours (verification link)
7//! - User JSON `email_verified` field — `true` once verified
8//!
9//! ## Flow
10//! 1. User registers → `email_verified` set to `false` in user record
11//! 2. `POST /auth/verify-email/send` → generates a verification token and hands it to the
12//!    configured [`EmailVerificationSender`]
13//! 3. `POST /auth/verify-email` → verifies token, sets `email_verified: true`
14//! 4. `POST /auth/resend-verification` → same as 2 for a not-yet-logged-in user
15//!
16//! The token proves control of the mailbox, so it is delivered ONLY through the sender
17//! (see [`ApiState::with_email_verification_sender`]) and is never part of a response.
18//! Without a sender nothing can be delivered and verification cannot complete.
19
20use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
21use axum::{Json, extract::State, http::HeaderMap};
22use ring::rand::SecureRandom;
23use serde::{Deserialize, Serialize};
24use std::time::Duration;
25
26/// Delivers a verification token to the mailbox it proves ownership of.
27///
28/// The token is a proof of inbox control, so it must travel ONLY through this channel and
29/// never appear in an HTTP response. Implementations send `token` to `email`; failures are
30/// logged by the caller (without the error text) and never reported to the requester. Errors
31/// returned here must not contain the token.
32#[async_trait::async_trait]
33pub trait EmailVerificationSender: Send + Sync {
34    /// Send `token` to `email`, the address registered for `user_id`.
35    async fn send_verification_token(
36        &self,
37        email: &str,
38        user_id: &str,
39        token: &str,
40    ) -> crate::errors::Result<()>;
41}
42
43/// 24-hour TTL for verification tokens.
44const VERIFICATION_TOKEN_TTL: Duration = Duration::from_secs(24 * 60 * 60);
45
46/// KV key prefix for email verification tokens.
47const VERIFY_KEY_PREFIX: &str = "email_verify:";
48
49/// Response to a request to send a verification message. It never contains the token.
50#[derive(Debug, Serialize)]
51pub struct VerificationSentResponse {
52    /// Whether a request was accepted (identical for every address on the public path).
53    pub sent: bool,
54    /// Human-readable message.
55    pub message: String,
56}
57
58const GENERIC_SENT_MESSAGE: &str = "If an account with that email exists and is not yet verified, a verification message has been sent.";
59
60fn generic_sent() -> ApiResponse<VerificationSentResponse> {
61    ApiResponse::success(VerificationSentResponse {
62        sent: true,
63        message: GENERIC_SENT_MESSAGE.to_string(),
64    })
65}
66
67/// Mint a token for `user_id`, store it, and deliver it to `email` through the sender.
68/// Delivery problems are logged and never reported to the requester.
69async fn issue_and_deliver(
70    state: &ApiState,
71    user_id: &str,
72    email: &str,
73) -> Result<(), &'static str> {
74    let token = generate_verification_token().map_err(|_| "token generation failed")?;
75    let verify_key = format!("{VERIFY_KEY_PREFIX}{token}");
76    // The token is bound to the address it is mailed to, so a later change of the
77    // account's address cannot be verified with a message sent to the old one.
78    let binding = serde_json::json!({ "user_id": user_id, "email": email });
79    state
80        .auth_framework
81        .storage()
82        .store_kv(
83            &verify_key,
84            binding.to_string().as_bytes(),
85            Some(VERIFICATION_TOKEN_TTL),
86        )
87        .await
88        .map_err(|_| "token storage failed")?;
89    match &state.email_verification_sender {
90        Some(sender) => {
91            // Delivery runs off the request path so that a slow mail gateway cannot be
92            // used to tell a pending address from an unknown or verified one by timing.
93            let sender = sender.clone();
94            let (email, user_id) = (email.to_string(), user_id.to_string());
95            tokio::spawn(async move {
96                if sender
97                    .send_verification_token(&email, &user_id, &token)
98                    .await
99                    .is_err()
100                {
101                    // The sender's error text is deliberately not logged: it could echo the token.
102                    tracing::error!(user_id, "Verification message could not be delivered");
103                }
104            });
105        }
106        None => tracing::warn!(
107            user_id,
108            "No EmailVerificationSender configured; verification token cannot be delivered"
109        ),
110    }
111    Ok(())
112}
113
114/// Request body for `POST /auth/verify-email`.
115#[derive(Deserialize)]
116pub struct VerifyEmailRequest {
117    /// The verification token received via email or API.
118    pub token: String,
119}
120
121impl std::fmt::Debug for VerifyEmailRequest {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        let mut d = f.debug_struct("VerifyEmailRequest");
124        d.field("token", &crate::utils::redact::redacted(&self.token));
125        d.finish()
126    }
127}
128
129/// Request body for `POST /auth/resend-verification`.
130#[derive(Debug, Deserialize)]
131pub struct ResendVerificationRequest {
132    /// The email address to resend verification for.
133    pub email: String,
134}
135
136/// Generate a URL-safe verification token using the system CSPRNG.
137fn generate_verification_token() -> Result<String, crate::errors::AuthError> {
138    let rng = ring::rand::SystemRandom::new();
139    let mut buf = [0u8; 32];
140    rng.fill(&mut buf)
141        .map_err(|_| crate::errors::AuthError::crypto("Failed to generate verification token"))?;
142    Ok(base64::Engine::encode(
143        &base64::engine::general_purpose::URL_SAFE_NO_PAD,
144        buf,
145    ))
146}
147
148/// `POST /auth/verify-email/send`
149///
150/// Sends a verification message to the authenticated user's email address through the
151/// configured [`EmailVerificationSender`]. Requires a valid bearer token.
152pub async fn send_verification(
153    State(state): State<ApiState>,
154    headers: HeaderMap,
155) -> ApiResponse<VerificationSentResponse> {
156    let token = match extract_bearer_token(&headers) {
157        Some(t) => t,
158        None => {
159            return ApiResponse::error_typed("AUTH_REQUIRED", "Bearer token required");
160        }
161    };
162
163    let auth_token = match validate_api_token(&state.auth_framework, &token).await {
164        Ok(t) => t,
165        Err(_) => {
166            return ApiResponse::error_typed("INVALID_TOKEN", "Invalid or expired token");
167        }
168    };
169
170    let user_id = &auth_token.user_id;
171
172    // Check if already verified
173    let user_key = format!("user:{user_id}");
174    let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
175        Ok(Some(b)) => b,
176        _ => {
177            return ApiResponse::error_typed("USER_NOT_FOUND", "User not found");
178        }
179    };
180    let user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
181        Ok(v) => v,
182        Err(_) => {
183            return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to read user record");
184        }
185    };
186
187    if user_json
188        .get("email_verified")
189        .and_then(|v| v.as_bool())
190        .unwrap_or(false)
191    {
192        return ApiResponse::success(VerificationSentResponse {
193            sent: false,
194            message: "Email is already verified".to_string(),
195        });
196    }
197
198    let email = match user_json.get("email").and_then(|v| v.as_str()) {
199        Some(e) if !e.is_empty() => e.to_string(),
200        _ => return ApiResponse::error_typed("INTERNAL_ERROR", "User has no email address"),
201    };
202    if issue_and_deliver(&state, user_id, &email).await.is_err() {
203        return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to create verification token");
204    }
205    generic_sent()
206}
207
208/// `POST /auth/verify-email`
209///
210/// Verifies a user's email address using the provided token.
211/// This endpoint is public (no bearer token required) since the
212/// verification token itself serves as proof of email ownership.
213pub async fn verify_email(
214    State(state): State<ApiState>,
215    Json(body): Json<VerifyEmailRequest>,
216) -> ApiResponse<serde_json::Value> {
217    if body.token.is_empty() {
218        return ApiResponse::error_typed("VALIDATION_ERROR", "Verification token is required");
219    }
220
221    // Look up verification token
222    let verify_key = format!("{VERIFY_KEY_PREFIX}{}", body.token);
223    let binding_bytes = match state.auth_framework.storage().get_kv(&verify_key).await {
224        Ok(Some(b)) => b,
225        Ok(None) => {
226            return ApiResponse::error_typed(
227                "INVALID_TOKEN",
228                "Verification token is invalid or expired",
229            );
230        }
231        Err(_) => {
232            return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to look up token");
233        }
234    };
235
236    // A token names the account AND the address it was mailed to. Anything else (including
237    // tokens stored in an older format) is not accepted.
238    let binding: serde_json::Value = match serde_json::from_slice(&binding_bytes) {
239        Ok(v) => v,
240        Err(_) => {
241            return ApiResponse::error_typed(
242                "INVALID_TOKEN",
243                "Verification token is invalid or expired",
244            );
245        }
246    };
247    let (Some(user_id), Some(bound_email)) = (
248        binding["user_id"].as_str().map(String::from),
249        binding["email"].as_str().map(String::from),
250    ) else {
251        return ApiResponse::error_typed(
252            "INVALID_TOKEN",
253            "Verification token is invalid or expired",
254        );
255    };
256
257    // Update user record: set email_verified = true
258    let user_key = format!("user:{user_id}");
259    let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
260        Ok(Some(b)) => b,
261        _ => {
262            return ApiResponse::error_typed("USER_NOT_FOUND", "User not found");
263        }
264    };
265
266    let mut user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
267        Ok(v) => v,
268        Err(_) => {
269            return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to read user record");
270        }
271    };
272
273    // The token only proves control of the address it was mailed to.
274    if user_json["email"].as_str() != Some(bound_email.as_str()) {
275        let _ = state.auth_framework.storage().delete_kv(&verify_key).await;
276        return ApiResponse::error_typed(
277            "INVALID_TOKEN",
278            "Verification token is invalid or expired",
279        );
280    }
281
282    user_json["email_verified"] = serde_json::Value::Bool(true);
283
284    if state
285        .auth_framework
286        .storage()
287        .store_kv(&user_key, user_json.to_string().as_bytes(), None)
288        .await
289        .is_err()
290    {
291        return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to update user record");
292    }
293
294    // Delete the used verification token (one-time use)
295    let _ = state.auth_framework.storage().delete_kv(&verify_key).await;
296
297    ApiResponse::success(serde_json::json!({
298        "verified": true,
299        "user_id": user_id,
300        "message": "Email address verified successfully"
301    }))
302}
303
304/// `POST /auth/resend-verification`
305///
306/// Sends a new verification message to the given email address. This endpoint is public
307/// so users who haven't logged in yet can request a new verification; it returns the same
308/// response for every address. Rate limiting should be applied at the middleware level.
309pub async fn resend_verification(
310    State(state): State<ApiState>,
311    Json(body): Json<ResendVerificationRequest>,
312) -> ApiResponse<VerificationSentResponse> {
313    if body.email.is_empty() {
314        return ApiResponse::error_typed("VALIDATION_ERROR", "Email address is required");
315    }
316
317    // Every outcome below (unknown address, already verified, mail sent, mail failed)
318    // returns the same response, so the endpoint reveals nothing about the account.
319    let email_key = format!("user:email:{}", body.email);
320    let Ok(Some(id_bytes)) = state.auth_framework.storage().get_kv(&email_key).await else {
321        return generic_sent();
322    };
323    let Ok(user_id) = String::from_utf8(id_bytes) else {
324        return generic_sent();
325    };
326    let Ok(Some(user_bytes)) = state
327        .auth_framework
328        .storage()
329        .get_kv(&format!("user:{user_id}"))
330        .await
331    else {
332        return generic_sent();
333    };
334    let Ok(user_json) = serde_json::from_slice::<serde_json::Value>(&user_bytes) else {
335        return generic_sent();
336    };
337    if user_json
338        .get("email_verified")
339        .and_then(|v| v.as_bool())
340        .unwrap_or(false)
341    {
342        return generic_sent();
343    }
344
345    // Only the address on the account record receives a token; a stale index entry
346    // pointing at a changed address is ignored.
347    if user_json.get("email").and_then(|v| v.as_str()) != Some(body.email.as_str()) {
348        return generic_sent();
349    }
350    if issue_and_deliver(&state, &user_id, &body.email)
351        .await
352        .is_err()
353    {
354        tracing::error!(user_id, "Could not create a verification token");
355    }
356    generic_sent()
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    #[test]
364    fn test_generate_verification_token() {
365        let token1 = generate_verification_token().expect("should generate token");
366        let token2 = generate_verification_token().expect("should generate token");
367        // Tokens should be unique
368        assert_ne!(token1, token2);
369        // 32 bytes → 43 chars in URL-safe base64 (no padding)
370        assert_eq!(token1.len(), 43);
371        // Should be URL-safe
372        assert!(!token1.contains('+'));
373        assert!(!token1.contains('/'));
374    }
375
376    #[test]
377    fn test_verification_token_ttl() {
378        assert_eq!(VERIFICATION_TOKEN_TTL.as_secs(), 86400);
379    }
380}