use super::{Credential, CredentialModel, CredentialType};
use crate::error::{GarrisonError, GarrisonResult};
use crate::secure::email::EmailVerificationService;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
pub const EMAIL_CODE_CREDENTIAL_TYPE: &str = "email-code";
#[derive(Debug, Clone, Serialize, Deserialize)]
struct EmailSecretData {
email: String,
}
impl EmailSecretData {
fn from_json(secret_data: &str) -> GarrisonResult<Self> {
serde_json::from_str(secret_data)
.map_err(|e| GarrisonError::InvalidParam(format!("account-email-parse-failed::{}", e)))
}
}
pub struct EmailCodeCredential {
model: CredentialModel,
service: Arc<EmailVerificationService>,
}
impl EmailCodeCredential {
pub fn new(model: CredentialModel, service: Arc<EmailVerificationService>) -> Self {
Self { model, service }
}
pub fn email(&self) -> GarrisonResult<String> {
Ok(EmailSecretData::from_json(&self.model.secret_data)?.email)
}
}
#[async_trait]
impl Credential for EmailCodeCredential {
fn credential_type(&self) -> CredentialType {
EMAIL_CODE_CREDENTIAL_TYPE
}
fn to_model(&self) -> CredentialModel {
self.model.clone()
}
async fn verify(&self, input: &str) -> GarrisonResult<bool> {
let data = EmailSecretData::from_json(&self.model.secret_data)?;
match self.service.verify_code(&data.email, input).await {
Ok(()) => Ok(true),
Err(GarrisonError::EmailCodeNotFound) => Ok(false),
Err(GarrisonError::InvalidParam(msg))
if msg.starts_with(crate::secure::email::service::ERR_EMAIL_CODE_WRONG) =>
{
Ok(false)
},
Err(e) => Err(e),
}
}
}
pub struct EmailCodeCredentialBuilder {
#[cfg_attr(not(feature = "account-authflow"), allow(dead_code))]
service: Arc<EmailVerificationService>,
}
impl EmailCodeCredentialBuilder {
pub fn new(service: Arc<EmailVerificationService>) -> Self {
Self { service }
}
}
#[cfg(feature = "account-authflow")]
#[async_trait]
impl crate::account::authflow::executor::CredentialBuilder for EmailCodeCredentialBuilder {
fn build(&self, model: CredentialModel) -> GarrisonResult<Box<dyn Credential>> {
Ok(Box::new(EmailCodeCredential::new(
model,
self.service.clone(),
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::tests::MockDao;
use crate::dao::GarrisonDao;
use crate::secure::email::{EmailRateLimiter, EmailSender};
struct CapturingSender {
mail: parking_lot::Mutex<Option<(String, String)>>,
}
#[async_trait]
impl EmailSender for CapturingSender {
async fn send(&self, to: &str, subject: &str, _body: &str) -> GarrisonResult<()> {
*self.mail.lock() = Some((to.to_string(), subject.to_string()));
Ok(())
}
}
fn make_cred() -> (
EmailCodeCredential,
Arc<EmailVerificationService>,
Arc<dyn GarrisonDao>,
) {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let service = Arc::new(EmailVerificationService::new(
EmailRateLimiter::new(dao.clone(), 100, 100),
Arc::new(CapturingSender {
mail: parking_lot::Mutex::new(None),
}),
dao.clone(),
3,
100,
600,
));
let model = CredentialModel {
id: "cred-email-001".to_string(),
user_id: "alice".to_string(),
credential_type: EMAIL_CODE_CREDENTIAL_TYPE.to_string(),
secret_data: r#"{"email":"alice@example.com"}"#.to_string(),
label: Some("邮箱验证码".to_string()),
created_at: 0,
enabled: true,
priority: 0,
};
(
EmailCodeCredential::new(model, service.clone()),
service,
dao,
)
}
#[test]
fn email_credential_type_returns_email_code() {
let (cred, _, _) = make_cred();
assert_eq!(cred.credential_type(), "email-code");
}
#[test]
fn email_credential_to_model_returns_original() {
let (cred, _, _) = make_cred();
let model = cred.to_model();
assert_eq!(model.id, "cred-email-001");
assert_eq!(model.user_id, "alice");
assert_eq!(model.credential_type, "email-code");
assert!(model.secret_data.contains("alice@example.com"));
}
#[test]
fn email_credential_email_accessor_parses_address() {
let (cred, _, _) = make_cred();
assert_eq!(cred.email().unwrap(), "alice@example.com");
}
#[tokio::test]
async fn email_credential_verify_correct_code() {
let (cred, _, dao) = make_cred();
dao.set("email:code:alice@example.com", "123456", 600)
.await
.unwrap();
let result = cred.verify("123456").await.unwrap();
assert!(result, "正确验证码应返回 Ok(true)");
let stored = dao.get("email:code:alice@example.com").await.unwrap();
assert!(stored.is_none(), "验证通过后验证码应被消费删除");
}
#[tokio::test]
async fn email_credential_verify_missing_code_returns_false() {
let (cred, _, _) = make_cred();
let result = cred.verify("123456").await.unwrap();
assert!(!result, "未发送验证码应返回 Ok(false)");
}
#[tokio::test]
async fn email_credential_verify_max_attempts_propagates() {
let (cred, service, _) = make_cred();
service.send_code("alice@example.com").await.unwrap();
for _ in 0..3 {
assert!(
!cred.verify("000000").await.unwrap(),
"前 3 次应为 Ok(false)"
);
}
let result = cred.verify("000000").await;
assert!(
matches!(result, Err(GarrisonError::EmailVerifyMaxAttempts)),
"第 4 次应透传 EmailVerifyMaxAttempts,实际: {:?}",
result
);
}
#[tokio::test]
async fn email_credential_invalid_secret_data_returns_error() {
let (_, service, _) = make_cred();
let model = CredentialModel {
id: "bad".to_string(),
user_id: "alice".to_string(),
credential_type: EMAIL_CODE_CREDENTIAL_TYPE.to_string(),
secret_data: "not-json".to_string(),
label: None,
created_at: 0,
enabled: true,
priority: 0,
};
let cred = EmailCodeCredential::new(model, service);
let result = cred.verify("123456").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg.starts_with("account-email-parse-failed")),
"非法 secret_data 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn email_credential_usable_as_dyn_credential() {
let (cred, _, dao) = make_cred();
dao.set("email:code:alice@example.com", "654321", 600)
.await
.unwrap();
let dyn_cred: Box<dyn Credential> = Box::new(cred);
assert_eq!(dyn_cred.credential_type(), "email-code");
assert!(
dyn_cred.verify("654321").await.unwrap(),
"dyn 凭证正确码应通过"
);
}
#[cfg(feature = "account-authflow")]
#[tokio::test]
async fn email_credential_builder_builds_dyn_credential() {
use crate::account::authflow::executor::CredentialBuilder;
let (_, service, _) = make_cred();
let builder = EmailCodeCredentialBuilder::new(service);
let model = CredentialModel {
id: "cred-email-002".to_string(),
user_id: "bob".to_string(),
credential_type: EMAIL_CODE_CREDENTIAL_TYPE.to_string(),
secret_data: r#"{"email":"bob@example.com"}"#.to_string(),
label: None,
created_at: 0,
enabled: true,
priority: 0,
};
let dyn_cred = builder.build(model).unwrap();
assert_eq!(dyn_cred.credential_type(), "email-code");
}
}