use crate::constants::DaoKeyPrefix;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::strategy::firewall::{FirewallContext, GarrisonFirewallStrategy, StrategyRegistration};
use async_trait::async_trait;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use super::{LockoutState, UserLockoutConfig, UserLockoutStrategy, WaitStrategy};
impl Default for UserLockoutConfig {
fn default() -> Self {
Self {
max_failure_factor: 5,
permanent_lockout: true,
max_temporary_lockouts: 3,
wait_strategy: WaitStrategy::Multiple {
base_seconds: 60,
multiplier: 2,
},
failure_window_seconds: 300,
}
}
}
pub(super) fn now_timestamp() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
fn calculate_lock_seconds(strategy: &WaitStrategy, n: u32) -> u64 {
let n = n.max(1);
match strategy {
WaitStrategy::Multiple {
base_seconds,
multiplier,
} => {
let factor = (*multiplier as u64).saturating_pow(n - 1);
base_seconds.saturating_mul(factor)
},
WaitStrategy::Linear { base_seconds } => base_seconds.saturating_mul(n as u64),
}
}
const MAX_STATE_CAS_RETRIES: u32 = 5;
enum LockoutTrigger {
None,
Temporary,
Permanent,
}
pub(super) const LOCKOUT_TTL_MARGIN_SECONDS: u64 = 60;
pub(super) fn state_ttl_seconds(
state: &LockoutState,
now: i64,
failure_window_seconds: u64,
) -> u64 {
if state.permanent_locked || state.temporary_lockout_count > 0 {
return 0;
}
let window_end = state.first_failure_at.map_or(now, |first| {
first.saturating_add(failure_window_seconds as i64)
});
let horizon = window_end.max(state.locked_until);
let remaining = horizon.saturating_sub(now);
if remaining <= 0 {
LOCKOUT_TTL_MARGIN_SECONDS
} else {
(remaining as u64).saturating_add(LOCKOUT_TTL_MARGIN_SECONDS)
}
}
impl UserLockoutStrategy {
pub fn new(config: UserLockoutConfig, dao: Arc<dyn GarrisonDao>) -> Self {
let config = match config.validate() {
Ok(()) => config,
Err(e) => {
tracing::warn!(
error = %e,
"UserLockoutConfig invalid, falling back to default config \
(degenerate values such as max_failure_factor=0 would lock on first failure)"
);
UserLockoutConfig::default()
},
};
Self {
config,
dao,
#[cfg(feature = "metrics-prometheus")]
metrics: None,
}
}
#[cfg(feature = "metrics-prometheus")]
pub fn with_metrics(mut self, metrics: Arc<crate::account::metrics::AccountMetrics>) -> Self {
self.metrics = Some(metrics);
self
}
pub(super) async fn get_state(&self, user_id: &str) -> GarrisonResult<LockoutState> {
let key = DaoKeyPrefix::Lockout.build_key(user_id);
match self.dao.get(&key).await? {
Some(json) => serde_json::from_str(&json)
.map_err(|e| GarrisonError::Dao(format!("account-lockout-deserialize::{}", e))),
None => Ok(LockoutState::default()),
}
}
pub(super) async fn set_state(
&self,
user_id: &str,
state: &LockoutState,
) -> GarrisonResult<()> {
let key = DaoKeyPrefix::Lockout.build_key(user_id);
let json = serde_json::to_string(state)
.map_err(|e| GarrisonError::Dao(format!("account-lockout-serialize::{}", e)))?;
let ttl = state_ttl_seconds(state, now_timestamp(), self.config.failure_window_seconds);
self.dao.set(&key, &json, ttl).await
}
pub(super) async fn cas_state(
&self,
user_id: &str,
expected: Option<&str>,
state: &LockoutState,
) -> GarrisonResult<bool> {
let key = DaoKeyPrefix::Lockout.build_key(user_id);
let json = serde_json::to_string(state)
.map_err(|e| GarrisonError::Dao(format!("account-lockout-serialize::{}", e)))?;
let ttl = state_ttl_seconds(state, now_timestamp(), self.config.failure_window_seconds);
self.dao.compare_and_swap(&key, expected, &json, ttl).await
}
pub async fn record_failure(&self, user_id: &str) -> GarrisonResult<()> {
let now = now_timestamp();
for attempt in 1..=MAX_STATE_CAS_RETRIES {
let key = DaoKeyPrefix::Lockout.build_key(user_id);
let old_json = self.dao.get(&key).await?;
let mut state = match &old_json {
Some(json) => serde_json::from_str(json).map_err(|e| {
GarrisonError::Dao(format!("account-lockout-deserialize::{}", e))
})?,
None => LockoutState::default(),
};
#[cfg_attr(not(feature = "metrics-prometheus"), allow(unused_variables))]
let trigger = self.advance_failure_state(&mut state, now);
if self.cas_state(user_id, old_json.as_deref(), &state).await? {
#[cfg(feature = "metrics-prometheus")]
if let Some(metrics) = &self.metrics {
match trigger {
LockoutTrigger::Permanent => metrics.record_lockout(true),
LockoutTrigger::Temporary => metrics.record_lockout(false),
LockoutTrigger::None => {},
}
}
return Ok(());
}
tracing::debug!(
user_id = user_id,
attempt = attempt,
max_retries = MAX_STATE_CAS_RETRIES,
"lockout state CAS conflict on record_failure, retrying"
);
}
Err(GarrisonError::Dao(format!(
"account-lockout-cas-retry-exhausted::{}",
user_id
)))
}
fn advance_failure_state(&self, state: &mut LockoutState, now: i64) -> LockoutTrigger {
match state.first_failure_at {
Some(first_at) if now - first_at > self.config.failure_window_seconds as i64 => {
state.failure_count = 0;
state.first_failure_at = Some(now);
},
None => {
state.first_failure_at = Some(now);
},
Some(_) => {},
}
state.failure_count = state.failure_count.saturating_add(1);
if state.failure_count < self.config.max_failure_factor {
return LockoutTrigger::None;
}
if self.config.permanent_lockout
&& state.temporary_lockout_count.saturating_add(1) > self.config.max_temporary_lockouts
{
state.permanent_locked = true;
return LockoutTrigger::Permanent;
}
state.temporary_lockout_count = state.temporary_lockout_count.saturating_add(1);
let lock_seconds =
calculate_lock_seconds(&self.config.wait_strategy, state.temporary_lockout_count);
let lock_seconds_i64 = i64::try_from(lock_seconds).unwrap_or(i64::MAX);
state.locked_until = now.saturating_add(lock_seconds_i64);
LockoutTrigger::Temporary
}
pub async fn record_success(&self, user_id: &str) -> GarrisonResult<()> {
for attempt in 1..=MAX_STATE_CAS_RETRIES {
let key = DaoKeyPrefix::Lockout.build_key(user_id);
let old_json = self.dao.get(&key).await?;
let mut state = match &old_json {
Some(json) => serde_json::from_str(json).map_err(|e| {
GarrisonError::Dao(format!("account-lockout-deserialize::{}", e))
})?,
None => LockoutState::default(),
};
state.failure_count = 0;
state.first_failure_at = None;
state.temporary_lockout_count = 0;
state.locked_until = 0;
if self.cas_state(user_id, old_json.as_deref(), &state).await? {
return Ok(());
}
tracing::debug!(
user_id = user_id,
attempt = attempt,
max_retries = MAX_STATE_CAS_RETRIES,
"lockout state CAS conflict on record_success, retrying"
);
}
Err(GarrisonError::Dao(format!(
"account-lockout-cas-retry-exhausted::{}",
user_id
)))
}
pub async fn unlock(&self, user_id: &str) -> GarrisonResult<()> {
let state = LockoutState::default();
self.set_state(user_id, &state).await
}
}
#[async_trait]
impl GarrisonFirewallStrategy for UserLockoutStrategy {
async fn check(&self, ctx: &FirewallContext) -> GarrisonResult<()> {
let user_id = match &ctx.login_id {
Some(id) => id.as_str(),
None => return Ok(()),
};
let state = self.get_state(user_id).await?;
if state.permanent_locked {
return Err(GarrisonError::FirewallBlocked(format!(
"user-lockout-permanent::{}",
user_id
)));
}
let now = now_timestamp();
if state.locked_until > now {
return Err(GarrisonError::FirewallBlocked(format!(
"user-lockout-temporary::{}::{}",
user_id, state.locked_until
)));
}
Ok(())
}
}
inventory::submit! {
StrategyRegistration {
name: "user-lockout",
}
}