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 tracing::{debug, error, info, warn};
10
11/// Email provider configuration for production email sending
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct EmailProviderConfig {
14    /// Email provider type
15    pub provider: EmailProvider,
16    /// Sender email address
17    pub from_email: String,
18    /// Sender name
19    pub from_name: Option<String>,
20    /// Provider-specific configuration
21    pub provider_config: ProviderConfig,
22}
23
24/// Supported email providers
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub enum EmailProvider {
27    /// SendGrid email service
28    SendGrid,
29    /// Amazon Simple Email Service
30    AwsSes,
31    /// SMTP server
32    Smtp,
33    /// Development mode (console logging only)
34    Development,
35}
36
37/// Provider-specific configuration
38#[derive(Clone, Serialize, Deserialize)]
39pub enum ProviderConfig {
40    /// SendGrid configuration
41    SendGrid {
42        api_key: String,
43        endpoint: Option<String>,
44    },
45    /// AWS SES configuration
46    AwsSes {
47        region: String,
48        access_key_id: String,
49        secret_access_key: String,
50    },
51    /// SMTP configuration
52    Smtp {
53        host: String,
54        port: u16,
55        username: String,
56        password: String,
57        use_tls: bool,
58    },
59    /// Development configuration
60    Development,
61}
62
63impl std::fmt::Debug for ProviderConfig {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        use crate::utils::redact::redacted;
66        match self {
67            Self::SendGrid { api_key, endpoint } => f
68                .debug_struct("SendGrid")
69                .field("api_key", &redacted(api_key))
70                .field("endpoint", endpoint)
71                .finish(),
72            Self::AwsSes {
73                region,
74                access_key_id,
75                secret_access_key,
76            } => f
77                .debug_struct("AwsSes")
78                .field("region", region)
79                .field("access_key_id", access_key_id)
80                .field("secret_access_key", &redacted(secret_access_key))
81                .finish(),
82            Self::Smtp {
83                host,
84                port,
85                username,
86                password,
87                use_tls,
88            } => f
89                .debug_struct("Smtp")
90                .field("host", host)
91                .field("port", port)
92                .field("username", username)
93                .field("password", &redacted(password))
94                .field("use_tls", use_tls)
95                .finish(),
96            Self::Development => f.write_str("Development"),
97        }
98    }
99}
100
101impl Default for EmailProviderConfig {
102    fn default() -> Self {
103        Self {
104            provider: EmailProvider::Development,
105            from_email: "noreply@example.com".to_string(),
106            from_name: Some("AuthFramework".to_string()),
107            provider_config: ProviderConfig::Development,
108        }
109    }
110}
111
112/// Email manager for handling email-based MFA with production providers
113pub struct EmailManager {
114    storage: Arc<dyn AuthStorage>,
115    email_config: EmailProviderConfig,
116}
117
118impl EmailManager {
119    /// Create a new email manager with default development configuration
120    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
121        Self {
122            storage,
123            email_config: EmailProviderConfig::default(),
124        }
125    }
126
127    /// Create a new email manager with custom provider configuration
128    pub fn new_with_config(
129        storage: Arc<dyn AuthStorage>,
130        email_config: EmailProviderConfig,
131    ) -> Self {
132        Self {
133            storage,
134            email_config,
135        }
136    }
137
138    /// Register email for email MFA
139    pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
140        debug!("Registering email for user '{}'", user_id);
141
142        // Validate email format
143        if email.is_empty() {
144            return Err(AuthError::validation("Email address cannot be empty"));
145        }
146
147        // Basic email validation
148        if !email.contains('@') || !email.contains('.') {
149            return Err(AuthError::validation(
150                "Email address must be in valid format (user@domain.com)",
151            ));
152        }
153
154        // More comprehensive email validation
155        let parts: Vec<&str> = email.split('@').collect();
156        if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
157            return Err(AuthError::validation("Email address format is invalid"));
158        }
159
160        let domain = parts[1];
161        if !domain.contains('.') || domain.starts_with('.') || domain.ends_with('.') {
162            return Err(AuthError::validation("Email domain format is invalid"));
163        }
164
165        // Store email in user's profile/data
166        let key = format!("user:{}:email", user_id);
167        self.storage.store_kv(&key, email.as_bytes(), None).await?;
168
169        info!("Email registered for user '{}': {}", user_id, email);
170        Ok(())
171    }
172
173    /// Initiate email challenge
174    pub async fn initiate_challenge(&self, user_id: &str) -> Result<String> {
175        debug!("Initiating email challenge for user '{}'", user_id);
176
177        let challenge_id = crate::utils::string::generate_id(Some("email"));
178
179        info!("Email challenge initiated for user '{}'", user_id);
180        Ok(challenge_id)
181    }
182
183    /// Generate email code
184    pub async fn generate_code(&self, challenge_id: &str) -> Result<String> {
185        debug!("Generating email code for challenge '{}'", challenge_id);
186
187        let code = format!("{:06}", rand::random::<u32>() % 1000000);
188
189        // Store the code for later verification
190        let email_key = format!("email_challenge:{}:code", challenge_id);
191        self.storage
192            .store_kv(
193                &email_key,
194                code.as_bytes(),
195                Some(Duration::from_secs(300)), // 5 minute expiry
196            )
197            .await?;
198
199        Ok(code)
200    }
201
202    /// Verify email code
203    pub async fn verify_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
204        debug!("Verifying email code for challenge '{}'", challenge_id);
205
206        // Validate input parameters
207        if challenge_id.is_empty() {
208            return Err(AuthError::validation("Challenge ID cannot be empty"));
209        }
210
211        if code.is_empty() {
212            return Err(AuthError::validation("Email code cannot be empty"));
213        }
214
215        // Check if challenge exists by looking for stored code
216        let email_key = format!("email_challenge:{}:code", challenge_id);
217        if let Some(stored_code_data) = self.storage.get_kv(&email_key).await? {
218            let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
219
220            // Validate code format
221            let is_valid_format = code.len() == 6 && code.chars().all(|c| c.is_ascii_digit());
222
223            if !is_valid_format {
224                return Ok(false);
225            }
226
227            // Verify against stored code
228            let is_valid = stored_code == code;
229
230            if is_valid {
231                // Remove the code after successful verification to prevent reuse
232                let _ = self.storage.delete_kv(&email_key).await;
233            }
234
235            Ok(is_valid)
236        } else {
237            // Challenge not found or expired
238            Err(AuthError::validation("Invalid or expired challenge ID"))
239        }
240    }
241
242    /// Send email code (placeholder - would integrate with email provider)
243    pub async fn send_code(&self, user_id: &str, code: &str) -> Result<()> {
244        debug!("Sending email code to user '{}'", user_id);
245
246        // Get user's email address
247        let email_key = format!("user:{}:email", user_id);
248        if let Some(email_data) = self.storage.get_kv(&email_key).await? {
249            let email_address = String::from_utf8(email_data).map_err(|e| {
250                AuthError::internal(format!("Failed to parse email address: {}", e))
251            })?;
252
253            // Production-grade email sending with multiple provider support
254            match self.send_email_via_provider(&email_address, "MFA Code", &format!(
255                "Your authentication code is: {}\n\nThis code will expire in 5 minutes.\nIf you didn't request this code, please ignore this email.",
256                code
257            )).await {
258                Ok(()) => {
259                    info!(
260                        "Email code sent successfully to {} for user '{}' via {:?}",
261                        email_address, user_id, self.email_config.provider
262                    );
263                    Ok(())
264                }
265                Err(e) => {
266                    error!(
267                        "Failed to send email code to {} for user '{}': {}",
268                        email_address, user_id, e
269                    );
270                    Err(e)
271                }
272            }
273        } else {
274            Err(AuthError::validation(
275                "No email address registered for user",
276            ))
277        }
278    }
279
280    /// Get user's email address
281    pub async fn get_user_email(&self, user_id: &str) -> Result<Option<String>> {
282        let email_key = format!("user:{}:email", user_id);
283
284        if let Some(email_data) = self.storage.get_kv(&email_key).await? {
285            Ok(Some(String::from_utf8(email_data).map_err(|e| {
286                AuthError::internal(format!("Failed to parse email address: {}", e))
287            })?))
288        } else {
289            Ok(None)
290        }
291    }
292
293    /// Send email via configured provider with production-grade implementation
294    async fn send_email_via_provider(
295        &self,
296        to_email: &str,
297        subject: &str,
298        body: &str,
299    ) -> Result<()> {
300        match &self.email_config.provider {
301            EmailProvider::SendGrid => self.send_via_sendgrid(to_email, subject, body).await,
302            EmailProvider::AwsSes => self.send_via_aws_ses(to_email, subject, body).await,
303            EmailProvider::Smtp => self.send_via_smtp(to_email, subject, body).await,
304            EmailProvider::Development => {
305                // Development mode: log to console instead of sending
306                info!("📧 [DEVELOPMENT] Email would be sent:");
307                info!("   To: {}", to_email);
308                info!("   Subject: {}", subject);
309                info!("   Body: <{} bytes, not logged>", body.len());
310                Ok(())
311            }
312        }
313    }
314
315    /// Send email via SendGrid API
316    async fn send_via_sendgrid(&self, to_email: &str, subject: &str, body: &str) -> Result<()> {
317        if let ProviderConfig::SendGrid { api_key, endpoint } = &self.email_config.provider_config {
318            let client = reqwest::Client::new();
319            let sendgrid_endpoint = endpoint
320                .as_deref()
321                .unwrap_or("https://api.sendgrid.com/v3/mail/send");
322
323            let payload = json!({
324                "personalizations": [{
325                    "to": [{"email": to_email}]
326                }],
327                "from": {
328                    "email": self.email_config.from_email,
329                    "name": self.email_config.from_name.as_deref().unwrap_or("AuthFramework")
330                },
331                "subject": subject,
332                "content": [{
333                    "type": "text/plain",
334                    "value": body
335                }]
336            });
337
338            let response = client
339                .post(sendgrid_endpoint)
340                .header("Authorization", format!("Bearer {}", api_key))
341                .header("Content-Type", "application/json")
342                .json(&payload)
343                .send()
344                .await
345                .map_err(|e| AuthError::internal(format!("SendGrid request failed: {}", e)))?;
346
347            let status = response.status();
348            if status.is_success() {
349                debug!("SendGrid email sent successfully to {}", to_email);
350                Ok(())
351            } else {
352                let error_text = response.text().await.unwrap_or_default();
353                Err(AuthError::internal(format!(
354                    "SendGrid API error: {} - {}",
355                    status, error_text
356                )))
357            }
358        } else {
359            Err(AuthError::internal("Invalid SendGrid configuration"))
360        }
361    }
362
363    /// Send email via AWS SES
364    async fn send_via_aws_ses(&self, to_email: &str, subject: &str, body: &str) -> Result<()> {
365        if let ProviderConfig::AwsSes {
366            region,
367            access_key_id: _,
368            secret_access_key: _,
369        } = &self.email_config.provider_config
370        {
371            // Note: In production, use the AWS SDK for Rust (aws-sdk-ses)
372            // For now, implement basic SES API call via REST
373            warn!("AWS SES integration requires aws-sdk-ses dependency");
374            warn!("Using development fallback for AWS SES");
375
376            info!("📧 [AWS SES DEV] Email would be sent:");
377            info!("   Region: {}", region);
378            info!("   To: {}", to_email);
379            info!("   Subject: {}", subject);
380            info!("   Body: {}", body);
381
382            Ok(())
383        } else {
384            Err(AuthError::internal("Invalid AWS SES configuration"))
385        }
386    }
387
388    /// Send email via SMTP
389    async fn send_via_smtp(&self, to_email: &str, subject: &str, body: &str) -> Result<()> {
390        if let ProviderConfig::Smtp {
391            host,
392            port,
393            username: _,
394            password: _,
395            use_tls,
396        } = &self.email_config.provider_config
397        {
398            // Note: In production, use lettre crate for SMTP
399            warn!("SMTP integration requires lettre dependency");
400            warn!("Using development fallback for SMTP");
401
402            info!("📧 [SMTP DEV] Email would be sent:");
403            info!("   Host: {}:{}", host, port);
404            info!("   TLS: {}", use_tls);
405            info!("   To: {}", to_email);
406            info!("   Subject: {}", subject);
407            info!("   Body: {}", body);
408
409            Ok(())
410        } else {
411            Err(AuthError::internal("Invalid SMTP configuration"))
412        }
413    }
414
415    /// Check if user has email configured
416    pub async fn has_email(&self, user_id: &str) -> Result<bool> {
417        let email_key = format!("email:{}", user_id);
418        match self.storage.get_kv(&email_key).await {
419            Ok(Some(_)) => Ok(true),
420            Ok(None) => Ok(false),
421            Err(_) => Ok(false), // Assume false on error
422        }
423    }
424
425    /// Send email code and return the generated code (mock implementation)
426    pub async fn send_email_code(&self, user_id: &str) -> Result<String> {
427        // Generate a 6-digit code
428        let code = format!("{:06}", rand::random::<u32>() % 1_000_000);
429
430        // In a real implementation, get the email address and send actual email
431        tracing::info!("Mock email code sent to user {}", user_id);
432
433        // Store the code for later verification
434        let email_key = format!("email_code:{}", user_id);
435        self.storage
436            .store_kv(
437                &email_key,
438                code.as_bytes(),
439                Some(std::time::Duration::from_secs(300)),
440            )
441            .await?;
442
443        Ok(code)
444    }
445}