use super::{GarrisonDao, GarrisonResult, SmsRateLimiter};
use crate::error::GarrisonError;
use crate::limiteron::GarrisonDaoDistributedLimiter;
use std::sync::Arc;
use std::time::Duration;
pub(super) fn validate_phone(phone: &str) -> GarrisonResult<()> {
if phone.is_empty() {
return Err(GarrisonError::InvalidParam(
"secure-phone-empty::".to_string(),
));
}
if phone.contains(':') {
return Err(GarrisonError::InvalidParam(
"secure-phone-no-colon".to_string(),
));
}
if phone.chars().any(|c| c.is_control()) {
return Err(GarrisonError::InvalidParam(
"secure-phone-no-control-char".to_string(),
));
}
if phone.len() > 20 {
return Err(GarrisonError::InvalidParam(
"secure-phone-too-long".to_string(),
));
}
Ok(())
}
impl SmsRateLimiter {
pub fn new(dao: Arc<dyn GarrisonDao>, hourly_limit: u32, daily_limit: u32) -> Self {
let limiter = Arc::new(GarrisonDaoDistributedLimiter::new(dao.clone()));
Self {
dao,
limiter,
hourly_limit,
daily_limit,
}
}
pub(super) async fn decrement_counter(dao: &dyn GarrisonDao, key: &str) -> GarrisonResult<()> {
dao.decr(key).await.map(|_| ())
}
pub async fn check_and_increment(&self, phone: &str) -> GarrisonResult<()> {
validate_phone(phone)?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| GarrisonError::Internal(format!("secure-system-time::{}", e)))?;
let hour_bucket = now.as_secs() / 3600;
let date = chrono::Utc::now().format("%Y-%m-%d").to_string();
let hour_key = format!("sms:rate:{}:hour:{}", phone, hour_bucket);
let hour_count = self
.limiter
.incr_with_ttl(&hour_key, 1, Duration::from_secs(3600))
.await
.map_err(|e| GarrisonError::Internal(format!("secure-limiter-incr::{}", e)))?;
if hour_count > self.hourly_limit as u64 {
if let Err(e) = Self::decrement_counter(&*self.dao, &hour_key).await {
tracing::warn!(error = %e, key = %hour_key, "rollback hourly window counter failed");
}
return Err(GarrisonError::SmsRateLimitExceeded {
window: "hourly".to_string(),
});
}
let day_key = format!("sms:rate:{}:day:{}", phone, date);
let day_count = self
.limiter
.incr_with_ttl(&day_key, 1, Duration::from_secs(86400))
.await
.map_err(|e| GarrisonError::Internal(format!("secure-limiter-incr::{}", e)))?;
if day_count > self.daily_limit as u64 {
if let Err(e) = Self::decrement_counter(&*self.dao, &day_key).await {
tracing::warn!(error = %e, key = %day_key, "rollback daily window counter failed");
}
if let Err(e) = Self::decrement_counter(&*self.dao, &hour_key).await {
tracing::warn!(error = %e, key = %hour_key, "rollback hourly window counter failed");
}
return Err(GarrisonError::SmsRateLimitExceeded {
window: "daily".to_string(),
});
}
Ok(())
}
pub async fn rollback(&self, phone: &str) -> GarrisonResult<()> {
validate_phone(phone)?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| GarrisonError::Internal(format!("secure-system-time::{}", e)))?;
let hour_bucket = now.as_secs() / 3600;
let date = chrono::Utc::now().format("%Y-%m-%d").to_string();
let hour_key = format!("sms:rate:{}:hour:{}", phone, hour_bucket);
Self::decrement_counter(&*self.dao, &hour_key).await?;
let day_key = format!("sms:rate:{}:day:{}", phone, date);
Self::decrement_counter(&*self.dao, &day_key).await?;
Ok(())
}
}