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