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(Debug, Deserialize)]
116pub struct VerifyEmailRequest {
117    /// The verification token received via email or API.
118    pub token: String,
119}
120
121/// Request body for `POST /auth/resend-verification`.
122#[derive(Debug, Deserialize)]
123pub struct ResendVerificationRequest {
124    /// The email address to resend verification for.
125    pub email: String,
126}
127
128/// Generate a URL-safe verification token using the system CSPRNG.
129fn generate_verification_token() -> Result<String, crate::errors::AuthError> {
130    let rng = ring::rand::SystemRandom::new();
131    let mut buf = [0u8; 32];
132    rng.fill(&mut buf)
133        .map_err(|_| crate::errors::AuthError::crypto("Failed to generate verification token"))?;
134    Ok(base64::Engine::encode(
135        &base64::engine::general_purpose::URL_SAFE_NO_PAD,
136        buf,
137    ))
138}
139
140/// `POST /auth/verify-email/send`
141///
142/// Sends a verification message to the authenticated user's email address through the
143/// configured [`EmailVerificationSender`]. Requires a valid bearer token.
144pub async fn send_verification(
145    State(state): State<ApiState>,
146    headers: HeaderMap,
147) -> ApiResponse<VerificationSentResponse> {
148    let token = match extract_bearer_token(&headers) {
149        Some(t) => t,
150        None => {
151            return ApiResponse::error_typed("AUTH_REQUIRED", "Bearer token required");
152        }
153    };
154
155    let auth_token = match validate_api_token(&state.auth_framework, &token).await {
156        Ok(t) => t,
157        Err(_) => {
158            return ApiResponse::error_typed("INVALID_TOKEN", "Invalid or expired token");
159        }
160    };
161
162    let user_id = &auth_token.user_id;
163
164    // Check if already verified
165    let user_key = format!("user:{user_id}");
166    let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
167        Ok(Some(b)) => b,
168        _ => {
169            return ApiResponse::error_typed("USER_NOT_FOUND", "User not found");
170        }
171    };
172    let user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
173        Ok(v) => v,
174        Err(_) => {
175            return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to read user record");
176        }
177    };
178
179    if user_json
180        .get("email_verified")
181        .and_then(|v| v.as_bool())
182        .unwrap_or(false)
183    {
184        return ApiResponse::success(VerificationSentResponse {
185            sent: false,
186            message: "Email is already verified".to_string(),
187        });
188    }
189
190    let email = match user_json.get("email").and_then(|v| v.as_str()) {
191        Some(e) if !e.is_empty() => e.to_string(),
192        _ => return ApiResponse::error_typed("INTERNAL_ERROR", "User has no email address"),
193    };
194    if issue_and_deliver(&state, user_id, &email).await.is_err() {
195        return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to create verification token");
196    }
197    generic_sent()
198}
199
200/// `POST /auth/verify-email`
201///
202/// Verifies a user's email address using the provided token.
203/// This endpoint is public (no bearer token required) since the
204/// verification token itself serves as proof of email ownership.
205pub async fn verify_email(
206    State(state): State<ApiState>,
207    Json(body): Json<VerifyEmailRequest>,
208) -> ApiResponse<serde_json::Value> {
209    if body.token.is_empty() {
210        return ApiResponse::error_typed("VALIDATION_ERROR", "Verification token is required");
211    }
212
213    // Look up verification token
214    let verify_key = format!("{VERIFY_KEY_PREFIX}{}", body.token);
215    let binding_bytes = match state.auth_framework.storage().get_kv(&verify_key).await {
216        Ok(Some(b)) => b,
217        Ok(None) => {
218            return ApiResponse::error_typed(
219                "INVALID_TOKEN",
220                "Verification token is invalid or expired",
221            );
222        }
223        Err(_) => {
224            return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to look up token");
225        }
226    };
227
228    // A token names the account AND the address it was mailed to. Anything else (including
229    // tokens stored in an older format) is not accepted.
230    let binding: serde_json::Value = match serde_json::from_slice(&binding_bytes) {
231        Ok(v) => v,
232        Err(_) => {
233            return ApiResponse::error_typed(
234                "INVALID_TOKEN",
235                "Verification token is invalid or expired",
236            );
237        }
238    };
239    let (Some(user_id), Some(bound_email)) = (
240        binding["user_id"].as_str().map(String::from),
241        binding["email"].as_str().map(String::from),
242    ) else {
243        return ApiResponse::error_typed(
244            "INVALID_TOKEN",
245            "Verification token is invalid or expired",
246        );
247    };
248
249    // Update user record: set email_verified = true
250    let user_key = format!("user:{user_id}");
251    let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
252        Ok(Some(b)) => b,
253        _ => {
254            return ApiResponse::error_typed("USER_NOT_FOUND", "User not found");
255        }
256    };
257
258    let mut user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
259        Ok(v) => v,
260        Err(_) => {
261            return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to read user record");
262        }
263    };
264
265    // The token only proves control of the address it was mailed to.
266    if user_json["email"].as_str() != Some(bound_email.as_str()) {
267        let _ = state.auth_framework.storage().delete_kv(&verify_key).await;
268        return ApiResponse::error_typed(
269            "INVALID_TOKEN",
270            "Verification token is invalid or expired",
271        );
272    }
273
274    user_json["email_verified"] = serde_json::Value::Bool(true);
275
276    if state
277        .auth_framework
278        .storage()
279        .store_kv(&user_key, user_json.to_string().as_bytes(), None)
280        .await
281        .is_err()
282    {
283        return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to update user record");
284    }
285
286    // Delete the used verification token (one-time use)
287    let _ = state.auth_framework.storage().delete_kv(&verify_key).await;
288
289    ApiResponse::success(serde_json::json!({
290        "verified": true,
291        "user_id": user_id,
292        "message": "Email address verified successfully"
293    }))
294}
295
296/// `POST /auth/resend-verification`
297///
298/// Sends a new verification message to the given email address. This endpoint is public
299/// so users who haven't logged in yet can request a new verification; it returns the same
300/// response for every address. Rate limiting should be applied at the middleware level.
301pub async fn resend_verification(
302    State(state): State<ApiState>,
303    Json(body): Json<ResendVerificationRequest>,
304) -> ApiResponse<VerificationSentResponse> {
305    if body.email.is_empty() {
306        return ApiResponse::error_typed("VALIDATION_ERROR", "Email address is required");
307    }
308
309    // Every outcome below (unknown address, already verified, mail sent, mail failed)
310    // returns the same response, so the endpoint reveals nothing about the account.
311    let email_key = format!("user:email:{}", body.email);
312    let Ok(Some(id_bytes)) = state.auth_framework.storage().get_kv(&email_key).await else {
313        return generic_sent();
314    };
315    let Ok(user_id) = String::from_utf8(id_bytes) else {
316        return generic_sent();
317    };
318    let Ok(Some(user_bytes)) = state
319        .auth_framework
320        .storage()
321        .get_kv(&format!("user:{user_id}"))
322        .await
323    else {
324        return generic_sent();
325    };
326    let Ok(user_json) = serde_json::from_slice::<serde_json::Value>(&user_bytes) else {
327        return generic_sent();
328    };
329    if user_json
330        .get("email_verified")
331        .and_then(|v| v.as_bool())
332        .unwrap_or(false)
333    {
334        return generic_sent();
335    }
336
337    // Only the address on the account record receives a token; a stale index entry
338    // pointing at a changed address is ignored.
339    if user_json.get("email").and_then(|v| v.as_str()) != Some(body.email.as_str()) {
340        return generic_sent();
341    }
342    if issue_and_deliver(&state, &user_id, &body.email)
343        .await
344        .is_err()
345    {
346        tracing::error!(user_id, "Could not create a verification token");
347    }
348    generic_sent()
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn test_generate_verification_token() {
357        let token1 = generate_verification_token().expect("should generate token");
358        let token2 = generate_verification_token().expect("should generate token");
359        // Tokens should be unique
360        assert_ne!(token1, token2);
361        // 32 bytes → 43 chars in URL-safe base64 (no padding)
362        assert_eq!(token1.len(), 43);
363        // Should be URL-safe
364        assert!(!token1.contains('+'));
365        assert!(!token1.contains('/'));
366    }
367
368    #[test]
369    fn test_verification_token_ttl() {
370        assert_eq!(VERIFICATION_TOKEN_TTL.as_secs(), 86400);
371    }
372}