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