Skip to main content

auth_framework/auth_modular/mfa/
sms_kit.rs

1//! Next-generation SMS MFA manager powered by SMSKit
2
3use crate::errors::{AuthError, Result};
4use crate::storage::AuthStorage;
5use ring::rand::SecureRandom;
6use serde::{Deserialize, Serialize};
7use std::sync::Arc;
8use std::time::Duration;
9use subtle::ConstantTimeEq;
10use tracing::{debug, error, info, warn};
11use uuid::Uuid;
12
13/// SMSKit configuration for AuthFramework
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct SmsKitConfig {
16    /// Primary SMS provider
17    pub provider: SmsKitProvider,
18    /// Provider-specific configuration
19    pub config: SmsKitProviderConfig,
20    /// Fallback provider (optional)
21    pub fallback_provider: Option<SmsKitProvider>,
22    /// Fallback configuration (optional)
23    pub fallback_config: Option<SmsKitProviderConfig>,
24    /// Webhook configuration for delivery status
25    pub webhook_config: Option<WebhookConfig>,
26    /// Rate limiting configuration
27    pub rate_limiting: RateLimitConfig,
28}
29
30impl Default for SmsKitConfig {
31    fn default() -> Self {
32        Self {
33            provider: SmsKitProvider::Development,
34            config: SmsKitProviderConfig::Development,
35            fallback_provider: None,
36            fallback_config: None,
37            webhook_config: None,
38            rate_limiting: RateLimitConfig::default(),
39        }
40    }
41}
42
43/// Supported SMSKit providers
44///
45/// `Plivo` requires the `smskit` feature flag and its SDK crate (`sms-plivo`).
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub enum SmsKitProvider {
48    Twilio,
49    /// Requires `smskit` feature and `sms-plivo` crate.
50    Plivo,
51    Development,
52}
53
54/// Provider-specific configuration
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub enum SmsKitProviderConfig {
57    Twilio {
58        account_sid: String,
59        auth_token: String,
60        from_number: String,
61        webhook_url: Option<String>,
62    },
63    Plivo {
64        auth_id: String,
65        auth_token: String,
66        from_number: String,
67        webhook_url: Option<String>,
68    },
69    Development,
70}
71
72/// Webhook configuration for SMS delivery status
73#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct WebhookConfig {
75    pub endpoint_url: String,
76    pub webhook_secret: String,
77    pub track_delivery: bool,
78    pub track_clicks: bool,
79}
80
81/// Rate limiting configuration
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct RateLimitConfig {
84    pub max_per_hour: u32,
85    pub max_per_day: u32,
86    pub cooldown_seconds: u64,
87}
88
89impl Default for RateLimitConfig {
90    fn default() -> Self {
91        Self {
92            max_per_hour: 10,
93            max_per_day: 20,
94            cooldown_seconds: 60,
95        }
96    }
97}
98
99/// Enhanced SMS manager powered by SMSKit
100pub struct SmsKitManager {
101    storage: Arc<dyn AuthStorage>,
102    config: SmsKitConfig,
103}
104
105impl SmsKitManager {
106    /// Create a new SMSKit manager with default configuration
107    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
108        Self {
109            storage,
110            config: SmsKitConfig::default(),
111        }
112    }
113
114    /// Create a new SMSKit manager with custom configuration
115    pub fn new_with_config(storage: Arc<dyn AuthStorage>, config: SmsKitConfig) -> Result<Self> {
116        let manager = Self { storage, config };
117        Ok(manager)
118    }
119
120    /// Register phone number for SMS MFA
121    pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
122        debug!("Registering phone number for user '{}' via SMSKit", user_id);
123
124        if phone_number.is_empty() {
125            return Err(AuthError::validation("Phone number cannot be empty"));
126        }
127
128        if !phone_number.starts_with('+') || phone_number.len() < 10 {
129            return Err(AuthError::validation(
130                "Phone number must be in international format (+1234567890)",
131            ));
132        }
133
134        let digits = &phone_number[1..];
135        if !digits.chars().all(|c| c.is_ascii_digit()) {
136            return Err(AuthError::validation(
137                "Phone number must contain only digits after the + sign",
138            ));
139        }
140
141        if digits.len() > 15 || digits.len() < 7 {
142            return Err(AuthError::validation(
143                "Phone number must be between 7 and 15 digits (E.164 format)",
144            ));
145        }
146
147        let key = format!("user:{}:phone", user_id);
148        self.storage
149            .store_kv(&key, phone_number.as_bytes(), None)
150            .await?;
151
152        info!(
153            "Phone number registered for user '{}': {} (SMSKit enabled)",
154            user_id, phone_number
155        );
156
157        Ok(())
158    }
159
160    /// Initiate SMS challenge with rate limiting
161    pub async fn initiate_challenge(&self, user_id: &str) -> Result<String> {
162        debug!("Initiating SMS challenge for user '{}' via SMSKit", user_id);
163
164        if user_id.is_empty() {
165            return Err(AuthError::validation("User ID cannot be empty"));
166        }
167
168        self.check_rate_limits(user_id).await?;
169
170        let challenge_id = crate::utils::string::generate_id(Some("smskit"));
171
172        info!("SMS challenge initiated for user '{}' via SMSKit", user_id);
173        Ok(challenge_id)
174    }
175
176    async fn check_rate_limits(&self, user_id: &str) -> Result<()> {
177        let now = chrono::Utc::now().timestamp();
178        let hour_ago = now - 3600;
179        let day_ago = now - 86400;
180
181        let hourly_key = format!("smskit:{}:hourly", user_id);
182        let hourly_count = self.get_sms_count(&hourly_key, hour_ago).await?;
183        if hourly_count >= self.config.rate_limiting.max_per_hour {
184            return Err(AuthError::rate_limited("SMS hourly limit exceeded"));
185        }
186
187        let daily_key = format!("smskit:{}:daily", user_id);
188        let daily_count = self.get_sms_count(&daily_key, day_ago).await?;
189        if daily_count >= self.config.rate_limiting.max_per_day {
190            return Err(AuthError::rate_limited("SMS daily limit exceeded"));
191        }
192
193        let last_sent_key = format!("smskit:{}:last_sent", user_id);
194        if let Some(last_sent_data) = self.storage.get_kv(&last_sent_key).await?
195            && let Ok(last_sent_str) = std::str::from_utf8(&last_sent_data)
196            && let Ok(last_sent) = last_sent_str.parse::<i64>()
197        {
198            let elapsed = now - last_sent;
199            if elapsed < self.config.rate_limiting.cooldown_seconds as i64 {
200                let remaining = self.config.rate_limiting.cooldown_seconds as i64 - elapsed;
201                return Err(AuthError::rate_limited(format!(
202                    "SMS cooldown active. Please wait {} seconds",
203                    remaining
204                )));
205            }
206        }
207
208        Ok(())
209    }
210
211    async fn get_sms_count(&self, key: &str, _since: i64) -> Result<u32> {
212        if let Some(count_data) = self.storage.get_kv(key).await?
213            && let Ok(count_str) = std::str::from_utf8(&count_data)
214            && let Ok(count) = count_str.parse::<u32>()
215        {
216            return Ok(count);
217        }
218        Ok(0)
219    }
220
221    /// Generate SMS verification code
222    pub async fn generate_code(&self, challenge_id: &str) -> Result<String> {
223        debug!(
224            "Generating SMS code for challenge '{}' via SMSKit",
225            challenge_id
226        );
227
228        let rng = ring::rand::SystemRandom::new();
229        let mut buf = [0u8; 4];
230        rng.fill(&mut buf).expect("system RNG failure");
231        let val = u32::from_le_bytes(buf) % 1_000_000;
232        let code = format!("{:06}", val);
233
234        let sms_key = format!("smskit_challenge:{}:code", challenge_id);
235        self.storage
236            .store_kv(&sms_key, code.as_bytes(), Some(Duration::from_secs(300)))
237            .await?;
238
239        Ok(code)
240    }
241
242    /// Verify SMS code
243    pub async fn verify_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
244        debug!(
245            "Verifying SMS code for challenge '{}' via SMSKit",
246            challenge_id
247        );
248
249        if challenge_id.is_empty() {
250            return Err(AuthError::validation("Challenge ID cannot be empty"));
251        }
252
253        if code.is_empty() {
254            return Err(AuthError::validation("SMS code cannot be empty"));
255        }
256
257        if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
258            return Ok(false);
259        }
260
261        let sms_key = format!("smskit_challenge:{}:code", challenge_id);
262        if let Some(stored_code_data) = self.storage.get_kv(&sms_key).await? {
263            let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
264            let is_valid: bool = stored_code.as_bytes().ct_eq(code.as_bytes()).into();
265
266            if is_valid {
267                let _ = self.storage.delete_kv(&sms_key).await;
268            }
269
270            Ok(is_valid)
271        } else {
272            Err(AuthError::validation("Invalid or expired challenge ID"))
273        }
274    }
275
276    /// Send SMS code using SMSKit with fallback support
277    pub async fn send_code(&self, user_id: &str, code: &str) -> Result<()> {
278        debug!("Sending SMS code to user '{}' via SMSKit", user_id);
279
280        let phone_key = format!("user:{}:phone", user_id);
281        let phone_number = if let Some(phone_data) = self.storage.get_kv(&phone_key).await? {
282            String::from_utf8(phone_data)
283                .map_err(|e| AuthError::internal(format!("Failed to parse phone number: {}", e)))?
284        } else {
285            return Err(AuthError::validation("No phone number registered for user"));
286        };
287
288        self.check_rate_limits(user_id).await?;
289
290        let message = format!(
291            "Your verification code is: {}. This code expires in 5 minutes. Do not share this code with anyone.",
292            code
293        );
294
295        match self.send_sms_with_fallback(&phone_number, &message).await {
296            Ok(message_id) => {
297                info!(
298                    "SMS code sent successfully to user '{}' (Message ID: {})",
299                    user_id, message_id
300                );
301                self.update_rate_limits(user_id).await?;
302                Ok(())
303            }
304            Err(e) => {
305                error!("Failed to send SMS to user '{}': {}", user_id, e);
306                Err(e)
307            }
308        }
309    }
310
311    async fn send_sms_with_fallback(&self, phone_number: &str, message: &str) -> Result<String> {
312        let result = match &self.config.provider {
313            SmsKitProvider::Twilio => self.send_via_twilio(phone_number, message).await,
314            SmsKitProvider::Plivo => self.send_via_plivo(phone_number, message).await,
315            SmsKitProvider::Development => {
316                info!("📱 [SMSKit Development] SMS sent to: {}", phone_number);
317                info!("   Message: {}", message);
318                Ok(format!("dev_msg_{}", chrono::Utc::now().timestamp()))
319            }
320        };
321
322        // On failure, try fallback provider if configured
323        match result {
324            Ok(msg_id) => Ok(msg_id),
325            Err(primary_err) => {
326                if let Some(fallback_provider) = &self.config.fallback_provider {
327                    warn!(
328                        "Primary SMS provider failed ({}), trying fallback: {:?}",
329                        primary_err, fallback_provider
330                    );
331                    match fallback_provider {
332                        SmsKitProvider::Development => {
333                            info!(
334                                "📱 [SMSKit Development Fallback] SMS sent to: {}",
335                                phone_number
336                            );
337                            info!("   Message: {}", message);
338                            Ok(format!(
339                                "dev_fallback_msg_{}",
340                                chrono::Utc::now().timestamp()
341                            ))
342                        }
343                        _ => Err(primary_err),
344                    }
345                } else {
346                    Err(primary_err)
347                }
348            }
349        }
350    }
351
352    /// Send SMS via Twilio using sms-twilio crate
353    #[cfg(feature = "smskit")]
354    async fn send_via_twilio(&self, phone_number: &str, message: &str) -> Result<String> {
355        use sms_core::SmsClient;
356
357        let (client, from_number) = if let SmsKitProviderConfig::Twilio {
358            account_sid,
359            auth_token,
360            from_number,
361            ..
362        } = &self.config.config
363        {
364            if account_sid.is_empty() || auth_token.is_empty() || from_number.is_empty() {
365                return Err(AuthError::internal("Twilio credentials are incomplete"));
366            }
367            (
368                sms_twilio::TwilioClient::new(account_sid, auth_token),
369                from_number.clone(),
370            )
371        } else {
372            let from_number = std::env::var("TWILIO_FROM_NUMBER").map_err(|_| {
373                AuthError::internal("Twilio from number not configured: set TWILIO_FROM_NUMBER")
374            })?;
375            let c = sms_twilio::TwilioClient::from_env()
376                .map_err(|e| AuthError::internal(format!("Twilio env config failed: {}", e)))?;
377            (c, from_number)
378        };
379
380        let request = sms_core::SendRequest {
381            to: phone_number,
382            from: &from_number,
383            text: message,
384        };
385
386        let response = client
387            .send(request)
388            .await
389            .map_err(|e| AuthError::internal(format!("Twilio SMS send failed: {}", e)))?;
390
391        debug!("Twilio SMS sent successfully, ID: {}", response.id);
392        Ok(response.id)
393    }
394
395    #[cfg(not(feature = "smskit"))]
396    async fn send_via_twilio(&self, _phone_number: &str, _message: &str) -> Result<String> {
397        Err(AuthError::internal(
398            "Twilio SMS requires the 'smskit' feature flag to be enabled",
399        ))
400    }
401
402    /// Send SMS via Plivo using sms-plivo crate
403    #[cfg(feature = "smskit")]
404    async fn send_via_plivo(&self, phone_number: &str, message: &str) -> Result<String> {
405        use sms_core::SmsClient;
406
407        let (client, from_number) = if let SmsKitProviderConfig::Plivo {
408            auth_id,
409            auth_token,
410            from_number,
411            ..
412        } = &self.config.config
413        {
414            if auth_id.is_empty() || auth_token.is_empty() || from_number.is_empty() {
415                return Err(AuthError::internal("Plivo credentials are incomplete"));
416            }
417            (
418                sms_plivo::PlivoClient::new(auth_id, auth_token),
419                from_number.clone(),
420            )
421        } else {
422            let from_number = std::env::var("PLIVO_FROM_NUMBER").map_err(|_| {
423                AuthError::internal("Plivo from number not configured: set PLIVO_FROM_NUMBER")
424            })?;
425            let c = sms_plivo::PlivoClient::from_env()
426                .map_err(|e| AuthError::internal(format!("Plivo env config failed: {}", e)))?;
427            (c, from_number)
428        };
429
430        let request = sms_core::SendRequest {
431            to: phone_number,
432            from: &from_number,
433            text: message,
434        };
435
436        let response = client
437            .send(request)
438            .await
439            .map_err(|e| AuthError::internal(format!("Plivo SMS send failed: {}", e)))?;
440
441        debug!("Plivo SMS sent successfully, ID: {}", response.id);
442        Ok(response.id)
443    }
444
445    #[cfg(not(feature = "smskit"))]
446    async fn send_via_plivo(&self, _phone_number: &str, _message: &str) -> Result<String> {
447        Err(AuthError::internal(
448            "Plivo SMS requires the 'smskit' feature flag to be enabled",
449        ))
450    }
451
452    async fn update_rate_limits(&self, user_id: &str) -> Result<()> {
453        let now = chrono::Utc::now().timestamp();
454
455        let hourly_key = format!("smskit:{}:hourly", user_id);
456        let hourly_count = self.get_sms_count(&hourly_key, now - 3600).await? + 1;
457        self.storage
458            .store_kv(
459                &hourly_key,
460                hourly_count.to_string().as_bytes(),
461                Some(Duration::from_secs(3600)),
462            )
463            .await?;
464
465        let daily_key = format!("smskit:{}:daily", user_id);
466        let daily_count = self.get_sms_count(&daily_key, now - 86400).await? + 1;
467        self.storage
468            .store_kv(
469                &daily_key,
470                daily_count.to_string().as_bytes(),
471                Some(Duration::from_secs(86400)),
472            )
473            .await?;
474
475        let last_sent_key = format!("smskit:{}:last_sent", user_id);
476        self.storage
477            .store_kv(
478                &last_sent_key,
479                now.to_string().as_bytes(),
480                Some(Duration::from_secs(
481                    self.config.rate_limiting.cooldown_seconds,
482                )),
483            )
484            .await?;
485
486        Ok(())
487    }
488
489    /// Get user's phone number
490    pub async fn get_user_phone(&self, user_id: &str) -> Result<Option<String>> {
491        let phone_key = format!("user:{}:phone", user_id);
492
493        if let Some(phone_data) = self.storage.get_kv(&phone_key).await? {
494            Ok(Some(String::from_utf8(phone_data).map_err(|e| {
495                AuthError::internal(format!("Failed to parse phone number: {}", e))
496            })?))
497        } else {
498            Ok(None)
499        }
500    }
501
502    /// Check if user has phone number configured
503    pub async fn has_phone_number(&self, user_id: &str) -> Result<bool> {
504        let key = format!("user:{}:phone", user_id);
505        match self.storage.get_kv(&key).await {
506            Ok(Some(_)) => Ok(true),
507            Ok(None) => Ok(false),
508            Err(_) => Ok(false), // Assume false on error
509        }
510    }
511
512    /// Send verification code and return the generated code
513    pub async fn send_verification_code(&self, user_id: &str) -> Result<String> {
514        // Generate a 6-digit code
515        let code = format!("{:06}", rand::random::<u32>() % 1_000_000);
516
517        // Send the code via SMS
518        self.send_code(user_id, &code).await?;
519
520        // Store the code for later verification
521        let code_key = format!("sms_verification:{}:{}", user_id, Uuid::new_v4());
522        self.storage
523            .store_kv(
524                &code_key,
525                code.as_bytes(),
526                Some(std::time::Duration::from_secs(300)),
527            )
528            .await?;
529
530        Ok(code)
531    }
532}
533
534#[cfg(test)]
535mod aws_sns_removed_tests {
536    use super::*;
537
538    #[test]
539    fn removed_aws_sns_provider_no_longer_deserializes() {
540        assert!(serde_json::from_str::<SmsKitProvider>("\"AwsSns\"").is_err());
541        let cfg = r#"{"AwsSns":{"region":"r","access_key_id":"a","secret_access_key":"s"}}"#;
542        assert!(serde_json::from_str::<SmsKitProviderConfig>(cfg).is_err());
543        assert!(serde_json::from_str::<SmsKitProvider>("\"Twilio\"").is_ok());
544    }
545}