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