use super::TotpHandler;
use crate::dao::GarrisonDao;
use crate::error::GarrisonError;
const TEST_SECRET: &[u8] = b"12345678901234567890";
#[test]
fn new_with_default_params() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6);
assert!(handler.is_ok());
}
#[test]
fn new_with_custom_params() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 60, 8).unwrap();
let code = handler.generate(1700000000).unwrap();
assert_eq!(code.len(), 8);
}
#[test]
fn new_with_short_secret_errors() {
let result = TotpHandler::new(b"short".to_vec(), 30, 6);
assert!(result.is_err());
}
#[test]
fn generate_returns_6_digits() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let code = handler.generate(1700000000).unwrap();
assert_eq!(code.len(), 6);
assert!(code.chars().all(|c| c.is_ascii_digit()));
}
#[test]
fn generate_is_deterministic() {
let h1 = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let h2 = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
assert_eq!(
h1.generate(1700000000).unwrap(),
h2.generate(1700000000).unwrap()
);
}
#[test]
fn same_time_window_produces_same_code() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let c1 = handler.generate(1700000000).unwrap();
let c2 = handler.generate(1700000005).unwrap(); assert_eq!(c1, c2);
}
#[test]
fn different_time_window_produces_different_code() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let c1 = handler.generate(1700000000).unwrap();
let c2 = handler.generate(1700000030).unwrap(); assert_ne!(c1, c2);
}
#[test]
fn generate_negative_now_returns_invalid_param() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let result = handler.generate(-1);
assert!(
matches!(&result, Err(GarrisonError::InvalidParam(msg)) if msg.contains("secure-totp-negative-now")),
"负 now 应返回 InvalidParam(secure-totp-negative-now),实际: {:?}",
result
);
}
#[test]
fn validate_negative_now_returns_invalid_param() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let result = handler.validate("123456", -1);
assert!(
matches!(&result, Err(GarrisonError::InvalidParam(msg)) if msg.contains("secure-totp-negative-now")),
"负 now 应返回 InvalidParam(secure-totp-negative-now),实际: {:?}",
result
);
}
#[tokio::test]
async fn validate_and_consume_negative_now_returns_invalid_param() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let result = handler
.validate_and_consume("user-neg-now", "123456", -1, &dao)
.await;
assert!(
matches!(&result, Err(GarrisonError::InvalidParam(msg)) if msg.contains("secure-totp-negative-now")),
"负 now 应返回 InvalidParam(secure-totp-negative-now),实际: {:?}",
result
);
let stored = dao.get("totp:used:user-neg-now:123456").await.unwrap();
assert!(stored.is_none(), "负 now 拒绝时不应写入 replay_key");
}
#[test]
fn validate_current_window_succeeds() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let code = handler.generate(1700000000).unwrap();
assert!(handler.validate(&code, 1700000000).unwrap());
}
#[test]
fn validate_previous_window_succeeds() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let code = handler.generate(1699999970).unwrap(); assert!(handler.validate(&code, 1700000000).unwrap());
}
#[test]
fn validate_next_window_succeeds() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let code = handler.generate(1700000030).unwrap(); assert!(handler.validate(&code, 1700000000).unwrap());
}
#[test]
fn validate_beyond_tolerance_fails() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let code = handler.generate(1699999940).unwrap(); assert!(!handler.validate(&code, 1700000000).unwrap());
}
#[test]
fn validate_wrong_code_fails() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
assert!(!handler.validate("000000", 1700000000).unwrap());
}
#[test]
fn secret_from_base32_decodes_valid() {
let bytes = TotpHandler::secret_from_base32("JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP").unwrap();
assert!(!bytes.is_empty());
assert!(bytes.len() >= 16); }
#[test]
fn secret_from_base32_rejects_invalid() {
assert!(TotpHandler::secret_from_base32("invalid!base32").is_err());
}
#[test]
fn base32_secret_matches_raw_bytes() {
let b32_str = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP";
let bytes = TotpHandler::secret_from_base32(b32_str).unwrap();
let h1 = TotpHandler::new(bytes.clone(), 30, 6).unwrap();
let h2 = TotpHandler::new(bytes, 30, 6).unwrap();
assert_eq!(
h1.generate(1700000000).unwrap(),
h2.generate(1700000000).unwrap()
);
}
#[tokio::test]
async fn validate_and_consume_first_use_succeeds() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let code = handler.generate(1700000000).unwrap();
let result = handler
.validate_and_consume("user-001", &code, 1700000000, &dao)
.await;
assert!(result.is_ok(), "validate_and_consume 不应报错");
assert!(result.unwrap(), "首次使用正确验证码应返回 true");
}
#[tokio::test]
async fn validate_and_consume_rejects_replay() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let code = handler.generate(1700000000).unwrap();
let first = handler
.validate_and_consume("user-001", &code, 1700000000, &dao)
.await
.expect("首次校验不应报错");
assert!(first, "首次应通过");
let second = handler
.validate_and_consume("user-001", &code, 1700000000, &dao)
.await
.expect("二次校验不应报错");
assert!(!second, "同一验证码二次使用应被拒绝(C-5 重放防护)");
}
#[tokio::test]
async fn validate_and_consume_isolates_by_login_id() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let code = handler.generate(1700000000).unwrap();
let user_a = handler
.validate_and_consume("user-A", &code, 1700000000, &dao)
.await
.unwrap();
assert!(user_a, "user-A 首次应通过");
let user_b = handler
.validate_and_consume("user-B", &code, 1700000000, &dao)
.await
.unwrap();
assert!(user_b, "user-B 使用同一验证码应通过(不同 login_id 隔离)");
}
#[tokio::test]
async fn validate_and_consume_wrong_code_returns_false_without_recording() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let result = handler
.validate_and_consume("user-001", "000000", 1700000000, &dao)
.await
.unwrap();
assert!(!result, "错误验证码应返回 false");
let replay_key = "totp:used:user-001:000000";
let stored = dao.get(replay_key).await.unwrap();
assert!(
stored.is_none(),
"错误验证码不应记录到 DAO(避免无效码占用缓存)"
);
}
#[tokio::test]
async fn validate_and_consume_different_codes_both_succeed() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let code1 = handler.generate(1700000000).unwrap();
let code2 = handler.generate(1700000030).unwrap();
if code1 == code2 {
return;
}
let first = handler
.validate_and_consume("user-001", &code1, 1700000000, &dao)
.await
.unwrap();
assert!(first, "code1 应通过");
let second = handler
.validate_and_consume("user-001", &code2, 1700000030, &dao)
.await
.unwrap();
assert!(second, "code2(不同窗口)应通过");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn validate_and_consume_concurrent_no_double_accept() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = Arc::new(crate::dao::InMemoryDao::new());
let code = handler.generate(1700000000).unwrap();
let accept_count = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for _ in 0..10 {
let d = dao.clone();
let ac = accept_count.clone();
let code = code.clone();
handles.push(tokio::spawn(async move {
let h = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let result = h
.validate_and_consume("user-concurrent", &code, 1700000000, &*d)
.await
.unwrap();
if result {
ac.fetch_add(1, Ordering::SeqCst);
}
}));
}
for handle in handles {
handle.await.unwrap();
}
assert_eq!(
accept_count.load(Ordering::SeqCst),
1,
"并发调用同一 code 应只有 1 个通过(TOCTOU 防护),实际: {}",
accept_count.load(Ordering::SeqCst)
);
}
#[test]
fn e3_source_has_no_dashmap_or_unbounded_static() {
let source = include_str!("handler.rs");
let code_only: String = source
.lines()
.filter(|line| {
let trimmed = line.trim_start();
!(trimmed.starts_with("//!") || trimmed.starts_with("///") || trimmed.starts_with("//"))
})
.collect::<Vec<_>>()
.join("\n");
assert!(
!code_only.contains("use dashmap"),
"E3: handler.rs 代码不应再 import dashmap crate"
);
assert!(
!code_only.contains("DashMap::new"),
"E3: handler.rs 代码不应再实例化 DashMap"
);
assert!(
!code_only.contains("DashMap<"),
"E3: handler.rs 代码不应再使用 DashMap< 类型"
);
assert!(
!code_only.contains("static TOTP_LOCKS"),
"E3: handler.rs 代码不应再声明 TOTP_LOCKS 无界 static"
);
assert!(
!code_only.contains("use once_cell"),
"E3: handler.rs 代码不应再依赖 once_cell::sync::Lazy"
);
assert!(
!code_only.contains("Lazy::new"),
"E3: handler.rs 代码不应再使用 Lazy::new 初始化容器"
);
assert!(
code_only.contains("dao.incr"),
"E3: handler.rs 应使用 dao.incr 原子操作替代 per-login_id 锁"
);
assert!(
source.contains("E3 修复"),
"E3: handler.rs 文档应保留 E3 修复说明"
);
}
#[tokio::test]
async fn e3_incr_returns_1_on_first_call() {
let dao = crate::dao::InMemoryDao::new();
let count = dao.incr("totp:used:user-001:123456", 90).await.unwrap();
assert_eq!(count, 1, "E3: incr 首次调用应返回 1(视为首次使用验证码)");
}
#[tokio::test]
async fn e3_incr_returns_2_on_replay() {
let dao = crate::dao::InMemoryDao::new();
let key = "totp:used:user-001:123456";
let first = dao.incr(key, 90).await.unwrap();
let second = dao.incr(key, 90).await.unwrap();
assert_eq!(first, 1, "首次应返回 1");
assert_eq!(
second, 2,
"E3: incr 第二次调用应返回 2(重放检测,>1 即拒绝)"
);
}
#[tokio::test]
async fn e3_replay_key_format_is_correct() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let code = handler.generate(1700000000).unwrap();
handler
.validate_and_consume("user-format-test", &code, 1700000000, &dao)
.await
.unwrap();
let expected_key = format!("totp:used:user-format-test:{}", code);
let timeout = dao.get_timeout(&expected_key).await.unwrap();
assert!(
timeout.is_some(),
"E3: replay_key 应存在且设置 TTL,格式: totp:used:<login_id>:<code>"
);
}
#[tokio::test]
async fn e3_replay_key_ttl_is_step_times_3() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let code = handler.generate(1700000000).unwrap();
handler
.validate_and_consume("user-ttl-30", &code, 1700000000, &dao)
.await
.unwrap();
let replay_key = format!("totp:used:user-ttl-30:{}", code);
let timeout = dao.get_timeout(&replay_key).await.unwrap();
let remaining = timeout.expect("TTL 应存在");
assert!(
remaining.as_secs() <= 90,
"E3: step=30 时 TTL 应 ≤ 90s,实际: {:?}",
remaining
);
assert!(
remaining.as_secs() > 85,
"E3: step=30 时刚写入的 TTL 应接近 90s,实际: {:?}",
remaining
);
}
#[tokio::test]
async fn e3_step_60_produces_ttl_180() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 60, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let code = handler.generate(1700000000).unwrap();
handler
.validate_and_consume("user-ttl-60", &code, 1700000000, &dao)
.await
.unwrap();
let replay_key = format!("totp:used:user-ttl-60:{}", code);
let timeout = dao.get_timeout(&replay_key).await.unwrap();
let remaining = timeout.expect("TTL 应存在");
assert!(
remaining.as_secs() <= 180,
"E3: step=60 时 TTL 应 ≤ 180s,实际: {:?}",
remaining
);
assert!(
remaining.as_secs() > 175,
"E3: step=60 时刚写入的 TTL 应接近 180s,实际: {:?}",
remaining
);
}
#[tokio::test]
async fn e3_previous_window_code_accepted_first_time() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let prev_code = handler.generate(1699999970).unwrap();
let result = handler
.validate_and_consume("user-prev-win", &prev_code, 1700000000, &dao)
.await
.unwrap();
assert!(result, "E3: 前一窗口验证码首次使用应通过(skew=1 容差)");
}
#[tokio::test]
async fn e3_previous_window_code_rejected_on_replay() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let prev_code = handler.generate(1699999970).unwrap();
let first = handler
.validate_and_consume("user-prev-replay", &prev_code, 1700000000, &dao)
.await
.unwrap();
assert!(first, "首次应通过");
let second = handler
.validate_and_consume("user-prev-replay", &prev_code, 1700000000, &dao)
.await
.unwrap();
assert!(!second, "E3: 前一窗口验证码重放应被拒绝(incr 返回 2 > 1)");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn e3_concurrent_different_login_ids_no_interference() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = Arc::new(crate::dao::InMemoryDao::new());
let code = handler.generate(1700000000).unwrap();
let accept_count = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for i in 0..10 {
let d = dao.clone();
let ac = accept_count.clone();
let code = code.clone();
handles.push(tokio::spawn(async move {
let h = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let login_id = format!("user-isolated-{}", i);
let result = h
.validate_and_consume(&login_id, &code, 1700000000, &*d)
.await
.unwrap();
if result {
ac.fetch_add(1, Ordering::SeqCst);
}
}));
}
for handle in handles {
handle.await.unwrap();
}
assert_eq!(
accept_count.load(Ordering::SeqCst),
10,
"E3: 10 个不同 login_id 的并发调用应全部通过(隔离性)"
);
}
#[tokio::test]
async fn e3_replay_key_isolated_per_code() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let code1 = handler.generate(1700000000).unwrap();
let code2 = handler.generate(1700000030).unwrap();
if code1 == code2 {
return;
}
let r1 = handler
.validate_and_consume("user-multi-code", &code1, 1700000000, &dao)
.await
.unwrap();
let r2 = handler
.validate_and_consume("user-multi-code", &code2, 1700000030, &dao)
.await
.unwrap();
assert!(r1, "code1 首次应通过");
assert!(
r2,
"E3: code2(不同窗口)首次应通过,replay_key 按 (login_id, code) 隔离"
);
let key1 = format!("totp:used:user-multi-code:{}", code1);
let key2 = format!("totp:used:user-multi-code:{}", code2);
let t1 = dao.get_timeout(&key1).await.unwrap();
let t2 = dao.get_timeout(&key2).await.unwrap();
assert!(t1.is_some(), "code1 的 replay_key 应存在");
assert!(t2.is_some(), "code2 的 replay_key 应存在");
}
#[tokio::test]
async fn e3_wrong_code_does_not_write_replay_key() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let result = handler
.validate_and_consume("user-wrong-code", "000000", 1700000000, &dao)
.await
.unwrap();
assert!(!result, "错误验证码应返回 false");
let replay_key = "totp:used:user-wrong-code:000000";
let stored = dao.get(replay_key).await.unwrap();
assert!(
stored.is_none(),
"E3: 错误验证码不应写入 replay_key(避免无效码占用缓存)"
);
let timeout = dao.get_timeout(replay_key).await.unwrap();
assert!(timeout.is_none(), "E3: 错误验证码的 replay_key 不应有 TTL");
}
#[tokio::test]
async fn e3_incr_count_increments_with_replays() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 6).unwrap();
let dao = crate::dao::InMemoryDao::new();
let code = handler.generate(1700000000).unwrap();
let replay_key = format!("totp:used:user-count:{}", code);
for i in 0..4 {
let result = handler
.validate_and_consume("user-count", &code, 1700000000, &dao)
.await
.unwrap();
if i == 0 {
assert!(result, "首次应通过");
} else {
assert!(!result, "第 {} 次重放应被拒绝", i);
}
}
let stored = dao.get(&replay_key).await.unwrap();
assert_eq!(
stored,
Some("4".to_string()),
"E3: 4 次调用后 replay_key 的 incr 计数应为 4"
);
}
#[test]
fn rfc6238_appendix_b_sha1_official_vectors() {
let handler = TotpHandler::new(TEST_SECRET.to_vec(), 30, 8).unwrap();
let vectors: &[(i64, &str)] = &[
(59, "94287082"),
(1_111_111_109, "07081804"),
(1_111_111_111, "14050471"),
(1_234_567_890, "89005924"),
(2_000_000_000, "69279037"),
(20_000_000_000, "65353130"),
];
for (t, expected) in vectors {
let code = handler.generate(*t).unwrap();
assert_eq!(
code, *expected,
"T={t} 的 TOTP 应为官方向量 {expected}(RFC 6238 Appendix B SHA1)"
);
}
}
#[test]
fn rfc6238_appendix_b_sha256_official_vectors() {
use totp_rs::Algorithm;
let secret = b"12345678901234567890123456789012";
let handler =
TotpHandler::new_with_hash_algorithm(secret.to_vec(), 30, 8, Algorithm::SHA256).unwrap();
let vectors: &[(i64, &str)] = &[
(59, "46119246"),
(1_111_111_109, "68084774"),
(1_111_111_111, "67062674"),
(1_234_567_890, "91819424"),
(2_000_000_000, "90698825"),
(20_000_000_000, "77737706"),
];
for (t, expected) in vectors {
let code = handler.generate(*t).unwrap();
assert_eq!(
code, *expected,
"T={t} 的 TOTP 应为官方向量 {expected}(RFC 6238 Appendix B SHA256)"
);
}
}
#[test]
fn rfc6238_appendix_b_sha512_official_vectors() {
use totp_rs::Algorithm;
let secret = b"1234567890123456789012345678901234567890123456789012345678901234";
let handler =
TotpHandler::new_with_hash_algorithm(secret.to_vec(), 30, 8, Algorithm::SHA512).unwrap();
let vectors: &[(i64, &str)] = &[
(59, "90693936"),
(1_111_111_109, "25091201"),
(1_111_111_111, "99943326"),
(1_234_567_890, "93441116"),
(2_000_000_000, "38618901"),
(20_000_000_000, "47863826"),
];
for (t, expected) in vectors {
let code = handler.generate(*t).unwrap();
assert_eq!(
code, *expected,
"T={t} 的 TOTP 应为官方向量 {expected}(RFC 6238 Appendix B SHA512)"
);
}
}