1use crate::action::ActionContext;
15use crate::transport::client_ip::client_ip_identity;
16use async_trait::async_trait;
17use hmac::{Hmac, Mac};
18use rand_core::{OsRng, RngCore};
19use schemars::JsonSchema;
20use serde::Serialize;
21use sha2::Sha256;
22use std::fmt;
23use std::sync::Arc;
24use yang_base::BaseError;
25
26const RESERVE_SEND_SCRIPT: &str = r#"
27local cooldown_ttl = redis.call('TTL', KEYS[4])
28if cooldown_ttl > 0 then
29 return {2, cooldown_ttl}
30end
31
32local retry_after = 0
33local exceeded = 0
34for index = 1, 3 do
35 local current = redis.call('INCR', KEYS[index])
36 if current == 1 then
37 redis.call('EXPIRE', KEYS[index], ARGV[1])
38 end
39 local ttl = redis.call('TTL', KEYS[index])
40 if ttl < 1 then
41 redis.call('EXPIRE', KEYS[index], ARGV[1])
42 ttl = tonumber(ARGV[1])
43 end
44 if current > tonumber(ARGV[index + 1]) then
45 exceeded = 1
46 if ttl > retry_after then
47 retry_after = ttl
48 end
49 end
50end
51if exceeded == 1 then
52 return {1, retry_after}
53end
54
55redis.call('SET', KEYS[4], '1', 'EX', ARGV[5], 'NX')
56return {0, tonumber(ARGV[5])}
57"#;
58
59const VERIFY_AND_CONSUME_SCRIPT: &str = r#"
60local value = redis.call('GET', KEYS[1])
61if not value then
62 return 0
63end
64local separator = string.find(value, ':', 1, true)
65if not separator then
66 redis.call('DEL', KEYS[1])
67 return 0
68end
69local expected = string.sub(value, 1, separator - 1)
70local attempts = tonumber(string.sub(value, separator + 1))
71if not attempts then
72 redis.call('DEL', KEYS[1])
73 return 0
74end
75if expected == ARGV[1] then
76 redis.call('DEL', KEYS[1])
77 return 1
78end
79attempts = attempts + 1
80if attempts >= tonumber(ARGV[2]) then
81 redis.call('DEL', KEYS[1])
82 return -2
83end
84redis.call('SET', KEYS[1], expected .. ':' .. attempts, 'KEEPTTL')
85return -1
86"#;
87
88const DELETE_IF_CURRENT_SCRIPT: &str = r#"
89local value = redis.call('GET', KEYS[1])
90if value and string.sub(value, 1, string.len(ARGV[1]) + 1) == ARGV[1] .. ':' then
91 return redis.call('DEL', KEYS[1])
92end
93return 0
94"#;
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum EmailDeliveryError {
99 InvalidMessage,
101 Unavailable,
103}
104
105impl fmt::Display for EmailDeliveryError {
106 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
107 match self {
108 Self::InvalidMessage => formatter.write_str("邮件内容无效"),
109 Self::Unavailable => formatter.write_str("邮件服务暂不可用"),
110 }
111 }
112}
113
114impl std::error::Error for EmailDeliveryError {}
115
116#[async_trait]
120pub trait RegistrationEmailSender: Send + Sync + 'static {
121 async fn send_registration_code(
123 &self,
124 recipient: &str,
125 code: &str,
126 expires_in_seconds: u64,
127 ) -> Result<(), EmailDeliveryError>;
128}
129
130#[derive(Clone)]
132pub struct RegistrationEmailSenderHandle(Arc<dyn RegistrationEmailSender>);
133
134impl RegistrationEmailSenderHandle {
135 pub fn new<T>(sender: T) -> Self
137 where
138 T: RegistrationEmailSender,
139 {
140 Self(Arc::new(sender))
141 }
142
143 pub fn from_arc(sender: Arc<dyn RegistrationEmailSender>) -> Self {
145 Self(sender)
146 }
147
148 pub async fn send_registration_code(
150 &self,
151 recipient: &str,
152 code: &str,
153 expires_in_seconds: u64,
154 ) -> Result<(), EmailDeliveryError> {
155 self.0
156 .send_registration_code(recipient, code, expires_in_seconds)
157 .await
158 }
159}
160
161impl fmt::Debug for RegistrationEmailSenderHandle {
162 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
163 formatter
164 .debug_struct("RegistrationEmailSenderHandle")
165 .finish_non_exhaustive()
166 }
167}
168
169#[derive(Clone)]
171pub struct EmailVerificationConfig {
172 pub redis_key_prefix: String,
175 pub secret: String,
177 pub ttl_seconds: u64,
179 pub resend_cooldown_seconds: u64,
181 pub max_attempts: u32,
183 pub code_digits: usize,
185 pub send_window_seconds: u64,
187 pub send_ip_attempts: u64,
189 pub send_email_attempts: u64,
191 pub send_global_attempts: u64,
193 pub send_metric_name: &'static str,
195 pub verify_metric_name: &'static str,
197}
198
199impl fmt::Debug for EmailVerificationConfig {
200 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
201 formatter
202 .debug_struct("EmailVerificationConfig")
203 .field("redis_key_prefix", &self.redis_key_prefix)
204 .field("secret", &"[REDACTED]")
205 .field("ttl_seconds", &self.ttl_seconds)
206 .field("resend_cooldown_seconds", &self.resend_cooldown_seconds)
207 .field("max_attempts", &self.max_attempts)
208 .field("code_digits", &self.code_digits)
209 .field("send_window_seconds", &self.send_window_seconds)
210 .field("send_ip_attempts", &self.send_ip_attempts)
211 .field("send_email_attempts", &self.send_email_attempts)
212 .field("send_global_attempts", &self.send_global_attempts)
213 .field("send_metric_name", &self.send_metric_name)
214 .field("verify_metric_name", &self.verify_metric_name)
215 .finish()
216 }
217}
218
219#[derive(Debug, Clone, Serialize, JsonSchema)]
221pub struct RegistrationEmailCodeAccepted {
222 pub accepted: bool,
224 pub expires_in: u64,
226 pub resend_after: u64,
228}
229
230pub fn normalize_email(value: &str) -> Result<String, BaseError> {
236 let normalized = value.trim().to_ascii_lowercase();
237 if normalized.is_empty() || normalized.len() > 254 || !normalized.is_ascii() {
238 return Err(invalid_email());
239 }
240 let Some((local, domain)) = normalized.split_once('@') else {
241 return Err(invalid_email());
242 };
243 let local_valid = !local.is_empty()
244 && local.len() <= 64
245 && !local.starts_with('.')
246 && !local.ends_with('.')
247 && !local.contains("..")
248 && local.bytes().all(|byte| {
249 byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'%' | b'+' | b'-')
250 });
251 let labels = domain.split('.').collect::<Vec<_>>();
252 let domain_valid = labels.len() >= 2
253 && labels.iter().all(|label| {
254 !label.is_empty()
255 && !label.starts_with('-')
256 && !label.ends_with('-')
257 && label
258 .bytes()
259 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
260 })
261 && labels.last().is_some_and(|label| {
262 label.len() >= 2 && label.bytes().all(|byte| byte.is_ascii_alphabetic())
263 });
264 if !local_valid || !domain_valid {
265 return Err(invalid_email());
266 }
267 Ok(normalized)
268}
269
270pub struct RegistrationEmailVerification<'a> {
272 config: &'a EmailVerificationConfig,
273}
274
275impl<'a> RegistrationEmailVerification<'a> {
276 pub fn from_context(ctx: &'a ActionContext) -> Result<Self, BaseError> {
278 let config = ctx.tools().config::<EmailVerificationConfig>()?;
279 if !(1..=9).contains(&config.code_digits) {
280 return Err(BaseError::ConfigError(
281 "邮箱验证码位数必须在 1..=9 范围内".to_string(),
282 ));
283 }
284 Ok(Self { config })
285 }
286
287 pub async fn request(
292 &self,
293 ctx: &ActionContext,
294 email: &str,
295 deliver: bool,
296 ) -> Result<RegistrationEmailCodeAccepted, BaseError> {
297 let fingerprint = email_fingerprint(&self.config.secret, email);
298 let prefix = self.key_prefix();
299 let keys = [
300 format!(
301 "{prefix}:send:ip:{}",
302 client_ip_fingerprint(&self.config.secret, ctx)
303 ),
304 format!("{prefix}:send:email:{fingerprint}"),
305 format!("{prefix}:send:global"),
306 format!("{prefix}:cooldown:{fingerprint}"),
307 ];
308 let args = [
309 self.config.send_window_seconds.to_string(),
310 self.config.send_ip_attempts.to_string(),
311 self.config.send_email_attempts.to_string(),
312 self.config.send_global_attempts.to_string(),
313 self.config.resend_cooldown_seconds.to_string(),
314 ];
315 let cache = ctx.tools().cache()?;
316 let decision: (i64, i64) = cache
317 .eval_script(&cache.script(RESERVE_SEND_SCRIPT), &keys, &args)
318 .await?;
319 if decision.0 != 0 {
320 #[cfg(feature = "metrics")]
321 metrics::counter!(
322 self.config.send_metric_name,
323 "result" => if decision.0 == 2 { "cooldown" } else { "limited" }
324 )
325 .increment(1);
326 return Err(BaseError::RateLimitExceeded {
327 retry_after_seconds: u64::try_from(decision.1).unwrap_or(1).max(1),
328 });
329 }
330
331 if !deliver {
332 #[cfg(feature = "metrics")]
333 metrics::counter!(self.config.send_metric_name, "result" => "suppressed").increment(1);
334 return Ok(self.accepted());
335 }
336
337 let code = generate_code(self.config.code_digits);
338 let digest = code_digest(&self.config.secret, email, &code);
339 let code_key = format!("{prefix}:code:{fingerprint}");
340 cache
341 .setex(
342 code_key.clone(),
343 i64::try_from(self.config.ttl_seconds).map_err(|_| {
344 BaseError::ConfigError("邮箱验证码 TTL 超出 Redis 范围".to_string())
345 })?,
346 format!("{digest}:0"),
347 )
348 .await?;
349
350 let sender = ctx.tools().extension::<RegistrationEmailSenderHandle>()?;
351 if sender
352 .send_registration_code(email, &code, self.config.ttl_seconds)
353 .await
354 .is_err()
355 {
356 let _: i64 = cache
357 .eval_script(
358 &cache.script(DELETE_IF_CURRENT_SCRIPT),
359 &[code_key],
360 &[digest],
361 )
362 .await?;
363 #[cfg(feature = "metrics")]
364 metrics::counter!(self.config.send_metric_name, "result" => "failed").increment(1);
365 return Err(delivery_unavailable());
366 }
367 #[cfg(feature = "metrics")]
368 metrics::counter!(self.config.send_metric_name, "result" => "sent").increment(1);
369 Ok(self.accepted())
370 }
371
372 pub async fn consume(
374 &self,
375 ctx: &ActionContext,
376 email: &str,
377 code: &str,
378 ) -> Result<(), BaseError> {
379 if code.len() != self.config.code_digits || !code.bytes().all(|byte| byte.is_ascii_digit())
380 {
381 return Err(invalid_code());
382 }
383 let fingerprint = email_fingerprint(&self.config.secret, email);
384 let key = format!("{}:code:{fingerprint}", self.key_prefix());
385 let digest = code_digest(&self.config.secret, email, code);
386 let cache = ctx.tools().cache()?;
387 let result: i64 = cache
388 .eval_script(
389 &cache.script(VERIFY_AND_CONSUME_SCRIPT),
390 &[key],
391 &[digest, self.config.max_attempts.to_string()],
392 )
393 .await?;
394 if result != 1 {
395 #[cfg(feature = "metrics")]
396 metrics::counter!(self.config.verify_metric_name, "result" => "denied").increment(1);
397 return Err(invalid_code());
398 }
399 #[cfg(feature = "metrics")]
400 metrics::counter!(self.config.verify_metric_name, "result" => "consumed").increment(1);
401 Ok(())
402 }
403
404 fn key_prefix(&self) -> &str {
405 &self.config.redis_key_prefix
406 }
407
408 fn accepted(&self) -> RegistrationEmailCodeAccepted {
409 RegistrationEmailCodeAccepted {
410 accepted: true,
411 expires_in: self.config.ttl_seconds,
412 resend_after: self.config.resend_cooldown_seconds,
413 }
414 }
415}
416
417fn generate_code(code_digits: usize) -> String {
418 let code_space = 10_u32.pow(u32::try_from(code_digits).unwrap_or(6));
419 let unbiased_upper_bound = u32::MAX - (u32::MAX % code_space);
420 let value = loop {
421 let candidate = OsRng.next_u32();
422 if candidate < unbiased_upper_bound {
423 break candidate % code_space;
424 }
425 };
426 format!("{value:0code_digits$}")
427}
428
429fn client_ip_fingerprint(secret: &str, ctx: &ActionContext) -> String {
430 keyed_digest(
431 secret,
432 &[
433 b"registration-email-ip-v1",
434 client_ip_identity(ctx).as_bytes(),
435 ],
436 )
437}
438
439fn email_fingerprint(secret: &str, email: &str) -> String {
440 keyed_digest(secret, &[b"registration-email-key-v1", email.as_bytes()])
441}
442
443fn code_digest(secret: &str, email: &str, code: &str) -> String {
444 keyed_digest(
445 secret,
446 &[
447 b"registration-email-code-v1",
448 email.as_bytes(),
449 code.as_bytes(),
450 ],
451 )
452}
453
454fn keyed_digest(secret: &str, parts: &[&[u8]]) -> String {
455 let mut hasher = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
456 .unwrap_or_else(|_| unreachable!("HMAC-SHA256 接受任意长度密钥"));
457 for part in parts {
458 hasher.update(&(part.len() as u64).to_be_bytes());
459 hasher.update(part);
460 }
461 hasher
462 .finalize()
463 .into_bytes()
464 .iter()
465 .map(|byte| format!("{byte:02x}"))
466 .collect()
467}
468
469fn invalid_email() -> BaseError {
470 BaseError::ParamInvalid("email".to_string(), "邮箱格式无效".to_string())
471}
472
473fn invalid_code() -> BaseError {
474 BaseError::ParamInvalid(
475 "email_code".to_string(),
476 "邮箱验证码无效或已过期".to_string(),
477 )
478}
479
480fn delivery_unavailable() -> BaseError {
486 #[cfg(not(feature = "http"))]
487 {
488 BaseError::HttpRequestFailed("邮件服务暂不可用".to_string())
489 }
490 #[cfg(feature = "http")]
491 {
492 BaseError::Unknown("邮件服务暂不可用".to_string())
493 }
494}
495
496#[cfg(test)]
497mod tests {
498 use super::*;
499
500 const CODE_DIGITS: usize = 6;
501
502 #[test]
503 fn email_is_canonical_ascii_and_rejects_ambiguous_shapes() {
504 assert_eq!(
505 normalize_email(" Alice.Tag+demo@Example.COM ")
506 .unwrap_or_else(|error| panic!("合法邮箱应规范化: {error}")),
507 "alice.tag+demo@example.com"
508 );
509 for invalid in [
510 "alice@example",
511 "alice@@example.com",
512 ".alice@example.com",
513 "alice..tag@example.com",
514 "alice@-example.com",
515 "用户@example.com",
516 ] {
517 assert!(normalize_email(invalid).is_err(), "应拒绝 {invalid:?}");
518 }
519 }
520
521 #[test]
522 fn generated_code_and_redis_material_do_not_expose_plaintext_identity() {
523 let code = generate_code(CODE_DIGITS);
524 assert_eq!(code.len(), CODE_DIGITS);
525 assert!(code.bytes().all(|byte| byte.is_ascii_digit()));
526
527 let email = "alice@example.com";
528 let secret = "independent-email-verification-secret-32-bytes";
529 let fingerprint = email_fingerprint(secret, email);
530 let digest = code_digest(secret, email, &code);
531 assert_eq!(fingerprint.len(), 64);
532 assert_eq!(digest.len(), 64);
533 assert!(!fingerprint.contains(email));
534 assert!(!digest.contains(email));
535 assert!(!digest.contains(&code));
536 }
537
538 #[test]
539 fn config_debug_redacts_the_secret() {
540 let config = EmailVerificationConfig {
541 redis_key_prefix: "app:test:registration-email".to_string(),
542 secret: "independent-email-verification-secret-32-bytes".to_string(),
543 ttl_seconds: 600,
544 resend_cooldown_seconds: 60,
545 max_attempts: 5,
546 code_digits: CODE_DIGITS,
547 send_window_seconds: 3600,
548 send_ip_attempts: 20,
549 send_email_attempts: 5,
550 send_global_attempts: 1000,
551 send_metric_name: "test_registration_email_total",
552 verify_metric_name: "test_registration_email_verify_total",
553 };
554 let debug = format!("{config:?}");
555 assert!(!debug.contains("independent-email-verification-secret"));
556 assert!(debug.contains("[REDACTED]"));
557 }
558}