Files
knowledge-governance/internal/qawemail/smtp_stub_test.go
T
姚章浩 5e850e96f5
build / build (push) Successful in 2m18s
fix(qa-weekly-mail): 修复发送记录读回并区分未知投递
1) 发送记录读回(确定性回归):Sends() 的 SELECT 只有 6 列,Scan 却收 7 个字段(多出
message_id)。只要历史里存在任意一条发送记录,整个列表就返回 ErrUnavailable —— 发送
成功后页面刷新、以及“完成读真实发送记录”都会失败。改为查询带 message_id,并检查
rows.Err(),不把截断的列表当成完整历史。

2) 未知投递不再当成可重试失败:DATA 已提交但没收到最终 250(连接中断/超时)时,邮件可能
已被服务器接受;旧实现记 failed 并允许下一分钟重发,会重复投递。现在由 SMTPMailer 在
writer.Close() 失败处抛出窄类型 unknownDeliveryError,deliver 保留 sending 并记录原因,
自动/手动路径都不再重发(手动返回 ERRDeliveryUnknown,HTTP 409 说明原因)。连接建立前
失败、STARTTLS/AUTH/MAIL/RCPT/DATA 命令被拒、正文写入失败仍是确定失败,可如实 failed 并
重试一次。

3) SMTP 交互加有限期限:整体 90 秒(随请求 ctx 收紧),并用 context.AfterFunc 在取消时打断
阻塞读写,避免服务器接受 DATA 后不响应时挂死 worker 与发送行。

验证:真实隔离 PG 先 RED 后 GREEN(非空 sent+failed 历史读回成功并带真实 message_id;
HTTP GET /weekly-mail/sends 非空历史 200);本机 TLS SMTP 桩 + 真实 SMTPMailer 覆盖成功、
RCPT 550、DATA 后丢最终 250、DATA 阶段卡死(ctx 800ms 内返回)四类;真实 deliver 在未知
结果时留 sending 且不重发,在明确拒绝时 failed 并可重试一次成功。make verify 17 项全绿。
2026-11-09 01:06:09 +08:00

225 lines
5.0 KiB
Go

package qawemail
import (
"bufio"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"math/big"
"net"
"strings"
"sync"
"testing"
"time"
)
// smtpStub is a real TCP/TLS SMTP server for tests: it exercises the production SMTPMailer
// instead of mocking the Mailer interface, so the DATA-phase classification is proven end to end.
type smtpStub struct {
ln net.Listener
cert tls.Certificate
mu sync.Mutex
mode string
datas int
rejected int
closed chan struct{}
once sync.Once
}
const (
smtpStubAccept = "accept"
smtpStubRejectRcpt = "reject_rcpt"
smtpStubLostAck = "lost_ack"
smtpStubStall = "stall"
)
func newSMTPStub(t *testing.T) *smtpStub {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
stub := &smtpStub{ln: listener, cert: stubCertificate(t), mode: smtpStubAccept, closed: make(chan struct{})}
go stub.serve()
t.Cleanup(stub.Close)
return stub
}
func (s *smtpStub) Close() {
s.once.Do(func() {
close(s.closed)
_ = s.ln.Close()
})
}
func (s *smtpStub) port() int { return s.ln.Addr().(*net.TCPAddr).Port }
func (s *smtpStub) setMode(mode string) {
s.mu.Lock()
s.mode = mode
s.mu.Unlock()
}
func (s *smtpStub) currentMode() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.mode
}
// deliveries counts completed DATA uploads, whether or not the final 250 was delivered.
func (s *smtpStub) deliveries() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.datas
}
func (s *smtpStub) rejections() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.rejected
}
func (s *smtpStub) serve() {
for {
conn, err := s.ln.Accept()
if err != nil {
return
}
go s.handle(conn)
}
}
func (s *smtpStub) handle(raw net.Conn) {
defer raw.Close()
conn := raw
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
reply := func(line string) error {
if _, err := writer.WriteString(line + "\r\n"); err != nil {
return err
}
return writer.Flush()
}
if reply("220 stub ESMTP") != nil {
return
}
secured := false
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
upper := strings.ToUpper(strings.TrimSpace(line))
switch {
case strings.HasPrefix(upper, "EHLO"), strings.HasPrefix(upper, "HELO"):
lines := []string{"250-stub"}
if !secured {
lines = append(lines, "250-STARTTLS")
}
lines = append(lines, "250 OK")
for _, item := range lines {
if reply(item) != nil {
return
}
}
case upper == "STARTTLS":
if reply("220 ready to start TLS") != nil {
return
}
securedConn := tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{s.cert}, MinVersion: tls.VersionTLS12})
if err := securedConn.Handshake(); err != nil {
return
}
conn = securedConn
reader = bufio.NewReader(conn)
writer = bufio.NewWriter(conn)
secured = true
case strings.HasPrefix(upper, "MAIL FROM"):
_ = reply("250 OK")
case strings.HasPrefix(upper, "RCPT TO"):
if s.currentMode() == smtpStubRejectRcpt {
s.mu.Lock()
s.rejected++
s.mu.Unlock()
_ = reply("550 5.1.1 mailbox unavailable")
continue
}
_ = reply("250 OK")
case upper == "DATA":
if reply("354 end data with <CR><LF>.<CR><LF>") != nil {
return
}
if err := readSMTPData(reader); err != nil {
return
}
s.mu.Lock()
s.datas++
s.mu.Unlock()
switch s.currentMode() {
case smtpStubLostAck:
// Drop the connection instead of the final 250: the client cannot know whether
// the server queued the message.
return
case smtpStubStall:
select {
case <-s.closed:
case <-time.After(30 * time.Second):
}
return
default:
if reply("250 2.0.0 Ok: queued as stub-1") != nil {
return
}
}
case upper == "QUIT":
_ = reply("221 Bye")
return
default:
_ = reply("250 OK")
}
}
}
func readSMTPData(reader *bufio.Reader) error {
for {
line, err := reader.ReadString('\n')
if err != nil {
return err
}
if strings.TrimRight(line, "\r\n") == "." {
return nil
}
}
}
// stubCertificate builds a throwaway self-signed cert for 127.0.0.1. Tests trust it explicitly;
// production never sees it.
func stubCertificate(t *testing.T) tls.Certificate {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "kg-smtp-stub"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
IsCA: true,
BasicConstraintsValid: true,
}
der, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
}