Skip to main content

auth_framework/auth_modular/mfa/
email.rs

1//! Email-based MFA manager with production-grade email provider integration
2
3use crate::errors::{AuthError, Result};
4use crate::storage::AuthStorage;
5use serde::{Deserialize, Serialize};
6use serde_json::json;
7use std::sync::Arc;
8use std::time::Duration;
9use subtle::ConstantTimeEq;
10use tracing::{debug, error, info};
11
12/// Email provider configuration for production email sending
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct EmailProviderConfig {
15    /// Email provider type
16    pub provider: EmailProvider,
17    /// Sender email address
18    pub from_email: String,
19    /// Sender name
20    pub from_name: Option<String>,
21    /// Provider-specific configuration
22    pub provider_config: ProviderConfig,
23}
24
25/// Supported email providers
26///
27/// `AwsSes` requires the `aws-sdk-ses` crate (not compiled in by default).
28/// When selected without the dependency, `send_email_via_provider` returns a
29/// descriptive error at runtime.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub enum EmailProvider {
32    /// SendGrid email service
33    SendGrid,
34    /// Amazon Simple Email Service.
35    /// Requires the `aws-sdk-ses` crate (not included by default).
36    AwsSes,
37    /// SMTP server
38    Smtp,
39    /// Development mode (console logging only)
40    Development,
41}
42
43/// Provider-specific configuration
44#[derive(Clone, Serialize, Deserialize)]
45pub enum ProviderConfig {
46    /// SendGrid configuration
47    SendGrid {
48        api_key: String,
49        endpoint: Option<String>,
50    },
51    /// AWS SES configuration
52    AwsSes {
53        region: String,
54        access_key_id: String,
55        secret_access_key: String,
56    },
57    /// SMTP configuration
58    Smtp {
59        host: String,
60        port: u16,
61        username: String,
62        password: String,
63        use_tls: bool,
64    },
65    /// Development configuration
66    Development,
67}
68
69impl std::fmt::Debug for ProviderConfig {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        use crate::utils::redact::redacted;
72        match self {
73            Self::SendGrid { api_key, endpoint } => f
74                .debug_struct("SendGrid")
75                .field("api_key", &redacted(api_key))
76                .field("endpoint", endpoint)
77                .finish(),
78            Self::AwsSes {
79                region,
80                access_key_id,
81                secret_access_key,
82            } => f
83                .debug_struct("AwsSes")
84                .field("region", region)
85                .field("access_key_id", access_key_id)
86                .field("secret_access_key", &redacted(secret_access_key))
87                .finish(),
88            Self::Smtp {
89                host,
90                port,
91                username,
92                password,
93                use_tls,
94            } => f
95                .debug_struct("Smtp")
96                .field("host", host)
97                .field("port", port)
98                .field("username", username)
99                .field("password", &redacted(password))
100                .field("use_tls", use_tls)
101                .finish(),
102            Self::Development => f.write_str("Development"),
103        }
104    }
105}
106
107impl Default for EmailProviderConfig {
108    fn default() -> Self {
109        Self {
110            provider: EmailProvider::Development,
111            from_email: "noreply@example.com".to_string(),
112            from_name: Some("AuthFramework".to_string()),
113            provider_config: ProviderConfig::Development,
114        }
115    }
116}
117
118/// Email manager for handling email-based MFA with production providers
119pub struct EmailManager {
120    storage: Arc<dyn AuthStorage>,
121    email_config: EmailProviderConfig,
122}
123
124impl EmailManager {
125    /// Create a new email manager with default development configuration
126    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
127        Self {
128            storage,
129            email_config: EmailProviderConfig::default(),
130        }
131    }
132
133    /// Create a new email manager with custom provider configuration
134    pub fn new_with_config(
135        storage: Arc<dyn AuthStorage>,
136        email_config: EmailProviderConfig,
137    ) -> Self {
138        Self {
139            storage,
140            email_config,
141        }
142    }
143
144    /// Register email for email MFA
145    pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
146        debug!("Registering email for user '{}'", user_id);
147
148        // Validate email format
149        if email.is_empty() {
150            return Err(AuthError::validation("Email address cannot be empty"));
151        }
152
153        // Basic email validation
154        if !email.contains('@') || !email.contains('.') {
155            return Err(AuthError::validation(
156                "Email address must be in valid format (user@domain.com)",
157            ));
158        }
159
160        // More comprehensive email validation
161        let parts: Vec<&str> = email.split('@').collect();
162        if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
163            return Err(AuthError::validation("Email address format is invalid"));
164        }
165
166        let domain = parts[1];
167        if !domain.contains('.') || domain.starts_with('.') || domain.ends_with('.') {
168            return Err(AuthError::validation("Email domain format is invalid"));
169        }
170
171        // Store email in user's profile/data
172        let key = format!("user:{}:email", user_id);
173        self.storage.store_kv(&key, email.as_bytes(), None).await?;
174
175        info!("Email registered for user '{}': {}", user_id, email);
176        Ok(())
177    }
178
179    /// Initiate email challenge
180    pub async fn initiate_challenge(&self, user_id: &str) -> Result<String> {
181        debug!("Initiating email challenge for user '{}'", user_id);
182
183        let challenge_id = crate::utils::string::generate_id(Some("email"));
184
185        info!("Email challenge initiated for user '{}'", user_id);
186        Ok(challenge_id)
187    }
188
189    /// Generate email code
190    pub async fn generate_code(&self, challenge_id: &str) -> Result<String> {
191        debug!("Generating email code for challenge '{}'", challenge_id);
192
193        let code = format!("{:06}", rand::random::<u32>() % 1000000);
194
195        // Store the code for later verification
196        let email_key = format!("email_challenge:{}:code", challenge_id);
197        self.storage
198            .store_kv(
199                &email_key,
200                code.as_bytes(),
201                Some(Duration::from_secs(300)), // 5 minute expiry
202            )
203            .await?;
204
205        Ok(code)
206    }
207
208    /// Verify email code
209    pub async fn verify_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
210        debug!("Verifying email code for challenge '{}'", challenge_id);
211
212        // Validate input parameters
213        if challenge_id.is_empty() {
214            return Err(AuthError::validation("Challenge ID cannot be empty"));
215        }
216
217        if code.is_empty() {
218            return Err(AuthError::validation("Email code cannot be empty"));
219        }
220
221        // Check if challenge exists by looking for stored code
222        let email_key = format!("email_challenge:{}:code", challenge_id);
223        if let Some(stored_code_data) = self.storage.get_kv(&email_key).await? {
224            let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
225
226            // Validate code format
227            let is_valid_format = code.len() == 6 && code.chars().all(|c| c.is_ascii_digit());
228
229            if !is_valid_format {
230                return Ok(false);
231            }
232
233            // Verify against stored code (constant-time to prevent timing attacks)
234            let is_valid: bool = stored_code.as_bytes().ct_eq(code.as_bytes()).into();
235
236            if is_valid {
237                // Remove the code after successful verification to prevent reuse
238                let _ = self.storage.delete_kv(&email_key).await;
239            }
240
241            Ok(is_valid)
242        } else {
243            // Challenge not found or expired
244            Err(AuthError::validation("Invalid or expired challenge ID"))
245        }
246    }
247
248    /// Send email verification code to the user via the configured email provider
249    pub async fn send_code(&self, user_id: &str, code: &str) -> Result<()> {
250        debug!("Sending email code to user '{}'", user_id);
251
252        // Get user's email address
253        let email_key = format!("user:{}:email", user_id);
254        if let Some(email_data) = self.storage.get_kv(&email_key).await? {
255            let email_address = String::from_utf8(email_data).map_err(|e| {
256                AuthError::internal(format!("Failed to parse email address: {}", e))
257            })?;
258
259            // Production-grade email sending with multiple provider support
260            match self.send_email_via_provider(&email_address, "MFA Code", &format!(
261                "Your authentication code is: {}\n\nThis code will expire in 5 minutes.\nIf you didn't request this code, please ignore this email.",
262                code
263            )).await {
264                Ok(()) => {
265                    info!(
266                        "Email code sent successfully to {} for user '{}' via {:?}",
267                        email_address, user_id, self.email_config.provider
268                    );
269                    Ok(())
270                }
271                Err(e) => {
272                    error!(
273                        "Failed to send email code to {} for user '{}': {}",
274                        email_address, user_id, e
275                    );
276                    Err(e)
277                }
278            }
279        } else {
280            Err(AuthError::validation(
281                "No email address registered for user",
282            ))
283        }
284    }
285
286    /// Get user's email address
287    pub async fn get_user_email(&self, user_id: &str) -> Result<Option<String>> {
288        let email_key = format!("user:{}:email", user_id);
289
290        if let Some(email_data) = self.storage.get_kv(&email_key).await? {
291            Ok(Some(String::from_utf8(email_data).map_err(|e| {
292                AuthError::internal(format!("Failed to parse email address: {}", e))
293            })?))
294        } else {
295            Ok(None)
296        }
297    }
298
299    /// Send email via configured provider with production-grade implementation
300    async fn send_email_via_provider(
301        &self,
302        to_email: &str,
303        subject: &str,
304        body: &str,
305    ) -> Result<()> {
306        match &self.email_config.provider {
307            EmailProvider::SendGrid => self.send_via_sendgrid(to_email, subject, body).await,
308            EmailProvider::AwsSes => self.send_via_aws_ses(to_email, subject, body).await,
309            EmailProvider::Smtp => self.send_via_smtp(to_email, subject, body).await,
310            EmailProvider::Development => {
311                // Development mode: log to console instead of sending
312                info!("📧 [DEVELOPMENT] Email would be sent:");
313                info!("   To: {}", to_email);
314                info!("   Subject: {}", subject);
315                info!("   Body: <{} bytes, not logged>", body.len());
316                Ok(())
317            }
318        }
319    }
320
321    /// Send email via SendGrid API
322    async fn send_via_sendgrid(&self, to_email: &str, subject: &str, body: &str) -> Result<()> {
323        if let ProviderConfig::SendGrid { api_key, endpoint } = &self.email_config.provider_config {
324            let client = reqwest::Client::new();
325            let sendgrid_endpoint = endpoint
326                .as_deref()
327                .unwrap_or("https://api.sendgrid.com/v3/mail/send");
328
329            let payload = json!({
330                "personalizations": [{
331                    "to": [{"email": to_email}]
332                }],
333                "from": {
334                    "email": self.email_config.from_email,
335                    "name": self.email_config.from_name.as_deref().unwrap_or("AuthFramework")
336                },
337                "subject": subject,
338                "content": [{
339                    "type": "text/plain",
340                    "value": body
341                }]
342            });
343
344            let response = client
345                .post(sendgrid_endpoint)
346                .header("Authorization", format!("Bearer {}", api_key))
347                .header("Content-Type", "application/json")
348                .json(&payload)
349                .send()
350                .await
351                .map_err(|e| AuthError::internal(format!("SendGrid request failed: {}", e)))?;
352
353            let status = response.status();
354            if status.is_success() {
355                debug!("SendGrid email sent successfully to {}", to_email);
356                Ok(())
357            } else {
358                let error_text = response.text().await.unwrap_or_default();
359                Err(AuthError::internal(format!(
360                    "SendGrid API error: {} - {}",
361                    status, error_text
362                )))
363            }
364        } else {
365            Err(AuthError::internal("Invalid SendGrid configuration"))
366        }
367    }
368
369    /// Send email via AWS SES using the SendEmail REST API (v2)
370    async fn send_via_aws_ses(&self, to_email: &str, subject: &str, body: &str) -> Result<()> {
371        if let ProviderConfig::AwsSes {
372            region,
373            access_key_id,
374            secret_access_key,
375        } = &self.email_config.provider_config
376        {
377            let from_email = &self.email_config.from_email;
378            let from_name = self
379                .email_config
380                .from_name
381                .as_deref()
382                .unwrap_or("AuthFramework");
383
384            let host = format!("email.{}.amazonaws.com", region);
385            let url = format!("https://{}/v2/email/outbound-emails", host);
386            let now = chrono::Utc::now();
387            let date_stamp = now.format("%Y%m%d").to_string();
388            let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
389
390            let payload = serde_json::json!({
391                "Content": {
392                    "Simple": {
393                        "Subject": { "Data": subject, "Charset": "UTF-8" },
394                        "Body": { "Text": { "Data": body, "Charset": "UTF-8" } }
395                    }
396                },
397                "Destination": {
398                    "ToAddresses": [to_email]
399                },
400                "FromEmailAddress": format!("{} <{}>", from_name, from_email)
401            });
402            let payload_bytes = serde_json::to_vec(&payload).map_err(|e| {
403                AuthError::internal(format!("SES payload serialization failed: {}", e))
404            })?;
405
406            // AWS Signature Version 4
407            let payload_hash = ses_sha256_hex(&payload_bytes);
408            let canonical_headers = format!(
409                "content-type:application/json\nhost:{}\nx-amz-date:{}\n",
410                host, amz_date
411            );
412            let signed_headers = "content-type;host;x-amz-date";
413            let canonical_request = format!(
414                "POST\n/v2/email/outbound-emails\n\n{}\n{}\n{}",
415                canonical_headers, signed_headers, payload_hash
416            );
417
418            let credential_scope = format!("{}/{}/ses/aws4_request", date_stamp, region);
419            let string_to_sign = format!(
420                "AWS4-HMAC-SHA256\n{}\n{}\n{}",
421                amz_date,
422                credential_scope,
423                ses_sha256_hex(canonical_request.as_bytes())
424            );
425
426            let signing_key =
427                ses_sigv4_key(secret_access_key.as_bytes(), &date_stamp, region, "ses");
428            let signature = ses_hmac_sha256_hex(&signing_key, string_to_sign.as_bytes());
429
430            let authorization = format!(
431                "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}",
432                access_key_id, credential_scope, signed_headers, signature
433            );
434
435            let client = reqwest::Client::new();
436            let resp = client
437                .post(&url)
438                .header("Content-Type", "application/json")
439                .header("x-amz-date", &amz_date)
440                .header("Authorization", &authorization)
441                .body(payload_bytes)
442                .send()
443                .await
444                .map_err(|e| AuthError::internal(format!("AWS SES request failed: {}", e)))?;
445
446            let status = resp.status();
447            if status.is_success() {
448                debug!("AWS SES email sent successfully to {}", to_email);
449                Ok(())
450            } else {
451                let error_text = resp.text().await.unwrap_or_default();
452                Err(AuthError::internal(format!(
453                    "AWS SES error ({}): {}",
454                    status, error_text
455                )))
456            }
457        } else {
458            Err(AuthError::internal("Invalid AWS SES configuration"))
459        }
460    }
461
462    /// Send email via SMTP using lettre
463    async fn send_via_smtp(&self, to_email: &str, subject: &str, body: &str) -> Result<()> {
464        if let ProviderConfig::Smtp {
465            host,
466            port,
467            username,
468            password,
469            use_tls,
470        } = &self.email_config.provider_config
471        {
472            use lettre::{
473                Message, SmtpTransport, Transport, transport::smtp::authentication::Credentials,
474            };
475
476            let from_address = self.email_config.from_email.clone();
477            let from_name = self
478                .email_config
479                .from_name
480                .clone()
481                .unwrap_or_else(|| "AuthFramework".to_string());
482
483            let email = Message::builder()
484                .from(
485                    format!("{} <{}>", from_name, from_address)
486                        .parse()
487                        .map_err(|e| AuthError::internal(format!("Invalid from address: {}", e)))?,
488                )
489                .to(to_email
490                    .parse()
491                    .map_err(|e| AuthError::internal(format!("Invalid to address: {}", e)))?)
492                .subject(subject)
493                .body(body.to_string())
494                .map_err(|e| AuthError::internal(format!("Failed to build email: {}", e)))?;
495
496            let creds = Credentials::new(username.clone(), password.clone());
497
498            let host = host.clone();
499            let port = *port;
500            let use_tls = *use_tls;
501
502            // lettre's SmtpTransport is sync; run in a blocking task to avoid
503            // blocking the async runtime.
504            let result = tokio::task::spawn_blocking(move || {
505                let transport = if use_tls {
506                    SmtpTransport::relay(&host)
507                        .map_err(|e| AuthError::internal(format!("SMTP relay error: {}", e)))?
508                        .port(port)
509                        .credentials(creds)
510                        .build()
511                } else {
512                    SmtpTransport::builder_dangerous(&host)
513                        .port(port)
514                        .credentials(creds)
515                        .build()
516                };
517
518                transport
519                    .send(&email)
520                    .map_err(|e| AuthError::internal(format!("SMTP send failed: {}", e)))
521            })
522            .await
523            .map_err(|e| AuthError::internal(format!("SMTP task join error: {}", e)))?;
524
525            result?;
526            debug!("SMTP email sent successfully to {}", to_email);
527            Ok(())
528        } else {
529            Err(AuthError::internal("Invalid SMTP configuration"))
530        }
531    }
532
533    /// Check if user has email configured
534    pub async fn has_email(&self, user_id: &str) -> Result<bool> {
535        let email_key = format!("user:{}:email", user_id);
536        match self.storage.get_kv(&email_key).await {
537            Ok(Some(_)) => Ok(true),
538            Ok(None) => Ok(false),
539            Err(_) => Ok(false), // Assume false on error
540        }
541    }
542
543    /// Send email code and return the generated code
544    pub async fn send_email_code(&self, user_id: &str) -> Result<String> {
545        // Generate a 6-digit code
546        let code = format!("{:06}", rand::random::<u32>() % 1_000_000);
547
548        // Send the code via the configured email provider
549        self.send_code(user_id, &code).await?;
550
551        // Store the code for later verification
552        let email_key = format!("email_code:{}", user_id);
553        self.storage
554            .store_kv(
555                &email_key,
556                code.as_bytes(),
557                Some(std::time::Duration::from_secs(300)),
558            )
559            .await?;
560
561        Ok(code)
562    }
563}
564
565// ── AWS SigV4 helpers for SES ───────────────────────────────────────────────
566
567fn ses_sha256_hex(data: &[u8]) -> String {
568    use ring::digest;
569    let d = digest::digest(&digest::SHA256, data);
570    hex::encode(d.as_ref())
571}
572
573fn ses_hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
574    use ring::hmac;
575    let s_key = hmac::Key::new(hmac::HMAC_SHA256, key);
576    hmac::sign(&s_key, data).as_ref().to_vec()
577}
578
579fn ses_hmac_sha256_hex(key: &[u8], data: &[u8]) -> String {
580    hex::encode(ses_hmac_sha256(key, data))
581}
582
583fn ses_sigv4_key(secret: &[u8], date_stamp: &str, region: &str, service: &str) -> Vec<u8> {
584    let k_date = ses_hmac_sha256(&[b"AWS4", secret].concat(), date_stamp.as_bytes());
585    let k_region = ses_hmac_sha256(&k_date, region.as_bytes());
586    let k_service = ses_hmac_sha256(&k_region, service.as_bytes());
587    ses_hmac_sha256(&k_service, b"aws4_request")
588}