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;
12use zeroize::Zeroizing;
13
14/// SMSKit configuration for AuthFramework
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct SmsKitConfig {
17    /// Primary SMS provider
18    pub provider: SmsKitProvider,
19    /// Provider-specific configuration
20    pub config: SmsKitProviderConfig,
21    /// Fallback provider (optional)
22    pub fallback_provider: Option<SmsKitProvider>,
23    /// Fallback configuration (optional)
24    pub fallback_config: Option<SmsKitProviderConfig>,
25    /// Webhook configuration for delivery status
26    pub webhook_config: Option<WebhookConfig>,
27    /// Rate limiting configuration
28    pub rate_limiting: RateLimitConfig,
29}
30
31impl Default for SmsKitConfig {
32    fn default() -> Self {
33        Self {
34            provider: SmsKitProvider::Development,
35            config: SmsKitProviderConfig::Development,
36            fallback_provider: None,
37            fallback_config: None,
38            webhook_config: None,
39            rate_limiting: RateLimitConfig::default(),
40        }
41    }
42}
43
44/// Supported SMSKit providers
45///
46/// `Plivo` requires the `smskit` feature flag and its `sms-plivo` SDK crate.
47/// When selected without the feature enabled, `send_sms_with_fallback`
48/// returns a descriptive error at runtime.
49#[derive(Debug, Clone, Serialize)]
50pub enum SmsKitProvider {
51    Twilio,
52    /// Requires `smskit` feature and `sms-plivo` crate.
53    Plivo,
54    Development,
55}
56
57/// Manual `Deserialize` (rather than `#[derive]`) so a persisted `AwsSns`
58/// selection -- from before the `sms-aws-sns` backend was removed -- fails
59/// with an actionable migration message instead of serde's generic
60/// unknown-variant error. See `SmsKitProviderConfig`'s impl for the shadow
61/// enum this mirrors and the mutation tests in this module.
62impl<'de> Deserialize<'de> for SmsKitProvider {
63    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
64    where
65        D: serde::Deserializer<'de>,
66    {
67        #[derive(Deserialize)]
68        enum Shadow {
69            Twilio,
70            Plivo,
71            Development,
72            AwsSns,
73        }
74        match Shadow::deserialize(deserializer)? {
75            Shadow::Twilio => Ok(SmsKitProvider::Twilio),
76            Shadow::Plivo => Ok(SmsKitProvider::Plivo),
77            Shadow::Development => Ok(SmsKitProvider::Development),
78            Shadow::AwsSns => Err(serde::de::Error::custom(
79                "the `sms-aws-sns` SMS backend (SmsKitProvider::AwsSns) was \
80                 removed in 0.6.0 -- see CHANGELOG.md for migration details",
81            )),
82        }
83    }
84}
85
86/// Provider-specific configuration
87#[derive(Clone, Serialize)]
88pub enum SmsKitProviderConfig {
89    Twilio {
90        account_sid: String,
91        auth_token: String,
92        from_number: String,
93        webhook_url: Option<String>,
94    },
95    Plivo {
96        auth_id: String,
97        auth_token: String,
98        from_number: String,
99        webhook_url: Option<String>,
100    },
101    Development,
102}
103
104impl std::fmt::Debug for SmsKitProviderConfig {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        match self {
107            Self::Twilio {
108                account_sid,
109                auth_token,
110                from_number,
111                webhook_url,
112            } => f
113                .debug_struct("Twilio")
114                .field("account_sid", account_sid)
115                .field("auth_token", &crate::utils::redact::redacted(auth_token))
116                .field("from_number", from_number)
117                .field("webhook_url", webhook_url)
118                .finish(),
119            Self::Plivo {
120                auth_id,
121                auth_token,
122                from_number,
123                webhook_url,
124            } => f
125                .debug_struct("Plivo")
126                .field("auth_id", auth_id)
127                .field("auth_token", &crate::utils::redact::redacted(auth_token))
128                .field("from_number", from_number)
129                .field("webhook_url", webhook_url)
130                .finish(),
131            Self::Development => f.write_str("Development"),
132        }
133    }
134}
135
136/// Manual `Deserialize`: same reasoning as `SmsKitProvider` above -- a
137/// persisted `AwsSns { region, access_key_id, secret_access_key }` fails
138/// with an actionable message rather than deserializing successfully or
139/// failing with a generic unknown-variant error.
140impl<'de> Deserialize<'de> for SmsKitProviderConfig {
141    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
142    where
143        D: serde::Deserializer<'de>,
144    {
145        #[derive(Deserialize)]
146        enum Shadow {
147            Twilio {
148                account_sid: String,
149                auth_token: String,
150                from_number: String,
151                webhook_url: Option<String>,
152            },
153            Plivo {
154                auth_id: String,
155                auth_token: String,
156                from_number: String,
157                webhook_url: Option<String>,
158            },
159            Development,
160            AwsSns {
161                #[allow(
162                    dead_code,
163                    reason = "AwsSns is retained for configuration compatibility; no SMS provider reads these credentials"
164                )]
165                region: String,
166                #[allow(
167                    dead_code,
168                    reason = "AwsSns is retained for configuration compatibility; no SMS provider reads these credentials"
169                )]
170                access_key_id: String,
171                #[allow(
172                    dead_code,
173                    reason = "AwsSns is retained for configuration compatibility; no SMS provider reads these credentials"
174                )]
175                secret_access_key: String,
176            },
177        }
178        match Shadow::deserialize(deserializer)? {
179            Shadow::Twilio {
180                account_sid,
181                auth_token,
182                from_number,
183                webhook_url,
184            } => Ok(SmsKitProviderConfig::Twilio {
185                account_sid,
186                auth_token,
187                from_number,
188                webhook_url,
189            }),
190            Shadow::Plivo {
191                auth_id,
192                auth_token,
193                from_number,
194                webhook_url,
195            } => Ok(SmsKitProviderConfig::Plivo {
196                auth_id,
197                auth_token,
198                from_number,
199                webhook_url,
200            }),
201            Shadow::Development => Ok(SmsKitProviderConfig::Development),
202            Shadow::AwsSns { .. } => Err(serde::de::Error::custom(
203                "the `sms-aws-sns` SMS backend (SmsKitProviderConfig::AwsSns) \
204                 was removed in 0.6.0 -- see CHANGELOG.md for migration details",
205            )),
206        }
207    }
208}
209
210/// Webhook configuration for SMS delivery status
211#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct WebhookConfig {
213    pub endpoint_url: String,
214    pub webhook_secret: Zeroizing<String>,
215    pub track_delivery: bool,
216    pub track_clicks: bool,
217}
218
219/// Rate limiting configuration
220#[derive(Debug, Clone, Serialize, Deserialize)]
221pub struct RateLimitConfig {
222    pub max_per_hour: u32,
223    pub max_per_day: u32,
224    pub cooldown_seconds: u64,
225}
226
227impl Default for RateLimitConfig {
228    fn default() -> Self {
229        Self {
230            max_per_hour: 10,
231            max_per_day: 20,
232            cooldown_seconds: 60,
233        }
234    }
235}
236
237/// Enhanced SMS manager powered by SMSKit
238pub struct SmsKitManager {
239    storage: Arc<dyn AuthStorage>,
240    config: SmsKitConfig,
241}
242
243impl SmsKitManager {
244    /// Create a new SMSKit manager with default configuration
245    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
246        Self {
247            storage,
248            config: SmsKitConfig::default(),
249        }
250    }
251
252    /// Create a new SMSKit manager with custom configuration
253    pub fn new_with_config(storage: Arc<dyn AuthStorage>, config: SmsKitConfig) -> Result<Self> {
254        let manager = Self { storage, config };
255        Ok(manager)
256    }
257
258    /// Register phone number for SMS MFA
259    pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
260        debug!("Registering phone number for user '{}' via SMSKit", user_id);
261
262        if phone_number.is_empty() {
263            return Err(AuthError::validation("Phone number cannot be empty"));
264        }
265
266        if !phone_number.starts_with('+') || phone_number.len() < 10 {
267            return Err(AuthError::validation(
268                "Phone number must be in international format (+1234567890)",
269            ));
270        }
271
272        let digits = &phone_number[1..];
273        if !digits.chars().all(|c| c.is_ascii_digit()) {
274            return Err(AuthError::validation(
275                "Phone number must contain only digits after the + sign",
276            ));
277        }
278
279        if digits.len() > 15 || digits.len() < 7 {
280            return Err(AuthError::validation(
281                "Phone number must be between 7 and 15 digits (E.164 format)",
282            ));
283        }
284
285        let key = format!("user:{}:phone", user_id);
286        self.storage
287            .store_kv(&key, phone_number.as_bytes(), None)
288            .await?;
289
290        info!(
291            "Phone number registered for user '{}': {} (SMSKit enabled)",
292            user_id, phone_number
293        );
294
295        Ok(())
296    }
297
298    /// Initiate SMS challenge with rate limiting
299    pub async fn initiate_challenge(&self, user_id: &str) -> Result<String> {
300        debug!("Initiating SMS challenge for user '{}' via SMSKit", user_id);
301
302        if user_id.is_empty() {
303            return Err(AuthError::validation("User ID cannot be empty"));
304        }
305
306        self.check_rate_limits(user_id).await?;
307
308        let challenge_id = crate::utils::string::generate_id(Some("smskit"));
309
310        info!("SMS challenge initiated for user '{}' via SMSKit", user_id);
311        Ok(challenge_id)
312    }
313
314    async fn check_rate_limits(&self, user_id: &str) -> Result<()> {
315        let now = chrono::Utc::now().timestamp();
316        let hour_ago = now - 3600;
317        let day_ago = now - 86400;
318
319        let hourly_key = format!("smskit:{}:hourly", user_id);
320        let hourly_count = self.get_sms_count(&hourly_key, hour_ago).await?;
321        if hourly_count >= self.config.rate_limiting.max_per_hour {
322            return Err(AuthError::rate_limited("SMS hourly limit exceeded"));
323        }
324
325        let daily_key = format!("smskit:{}:daily", user_id);
326        let daily_count = self.get_sms_count(&daily_key, day_ago).await?;
327        if daily_count >= self.config.rate_limiting.max_per_day {
328            return Err(AuthError::rate_limited("SMS daily limit exceeded"));
329        }
330
331        let last_sent_key = format!("smskit:{}:last_sent", user_id);
332        if let Some(last_sent_data) = self.storage.get_kv(&last_sent_key).await?
333            && let Ok(last_sent_str) = std::str::from_utf8(&last_sent_data)
334            && let Ok(last_sent) = last_sent_str.parse::<i64>()
335        {
336            let elapsed = now - last_sent;
337            if elapsed < self.config.rate_limiting.cooldown_seconds as i64 {
338                let remaining = self.config.rate_limiting.cooldown_seconds as i64 - elapsed;
339                return Err(AuthError::rate_limited(format!(
340                    "SMS cooldown active. Please wait {} seconds",
341                    remaining
342                )));
343            }
344        }
345
346        Ok(())
347    }
348
349    async fn get_sms_count(&self, key: &str, _since: i64) -> Result<u32> {
350        if let Some(count_data) = self.storage.get_kv(key).await?
351            && let Ok(count_str) = std::str::from_utf8(&count_data)
352            && let Ok(count) = count_str.parse::<u32>()
353        {
354            return Ok(count);
355        }
356        Ok(0)
357    }
358
359    /// Generate SMS verification code
360    pub async fn generate_code(&self, challenge_id: &str) -> Result<String> {
361        debug!(
362            "Generating SMS code for challenge '{}' via SMSKit",
363            challenge_id
364        );
365
366        let rng = ring::rand::SystemRandom::new();
367        let mut buf = [0u8; 4];
368        rng.fill(&mut buf).expect("system RNG failure");
369        let val = u32::from_le_bytes(buf) % 1_000_000;
370        let code = format!("{:06}", val);
371
372        let sms_key = format!("smskit_challenge:{}:code", challenge_id);
373        self.storage
374            .store_kv(&sms_key, code.as_bytes(), Some(Duration::from_secs(300)))
375            .await?;
376
377        Ok(code)
378    }
379
380    /// Verify SMS code
381    pub async fn verify_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
382        debug!(
383            "Verifying SMS code for challenge '{}' via SMSKit",
384            challenge_id
385        );
386
387        if challenge_id.is_empty() {
388            return Err(AuthError::validation("Challenge ID cannot be empty"));
389        }
390
391        if code.is_empty() {
392            return Err(AuthError::validation("SMS code cannot be empty"));
393        }
394
395        if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
396            return Ok(false);
397        }
398
399        let sms_key = format!("smskit_challenge:{}:code", challenge_id);
400        if let Some(stored_code_data) = self.storage.get_kv(&sms_key).await? {
401            let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
402            let is_valid: bool = stored_code.as_bytes().ct_eq(code.as_bytes()).into();
403
404            if is_valid {
405                let _ = self.storage.delete_kv(&sms_key).await;
406            }
407
408            Ok(is_valid)
409        } else {
410            Err(AuthError::validation("Invalid or expired challenge ID"))
411        }
412    }
413
414    /// Send SMS code using SMSKit with fallback support
415    pub async fn send_code(&self, user_id: &str, code: &str) -> Result<()> {
416        debug!("Sending SMS code to user '{}' via SMSKit", user_id);
417
418        let phone_key = format!("user:{}:phone", user_id);
419        let phone_number = if let Some(phone_data) = self.storage.get_kv(&phone_key).await? {
420            String::from_utf8(phone_data)
421                .map_err(|e| AuthError::internal(format!("Failed to parse phone number: {}", e)))?
422        } else {
423            return Err(AuthError::validation("No phone number registered for user"));
424        };
425
426        self.check_rate_limits(user_id).await?;
427
428        let message = format!(
429            "Your verification code is: {}. This code expires in 5 minutes. Do not share this code with anyone.",
430            code
431        );
432
433        match self.send_sms_with_fallback(&phone_number, &message).await {
434            Ok(message_id) => {
435                info!(
436                    "SMS code sent successfully to user '{}' (Message ID: {})",
437                    user_id, message_id
438                );
439                self.update_rate_limits(user_id).await?;
440                Ok(())
441            }
442            Err(e) => {
443                error!("Failed to send SMS to user '{}': {}", user_id, e);
444                Err(e)
445            }
446        }
447    }
448
449    async fn send_sms_with_fallback(&self, phone_number: &str, message: &str) -> Result<String> {
450        let result = match &self.config.provider {
451            SmsKitProvider::Twilio => self.send_via_twilio(phone_number, message).await,
452            SmsKitProvider::Plivo => self.send_via_plivo(phone_number, message).await,
453            SmsKitProvider::Development => {
454                info!("📱 [SMSKit Development] SMS sent to: {}", phone_number);
455                info!("   Message: {}", message);
456                Ok(format!("dev_msg_{}", chrono::Utc::now().timestamp()))
457            }
458        };
459
460        // On failure, try fallback provider if configured
461        match result {
462            Ok(msg_id) => Ok(msg_id),
463            Err(primary_err) => {
464                if let Some(fallback_provider) = &self.config.fallback_provider {
465                    warn!(
466                        "Primary SMS provider failed ({}), trying fallback: {:?}",
467                        primary_err, fallback_provider
468                    );
469                    match fallback_provider {
470                        SmsKitProvider::Development => {
471                            info!(
472                                "📱 [SMSKit Development Fallback] SMS sent to: {}",
473                                phone_number
474                            );
475                            info!("   Message: {}", message);
476                            Ok(format!(
477                                "dev_fallback_msg_{}",
478                                chrono::Utc::now().timestamp()
479                            ))
480                        }
481                        _ => Err(primary_err),
482                    }
483                } else {
484                    Err(primary_err)
485                }
486            }
487        }
488    }
489
490    /// Send SMS via Twilio using sms-twilio crate
491    #[cfg(feature = "smskit")]
492    async fn send_via_twilio(&self, phone_number: &str, message: &str) -> Result<String> {
493        use sms_core::SmsClient;
494
495        let (client, from_number) = if let SmsKitProviderConfig::Twilio {
496            account_sid,
497            auth_token,
498            from_number,
499            ..
500        } = &self.config.config
501        {
502            if account_sid.is_empty() || auth_token.is_empty() || from_number.is_empty() {
503                return Err(AuthError::internal("Twilio credentials are incomplete"));
504            }
505            (
506                sms_twilio::TwilioClient::new(account_sid, auth_token),
507                from_number.clone(),
508            )
509        } else {
510            let from_number = std::env::var("TWILIO_FROM_NUMBER").map_err(|_| {
511                AuthError::internal("Twilio from number not configured: set TWILIO_FROM_NUMBER")
512            })?;
513            let c = sms_twilio::TwilioClient::from_env()
514                .map_err(|e| AuthError::internal(format!("Twilio env config failed: {}", e)))?;
515            (c, from_number)
516        };
517
518        let request = sms_core::SendRequest {
519            to: phone_number,
520            from: &from_number,
521            text: message,
522        };
523
524        let response = client
525            .send(request)
526            .await
527            .map_err(|e| AuthError::internal(format!("Twilio SMS send failed: {}", e)))?;
528
529        debug!("Twilio SMS sent successfully, ID: {}", response.id);
530        Ok(response.id)
531    }
532
533    #[cfg(not(feature = "smskit"))]
534    async fn send_via_twilio(&self, _phone_number: &str, _message: &str) -> Result<String> {
535        Err(AuthError::internal(
536            "Twilio SMS requires the 'smskit' feature flag to be enabled",
537        ))
538    }
539
540    /// Send SMS via Plivo using sms-plivo crate
541    #[cfg(feature = "smskit")]
542    async fn send_via_plivo(&self, phone_number: &str, message: &str) -> Result<String> {
543        use sms_core::SmsClient;
544
545        let (client, from_number) = if let SmsKitProviderConfig::Plivo {
546            auth_id,
547            auth_token,
548            from_number,
549            ..
550        } = &self.config.config
551        {
552            if auth_id.is_empty() || auth_token.is_empty() || from_number.is_empty() {
553                return Err(AuthError::internal("Plivo credentials are incomplete"));
554            }
555            (
556                sms_plivo::PlivoClient::new(auth_id, auth_token),
557                from_number.clone(),
558            )
559        } else {
560            let from_number = std::env::var("PLIVO_FROM_NUMBER").map_err(|_| {
561                AuthError::internal("Plivo from number not configured: set PLIVO_FROM_NUMBER")
562            })?;
563            let c = sms_plivo::PlivoClient::from_env()
564                .map_err(|e| AuthError::internal(format!("Plivo env config failed: {}", e)))?;
565            (c, from_number)
566        };
567
568        let request = sms_core::SendRequest {
569            to: phone_number,
570            from: &from_number,
571            text: message,
572        };
573
574        let response = client
575            .send(request)
576            .await
577            .map_err(|e| AuthError::internal(format!("Plivo SMS send failed: {}", e)))?;
578
579        debug!("Plivo SMS sent successfully, ID: {}", response.id);
580        Ok(response.id)
581    }
582
583    #[cfg(not(feature = "smskit"))]
584    async fn send_via_plivo(&self, _phone_number: &str, _message: &str) -> Result<String> {
585        Err(AuthError::internal(
586            "Plivo SMS requires the 'smskit' feature flag to be enabled",
587        ))
588    }
589
590    async fn update_rate_limits(&self, user_id: &str) -> Result<()> {
591        let now = chrono::Utc::now().timestamp();
592
593        let hourly_key = format!("smskit:{}:hourly", user_id);
594        let hourly_count = self.get_sms_count(&hourly_key, now - 3600).await? + 1;
595        self.storage
596            .store_kv(
597                &hourly_key,
598                hourly_count.to_string().as_bytes(),
599                Some(Duration::from_secs(3600)),
600            )
601            .await?;
602
603        let daily_key = format!("smskit:{}:daily", user_id);
604        let daily_count = self.get_sms_count(&daily_key, now - 86400).await? + 1;
605        self.storage
606            .store_kv(
607                &daily_key,
608                daily_count.to_string().as_bytes(),
609                Some(Duration::from_secs(86400)),
610            )
611            .await?;
612
613        let last_sent_key = format!("smskit:{}:last_sent", user_id);
614        self.storage
615            .store_kv(
616                &last_sent_key,
617                now.to_string().as_bytes(),
618                Some(Duration::from_secs(
619                    self.config.rate_limiting.cooldown_seconds,
620                )),
621            )
622            .await?;
623
624        Ok(())
625    }
626
627    /// Get user's phone number
628    pub async fn get_user_phone(&self, user_id: &str) -> Result<Option<String>> {
629        let phone_key = format!("user:{}:phone", user_id);
630
631        if let Some(phone_data) = self.storage.get_kv(&phone_key).await? {
632            Ok(Some(String::from_utf8(phone_data).map_err(|e| {
633                AuthError::internal(format!("Failed to parse phone number: {}", e))
634            })?))
635        } else {
636            Ok(None)
637        }
638    }
639
640    /// Check if user has phone number configured
641    pub async fn has_phone_number(&self, user_id: &str) -> Result<bool> {
642        let key = format!("user:{}:phone", user_id);
643        match self.storage.get_kv(&key).await {
644            Ok(Some(_)) => Ok(true),
645            Ok(None) => Ok(false),
646            Err(_) => Ok(false), // Assume false on error
647        }
648    }
649
650    /// Send verification code and return the generated code
651    pub async fn send_verification_code(&self, user_id: &str) -> Result<String> {
652        // Generate a 6-digit code
653        let code = format!("{:06}", rand::random::<u32>() % 1_000_000);
654
655        // Send the code via SMS
656        self.send_code(user_id, &code).await?;
657
658        // Store the code for later verification
659        let code_key = format!("sms_verification:{}:{}", user_id, Uuid::new_v4());
660        self.storage
661            .store_kv(
662                &code_key,
663                code.as_bytes(),
664                Some(std::time::Duration::from_secs(300)),
665            )
666            .await?;
667
668        Ok(code)
669    }
670}
671
672#[cfg(test)]
673mod deserialize_migration_tests {
674    use super::*;
675
676    /// Arm 1: a persisted `AwsSns` selection (the exact shape this crate's
677    /// own `Serialize` impl produced before the variant was removed) must
678    /// still FAIL to deserialize -- not fall back to another provider, not
679    /// succeed -- and the error must name the feature, the version it was
680    /// removed in, and where to look.
681    #[test]
682    fn aws_sns_provider_fails_with_actionable_migration_message() {
683        let err = serde_json::from_str::<SmsKitProvider>("\"AwsSns\"")
684            .expect_err("AwsSns must fail to deserialize, not succeed");
685        let msg = err.to_string();
686        assert!(
687            msg.contains("sms-aws-sns"),
688            "message should name the removed feature: {msg}"
689        );
690        assert!(
691            msg.contains("0.6.0"),
692            "message should name the removal version: {msg}"
693        );
694        assert!(
695            msg.contains("CHANGELOG"),
696            "message should say where to look: {msg}"
697        );
698    }
699
700    #[test]
701    fn aws_sns_provider_config_fails_with_actionable_migration_message() {
702        let json = r#"{"AwsSns":{"region":"us-east-1","access_key_id":"AKIA...","secret_access_key":"secret"}}"#;
703        let err = serde_json::from_str::<SmsKitProviderConfig>(json)
704            .expect_err("AwsSns config must fail to deserialize, not succeed");
705        let msg = err.to_string();
706        assert!(
707            msg.contains("sms-aws-sns"),
708            "message should name the removed feature: {msg}"
709        );
710        assert!(
711            msg.contains("0.6.0"),
712            "message should name the removal version: {msg}"
713        );
714        assert!(
715            msg.contains("CHANGELOG"),
716            "message should say where to look: {msg}"
717        );
718    }
719
720    /// Arm 2 (control): every provider that still exists must keep
721    /// deserializing cleanly. Without this arm, a manual `Deserialize` that
722    /// rejects everything would also pass arm 1.
723    ///
724    /// These JSON literals are hand-written, not round-tripped through this
725    /// crate's own `Serialize` -- a round-trip only proves self-consistency
726    /// (that Serialize and Deserialize agree with each other), not backward
727    /// compatibility with what an existing consumer's config already
728    /// contains. Confirmed the exact accepted spellings against the
729    /// PRE-#38 derived impl (`git show 0e47858^:src/auth_modular/mfa/sms_kit.rs`)
730    /// before writing these: no `#[serde(rename_all = ...)]`, no field or
731    /// variant renames, no aliases, no custom tagging -- plain externally-
732    /// tagged PascalCase, so `"Twilio"` / `{"Twilio": {...}}` etc. are what
733    /// the OLD derive actually accepted, not an assumption from this PR's
734    /// own types.
735    #[test]
736    fn literal_pre_existing_config_strings_still_deserialize() {
737        let twilio: SmsKitProvider = serde_json::from_str("\"Twilio\"").unwrap();
738        assert!(matches!(twilio, SmsKitProvider::Twilio));
739
740        let plivo: SmsKitProvider = serde_json::from_str("\"Plivo\"").unwrap();
741        assert!(matches!(plivo, SmsKitProvider::Plivo));
742
743        let dev: SmsKitProvider = serde_json::from_str("\"Development\"").unwrap();
744        assert!(matches!(dev, SmsKitProvider::Development));
745
746        let twilio_cfg: SmsKitProviderConfig = serde_json::from_str(
747            r#"{"Twilio":{"account_sid":"AC1","auth_token":"tok","from_number":"+15551234567","webhook_url":null}}"#,
748        )
749        .unwrap();
750        assert!(matches!(twilio_cfg, SmsKitProviderConfig::Twilio { .. }));
751
752        let plivo_cfg: SmsKitProviderConfig = serde_json::from_str(
753            r#"{"Plivo":{"auth_id":"id","auth_token":"tok","from_number":"+15551234567","webhook_url":null}}"#,
754        )
755        .unwrap();
756        assert!(matches!(plivo_cfg, SmsKitProviderConfig::Plivo { .. }));
757
758        let dev_cfg: SmsKitProviderConfig = serde_json::from_str(r#""Development""#).unwrap();
759        assert!(matches!(dev_cfg, SmsKitProviderConfig::Development));
760    }
761
762    /// Round-trip control: confirm Twilio's Serialize output still
763    /// deserializes through the new manual impl (not just hand-built JSON).
764    #[test]
765    fn round_trip_still_works_for_a_surviving_provider() {
766        let original = SmsKitProvider::Twilio;
767        let json = serde_json::to_string(&original).unwrap();
768        let round_tripped: SmsKitProvider = serde_json::from_str(&json).unwrap();
769        assert!(matches!(round_tripped, SmsKitProvider::Twilio));
770    }
771}