fix(auth): SMTP 信封发件人用裸地址,修 501;发信失败记日志

两个真问题,前者被后者掩盖:
1. mailer.go 把带显示名的 SMTP_FROM(「穿山甲 <noreply@x>」)直接当 SMTP
   信封发件人(MAIL FROM)传给 smtp.SendMail,Resend 报 501 Bad sender address
   syntax → 验证码发不出。改用 net/mail 解析出裸地址作信封发件人,From: 头
   仍保留完整显示名。
2. service.go 两处异步发信把错误静默吞了(_ = SendCode/SendAlreadyRegistered),
   导致 SMTP 故障日志无痕、难排查(本次端口被封+501 都被吞)。改为失败时
   slog.Error 记日志,邮箱经 maskEmail 打码,绝不记验证码(守 no-secret-in-logs)。

测试:TestEnvelopeFrom(显示名/裸址/unicode → 裸址)守 501 回归;TestMaskEmail
守日志脱敏。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
wangjia
2026-06-28 07:50:37 +08:00
parent b12519be0a
commit 77ce809d48
3 changed files with 81 additions and 4 deletions
+24 -2
View File
@@ -6,13 +6,29 @@ import (
"crypto/subtle"
"errors"
"fmt"
"log/slog"
"math/big"
"strings"
"time"
"github.com/redis/go-redis/v9"
"github.com/wangjia/pangolin/server/internal/apierr"
)
// maskEmail masks the local part of an email for safe logging (no full PII):
// "chenxin880812@gmail.com" -> "ch***@gmail.com". Used only in error logs.
func maskEmail(e string) string {
at := strings.IndexByte(e, '@')
if at <= 0 {
return "***"
}
local := e[:at]
if len(local) <= 2 {
return "***" + e[at:]
}
return local[:2] + "***" + e[at:]
}
// Redis key helpers for verification codes (doc/03 §4: auth:code:{email}).
func codeKey(email string) string { return "auth:code:" + email }
func codeAttemptsKey(email string) string { return "auth:code:attempts:" + email }
@@ -130,7 +146,10 @@ func (s *Service) SendCode(ctx context.Context, rawEmail, ip string) (retryAfter
go func(to string) {
sendCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_ = s.mailer.SendAlreadyRegistered(sendCtx, to)
if err := s.mailer.SendAlreadyRegistered(sendCtx, to); err != nil {
slog.Error("auth: send already-registered notice failed",
"email", maskEmail(to), "err", err)
}
}(email)
return 0, nil
} else if !errors.Is(err, ErrNotFound) {
@@ -154,7 +173,10 @@ func (s *Service) SendCode(ctx context.Context, rawEmail, ip string) (retryAfter
go func(to, c string) {
sendCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_ = s.mailer.SendCode(sendCtx, to, c)
if err := s.mailer.SendCode(sendCtx, to, c); err != nil {
slog.Error("auth: send verification code failed",
"email", maskEmail(to), "err", err)
}
}(email, code)
return 0, nil