1use 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
98const 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum EmailDeliveryError {
130 InvalidMessage,
132 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#[async_trait]
151pub trait RegistrationEmailSender: Send + Sync + 'static {
152 async fn send_registration_code(
154 &self,
155 recipient: &str,
156 code: &str,
157 expires_in_seconds: u64,
158 ) -> Result<(), EmailDeliveryError>;
159}
160
161#[derive(Clone)]
163pub struct RegistrationEmailSenderHandle(Arc<dyn RegistrationEmailSender>);
164
165impl RegistrationEmailSenderHandle {
166 pub fn new<T>(sender: T) -> Self
168 where
169 T: RegistrationEmailSender,
170 {
171 Self(Arc::new(sender))
172 }
173
174 pub fn from_arc(sender: Arc<dyn RegistrationEmailSender>) -> Self {
176 Self(sender)
177 }
178
179 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#[async_trait]
206pub trait VerificationCodeSender: Send + Sync + 'static {
207 async fn send_verification_code(
209 &self,
210 recipient: &str,
211 code: &str,
212 expires_in_seconds: u64,
213 ) -> Result<(), EmailDeliveryError>;
214}
215
216#[derive(Clone)]
218pub struct VerificationCodeSenderHandle(Arc<dyn VerificationCodeSender>);
219
220impl VerificationCodeSenderHandle {
221 pub fn new<T>(sender: T) -> Self
223 where
224 T: VerificationCodeSender,
225 {
226 Self(Arc::new(sender))
227 }
228
229 pub fn from_arc(sender: Arc<dyn VerificationCodeSender>) -> Self {
231 Self(sender)
232 }
233
234 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#[derive(Clone)]
257pub struct EmailVerificationConfig {
258 pub redis_key_prefix: String,
261 pub secret: String,
263 pub ttl_seconds: u64,
265 pub resend_cooldown_seconds: u64,
267 pub max_attempts: u32,
269 pub code_digits: usize,
271 pub send_window_seconds: u64,
273 pub send_ip_attempts: u64,
275 pub send_email_attempts: u64,
277 pub send_global_attempts: u64,
279 pub send_metric_name: &'static str,
281 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#[derive(Debug, Clone, Serialize, JsonSchema)]
307pub struct RegistrationEmailCodeAccepted {
308 pub accepted: bool,
310 pub expires_in: u64,
312 pub resend_after: u64,
314}
315
316pub 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
356pub struct RegistrationEmailVerification<'a> {
358 config: &'a EmailVerificationConfig,
359}
360
361impl<'a> RegistrationEmailVerification<'a> {
362 pub fn from_context(ctx: &'a ActionContext) -> Result<Self, BaseError> {
364 Self::from_config(ctx.tools().config::<EmailVerificationConfig>()?)
365 }
366
367 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 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 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 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 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 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
647fn 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}