use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::listener::{GarrisonEvent, GarrisonListenerManager};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::watch;
const MAX_SCAN: usize = 10_000;
const MAX_LOGIN_ID_LEN: usize = 128;
const RECORD_TTL_SECS: u64 = 86_400;
const SCAN_WINDOW_SECS: i64 = 3_600;
const SCAN_SLOW_THRESHOLD: Duration = Duration::from_secs(1);
const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LoginResult {
Success,
Failed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnomalousLoginRecord {
pub login_id: String,
pub ip: String,
pub geo: Option<String>,
pub device: Option<String>,
pub timestamp: i64,
pub result: LoginResult,
}
#[derive(Debug, Clone)]
pub struct AnomalousAnalyzerConfig {
pub interval_secs: u64,
pub burst_threshold: u32,
pub max_scan: usize,
}
impl Default for AnomalousAnalyzerConfig {
fn default() -> Self {
Self {
interval_secs: 3600,
burst_threshold: 5,
max_scan: MAX_SCAN,
}
}
}
impl AnomalousAnalyzerConfig {
pub fn validate(&self) -> GarrisonResult<()> {
if self.interval_secs == 0 {
return Err(GarrisonError::Config(
"strategy-interval-secs-zero::".to_string(),
));
}
if self.burst_threshold == 0 {
return Err(GarrisonError::Config(
"strategy-burst-threshold-zero::".to_string(),
));
}
if self.max_scan == 0 {
return Err(GarrisonError::Config(
"strategy-max-scan-zero::".to_string(),
));
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct AnomalousLoginDetected {
pub login_id: String,
pub reason: String,
pub detail: serde_json::Value,
pub timestamp: i64,
}
impl From<AnomalousLoginDetected> for GarrisonEvent {
fn from(e: AnomalousLoginDetected) -> Self {
GarrisonEvent::AnomalousLoginDetected {
login_id: e.login_id,
reason: e.reason,
detail: e.detail,
timestamp: e.timestamp,
request_context: None,
}
}
}
pub struct AnomalousLoginAnalyzer {
dao: Arc<dyn GarrisonDao>,
config: AnomalousAnalyzerConfig,
listener_manager: Option<Arc<GarrisonListenerManager>>,
shutdown_rx: watch::Receiver<bool>,
}
impl AnomalousLoginAnalyzer {
pub fn new(
dao: Arc<dyn GarrisonDao>,
config: AnomalousAnalyzerConfig,
shutdown_rx: watch::Receiver<bool>,
listener_manager: Option<Arc<GarrisonListenerManager>>,
) -> Self {
Self {
dao,
config,
listener_manager,
shutdown_rx,
}
}
pub async fn record_login(&self, record: &AnomalousLoginRecord) -> GarrisonResult<()> {
if record.login_id.is_empty() {
return Err(GarrisonError::InvalidParam(
"strategy-login-id-empty::".to_string(),
));
}
if record.login_id.contains(':') {
return Err(GarrisonError::InvalidParam(
"strategy-login-id-no-colon".to_string(),
));
}
if record.login_id.len() > MAX_LOGIN_ID_LEN {
return Err(GarrisonError::InvalidParam(format!(
"strategy-login-id-too-long::{}::{}",
record.login_id.len(),
MAX_LOGIN_ID_LEN
)));
}
let key = Self::make_storage_key(&record.login_id, record.timestamp);
let value = serde_json::to_string(record)
.map_err(|e| GarrisonError::Internal(format!("strategy-anomalous-serialize::{}", e)))?;
self.dao.set(&key, &value, RECORD_TTL_SECS).await
}
fn make_storage_key(login_id: &str, timestamp_secs: i64) -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(timestamp_secs as u128);
if nanos == timestamp_secs as u128 {
tracing::warn!(
login_id,
fallback_ts = timestamp_secs,
"anomalous_analyzer: system clock error, storage key falls back to second-precision timestamp (uniqueness not guaranteed)"
);
}
format!("anomalous:login:{}:{}", login_id, nanos)
}
pub async fn analyze(&self) -> GarrisonResult<Vec<AnomalousLoginDetected>> {
let now = chrono::Utc::now().timestamp();
Self::analyze_once(&self.dao, &self.config, now).await
}
async fn analyze_once(
dao: &Arc<dyn GarrisonDao>,
config: &AnomalousAnalyzerConfig,
now: i64,
) -> GarrisonResult<Vec<AnomalousLoginDetected>> {
let scan_start = std::time::Instant::now();
let keys = dao.keys("anomalous:login:*").await?;
let keys: Vec<String> = keys.into_iter().take(config.max_scan).collect();
let mut grouped: HashMap<String, Vec<AnomalousLoginRecord>> = HashMap::new();
for key in &keys {
match dao.get(key).await {
Ok(Some(value)) => match serde_json::from_str::<AnomalousLoginRecord>(&value) {
Ok(record) => {
if record.timestamp >= now - SCAN_WINDOW_SECS && record.timestamp <= now {
grouped
.entry(record.login_id.clone())
.or_default()
.push(record);
}
},
Err(e) => {
tracing::warn!("failed to deserialize login record (key={}): {}", key, e);
},
},
Ok(None) => {},
Err(e) => {
tracing::warn!("failed to read login record (key={}): {}", key, e);
},
}
}
let mut events = Vec::new();
for (login_id, records) in grouped {
if records.len() > config.burst_threshold as usize {
events.push(AnomalousLoginDetected {
login_id: login_id.clone(),
reason: "burst_login".to_string(),
detail: serde_json::json!({
"count": records.len(),
"threshold": config.burst_threshold,
}),
timestamp: now,
});
}
let distinct_geo: HashSet<&str> =
records.iter().filter_map(|r| r.geo.as_deref()).collect();
if distinct_geo.len() > 2 {
events.push(AnomalousLoginDetected {
login_id: login_id.clone(),
reason: "geo_jump".to_string(),
detail: serde_json::json!({
"distinct_geo": distinct_geo.len(),
"geo": distinct_geo.iter().collect::<Vec<_>>(),
}),
timestamp: now,
});
}
let distinct_device: HashSet<&str> =
records.iter().filter_map(|r| r.device.as_deref()).collect();
if distinct_device.len() > 3 {
events.push(AnomalousLoginDetected {
login_id: login_id.clone(),
reason: "device_mutation".to_string(),
detail: serde_json::json!({
"distinct_device": distinct_device.len(),
"device": distinct_device.iter().collect::<Vec<_>>(),
}),
timestamp: now,
});
}
}
let scan_elapsed = scan_start.elapsed();
if scan_elapsed > SCAN_SLOW_THRESHOLD {
tracing::warn!(
elapsed_ms = scan_elapsed.as_millis(),
key_count = keys.len(),
"anomaly login analysis scan exceeded 1s, Redis backend needs optimization to batch mget"
);
} else {
tracing::debug!(
elapsed_ms = scan_elapsed.as_millis(),
key_count = keys.len(),
"anomaly login analysis scan completed"
);
}
Ok(events)
}
pub fn start(self) -> tokio::task::JoinHandle<()> {
let dao = self.dao;
let config = self.config;
let listener_manager = self.listener_manager;
let mut shutdown_rx = self.shutdown_rx;
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(config.interval_secs));
loop {
tokio::select! {
_ = interval.tick() => {
let now = chrono::Utc::now().timestamp();
match Self::analyze_once(&dao, &config, now).await {
Ok(events) => {
for event in events {
if let Some(ref lm) = listener_manager {
let garrison_event: GarrisonEvent = event.into();
lm.broadcast(&garrison_event).await;
}
}
},
Err(e) => {
tracing::warn!("anomaly login analysis failed: {}", e);
},
}
},
_ = shutdown_rx.changed() => {
tracing::info!(
"anomaly login analysis engine received shutdown signal, stopping"
);
break;
},
}
}
})
}
pub async fn shutdown(
handle: tokio::task::JoinHandle<()>,
shutdown_tx: watch::Sender<bool>,
) -> GarrisonResult<()> {
Self::shutdown_with_timeout(handle, shutdown_tx, DEFAULT_SHUTDOWN_TIMEOUT).await
}
pub async fn shutdown_with_timeout(
handle: tokio::task::JoinHandle<()>,
shutdown_tx: watch::Sender<bool>,
timeout: Duration,
) -> GarrisonResult<()> {
let _ = shutdown_tx.send(true);
let abort_handle = handle.abort_handle();
match tokio::time::timeout(timeout, handle).await {
Ok(Ok(())) => Ok(()),
Ok(Err(e)) if e.is_cancelled() => Ok(()),
Ok(Err(e)) => Err(GarrisonError::Internal(format!(
"strategy-analyzer-panic::{}",
e
))),
Err(_) => {
abort_handle.abort();
Err(GarrisonError::Internal(format!(
"strategy-analyzer-shutdown-timeout::{}",
timeout.as_millis()
)))
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::tests::MockDao;
#[test]
fn login_result_serde_roundtrip() {
let success = LoginResult::Success;
let failed = LoginResult::Failed;
let success_json = serde_json::to_string(&success).unwrap();
let failed_json = serde_json::to_string(&failed).unwrap();
assert_eq!(success_json, "\"success\"");
assert_eq!(failed_json, "\"failed\"");
let success_de: LoginResult = serde_json::from_str(&success_json).unwrap();
let failed_de: LoginResult = serde_json::from_str(&failed_json).unwrap();
assert_eq!(success_de, LoginResult::Success);
assert_eq!(failed_de, LoginResult::Failed);
}
#[test]
fn anomalous_login_record_serde_roundtrip() {
let record = AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "1.2.3.4".to_string(),
geo: Some("CN-Beijing".to_string()),
device: Some("web-chrome".to_string()),
timestamp: 1700000000,
result: LoginResult::Success,
};
let json = serde_json::to_string(&record).unwrap();
let de: AnomalousLoginRecord = serde_json::from_str(&json).unwrap();
assert_eq!(de.login_id, "1001");
assert_eq!(de.ip, "1.2.3.4");
assert_eq!(de.geo, Some("CN-Beijing".to_string()));
assert_eq!(de.device, Some("web-chrome".to_string()));
assert_eq!(de.timestamp, 1700000000);
assert_eq!(de.result, LoginResult::Success);
}
#[test]
fn anomalous_login_record_optional_fields_none() {
let record = AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "1.2.3.4".to_string(),
geo: None,
device: None,
timestamp: 1700000000,
result: LoginResult::Failed,
};
let json = serde_json::to_string(&record).unwrap();
let de: AnomalousLoginRecord = serde_json::from_str(&json).unwrap();
assert!(de.geo.is_none());
assert!(de.device.is_none());
assert_eq!(de.result, LoginResult::Failed);
}
#[test]
fn analyzer_config_default() {
let config = AnomalousAnalyzerConfig::default();
assert_eq!(config.interval_secs, 3600);
assert_eq!(config.burst_threshold, 5);
assert_eq!(config.max_scan, 10_000);
}
#[test]
fn analyzer_config_validate_ok() {
let config = AnomalousAnalyzerConfig::default();
assert!(config.validate().is_ok());
}
#[test]
fn analyzer_config_validate_zero_interval() {
let config = AnomalousAnalyzerConfig {
interval_secs: 0,
burst_threshold: 5,
max_scan: 100,
};
assert!(config.validate().is_err());
}
#[test]
fn analyzer_config_validate_zero_burst() {
let config = AnomalousAnalyzerConfig {
interval_secs: 3600,
burst_threshold: 0,
max_scan: 100,
};
assert!(config.validate().is_err());
}
#[test]
fn analyzer_config_validate_zero_max_scan() {
let config = AnomalousAnalyzerConfig {
interval_secs: 3600,
burst_threshold: 5,
max_scan: 0,
};
assert!(config.validate().is_err());
}
#[tokio::test]
async fn record_login_persists_record() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let (tx, rx) = watch::channel(false);
let analyzer =
AnomalousLoginAnalyzer::new(dao.clone(), AnomalousAnalyzerConfig::default(), rx, None);
let record = AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "1.2.3.4".to_string(),
geo: Some("CN-Beijing".to_string()),
device: Some("web".to_string()),
timestamp: 1700000000,
result: LoginResult::Success,
};
analyzer.record_login(&record).await.unwrap();
let keys = dao.keys("anomalous:login:1001:*").await.unwrap();
assert_eq!(keys.len(), 1, "record_login 后应有 1 个 key");
let stored = dao.get(&keys[0]).await.unwrap();
assert!(stored.is_some());
let de: AnomalousLoginRecord = serde_json::from_str(&stored.unwrap()).unwrap();
assert_eq!(de.login_id, "1001");
assert_eq!(de.ip, "1.2.3.4");
let _ = tx;
}
#[tokio::test]
async fn record_login_empty_login_id_errors() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let (_tx, rx) = watch::channel(false);
let analyzer =
AnomalousLoginAnalyzer::new(dao, AnomalousAnalyzerConfig::default(), rx, None);
let record = AnomalousLoginRecord {
login_id: "".to_string(),
ip: "1.2.3.4".to_string(),
geo: None,
device: None,
timestamp: 1700000000,
result: LoginResult::Success,
};
let result = analyzer.record_login(&record).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"空 login_id 应返回 InvalidParam"
);
}
#[tokio::test]
async fn record_login_colon_in_login_id_errors() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let (_tx, rx) = watch::channel(false);
let analyzer =
AnomalousLoginAnalyzer::new(dao, AnomalousAnalyzerConfig::default(), rx, None);
let record = AnomalousLoginRecord {
login_id: "user:1001".to_string(),
ip: "1.2.3.4".to_string(),
geo: None,
device: None,
timestamp: 1700000000,
result: LoginResult::Success,
};
let result = analyzer.record_login(&record).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"包含 ':' 的 login_id 应返回 InvalidParam"
);
}
#[tokio::test]
async fn record_login_overlong_login_id_errors() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let (_tx, rx) = watch::channel(false);
let analyzer =
AnomalousLoginAnalyzer::new(dao, AnomalousAnalyzerConfig::default(), rx, None);
let record = AnomalousLoginRecord {
login_id: "a".repeat(129),
ip: "1.2.3.4".to_string(),
geo: None,
device: None,
timestamp: 1700000000,
result: LoginResult::Success,
};
let result = analyzer.record_login(&record).await;
assert!(
matches!(&result, Err(GarrisonError::InvalidParam(msg)) if msg.contains("too-long")),
"超过 128 字节的 login_id 应返回 InvalidParam,实际: {:?}",
result
);
let record_ok = AnomalousLoginRecord {
login_id: "b".repeat(128),
..record
};
assert!(
analyzer.record_login(&record_ok).await.is_ok(),
"恰好 128 字节的 login_id 应通过"
);
}
#[tokio::test]
async fn record_login_same_second_no_overwrite() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let (_tx, rx) = watch::channel(false);
let analyzer =
AnomalousLoginAnalyzer::new(dao.clone(), AnomalousAnalyzerConfig::default(), rx, None);
let now = 1700000000i64;
for i in 0..3 {
let record = AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("1.2.3.{}", i),
geo: None,
device: None,
timestamp: now,
result: LoginResult::Success,
};
analyzer.record_login(&record).await.unwrap();
}
let keys = dao.keys("anomalous:login:1001:*").await.unwrap();
assert_eq!(
keys.len(),
3,
"同秒内 3 次 record_login 应产生 3 个不同的 key(HIGH-002 修复)"
);
let unique: HashSet<&str> = keys.iter().map(|s| s.as_str()).collect();
assert_eq!(unique.len(), 3, "3 个 key 应互不相同");
}
async fn insert_records(dao: &Arc<dyn GarrisonDao>, records: &[AnomalousLoginRecord]) {
for record in records {
let key = format!("anomalous:login:{}:{}", record.login_id, record.timestamp);
let value = serde_json::to_string(record).unwrap();
dao.set(&key, &value, RECORD_TTL_SECS).await.unwrap();
}
}
#[tokio::test]
async fn analyze_empty_returns_empty() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, 1700000000)
.await
.unwrap();
assert!(events.is_empty());
}
#[tokio::test]
async fn analyze_burst_below_threshold() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let records: Vec<AnomalousLoginRecord> = (0..5)
.map(|i| AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("1.2.3.{}", i),
geo: None,
device: None,
timestamp: now - 100 - i as i64,
result: LoginResult::Success,
})
.collect();
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let burst_events: Vec<_> = events
.iter()
.filter(|e| e.reason == "burst_login")
.collect();
assert!(
burst_events.is_empty(),
"5 条记录(== 阈值 5)不应触发 burst"
);
}
#[tokio::test]
async fn analyze_burst_above_threshold() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let records: Vec<AnomalousLoginRecord> = (0..6)
.map(|i| AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("1.2.3.{}", i),
geo: None,
device: None,
timestamp: now - 100 - i as i64,
result: LoginResult::Success,
})
.collect();
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let burst_events: Vec<_> = events
.iter()
.filter(|e| e.reason == "burst_login")
.collect();
assert_eq!(
burst_events.len(),
1,
"6 条记录(> 阈值 5)应触发 1 次 burst"
);
assert_eq!(burst_events[0].login_id, "1001");
}
#[tokio::test]
async fn analyze_burst_event_fields() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let records: Vec<AnomalousLoginRecord> = (0..10)
.map(|i| AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("1.2.3.{}", i),
geo: None,
device: None,
timestamp: now - 50 - i as i64,
result: LoginResult::Success,
})
.collect();
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let burst = events.iter().find(|e| e.reason == "burst_login").unwrap();
assert_eq!(burst.login_id, "1001");
assert_eq!(burst.timestamp, now);
assert_eq!(burst.detail["count"], 10);
assert_eq!(burst.detail["threshold"], 5);
}
#[tokio::test]
async fn analyze_geo_jump_below_threshold() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let records = vec![
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "1.1.1.1".to_string(),
geo: Some("CN-Beijing".to_string()),
device: None,
timestamp: now - 100,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "2.2.2.2".to_string(),
geo: Some("CN-Shanghai".to_string()),
device: None,
timestamp: now - 50,
result: LoginResult::Success,
},
];
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let geo_events: Vec<_> = events.iter().filter(|e| e.reason == "geo_jump").collect();
assert!(
geo_events.is_empty(),
"2 个不同 geo(== 阈值 2)不应触发 geo_jump"
);
}
#[tokio::test]
async fn analyze_geo_jump_above_threshold() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let records = vec![
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "1.1.1.1".to_string(),
geo: Some("CN-Beijing".to_string()),
device: None,
timestamp: now - 100,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "2.2.2.2".to_string(),
geo: Some("CN-Shanghai".to_string()),
device: None,
timestamp: now - 80,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "3.3.3.3".to_string(),
geo: Some("US-NewYork".to_string()),
device: None,
timestamp: now - 50,
result: LoginResult::Success,
},
];
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let geo_events: Vec<_> = events.iter().filter(|e| e.reason == "geo_jump").collect();
assert_eq!(
geo_events.len(),
1,
"3 个不同 geo(> 阈值 2)应触发 1 次 geo_jump"
);
assert_eq!(geo_events[0].detail["distinct_geo"], 3);
}
#[tokio::test]
async fn analyze_geo_jump_none_excluded() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let mut records = vec![
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "1.1.1.1".to_string(),
geo: Some("CN-Beijing".to_string()),
device: None,
timestamp: now - 100,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "2.2.2.2".to_string(),
geo: Some("CN-Shanghai".to_string()),
device: None,
timestamp: now - 50,
result: LoginResult::Success,
},
];
for i in 0..10 {
records.push(AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("10.0.0.{}", i),
geo: None,
device: None,
timestamp: now - 10 - i as i64,
result: LoginResult::Success,
});
}
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let geo_events: Vec<_> = events.iter().filter(|e| e.reason == "geo_jump").collect();
assert!(
geo_events.is_empty(),
"None geo 不计入,2 个有 geo 不应触发 geo_jump"
);
}
#[tokio::test]
async fn analyze_device_mutation_below_threshold() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let records = vec![
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "1.1.1.1".to_string(),
geo: None,
device: Some("web".to_string()),
timestamp: now - 100,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "2.2.2.2".to_string(),
geo: None,
device: Some("ios".to_string()),
timestamp: now - 50,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "3.3.3.3".to_string(),
geo: None,
device: Some("android".to_string()),
timestamp: now - 30,
result: LoginResult::Success,
},
];
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let device_events: Vec<_> = events
.iter()
.filter(|e| e.reason == "device_mutation")
.collect();
assert!(
device_events.is_empty(),
"3 个不同 device(== 阈值 3)不应触发 device_mutation"
);
}
#[tokio::test]
async fn analyze_device_mutation_above_threshold() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let records = vec![
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "1.1.1.1".to_string(),
geo: None,
device: Some("web".to_string()),
timestamp: now - 100,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "2.2.2.2".to_string(),
geo: None,
device: Some("ios".to_string()),
timestamp: now - 80,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "3.3.3.3".to_string(),
geo: None,
device: Some("android".to_string()),
timestamp: now - 60,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "4.4.4.4".to_string(),
geo: None,
device: Some("tablet".to_string()),
timestamp: now - 40,
result: LoginResult::Success,
},
];
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let device_events: Vec<_> = events
.iter()
.filter(|e| e.reason == "device_mutation")
.collect();
assert_eq!(
device_events.len(),
1,
"4 个不同 device(> 阈值 3)应触发 1 次 device_mutation"
);
assert_eq!(device_events[0].detail["distinct_device"], 4);
}
#[tokio::test]
async fn analyze_device_mutation_none_excluded() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let mut records = vec![
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "1.1.1.1".to_string(),
geo: None,
device: Some("web".to_string()),
timestamp: now - 100,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "2.2.2.2".to_string(),
geo: None,
device: Some("ios".to_string()),
timestamp: now - 80,
result: LoginResult::Success,
},
AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: "3.3.3.3".to_string(),
geo: None,
device: Some("android".to_string()),
timestamp: now - 60,
result: LoginResult::Success,
},
];
for i in 0..10 {
records.push(AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("10.0.0.{}", i),
geo: None,
device: None,
timestamp: now - 10 - i as i64,
result: LoginResult::Success,
});
}
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let device_events: Vec<_> = events
.iter()
.filter(|e| e.reason == "device_mutation")
.collect();
assert!(
device_events.is_empty(),
"None device 不计入,3 个有 device 不应触发 device_mutation"
);
}
#[tokio::test]
async fn analyze_time_window_filter() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let in_window: Vec<AnomalousLoginRecord> = (0..6)
.map(|i| AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("1.2.3.{}", i),
geo: None,
device: None,
timestamp: now - 100 - i as i64,
result: LoginResult::Success,
})
.collect();
insert_records(&dao, &in_window).await;
let out_window: Vec<AnomalousLoginRecord> = (0..6)
.map(|i| AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("5.6.7.{}", i),
geo: None,
device: None,
timestamp: now - SCAN_WINDOW_SECS - 100 - i as i64,
result: LoginResult::Success,
})
.collect();
insert_records(&dao, &out_window).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let burst = events.iter().find(|e| e.reason == "burst_login").unwrap();
assert_eq!(burst.detail["count"], 6);
}
#[tokio::test]
async fn analyze_max_scan_limit() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let records: Vec<AnomalousLoginRecord> = (0..20)
.map(|i| AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("1.2.3.{}", i),
geo: None,
device: None,
timestamp: now - 100 - i as i64,
result: LoginResult::Success,
})
.collect();
insert_records(&dao, &records).await;
let config = AnomalousAnalyzerConfig {
interval_secs: 3600,
burst_threshold: 5,
max_scan: 5,
};
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let burst_events: Vec<_> = events
.iter()
.filter(|e| e.reason == "burst_login")
.collect();
assert!(
burst_events.is_empty(),
"max_scan=5 只扫描 5 条,不触发 burst"
);
}
#[tokio::test]
async fn analyze_deserialization_failure_skips() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let records: Vec<AnomalousLoginRecord> = (0..6)
.map(|i| AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("1.2.3.{}", i),
geo: None,
device: None,
timestamp: now - 100 - i as i64,
result: LoginResult::Success,
})
.collect();
insert_records(&dao, &records).await;
dao.set("anomalous:login:1001:bad1", "not-json", RECORD_TTL_SECS)
.await
.unwrap();
dao.set("anomalous:login:1001:bad2", "{invalid}", RECORD_TTL_SECS)
.await
.unwrap();
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let burst = events.iter().find(|e| e.reason == "burst_login");
assert!(burst.is_some(), "损坏记录应跳过,6 条有效记录仍触发 burst");
assert_eq!(burst.unwrap().detail["count"], 6);
}
#[tokio::test]
async fn analyze_multiple_users() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let now = 1700000000i64;
let user_a: Vec<AnomalousLoginRecord> = (0..6)
.map(|i| AnomalousLoginRecord {
login_id: "1001".to_string(),
ip: format!("1.2.3.{}", i),
geo: None,
device: None,
timestamp: now - 100 - i as i64,
result: LoginResult::Success,
})
.collect();
insert_records(&dao, &user_a).await;
let user_b: Vec<AnomalousLoginRecord> = (0..6)
.map(|i| AnomalousLoginRecord {
login_id: "1002".to_string(),
ip: format!("5.6.7.{}", i),
geo: None,
device: None,
timestamp: now - 100 - i as i64,
result: LoginResult::Success,
})
.collect();
insert_records(&dao, &user_b).await;
let config = AnomalousAnalyzerConfig::default();
let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
.await
.unwrap();
let burst_events: Vec<_> = events
.iter()
.filter(|e| e.reason == "burst_login")
.collect();
assert_eq!(burst_events.len(), 2, "两个用户各触发 1 次 burst");
let login_ids: HashSet<&str> = burst_events.iter().map(|e| e.login_id.as_str()).collect();
assert!(login_ids.contains("1001"));
assert!(login_ids.contains("1002"));
}
#[tokio::test]
async fn start_shutdown_stops_task() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let (tx, rx) = watch::channel(false);
let config = AnomalousAnalyzerConfig {
interval_secs: 3600,
burst_threshold: 5,
max_scan: 100,
};
let analyzer = AnomalousLoginAnalyzer::new(dao, config, rx, None);
let handle = analyzer.start();
let _ = tx.send(true);
tokio::time::timeout(Duration::from_secs(1), handle)
.await
.expect("任务应在 shutdown 信号后 1 秒内结束")
.expect("任务不应 panic");
}
#[test]
fn from_anomalous_login_detected_to_garrison_event() {
let detected = AnomalousLoginDetected {
login_id: "1001".to_string(),
reason: "burst_login".to_string(),
detail: serde_json::json!({"count": 10}),
timestamp: 1700000000,
};
let event: GarrisonEvent = detected.into();
match event {
GarrisonEvent::AnomalousLoginDetected {
login_id,
reason,
detail,
timestamp,
..
} => {
assert_eq!(login_id, "1001");
assert_eq!(reason, "burst_login");
assert_eq!(detail["count"], 10);
assert_eq!(timestamp, 1700000000);
},
_ => panic!("期望 AnomalousLoginDetected 事件"),
}
}
#[tokio::test]
async fn shutdown_with_timeout_aborts_slow_task() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let handle = tokio::spawn(async {
std::future::pending::<()>().await;
});
let (tx, _rx) = watch::channel(false);
let result =
AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_millis(100))
.await;
assert!(result.is_err(), "慢任务应超时返回 Err");
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("anomalous analyzer shutdown timeout"),
"错误信息应包含关闭超时标识(嵌套错误不经过翻译链,断言取 locale 无关片段),实际: {}",
err_msg
);
}
#[tokio::test]
async fn shutdown_with_timeout_normal_completion() {
let handle = tokio::spawn(async {
tokio::time::sleep(Duration::from_millis(10)).await;
});
let (tx, _rx) = watch::channel(false);
let result =
AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;
assert!(result.is_ok(), "正常结束的任务应返回 Ok");
}
#[tokio::test]
async fn shutdown_with_timeout_responds_to_signal() {
let (tx, rx) = watch::channel(false);
let rx = rx;
let handle = tokio::spawn(async move {
loop {
if rx.has_changed().unwrap_or(false) {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
});
let result =
AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;
assert!(result.is_ok(), "响应 shutdown 信号的任务应返回 Ok");
}
#[tokio::test]
async fn shutdown_with_timeout_already_cancelled() {
let handle = tokio::spawn(async {
tokio::time::sleep(Duration::from_millis(10)).await;
});
let (tx, _rx) = watch::channel(false);
handle.abort();
let result =
AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;
assert!(result.is_ok(), "已 cancelled 的任务应返回 Ok(幂等)");
}
#[tokio::test]
async fn shutdown_with_timeout_panic_task() {
let handle = tokio::spawn(async {
panic!("任务 panic 测试");
});
let (tx, _rx) = watch::channel(false);
tokio::time::sleep(Duration::from_millis(50)).await;
let result =
AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;
assert!(result.is_err(), "panic 任务应返回 Err");
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("panic"),
"错误信息应包含 'panic',实际: {}",
err_msg
);
}
#[tokio::test]
async fn start_then_shutdown_normal_stop() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let (tx, rx) = watch::channel(false);
let config = AnomalousAnalyzerConfig {
interval_secs: 3600,
burst_threshold: 5,
max_scan: 100,
};
let analyzer = AnomalousLoginAnalyzer::new(dao, config, rx, None);
let handle = analyzer.start();
let result =
AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;
assert!(result.is_ok(), "正常 shutdown 应返回 Ok");
}
}