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