Skip to main content

yang_base/action/auth/
email_verification.rs

1//! 一次性验证码:摘要存储、独立限流与原子单次消费。
2//!
3//! 典型用途是注册邮箱验证,但机制本身与具体业务无关:
4//!
5//! - 验证码与邮箱均以 HMAC 摘要形式进入 Redis,不保存明文身份;
6//! - 请求侧按来源 IP、目标身份与全局容量三维度限流,并有重发冷却;
7//! - 校验侧用 Lua 脚本原子比对并单次消费,错误尝试有上限且用尽即销毁;
8//!   [`RegistrationEmailVerification::verify_only`] 提供只验不消费变体
9//!   (两段式登录第一段用),失败路径与消费共享错误计数与上限销毁语义;
10//! - 邮件投递经业务实现的 [`RegistrationEmailSender`] 注入(如 SMTP 适配器),
11//!   投递失败会原子回收未消费的验证码,不留下可用凭证。
12//!
13//! TTL、验证码长度、密钥与限流阈值全部经 [`EmailVerificationConfig`] 注入,
14//! 不读取任何应用配置。
15
16use crate::action::ActionContext;
17use crate::transport::client_ip::client_ip_identity;
18use async_trait::async_trait;
19use hmac::{Hmac, Mac};
20use rand_core::{OsRng, RngCore};
21use schemars::JsonSchema;
22use serde::Serialize;
23use sha2::Sha256;
24use std::fmt;
25use std::sync::Arc;
26use yang_base::BaseError;
27
28const RESERVE_SEND_SCRIPT: &str = r#"
29local cooldown_ttl = redis.call('TTL', KEYS[4])
30if cooldown_ttl > 0 then
31    return {2, cooldown_ttl}
32end
33
34local retry_after = 0
35local exceeded = 0
36for index = 1, 3 do
37    local current = redis.call('INCR', KEYS[index])
38    if current == 1 then
39        redis.call('EXPIRE', KEYS[index], ARGV[1])
40    end
41    local ttl = redis.call('TTL', KEYS[index])
42    if ttl < 1 then
43        redis.call('EXPIRE', KEYS[index], ARGV[1])
44        ttl = tonumber(ARGV[1])
45    end
46    if current > tonumber(ARGV[index + 1]) then
47        exceeded = 1
48        if ttl > retry_after then
49            retry_after = ttl
50        end
51    end
52end
53if exceeded == 1 then
54    return {1, retry_after}
55end
56
57redis.call('SET', KEYS[4], '1', 'EX', ARGV[5], 'NX')
58return {0, tonumber(ARGV[5])}
59"#;
60
61const VERIFY_AND_CONSUME_SCRIPT: &str = r#"
62local value = redis.call('GET', KEYS[1])
63if not value then
64    return 0
65end
66local separator = string.find(value, ':', 1, true)
67if not separator then
68    redis.call('DEL', KEYS[1])
69    return 0
70end
71local expected = string.sub(value, 1, separator - 1)
72local attempts = tonumber(string.sub(value, separator + 1))
73if not attempts then
74    redis.call('DEL', KEYS[1])
75    return 0
76end
77if expected == ARGV[1] then
78    redis.call('DEL', KEYS[1])
79    return 1
80end
81attempts = attempts + 1
82if attempts >= tonumber(ARGV[2]) then
83    redis.call('DEL', KEYS[1])
84    return -2
85end
86redis.call('SET', KEYS[1], expected .. ':' .. attempts, 'KEEPTTL')
87return -1
88"#;
89
90const DELETE_IF_CURRENT_SCRIPT: &str = r#"
91local value = redis.call('GET', KEYS[1])
92if value and string.sub(value, 1, string.len(ARGV[1]) + 1) == ARGV[1] .. ':' then
93    return redis.call('DEL', KEYS[1])
94end
95return 0
96"#;
97
98// 只验不消费脚本:与 VERIFY_AND_CONSUME_SCRIPT 共享错误计数与上限销毁
99// 语义(错 N 次照常销毁),区别仅在摘要比对通过时不删除验证码,
100// 留待 consume 原子消费;损坏值不在此处清理,统一交给 consume 回收。
101const VERIFY_ONLY_SCRIPT: &str = r#"
102local value = redis.call('GET', KEYS[1])
103if not value then
104    return 0
105end
106local separator = string.find(value, ':', 1, true)
107if not separator then
108    return 0
109end
110local expected = string.sub(value, 1, separator - 1)
111local attempts = tonumber(string.sub(value, separator + 1))
112if not attempts then
113    return 0
114end
115if expected == ARGV[1] then
116    return 1
117end
118attempts = attempts + 1
119if attempts >= tonumber(ARGV[2]) then
120    redis.call('DEL', KEYS[1])
121    return -2
122end
123redis.call('SET', KEYS[1], expected .. ':' .. attempts, 'KEEPTTL')
124return -1
125"#;
126
127/// 邮件投递失败的脱敏类别;不携带 SMTP 响应、收件人或凭据。
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum EmailDeliveryError {
130    /// 邮件内容或地址无法构造。
131    InvalidMessage,
132    /// 邮件服务未接受邮件或暂不可用。
133    Unavailable,
134}
135
136impl fmt::Display for EmailDeliveryError {
137    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
138        match self {
139            Self::InvalidMessage => formatter.write_str("邮件内容无效"),
140            Self::Unavailable => formatter.write_str("邮件服务暂不可用"),
141        }
142    }
143}
144
145impl std::error::Error for EmailDeliveryError {}
146
147/// 验证码投递接口,由业务实现(SMTP、短信网关等)并注入。
148///
149/// 实现方不得记录 `recipient` 或 `code` 原文。
150#[async_trait]
151pub trait RegistrationEmailSender: Send + Sync + 'static {
152    /// 投递一枚短期验证码。
153    async fn send_registration_code(
154        &self,
155        recipient: &str,
156        code: &str,
157        expires_in_seconds: u64,
158    ) -> Result<(), EmailDeliveryError>;
159}
160
161/// 可放入 `Tools` 扩展槽的类型擦除投递句柄。
162#[derive(Clone)]
163pub struct RegistrationEmailSenderHandle(Arc<dyn RegistrationEmailSender>);
164
165impl RegistrationEmailSenderHandle {
166    /// 用业务投递器创建句柄。
167    pub fn new<T>(sender: T) -> Self
168    where
169        T: RegistrationEmailSender,
170    {
171        Self(Arc::new(sender))
172    }
173
174    /// 从已共享的投递器创建句柄。
175    pub fn from_arc(sender: Arc<dyn RegistrationEmailSender>) -> Self {
176        Self(sender)
177    }
178
179    /// 投递一枚短期验证码。
180    pub async fn send_registration_code(
181        &self,
182        recipient: &str,
183        code: &str,
184        expires_in_seconds: u64,
185    ) -> Result<(), EmailDeliveryError> {
186        self.0
187            .send_registration_code(recipient, code, expires_in_seconds)
188            .await
189    }
190}
191
192impl fmt::Debug for RegistrationEmailSenderHandle {
193    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
194        formatter
195            .debug_struct("RegistrationEmailSenderHandle")
196            .finish_non_exhaustive()
197    }
198}
199
200/// 通用一次性验证码投递接口(注册之外的场景,如登录 MFA 备用邮箱验证码)。
201///
202/// 与 [`RegistrationEmailSender`] 语义相同但类型独立:注册场景的邮件文案
203/// (「注册验证码」)不应出现在其他业务场景的投递中。实现方不得记录
204/// `recipient` 或 `code` 原文。
205#[async_trait]
206pub trait VerificationCodeSender: Send + Sync + 'static {
207    /// 投递一枚短期验证码。
208    async fn send_verification_code(
209        &self,
210        recipient: &str,
211        code: &str,
212        expires_in_seconds: u64,
213    ) -> Result<(), EmailDeliveryError>;
214}
215
216/// 可放入 `Tools` 扩展槽的类型擦除投递句柄([`VerificationCodeSender`])。
217#[derive(Clone)]
218pub struct VerificationCodeSenderHandle(Arc<dyn VerificationCodeSender>);
219
220impl VerificationCodeSenderHandle {
221    /// 用业务投递器创建句柄。
222    pub fn new<T>(sender: T) -> Self
223    where
224        T: VerificationCodeSender,
225    {
226        Self(Arc::new(sender))
227    }
228
229    /// 从已共享的投递器创建句柄。
230    pub fn from_arc(sender: Arc<dyn VerificationCodeSender>) -> Self {
231        Self(sender)
232    }
233
234    /// 投递一枚短期验证码。
235    pub async fn send_verification_code(
236        &self,
237        recipient: &str,
238        code: &str,
239        expires_in_seconds: u64,
240    ) -> Result<(), EmailDeliveryError> {
241        self.0
242            .send_verification_code(recipient, code, expires_in_seconds)
243            .await
244    }
245}
246
247impl fmt::Debug for VerificationCodeSenderHandle {
248    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
249        formatter
250            .debug_struct("VerificationCodeSenderHandle")
251            .finish_non_exhaustive()
252    }
253}
254
255/// [`RegistrationEmailVerification`] 的独立参数结构。
256#[derive(Clone)]
257pub struct EmailVerificationConfig {
258    /// Redis key 完整前缀(按应用与部署环境隔离,
259    /// 如 `"yang-system:prod:registration-email"`)。
260    pub redis_key_prefix: String,
261    /// 验证码摘要的独立服务端密钥,不得与 Token/Step-up 密钥复用。
262    pub secret: String,
263    /// 验证码有效期(秒)。
264    pub ttl_seconds: u64,
265    /// 同一身份的重发冷却(秒)。
266    pub resend_cooldown_seconds: u64,
267    /// 单枚验证码的最大错误尝试次数,用尽即销毁。
268    pub max_attempts: u32,
269    /// 验证码位数(1..=9,决定数字码空间 10^n)。
270    pub code_digits: usize,
271    /// 发送侧计数窗口长度(秒)。
272    pub send_window_seconds: u64,
273    /// 窗口内单来源 IP 允许的最大发送次数。
274    pub send_ip_attempts: u64,
275    /// 窗口内单身份允许的最大发送次数。
276    pub send_email_attempts: u64,
277    /// 窗口内全局允许的最大发送次数。
278    pub send_global_attempts: u64,
279    /// 发送侧计数器指标名(`metrics` feature 启用时发出)。
280    pub send_metric_name: &'static str,
281    /// 校验侧计数器指标名(`metrics` feature 启用时发出)。
282    pub verify_metric_name: &'static str,
283}
284
285impl fmt::Debug for EmailVerificationConfig {
286    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
287        formatter
288            .debug_struct("EmailVerificationConfig")
289            .field("redis_key_prefix", &self.redis_key_prefix)
290            .field("secret", &"[REDACTED]")
291            .field("ttl_seconds", &self.ttl_seconds)
292            .field("resend_cooldown_seconds", &self.resend_cooldown_seconds)
293            .field("max_attempts", &self.max_attempts)
294            .field("code_digits", &self.code_digits)
295            .field("send_window_seconds", &self.send_window_seconds)
296            .field("send_ip_attempts", &self.send_ip_attempts)
297            .field("send_email_attempts", &self.send_email_attempts)
298            .field("send_global_attempts", &self.send_global_attempts)
299            .field("send_metric_name", &self.send_metric_name)
300            .field("verify_metric_name", &self.verify_metric_name)
301            .finish()
302    }
303}
304
305/// 验证码请求被接受后的通用响应(不暴露身份是否真实存在)。
306#[derive(Debug, Clone, Serialize, JsonSchema)]
307pub struct RegistrationEmailCodeAccepted {
308    /// 请求已被接受(不保证邮件真实投递)。
309    pub accepted: bool,
310    /// 验证码有效期(秒)。
311    pub expires_in: u64,
312    /// 重发冷却(秒)。
313    pub resend_after: u64,
314}
315
316/// 规范化邮箱地址:去空白、小写化,并做严格的 ASCII 结构校验。
317///
318/// 结构校验完整覆盖 dot-atom 本地部分与标签化域名规则(单 `@`、本地部分不含
319/// 连续/首尾点号、域名标签只允许字母数字与内部连字符、顶级标签为纯字母且至少
320/// 两字符),因此不再需要额外的地址解析库。
321pub fn normalize_email(value: &str) -> Result<String, BaseError> {
322    let normalized = value.trim().to_ascii_lowercase();
323    if normalized.is_empty() || normalized.len() > 254 || !normalized.is_ascii() {
324        return Err(invalid_email());
325    }
326    let Some((local, domain)) = normalized.split_once('@') else {
327        return Err(invalid_email());
328    };
329    let local_valid = !local.is_empty()
330        && local.len() <= 64
331        && !local.starts_with('.')
332        && !local.ends_with('.')
333        && !local.contains("..")
334        && local.bytes().all(|byte| {
335            byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'%' | b'+' | b'-')
336        });
337    let labels = domain.split('.').collect::<Vec<_>>();
338    let domain_valid = labels.len() >= 2
339        && labels.iter().all(|label| {
340            !label.is_empty()
341                && !label.starts_with('-')
342                && !label.ends_with('-')
343                && label
344                    .bytes()
345                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
346        })
347        && labels.last().is_some_and(|label| {
348            label.len() >= 2 && label.bytes().all(|byte| byte.is_ascii_alphabetic())
349        });
350    if !local_valid || !domain_valid {
351        return Err(invalid_email());
352    }
353    Ok(normalized)
354}
355
356/// 一次性验证码引擎:配置经 `Tools` 的 config 槽注入,投递器经 extension 槽注入。
357pub struct RegistrationEmailVerification<'a> {
358    config: &'a EmailVerificationConfig,
359}
360
361impl<'a> RegistrationEmailVerification<'a> {
362    /// 从 Action 上下文的 `Tools` config 槽读取 [`EmailVerificationConfig`] 构建引擎。
363    pub fn from_context(ctx: &'a ActionContext) -> Result<Self, BaseError> {
364        Self::from_config(ctx.tools().config::<EmailVerificationConfig>()?)
365    }
366
367    /// 从显式配置构建引擎。
368    ///
369    /// 用于同一 `Tools` 中需要第二套验证码 key 域的场景(如邮箱换绑验证码,
370    /// 与注册验证码的 Redis key 前缀和密钥隔离)。调用方保证该配置来自
371    /// 独立注入的 config 槽,且与注册验证码的密钥不冲突。
372    pub fn from_config(config: &'a EmailVerificationConfig) -> Result<Self, BaseError> {
373        if !(1..=9).contains(&config.code_digits) {
374            return Err(BaseError::ConfigError(
375                "邮箱验证码位数必须在 1..=9 范围内".to_string(),
376            ));
377        }
378        Ok(Self { config })
379    }
380
381    /// 请求签发一枚验证码。
382    ///
383    /// `deliver = false` 时(如身份已存在的防枚举场景)只消耗限额、不真实投递,
384    /// 仍返回通用接受响应。
385    pub async fn request(
386        &self,
387        ctx: &ActionContext,
388        email: &str,
389        deliver: bool,
390    ) -> Result<RegistrationEmailCodeAccepted, BaseError> {
391        self.request_inner(ctx, email, deliver, None).await
392    }
393
394    /// 与 [`Self::request`] 相同,但验证码经显式传入的投递器发送。
395    ///
396    /// 用于注册之外的验证码场景(如登录 MFA 备用邮箱验证码):邮件文案由
397    /// 业务侧 [`VerificationCodeSender`] 决定,与注册投递器解耦;存储、限流、
398    /// 冷却与防枚举语义与 [`Self::request`] 完全一致。
399    pub async fn request_via(
400        &self,
401        ctx: &ActionContext,
402        email: &str,
403        deliver: bool,
404        sender: &VerificationCodeSenderHandle,
405    ) -> Result<RegistrationEmailCodeAccepted, BaseError> {
406        self.request_inner(ctx, email, deliver, Some(sender)).await
407    }
408
409    async fn request_inner(
410        &self,
411        ctx: &ActionContext,
412        email: &str,
413        deliver: bool,
414        sender: Option<&VerificationCodeSenderHandle>,
415    ) -> Result<RegistrationEmailCodeAccepted, BaseError> {
416        let fingerprint = email_fingerprint(&self.config.secret, email);
417        let prefix = self.key_prefix();
418        let keys = [
419            format!(
420                "{prefix}:send:ip:{}",
421                client_ip_fingerprint(&self.config.secret, ctx)
422            ),
423            format!("{prefix}:send:email:{fingerprint}"),
424            format!("{prefix}:send:global"),
425            format!("{prefix}:cooldown:{fingerprint}"),
426        ];
427        let args = [
428            self.config.send_window_seconds.to_string(),
429            self.config.send_ip_attempts.to_string(),
430            self.config.send_email_attempts.to_string(),
431            self.config.send_global_attempts.to_string(),
432            self.config.resend_cooldown_seconds.to_string(),
433        ];
434        let cache = ctx.tools().cache()?;
435        let decision: (i64, i64) = cache
436            .eval_script(&cache.script(RESERVE_SEND_SCRIPT), &keys, &args)
437            .await?;
438        if decision.0 != 0 {
439            #[cfg(feature = "metrics")]
440            metrics::counter!(
441                self.config.send_metric_name,
442                "result" => if decision.0 == 2 { "cooldown" } else { "limited" }
443            )
444            .increment(1);
445            return Err(BaseError::RateLimitExceeded {
446                retry_after_seconds: u64::try_from(decision.1).unwrap_or(1).max(1),
447            });
448        }
449
450        if !deliver {
451            #[cfg(feature = "metrics")]
452            metrics::counter!(self.config.send_metric_name, "result" => "suppressed").increment(1);
453            return Ok(self.accepted());
454        }
455
456        let code = generate_code(self.config.code_digits);
457        let digest = code_digest(&self.config.secret, email, &code);
458        let code_key = format!("{prefix}:code:{fingerprint}");
459        cache
460            .setex(
461                code_key.clone(),
462                i64::try_from(self.config.ttl_seconds).map_err(|_| {
463                    BaseError::ConfigError("邮箱验证码 TTL 超出 Redis 范围".to_string())
464                })?,
465                format!("{digest}:0"),
466            )
467            .await?;
468
469        let send_result = match sender {
470            Some(sender) => {
471                sender
472                    .send_verification_code(email, &code, self.config.ttl_seconds)
473                    .await
474            }
475            None => {
476                ctx.tools()
477                    .extension::<RegistrationEmailSenderHandle>()?
478                    .send_registration_code(email, &code, self.config.ttl_seconds)
479                    .await
480            }
481        };
482        if send_result.is_err() {
483            let _: i64 = cache
484                .eval_script(
485                    &cache.script(DELETE_IF_CURRENT_SCRIPT),
486                    &[code_key],
487                    &[digest],
488                )
489                .await?;
490            #[cfg(feature = "metrics")]
491            metrics::counter!(self.config.send_metric_name, "result" => "failed").increment(1);
492            return Err(delivery_unavailable());
493        }
494        #[cfg(feature = "metrics")]
495        metrics::counter!(self.config.send_metric_name, "result" => "sent").increment(1);
496        Ok(self.accepted())
497    }
498
499    /// 校验并原子消费一枚验证码;任何失败都返回统一的无效验证码错误。
500    pub async fn consume(
501        &self,
502        ctx: &ActionContext,
503        email: &str,
504        code: &str,
505    ) -> Result<(), BaseError> {
506        let (key, digest) = self.verify_material(email, code)?;
507        let cache = ctx.tools().cache()?;
508        let result: i64 = cache
509            .eval_script(
510                &cache.script(VERIFY_AND_CONSUME_SCRIPT),
511                &[key],
512                &[digest, self.config.max_attempts.to_string()],
513            )
514            .await?;
515        if result != 1 {
516            #[cfg(feature = "metrics")]
517            metrics::counter!(self.config.verify_metric_name, "result" => "denied").increment(1);
518            return Err(invalid_code());
519        }
520        #[cfg(feature = "metrics")]
521        metrics::counter!(self.config.verify_metric_name, "result" => "consumed").increment(1);
522        Ok(())
523    }
524
525    /// 只校验不消费一枚验证码;任何失败都返回统一的无效验证码错误。
526    ///
527    /// 供两段式登录的第一段使用:先确认验证码有效但不销毁,待第二因子
528    /// (如 TOTP)也通过后再由 [`Self::consume`] 完成原子消费。失败路径与
529    /// [`Self::consume`] 共享错误计数与上限销毁语义——错误尝试照常计数、
530    /// 达上限即销毁,不存在不计次的暴力枚举旁路。
531    ///
532    /// 本接口不构成最终持有证明:验证码在 TTL 内仍可被消费。调用方在签发
533    /// 任何凭据前必须以 [`Self::consume`] 完成原子消费。
534    pub async fn verify_only(
535        &self,
536        ctx: &ActionContext,
537        email: &str,
538        code: &str,
539    ) -> Result<(), BaseError> {
540        let (key, digest) = self.verify_material(email, code)?;
541        let cache = ctx.tools().cache()?;
542        let result: i64 = cache
543            .eval_script(
544                &cache.script(VERIFY_ONLY_SCRIPT),
545                &[key],
546                &[digest, self.config.max_attempts.to_string()],
547            )
548            .await?;
549        if result != 1 {
550            #[cfg(feature = "metrics")]
551            metrics::counter!(self.config.verify_metric_name, "result" => "denied").increment(1);
552            return Err(invalid_code());
553        }
554        #[cfg(feature = "metrics")]
555        metrics::counter!(self.config.verify_metric_name, "result" => "peeked").increment(1);
556        Ok(())
557    }
558
559    /// 校验侧的公共前置:验证码形态预检与 Redis key/摘要派生。
560    fn verify_material(&self, email: &str, code: &str) -> Result<(String, String), BaseError> {
561        if code.len() != self.config.code_digits || !code.bytes().all(|byte| byte.is_ascii_digit())
562        {
563            return Err(invalid_code());
564        }
565        let fingerprint = email_fingerprint(&self.config.secret, email);
566        let key = format!("{}:code:{fingerprint}", self.key_prefix());
567        let digest = code_digest(&self.config.secret, email, code);
568        Ok((key, digest))
569    }
570
571    fn key_prefix(&self) -> &str {
572        &self.config.redis_key_prefix
573    }
574
575    fn accepted(&self) -> RegistrationEmailCodeAccepted {
576        RegistrationEmailCodeAccepted {
577            accepted: true,
578            expires_in: self.config.ttl_seconds,
579            resend_after: self.config.resend_cooldown_seconds,
580        }
581    }
582}
583
584fn generate_code(code_digits: usize) -> String {
585    let code_space = 10_u32.pow(u32::try_from(code_digits).unwrap_or(6));
586    let unbiased_upper_bound = u32::MAX - (u32::MAX % code_space);
587    let value = loop {
588        let candidate = OsRng.next_u32();
589        if candidate < unbiased_upper_bound {
590            break candidate % code_space;
591        }
592    };
593    format!("{value:0code_digits$}")
594}
595
596fn client_ip_fingerprint(secret: &str, ctx: &ActionContext) -> String {
597    keyed_digest(
598        secret,
599        &[
600            b"registration-email-ip-v1",
601            client_ip_identity(ctx).as_bytes(),
602        ],
603    )
604}
605
606fn email_fingerprint(secret: &str, email: &str) -> String {
607    keyed_digest(secret, &[b"registration-email-key-v1", email.as_bytes()])
608}
609
610fn code_digest(secret: &str, email: &str, code: &str) -> String {
611    keyed_digest(
612        secret,
613        &[
614            b"registration-email-code-v1",
615            email.as_bytes(),
616            code.as_bytes(),
617        ],
618    )
619}
620
621fn keyed_digest(secret: &str, parts: &[&[u8]]) -> String {
622    let mut hasher = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
623        .unwrap_or_else(|_| unreachable!("HMAC-SHA256 接受任意长度密钥"));
624    for part in parts {
625        hasher.update(&(part.len() as u64).to_be_bytes());
626        hasher.update(part);
627    }
628    hasher
629        .finalize()
630        .into_bytes()
631        .iter()
632        .map(|byte| format!("{byte:02x}"))
633        .collect()
634}
635
636fn invalid_email() -> BaseError {
637    BaseError::ParamInvalid("email".to_string(), "邮箱格式无效".to_string())
638}
639
640fn invalid_code() -> BaseError {
641    BaseError::ParamInvalid(
642        "email_code".to_string(),
643        "邮箱验证码无效或已过期".to_string(),
644    )
645}
646
647/// 投递失败的脱敏映射:一律是**同一个**脱敏的、可重试的上游失败。
648///
649/// 文案不含任何 SMTP 侧细节(地址、响应码、异常文本),避免把投递设施的信息泄露给
650/// 注册/重置接口的调用方。分类为 `Transient`(HTTP 边界 → **503**)是因为 SMTP
651/// 不可用几乎总是瞬时的,客户端按 503 重试是正确行为。
652///
653/// **不要改回 `HttpRequestFailed`**:该变体在 `http` feature 开启时持有
654/// `reqwest::Error`、关闭时持有 `String`,用它会让本函数的错误分类随**构建配置**
655/// 漂移。此前正是如此:开启 `http` 后退化成 `Unknown`,分类从 Transient 变成
656/// Server、错误码从 300002 变成 999999、HTTP 从 503 变成 500,客户端不再重试——
657/// 而当时这里的注释还写着这是「等价的脱敏服务端错误」。两者并不等价。
658/// [`BaseError::UpstreamUnavailable`] 与传输和 feature 都无关,正是为此而设。
659fn delivery_unavailable() -> BaseError {
660    BaseError::UpstreamUnavailable("邮件服务暂不可用".to_string())
661}
662
663#[cfg(test)]
664mod tests {
665    use super::*;
666
667    const CODE_DIGITS: usize = 6;
668
669    #[test]
670    fn email_is_canonical_ascii_and_rejects_ambiguous_shapes() {
671        assert_eq!(
672            normalize_email(" Alice.Tag+demo@Example.COM ")
673                .unwrap_or_else(|error| panic!("合法邮箱应规范化: {error}")),
674            "alice.tag+demo@example.com"
675        );
676        for invalid in [
677            "alice@example",
678            "alice@@example.com",
679            ".alice@example.com",
680            "alice..tag@example.com",
681            "alice@-example.com",
682            "用户@example.com",
683        ] {
684            assert!(normalize_email(invalid).is_err(), "应拒绝 {invalid:?}");
685        }
686    }
687
688    #[test]
689    fn generated_code_and_redis_material_do_not_expose_plaintext_identity() {
690        let code = generate_code(CODE_DIGITS);
691        assert_eq!(code.len(), CODE_DIGITS);
692        assert!(code.bytes().all(|byte| byte.is_ascii_digit()));
693
694        let email = "alice@example.com";
695        let secret = "independent-email-verification-secret-32-bytes";
696        let fingerprint = email_fingerprint(secret, email);
697        let digest = code_digest(secret, email, &code);
698        assert_eq!(fingerprint.len(), 64);
699        assert_eq!(digest.len(), 64);
700        assert!(!fingerprint.contains(email));
701        assert!(!digest.contains(email));
702        assert!(!digest.contains(&code));
703    }
704
705    #[test]
706    fn config_debug_redacts_the_secret() {
707        let config = EmailVerificationConfig {
708            redis_key_prefix: "app:test:registration-email".to_string(),
709            secret: "independent-email-verification-secret-32-bytes".to_string(),
710            ttl_seconds: 600,
711            resend_cooldown_seconds: 60,
712            max_attempts: 5,
713            code_digits: CODE_DIGITS,
714            send_window_seconds: 3600,
715            send_ip_attempts: 20,
716            send_email_attempts: 5,
717            send_global_attempts: 1000,
718            send_metric_name: "test_registration_email_total",
719            verify_metric_name: "test_registration_email_verify_total",
720        };
721        let debug = format!("{config:?}");
722        assert!(!debug.contains("independent-email-verification-secret"));
723        assert!(debug.contains("[REDACTED]"));
724    }
725}