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