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(Clone, Serialize)]
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
72impl std::fmt::Debug for SmsKitProviderConfig {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        match self {
75            Self::Twilio {
76                account_sid,
77                auth_token,
78                from_number,
79                webhook_url,
80            } => f
81                .debug_struct("Twilio")
82                .field("account_sid", account_sid)
83                .field("auth_token", &crate::utils::redact::redacted(auth_token))
84                .field("from_number", from_number)
85                .field("webhook_url", webhook_url)
86                .finish(),
87            Self::Plivo {
88                auth_id,
89                auth_token,
90                from_number,
91                webhook_url,
92            } => f
93                .debug_struct("Plivo")
94                .field("auth_id", auth_id)
95                .field("auth_token", &crate::utils::redact::redacted(auth_token))
96                .field("from_number", from_number)
97                .field("webhook_url", webhook_url)
98                .finish(),
99            Self::Development => f.write_str("Development"),
100        }
101    }
102}
103
104/// Manual `Deserialize`: same reasoning as `SmsKitProvider` above -- a
105/// persisted `AwsSns { region, access_key_id, secret_access_key }` fails
106/// with an actionable message rather than deserializing successfully or
107/// failing with a generic unknown-variant error.
108impl<'de> Deserialize<'de> for SmsKitProviderConfig {
109    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
110    where
111        D: serde::Deserializer<'de>,
112    {
113        #[derive(Deserialize)]
114        enum Shadow {
115            Twilio {
116                account_sid: String,
117                auth_token: String,
118                from_number: String,
119                webhook_url: Option<String>,
120            },
121            Plivo {
122                auth_id: String,
123                auth_token: String,
124                from_number: String,
125                webhook_url: Option<String>,
126            },
127            Development,
128            AwsSns {
129                #[allow(
130                    dead_code,
131                    reason = "AwsSns is retained for configuration compatibility; no SMS provider reads these credentials"
132                )]
133                region: String,
134                #[allow(
135                    dead_code,
136                    reason = "AwsSns is retained for configuration compatibility; no SMS provider reads these credentials"
137                )]
138                access_key_id: String,
139                #[allow(
140                    dead_code,
141                    reason = "AwsSns is retained for configuration compatibility; no SMS provider reads these credentials"
142                )]
143                secret_access_key: String,
144            },
145        }
146        match Shadow::deserialize(deserializer)? {
147            Shadow::Twilio {
148                account_sid,
149                auth_token,
150                from_number,
151                webhook_url,
152            } => Ok(SmsKitProviderConfig::Twilio {
153                account_sid,
154                auth_token,
155                from_number,
156                webhook_url,
157            }),
158            Shadow::Plivo {
159                auth_id,
160                auth_token,
161                from_number,
162                webhook_url,
163            } => Ok(SmsKitProviderConfig::Plivo {
164                auth_id,
165                auth_token,
166                from_number,
167                webhook_url,
168            }),
169            Shadow::Development => Ok(SmsKitProviderConfig::Development),
170            Shadow::AwsSns { .. } => Err(serde::de::Error::custom(
171                "the `sms-aws-sns` SMS backend (SmsKitProviderConfig::AwsSns) \
172                 was removed in 0.6.0 -- see CHANGELOG.md for migration details",
173            )),
174        }
175    }
176}
177
178/// Webhook configuration for SMS delivery status
179#[derive(Clone, Serialize, Deserialize)]
180pub struct WebhookConfig {
181    pub endpoint_url: String,
182    pub webhook_secret: String,
183    pub track_delivery: bool,
184    pub track_clicks: bool,
185}
186
187impl std::fmt::Debug for WebhookConfig {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        let mut d = f.debug_struct("WebhookConfig");
190        d.field("endpoint_url", &self.endpoint_url);
191        d.field(
192            "webhook_secret",
193            &crate::utils::redact::redacted(&self.webhook_secret),
194        );
195        d.field("track_delivery", &self.track_delivery);
196        d.field("track_clicks", &self.track_clicks);
197        d.finish()
198    }
199}
200
201/// Rate limiting configuration
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct RateLimitConfig {
204    pub max_per_hour: u32,
205    pub max_per_day: u32,
206    pub cooldown_seconds: u64,
207}
208
209impl Default for RateLimitConfig {
210    fn default() -> Self {
211        Self {
212            max_per_hour: 10,
213            max_per_day: 20,
214            cooldown_seconds: 60,
215        }
216    }
217}
218
219/// Enhanced SMS manager powered by SMSKit
220pub struct SmsKitManager {
221    storage: Arc<dyn AuthStorage>,
222    config: SmsKitConfig,
223}
224
225impl SmsKitManager {
226    /// Create a new SMSKit manager with default configuration
227    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
228        Self {
229            storage,
230            config: SmsKitConfig::default(),
231        }
232    }
233
234    /// Create a new SMSKit manager with custom configuration
235    pub fn new_with_config(storage: Arc<dyn AuthStorage>, config: SmsKitConfig) -> Result<Self> {
236        let manager = Self { storage, config };
237        Ok(manager)
238    }
239
240    /// Register phone number for SMS MFA
241    pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
242        debug!("Registering phone number for user '{}' via SMSKit", user_id);
243
244        if phone_number.is_empty() {
245            return Err(AuthError::validation("Phone number cannot be empty"));
246        }
247
248        if !phone_number.starts_with('+') || phone_number.len() < 10 {
249            return Err(AuthError::validation(
250                "Phone number must be in international format (+1234567890)",
251            ));
252        }
253
254        let digits = &phone_number[1..];
255        if !digits.chars().all(|c| c.is_ascii_digit()) {
256            return Err(AuthError::validation(
257                "Phone number must contain only digits after the + sign",
258            ));
259        }
260
261        if digits.len() > 15 || digits.len() < 7 {
262            return Err(AuthError::validation(
263                "Phone number must be between 7 and 15 digits (E.164 format)",
264            ));
265        }
266
267        let key = format!("user:{}:phone", user_id);
268        self.storage
269            .store_kv(&key, phone_number.as_bytes(), None)
270            .await?;
271
272        info!(
273            "Phone number registered for user '{}': {} (SMSKit enabled)",
274            user_id, phone_number
275        );
276
277        Ok(())
278    }
279
280    /// Initiate SMS challenge with rate limiting
281    pub async fn initiate_challenge(&self, user_id: &str) -> Result<String> {
282        debug!("Initiating SMS challenge for user '{}' via SMSKit", user_id);
283
284        if user_id.is_empty() {
285            return Err(AuthError::validation("User ID cannot be empty"));
286        }
287
288        self.check_rate_limits(user_id).await?;
289
290        let challenge_id = crate::utils::string::generate_id(Some("smskit"));
291
292        info!("SMS challenge initiated for user '{}' via SMSKit", user_id);
293        Ok(challenge_id)
294    }
295
296    async fn check_rate_limits(&self, user_id: &str) -> Result<()> {
297        let now = chrono::Utc::now().timestamp();
298        let hour_ago = now - 3600;
299        let day_ago = now - 86400;
300
301        let hourly_key = format!("smskit:{}:hourly", user_id);
302        let hourly_count = self.get_sms_count(&hourly_key, hour_ago).await?;
303        if hourly_count >= self.config.rate_limiting.max_per_hour {
304            return Err(AuthError::rate_limited("SMS hourly limit exceeded"));
305        }
306
307        let daily_key = format!("smskit:{}:daily", user_id);
308        let daily_count = self.get_sms_count(&daily_key, day_ago).await?;
309        if daily_count >= self.config.rate_limiting.max_per_day {
310            return Err(AuthError::rate_limited("SMS daily limit exceeded"));
311        }
312
313        let last_sent_key = format!("smskit:{}:last_sent", user_id);
314        if let Some(last_sent_data) = self.storage.get_kv(&last_sent_key).await?
315            && let Ok(last_sent_str) = std::str::from_utf8(&last_sent_data)
316            && let Ok(last_sent) = last_sent_str.parse::<i64>()
317        {
318            let elapsed = now - last_sent;
319            if elapsed < self.config.rate_limiting.cooldown_seconds as i64 {
320                let remaining = self.config.rate_limiting.cooldown_seconds as i64 - elapsed;
321                return Err(AuthError::rate_limited(format!(
322                    "SMS cooldown active. Please wait {} seconds",
323                    remaining
324                )));
325            }
326        }
327
328        Ok(())
329    }
330
331    async fn get_sms_count(&self, key: &str, _since: i64) -> Result<u32> {
332        if let Some(count_data) = self.storage.get_kv(key).await?
333            && let Ok(count_str) = std::str::from_utf8(&count_data)
334            && let Ok(count) = count_str.parse::<u32>()
335        {
336            return Ok(count);
337        }
338        Ok(0)
339    }
340
341    /// Generate SMS verification code
342    pub async fn generate_code(&self, challenge_id: &str) -> Result<String> {
343        debug!(
344            "Generating SMS code for challenge '{}' via SMSKit",
345            challenge_id
346        );
347
348        let rng = ring::rand::SystemRandom::new();
349        let mut buf = [0u8; 4];
350        rng.fill(&mut buf).expect("system RNG failure");
351        let val = u32::from_le_bytes(buf) % 1_000_000;
352        let code = format!("{:06}", val);
353
354        let sms_key = format!("smskit_challenge:{}:code", challenge_id);
355        self.storage
356            .store_kv(&sms_key, code.as_bytes(), Some(Duration::from_secs(300)))
357            .await?;
358
359        Ok(code)
360    }
361
362    /// Verify SMS code
363    pub async fn verify_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
364        debug!(
365            "Verifying SMS code for challenge '{}' via SMSKit",
366            challenge_id
367        );
368
369        if challenge_id.is_empty() {
370            return Err(AuthError::validation("Challenge ID cannot be empty"));
371        }
372
373        if code.is_empty() {
374            return Err(AuthError::validation("SMS code cannot be empty"));
375        }
376
377        if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
378            return Ok(false);
379        }
380
381        let sms_key = format!("smskit_challenge:{}:code", challenge_id);
382        if let Some(stored_code_data) = self.storage.get_kv(&sms_key).await? {
383            let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
384            let is_valid: bool = stored_code.as_bytes().ct_eq(code.as_bytes()).into();
385
386            if is_valid {
387                let _ = self.storage.delete_kv(&sms_key).await;
388            }
389
390            Ok(is_valid)
391        } else {
392            Err(AuthError::validation("Invalid or expired challenge ID"))
393        }
394    }
395
396    /// Send SMS code using SMSKit with fallback support
397    pub async fn send_code(&self, user_id: &str, code: &str) -> Result<()> {
398        debug!("Sending SMS code to user '{}' via SMSKit", user_id);
399
400        let phone_key = format!("user:{}:phone", user_id);
401        let phone_number = if let Some(phone_data) = self.storage.get_kv(&phone_key).await? {
402            String::from_utf8(phone_data)
403                .map_err(|e| AuthError::internal(format!("Failed to parse phone number: {}", e)))?
404        } else {
405            return Err(AuthError::validation("No phone number registered for user"));
406        };
407
408        self.check_rate_limits(user_id).await?;
409
410        let message = format!(
411            "Your verification code is: {}. This code expires in 5 minutes. Do not share this code with anyone.",
412            code
413        );
414
415        match self.send_sms_with_fallback(&phone_number, &message).await {
416            Ok(message_id) => {
417                info!(
418                    "SMS code sent successfully to user '{}' (Message ID: {})",
419                    user_id, message_id
420                );
421                self.update_rate_limits(user_id).await?;
422                Ok(())
423            }
424            Err(e) => {
425                error!("Failed to send SMS to user '{}': {}", user_id, e);
426                Err(e)
427            }
428        }
429    }
430
431    async fn send_sms_with_fallback(&self, phone_number: &str, message: &str) -> Result<String> {
432        let result = match &self.config.provider {
433            SmsKitProvider::Twilio => self.send_via_twilio(phone_number, message).await,
434            SmsKitProvider::Plivo => self.send_via_plivo(phone_number, message).await,
435            SmsKitProvider::Development => {
436                info!("📱 [SMSKit Development] SMS sent to: {}", phone_number);
437                info!("   Message: <{} bytes, not logged>", message.len());
438                Ok(format!("dev_msg_{}", chrono::Utc::now().timestamp()))
439            }
440        };
441
442        // On failure, try fallback provider if configured
443        match result {
444            Ok(msg_id) => Ok(msg_id),
445            Err(primary_err) => {
446                if let Some(fallback_provider) = &self.config.fallback_provider {
447                    warn!(
448                        "Primary SMS provider failed ({}), trying fallback: {:?}",
449                        primary_err, fallback_provider
450                    );
451                    match fallback_provider {
452                        SmsKitProvider::Development => {
453                            info!(
454                                "📱 [SMSKit Development Fallback] SMS sent to: {}",
455                                phone_number
456                            );
457                            info!("   Message: <{} bytes, not logged>", message.len());
458                            Ok(format!(
459                                "dev_fallback_msg_{}",
460                                chrono::Utc::now().timestamp()
461                            ))
462                        }
463                        _ => Err(primary_err),
464                    }
465                } else {
466                    Err(primary_err)
467                }
468            }
469        }
470    }
471
472    /// Send SMS via Twilio using sms-twilio crate
473    #[cfg(feature = "smskit")]
474    async fn send_via_twilio(&self, phone_number: &str, message: &str) -> Result<String> {
475        use sms_core::SmsClient;
476
477        let (client, from_number) = if let SmsKitProviderConfig::Twilio {
478            account_sid,
479            auth_token,
480            from_number,
481            ..
482        } = &self.config.config
483        {
484            if account_sid.is_empty() || auth_token.is_empty() || from_number.is_empty() {
485                return Err(AuthError::internal("Twilio credentials are incomplete"));
486            }
487            (
488                sms_twilio::TwilioClient::new(account_sid, auth_token),
489                from_number.clone(),
490            )
491        } else {
492            let from_number = std::env::var("TWILIO_FROM_NUMBER").map_err(|_| {
493                AuthError::internal("Twilio from number not configured: set TWILIO_FROM_NUMBER")
494            })?;
495            let c = sms_twilio::TwilioClient::from_env()
496                .map_err(|e| AuthError::internal(format!("Twilio env config failed: {}", e)))?;
497            (c, from_number)
498        };
499
500        let request = sms_core::SendRequest {
501            to: phone_number,
502            from: &from_number,
503            text: message,
504        };
505
506        let response = client
507            .send(request)
508            .await
509            .map_err(|e| AuthError::internal(format!("Twilio SMS send failed: {}", e)))?;
510
511        debug!("Twilio SMS sent successfully, ID: {}", response.id);
512        Ok(response.id)
513    }
514
515    #[cfg(not(feature = "smskit"))]
516    async fn send_via_twilio(&self, _phone_number: &str, _message: &str) -> Result<String> {
517        Err(AuthError::internal(
518            "Twilio SMS requires the 'smskit' feature flag to be enabled",
519        ))
520    }
521
522    /// Send SMS via Plivo using sms-plivo crate
523    #[cfg(feature = "smskit")]
524    async fn send_via_plivo(&self, phone_number: &str, message: &str) -> Result<String> {
525        use sms_core::SmsClient;
526
527        let (client, from_number) = if let SmsKitProviderConfig::Plivo {
528            auth_id,
529            auth_token,
530            from_number,
531            ..
532        } = &self.config.config
533        {
534            if auth_id.is_empty() || auth_token.is_empty() || from_number.is_empty() {
535                return Err(AuthError::internal("Plivo credentials are incomplete"));
536            }
537            (
538                sms_plivo::PlivoClient::new(auth_id, auth_token),
539                from_number.clone(),
540            )
541        } else {
542            let from_number = std::env::var("PLIVO_FROM_NUMBER").map_err(|_| {
543                AuthError::internal("Plivo from number not configured: set PLIVO_FROM_NUMBER")
544            })?;
545            let c = sms_plivo::PlivoClient::from_env()
546                .map_err(|e| AuthError::internal(format!("Plivo env config failed: {}", e)))?;
547            (c, from_number)
548        };
549
550        let request = sms_core::SendRequest {
551            to: phone_number,
552            from: &from_number,
553            text: message,
554        };
555
556        let response = client
557            .send(request)
558            .await
559            .map_err(|e| AuthError::internal(format!("Plivo SMS send failed: {}", e)))?;
560
561        debug!("Plivo SMS sent successfully, ID: {}", response.id);
562        Ok(response.id)
563    }
564
565    #[cfg(not(feature = "smskit"))]
566    async fn send_via_plivo(&self, _phone_number: &str, _message: &str) -> Result<String> {
567        Err(AuthError::internal(
568            "Plivo SMS requires the 'smskit' feature flag to be enabled",
569        ))
570    }
571
572    async fn update_rate_limits(&self, user_id: &str) -> Result<()> {
573        let now = chrono::Utc::now().timestamp();
574
575        let hourly_key = format!("smskit:{}:hourly", user_id);
576        let hourly_count = self.get_sms_count(&hourly_key, now - 3600).await? + 1;
577        self.storage
578            .store_kv(
579                &hourly_key,
580                hourly_count.to_string().as_bytes(),
581                Some(Duration::from_secs(3600)),
582            )
583            .await?;
584
585        let daily_key = format!("smskit:{}:daily", user_id);
586        let daily_count = self.get_sms_count(&daily_key, now - 86400).await? + 1;
587        self.storage
588            .store_kv(
589                &daily_key,
590                daily_count.to_string().as_bytes(),
591                Some(Duration::from_secs(86400)),
592            )
593            .await?;
594
595        let last_sent_key = format!("smskit:{}:last_sent", user_id);
596        self.storage
597            .store_kv(
598                &last_sent_key,
599                now.to_string().as_bytes(),
600                Some(Duration::from_secs(
601                    self.config.rate_limiting.cooldown_seconds,
602                )),
603            )
604            .await?;
605
606        Ok(())
607    }
608
609    /// Get user's phone number
610    pub async fn get_user_phone(&self, user_id: &str) -> Result<Option<String>> {
611        let phone_key = format!("user:{}:phone", user_id);
612
613        if let Some(phone_data) = self.storage.get_kv(&phone_key).await? {
614            Ok(Some(String::from_utf8(phone_data).map_err(|e| {
615                AuthError::internal(format!("Failed to parse phone number: {}", e))
616            })?))
617        } else {
618            Ok(None)
619        }
620    }
621
622    /// Check if user has phone number configured
623    pub async fn has_phone_number(&self, user_id: &str) -> Result<bool> {
624        let key = format!("user:{}:phone", user_id);
625        match self.storage.get_kv(&key).await {
626            Ok(Some(_)) => Ok(true),
627            Ok(None) => Ok(false),
628            Err(_) => Ok(false), // Assume false on error
629        }
630    }
631
632    /// Send verification code and return the generated code
633    pub async fn send_verification_code(&self, user_id: &str) -> Result<String> {
634        // Generate a 6-digit code
635        let code = format!("{:06}", rand::random::<u32>() % 1_000_000);
636
637        // Send the code via SMS
638        self.send_code(user_id, &code).await?;
639
640        // Store the code for later verification
641        let code_key = format!("sms_verification:{}:{}", user_id, Uuid::new_v4());
642        self.storage
643            .store_kv(
644                &code_key,
645                code.as_bytes(),
646                Some(std::time::Duration::from_secs(300)),
647            )
648            .await?;
649
650        Ok(code)
651    }
652}
653
654#[cfg(test)]
655mod aws_sns_removed_tests {
656    use super::*;
657
658    #[test]
659    fn removed_aws_sns_provider_no_longer_deserializes() {
660        assert!(serde_json::from_str::<SmsKitProvider>("\"AwsSns\"").is_err());
661        let cfg = r#"{"AwsSns":{"region":"r","access_key_id":"a","secret_access_key":"s"}}"#;
662        assert!(serde_json::from_str::<SmsKitProviderConfig>(cfg).is_err());
663        assert!(serde_json::from_str::<SmsKitProvider>("\"Twilio\"").is_ok());
664    }
665}