use super::{Credential, CredentialModel, CredentialType};
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::secure::totp::TotpHandler;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TotpSecretData {
secret: String,
step: u64,
digits: u32,
}
const MAX_TOTP_STEP: u64 = 3600;
impl TotpSecretData {
fn from_json(secret_data: &str) -> GarrisonResult<Self> {
serde_json::from_str(secret_data)
.map_err(|e| GarrisonError::InvalidParam(format!("account-totp-parse-failed::{}", e)))
}
fn to_handler(&self) -> GarrisonResult<TotpHandler> {
if self.step == 0 || self.step > MAX_TOTP_STEP {
return Err(GarrisonError::InvalidParam(format!(
"credential-totp-step-invalid::step={}",
self.step
)));
}
let secret_bytes = TotpHandler::secret_from_base32(&self.secret)?;
TotpHandler::new(secret_bytes, self.step, self.digits)
}
}
#[cfg_attr(
feature = "credential-zeroize",
derive(zeroize::Zeroize, zeroize::ZeroizeOnDrop)
)]
pub struct TotpCredential {
model: CredentialModel,
}
impl TotpCredential {
fn check_and_record_replay(
user_id: &str,
cred_id: &str,
code: &str,
step: u64,
now: i64,
) -> bool {
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
static SEEN: LazyLock<Mutex<HashMap<String, i64>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
const MAX_CACHE_ENTRIES: usize = 4096;
let ttl_secs = step.saturating_mul(3) as i64;
let key = format!("totp:verify-used:{user_id}:{cred_id}:{code}");
let mut map = SEEN.lock().expect("totp verify replay cache poisoned");
if map.len() >= MAX_CACHE_ENTRIES {
map.retain(|_, exp| *exp > now);
}
match map.get(&key) {
Some(expiry) if *expiry > now => false,
_ => {
map.insert(key, now.saturating_add(ttl_secs));
true
},
}
}
pub fn new(model: CredentialModel) -> Self {
Self { model }
}
pub fn generate_current(&self) -> GarrisonResult<String> {
let data = TotpSecretData::from_json(&self.model.secret_data)?;
let handler = data.to_handler()?;
let now = chrono::Utc::now().timestamp();
handler.generate(now)
}
pub async fn verify_with_replay_check(
&self,
input: &str,
login_id: &str,
dao: &dyn GarrisonDao,
) -> GarrisonResult<bool> {
let data = TotpSecretData::from_json(&self.model.secret_data)?;
let handler = data.to_handler()?;
let now = chrono::Utc::now().timestamp();
handler
.validate_and_consume(login_id, input, now, dao)
.await
}
}
#[async_trait]
impl Credential for TotpCredential {
fn credential_type(&self) -> CredentialType {
"totp"
}
fn to_model(&self) -> CredentialModel {
self.model.clone()
}
async fn verify(&self, input: &str) -> GarrisonResult<bool> {
let data = TotpSecretData::from_json(&self.model.secret_data)?;
let handler = data.to_handler()?;
let now = chrono::Utc::now().timestamp();
if !handler.validate(input, now)? {
return Ok(false);
}
Ok(Self::check_and_record_replay(
&self.model.user_id,
&self.model.id,
input,
data.step,
now,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_totp_cred(tag: &str) -> (TotpCredential, String) {
let secret_data = r#"{"secret":"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ","step":30,"digits":6}"#;
let model = CredentialModel {
id: format!("cred-totp-{tag}"),
user_id: format!("user-{tag}"),
credential_type: "totp".to_string(),
secret_data: secret_data.to_string(),
label: Some("iPhone TOTP".to_string()),
created_at: 0,
enabled: true,
priority: 0,
};
let cred = TotpCredential::new(model);
let code = cred.generate_current().expect("generate_current 应成功");
(cred, code)
}
#[test]
fn totp_credential_type_returns_totp() {
let (cred, _) = make_totp_cred("t001");
assert_eq!(cred.credential_type(), "totp");
}
#[test]
fn totp_credential_to_model_returns_original() {
let (cred, _) = make_totp_cred("t002");
let model = cred.to_model();
assert_eq!(model.id, "cred-totp-t002");
assert_eq!(model.user_id, "user-t002");
assert_eq!(model.credential_type, "totp");
assert!(model.secret_data.contains("GEZDGNBVGY3TQOJQ"));
assert_eq!(model.label, Some("iPhone TOTP".to_string()));
}
#[tokio::test]
async fn totp_credential_verify_correct_code() {
let (cred, code) = make_totp_cred("t003");
let result = cred.verify(&code).await.expect("verify 应成功");
assert!(result, "正确 TOTP code 应校验通过");
}
#[tokio::test]
async fn totp_credential_verify_wrong_code() {
let (cred, _) = make_totp_cred("t004");
let result = cred
.verify("000000")
.await
.expect("verify 应成功(返回 false 而非报错)");
assert!(!result, "错误 TOTP code 应校验失败");
}
#[tokio::test]
async fn totp_credential_verify_rejects_replayed_code() {
let (cred, code) = make_totp_cred("t005");
let first = cred.verify(&code).await.expect("首次 verify 不应报错");
assert!(first, "首次提交应通过");
let replay = cred.verify(&code).await.expect("重放 verify 不应报错");
assert!(!replay, "同一验证码窗口内重复提交应被拒绝(重放防护)");
}
#[tokio::test]
async fn totp_credential_step_over_upper_bound_returns_error() {
let model = CredentialModel {
id: "cred-totp-big-step".to_string(),
user_id: "user-big-step".to_string(),
credential_type: "totp".to_string(),
secret_data: r#"{"secret":"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ","step":18446744073709551615,"digits":6}"#.to_string(),
label: None,
created_at: 0,
enabled: true,
priority: 0,
};
let cred = TotpCredential::new(model);
let result = cred.verify("123456").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("step")),
"step 超上界应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn totp_credential_step_zero_returns_error() {
let model = CredentialModel {
id: "cred-totp-zero-step".to_string(),
user_id: "user-zero-step".to_string(),
credential_type: "totp".to_string(),
secret_data: r#"{"secret":"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ","step":0,"digits":6}"#
.to_string(),
label: None,
created_at: 0,
enabled: true,
priority: 0,
};
let cred = TotpCredential::new(model);
let result = cred.verify("123456").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("step")),
"step=0 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn totp_credential_invalid_secret_data_returns_error() {
let model = CredentialModel {
id: "bad".to_string(),
user_id: "alice".to_string(),
credential_type: "totp".to_string(),
secret_data: "not-json".to_string(),
label: None,
created_at: 0,
enabled: true,
priority: 0,
};
let cred = TotpCredential::new(model);
let result = cred.verify("123456").await;
assert!(
result.is_err(),
"非法 secret_data 应返回错误,实际: {:?}",
result
);
}
#[tokio::test]
async fn totp_credential_invalid_base32_returns_error() {
let model = CredentialModel {
id: "bad2".to_string(),
user_id: "alice".to_string(),
credential_type: "totp".to_string(),
secret_data: r#"{"secret":"invalid!base32","step":30,"digits":6}"#.to_string(),
label: None,
created_at: 0,
enabled: true,
priority: 0,
};
let cred = TotpCredential::new(model);
let result = cred.verify("123456").await;
assert!(result.is_err(), "非法 Base32 应返回错误");
}
#[test]
fn totp_credential_generate_current_returns_6_digits() {
let (cred, _) = make_totp_cred("t006");
let code = cred.generate_current().expect("generate_current 应成功");
assert_eq!(code.len(), 6, "验证码应为 6 位");
assert!(
code.chars().all(|c| c.is_ascii_digit()),
"验证码应全为数字,实际: {}",
code
);
}
#[tokio::test]
async fn totp_credential_usable_as_dyn_credential() {
let (cred, code) = make_totp_cred("t007");
let dyn_cred: Box<dyn Credential> = Box::new(cred);
assert_eq!(dyn_cred.credential_type(), "totp");
let result = dyn_cred.verify(&code).await.expect("verify 应成功");
assert!(result, "dyn Credential 正确 code 应校验通过");
}
#[tokio::test]
async fn totp_credential_verify_with_replay_check_rejects_replay() {
let (cred, code) = make_totp_cred("t008");
let dao = crate::dao::tests::MockDao::new();
let first = cred
.verify_with_replay_check(&code, "user-001", &dao)
.await
.expect("首次校验不应报错");
assert!(first, "首次应通过");
let second = cred
.verify_with_replay_check(&code, "user-001", &dao)
.await
.expect("二次校验不应报错");
assert!(!second, "同一验证码二次使用应被拒绝(C-5 重放防护)");
}
}