use crate::error::GarrisonResult;
use crate::session::GarrisonSession;
use async_trait::async_trait;
use std::sync::Arc;
use uuid::Uuid;
use super::{AnomalyDetector, AnomalyType, SecurityAlertEvent};
pub struct IpChangeDetector {
session: Arc<GarrisonSession>,
}
impl IpChangeDetector {
pub fn new(session: Arc<GarrisonSession>) -> Self {
Self { session }
}
}
#[async_trait]
impl AnomalyDetector for IpChangeDetector {
async fn check_on_login(
&self,
login_id: &str,
_device_id: &str,
ip: Option<&str>,
) -> GarrisonResult<Vec<SecurityAlertEvent>> {
let current_ip = match ip {
Some(ip) => ip,
None => return Ok(Vec::new()),
};
let tokens = self.session.get_tokens_by_login_id(login_id);
if tokens.is_empty() {
return Ok(Vec::new()); }
let mut latest_ip: Option<String> = None;
let mut latest_active_at: i64 = i64::MIN;
for token in &tokens {
if let Some(ts) = self.session.get_token_session(token).await? {
if ts.last_active_at > latest_active_at {
latest_active_at = ts.last_active_at;
latest_ip = ts.ip;
}
}
}
let historical_ip = match latest_ip {
Some(ip) => ip,
None => return Ok(Vec::new()),
};
if historical_ip == current_ip {
return Ok(Vec::new());
}
Ok(vec![SecurityAlertEvent::AnomalyLogin {
login_id: login_id.to_string(),
anomaly_type: AnomalyType::IpChanged,
detail: format!("IP 从 {} 变为 {}", historical_ip, current_ip),
trace_id: Uuid::new_v4().to_string(),
}])
}
async fn check_on_check_login(
&self,
_login_id: &str,
_token: &str,
) -> GarrisonResult<Vec<SecurityAlertEvent>> {
Ok(Vec::new())
}
}
pub struct RapidSuccessiveDetector {
session: Arc<GarrisonSession>,
threshold: usize,
}
impl RapidSuccessiveDetector {
pub fn new(session: Arc<GarrisonSession>) -> Self {
Self {
session,
threshold: 5,
}
}
pub fn with_threshold(session: Arc<GarrisonSession>, threshold: usize) -> Self {
Self { session, threshold }
}
}
#[async_trait]
impl AnomalyDetector for RapidSuccessiveDetector {
async fn check_on_login(
&self,
login_id: &str,
_device_id: &str,
_ip: Option<&str>,
) -> GarrisonResult<Vec<SecurityAlertEvent>> {
let tokens = self.session.get_tokens_by_login_id(login_id);
let count = tokens.len();
if count >= self.threshold {
return Ok(vec![SecurityAlertEvent::AnomalyLogin {
login_id: login_id.to_string(),
anomaly_type: AnomalyType::RapidSuccessiveLogin,
detail: format!("{} 个 token 同时在线(阈值 {})", count, self.threshold),
trace_id: Uuid::new_v4().to_string(),
}]);
}
Ok(Vec::new())
}
async fn check_on_check_login(
&self,
_login_id: &str,
_token: &str,
) -> GarrisonResult<Vec<SecurityAlertEvent>> {
Ok(Vec::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::session::TokenSession;
use crate::stp::LoginParams;
fn make_session() -> (Arc<MockDao>, Arc<GarrisonSession>) {
let dao: Arc<MockDao> = Arc::new(MockDao::new());
let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400));
(dao, session)
}
async fn create_session_with_ip(
session: &GarrisonSession,
login_id: &str,
token: &str,
ip: &str,
) {
let params = LoginParams {
ip: Some(ip.to_string()),
..Default::default()
};
session
.create_token_session(login_id, token, ¶ms)
.await
.unwrap();
}
async fn set_last_active_at(dao: &MockDao, token: &str, last_active_at: i64) {
let key = format!("token:session:{}", token);
let json = dao.get(&key).await.unwrap().unwrap();
let mut ts: TokenSession = serde_json::from_str(&json).unwrap();
ts.last_active_at = last_active_at;
let new_json = serde_json::to_string(&ts).unwrap();
dao.set(&key, &new_json, 3600).await.unwrap();
}
#[tokio::test]
async fn ip_same_no_alert() {
let (_dao, session) = make_session();
create_session_with_ip(&session, "1001", "T1", "1.2.3.4").await;
let detector = IpChangeDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", Some("1.2.3.4"))
.await
.unwrap();
assert!(alerts.is_empty(), "IP 相同时不应告警");
}
#[tokio::test]
async fn ip_different_emits_alert() {
let (_dao, session) = make_session();
create_session_with_ip(&session, "1001", "T1", "1.2.3.4").await;
let detector = IpChangeDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", Some("5.6.7.8"))
.await
.unwrap();
assert_eq!(alerts.len(), 1, "IP 不同时应返回 1 个告警");
match &alerts[0] {
SecurityAlertEvent::AnomalyLogin { detail, .. } => {
assert!(detail.contains("1.2.3.4"), "detail 应包含历史 IP");
assert!(detail.contains("5.6.7.8"), "detail 应包含当前 IP");
},
_ => panic!("期望 AnomalyLogin 事件"),
}
}
#[tokio::test]
async fn no_history_no_alert() {
let (_dao, session) = make_session();
let detector = IpChangeDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", Some("1.2.3.4"))
.await
.unwrap();
assert!(alerts.is_empty(), "无历史 session 时不应告警");
}
#[tokio::test]
async fn no_current_ip_no_alert() {
let (_dao, session) = make_session();
create_session_with_ip(&session, "1001", "T1", "1.2.3.4").await;
let detector = IpChangeDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", None)
.await
.unwrap();
assert!(alerts.is_empty(), "当前 IP 为 None 时不应告警");
}
#[tokio::test]
async fn check_on_login_returns_ok() {
let (_dao, session) = make_session();
create_session_with_ip(&session, "1001", "T1", "1.2.3.4").await;
let detector = IpChangeDetector::new(session);
let result = detector
.check_on_login("1001", "dev-1", Some("1.2.3.4"))
.await;
assert!(result.is_ok(), "check_on_login 应返回 Ok");
}
#[tokio::test]
async fn check_on_check_login_returns_empty() {
let (_dao, session) = make_session();
create_session_with_ip(&session, "1001", "T1", "1.2.3.4").await;
let detector = IpChangeDetector::new(session);
let alerts = detector.check_on_check_login("1001", "T1").await.unwrap();
assert!(alerts.is_empty(), "check_on_check_login 应返回空 Vec");
}
#[tokio::test]
async fn multiple_sessions_uses_latest_ip() {
let (dao, session) = make_session();
create_session_with_ip(&session, "1001", "T1", "1.1.1.1").await;
create_session_with_ip(&session, "1001", "T2", "2.2.2.2").await;
set_last_active_at(&dao, "T1", 1000).await;
let detector = IpChangeDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", Some("3.3.3.3"))
.await
.unwrap();
assert_eq!(alerts.len(), 1, "应返回 1 个告警");
match &alerts[0] {
SecurityAlertEvent::AnomalyLogin { detail, .. } => {
assert!(
detail.contains("2.2.2.2"),
"detail 应包含最近活跃 session 的 IP (2.2.2.2),实际: {}",
detail
);
assert!(
!detail.contains("1.1.1.1"),
"detail 不应包含旧 session 的 IP"
);
},
_ => panic!("期望 AnomalyLogin 事件"),
}
}
#[tokio::test]
async fn alert_contains_correct_anomaly_type() {
let (_dao, session) = make_session();
create_session_with_ip(&session, "1001", "T1", "1.2.3.4").await;
let detector = IpChangeDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", Some("5.6.7.8"))
.await
.unwrap();
assert_eq!(alerts.len(), 1);
match &alerts[0] {
SecurityAlertEvent::AnomalyLogin { anomaly_type, .. } => {
assert_eq!(
*anomaly_type,
AnomalyType::IpChanged,
"anomaly_type 应为 IpChanged"
);
},
_ => panic!("期望 AnomalyLogin 事件"),
}
}
async fn create_n_tokens(session: &GarrisonSession, login_id: &str, count: usize) {
for i in 0..count {
let token = format!("T{}", i);
session
.create_token_session(login_id, &token, &LoginParams::default())
.await
.unwrap();
}
}
#[tokio::test]
async fn below_threshold_no_alert() {
let (_dao, session) = make_session();
create_n_tokens(&session, "1001", 3).await;
let detector = RapidSuccessiveDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", None)
.await
.unwrap();
assert!(alerts.is_empty(), "token 数量 < 阈值时不应告警");
}
#[tokio::test]
async fn above_threshold_emits_alert() {
let (_dao, session) = make_session();
create_n_tokens(&session, "1001", 6).await;
let detector = RapidSuccessiveDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", None)
.await
.unwrap();
assert_eq!(alerts.len(), 1, "token 数量 >= 阈值时应返回 1 个告警");
}
#[tokio::test]
async fn threshold_boundary() {
let (_dao, session) = make_session();
create_n_tokens(&session, "1001", 3).await;
let detector = RapidSuccessiveDetector::with_threshold(session, 3);
let alerts = detector
.check_on_login("1001", "dev-1", None)
.await
.unwrap();
assert_eq!(alerts.len(), 1, "token 数量 == 阈值时应返回告警(>= 触发)");
}
#[tokio::test]
async fn no_existing_tokens_no_alert() {
let (_dao, session) = make_session();
let detector = RapidSuccessiveDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", None)
.await
.unwrap();
assert!(alerts.is_empty(), "无历史 token 时不应告警");
}
#[tokio::test]
async fn rapid_check_on_check_login_returns_empty() {
let (_dao, session) = make_session();
create_n_tokens(&session, "1001", 6).await;
let detector = RapidSuccessiveDetector::new(session);
let alerts = detector.check_on_check_login("1001", "T0").await.unwrap();
assert!(alerts.is_empty(), "check_on_check_login 应返回空 Vec");
}
#[tokio::test]
async fn rapid_alert_contains_correct_anomaly_type() {
let (_dao, session) = make_session();
create_n_tokens(&session, "1001", 5).await;
let detector = RapidSuccessiveDetector::new(session);
let alerts = detector
.check_on_login("1001", "dev-1", None)
.await
.unwrap();
assert_eq!(alerts.len(), 1);
match &alerts[0] {
SecurityAlertEvent::AnomalyLogin { anomaly_type, .. } => {
assert_eq!(
*anomaly_type,
AnomalyType::RapidSuccessiveLogin,
"anomaly_type 应为 RapidSuccessiveLogin"
);
},
_ => panic!("期望 AnomalyLogin 事件"),
}
}
}