修复邮件协议认证错误分类并补齐真实响应验收

This commit is contained in:
xuans committed 2026-09-17 13:05:39 +08:00
1 parent 0169676923
commit b04dce7bcf
8 files changed
+166 -14

No files matched your search

+6 -1
View File
@@ -17,6 +17,9 @@ const maxPOP3CommandLineBytes = 8 << 10
var errPOP3CommandLineTooLong = errors.New("POP3 command line exceeds the allowed size")
// ErrAuthenticationTemporary 仅用于映射固定的临时失败响应,不回显内部错误。
var ErrAuthenticationTemporary = errors.New("[SYS/TEMP] Authentication temporarily unavailable")
// Server Pop3服务实例
type Server struct {
Domain string // 域名
@@ -215,7 +218,9 @@ func (s *Server) handleClient(conn net.Conn) {
case "PASS":
password := getSafeArg(args, 0)
cmdError = s.Action.Pass(session, password)
if cmdError != nil {
if errors.Is(cmdError, ErrAuthenticationTemporary) {
fmt.Fprint(conn, "-ERR [SYS/TEMP] Authentication temporarily unavailable"+eol)
} else if cmdError != nil {
fmt.Fprint(conn, "-ERR Password incorrect!"+eol)
} else {
fmt.Fprint(conn, "+OK User signed in"+eol)
+52 -1
View File
@@ -18,7 +18,8 @@ import (
)
type securityTestAction struct {
quitErr error
quitErr error
passErrors []error
}
func (a *securityTestAction) User(session *Session, username string) error {
@@ -27,6 +28,13 @@ func (a *securityTestAction) User(session *Session, username string) error {
}
func (a *securityTestAction) Pass(session *Session, password string) error {
if len(a.passErrors) > 0 {
err := a.passErrors[0]
a.passErrors = a.passErrors[1:]
if err != nil {
return err
}
}
session.Status = TRANSACTION
return nil
}
@@ -100,6 +108,49 @@ func TestQuitReportsMailboxUpdateResult(t *testing.T) {
}
}
func TestPassReportsTemporaryFailureWithoutLeakingInternalErrors(t *testing.T) {
serverConn, clientConn := net.Pipe()
t.Cleanup(func() { _ = clientConn.Close() })
if err := clientConn.SetDeadline(time.Now().Add(3 * time.Second)); err != nil {
t.Fatal(err)
}
server := &Server{Domain: "test", Action: &securityTestAction{passErrors: []error{
ErrAuthenticationTemporary,
fmt.Errorf("private database detail: %w", ErrAuthenticationTemporary),
errors.New("[SYS/TEMP] untrusted detail\r\n+OK injected"),
errors.New("private credential detail"),
}}}
done := make(chan struct{})
go func() {
server.handleClient(serverConn)
close(done)
}()
reader := bufio.NewReader(clientConn)
readResponseLine(t, reader, "+OK")
writeCommand(t, clientConn, "USER user")
readResponseLine(t, reader, "+OK")
for _, want := range []string{
"-ERR [SYS/TEMP] Authentication temporarily unavailable\r\n",
"-ERR [SYS/TEMP] Authentication temporarily unavailable\r\n",
"-ERR Password incorrect!\r\n",
"-ERR Password incorrect!\r\n",
"+OK User signed in\r\n",
} {
writeCommand(t, clientConn, "PASS test-password")
line, err := reader.ReadString('\n')
if err != nil || line != want {
t.Fatalf("POP3 认证响应错误:%q,预期 %q,错误 %v", line, want, err)
}
}
writeCommand(t, clientConn, "QUIT")
readResponseLine(t, reader, "+OK Bye")
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("POP3 恢复认证后未正常退出")
}
}
func TestSTLSUpgradesConnectionBeforeAuthentication(t *testing.T) {
serverConn, clientConn := net.Pipe()
t.Cleanup(func() { _ = clientConn.Close() })
+1 -1
View File
@@ -107,7 +107,7 @@ func (a action) Pass(session *gopop.Session, pwd string) error {
user, err := auth.AuthenticateProtocol("pop3", remoteAddress, session.User, pwd)
if err != nil {
if errors2.Is(err, password.ErrBusy) {
return errors2.New("[SYS/TEMP] Authentication temporarily unavailable")
return gopop.ErrAuthenticationTemporary
}
log.WithContext(session.Ctx).WithFields(log.Fields{
"action": "POP3 客户端登录",
+2 -2
View File
@@ -1,7 +1,7 @@
package pop3_server
import (
"strings"
"errors"
"testing"
"git.pcux.cn/xuans/Smail/config"
@@ -21,7 +21,7 @@ func TestPOP3BusyReturnsTemporaryAuthenticationFailure(t *testing.T) {
release := passwordtest.Hold(t)
for index := 0; index < 12; index++ {
err := (action{}).Pass(session, code)
if err == nil || !strings.HasPrefix(err.Error(), "[SYS/TEMP]") || session.Status == gopop.TRANSACTION || ctx.UserID != 0 {
if !errors.Is(err, gopop.ErrAuthenticationTemporary) || session.Status == gopop.TRANSACTION || ctx.UserID != 0 {
t.Fatalf("POP3 繁忙响应或会话状态错误:%v", err)
}
}
+1 -1
View File
@@ -73,7 +73,7 @@ func (s *Session) AuthPlain(username, pwd string) error {
"result": "failure",
"object": s.RemoteAddress.String(),
}).Info("SMTP 客户端认证失败")
return errors.New("password error")
return &smtp.SMTPError{Code: 535, EnhancedCode: smtp.EnhancedCode{5, 7, 8}, Message: "Authentication credentials invalid"}
}
s.User = user.Account
@@ -1,9 +1,15 @@
package smtp_server
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"net"
"net/textproto"
"strings"
"testing"
"time"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/db"
@@ -31,3 +37,65 @@ func TestSMTPBusyReturnsTemporaryAuthenticationFailure(t *testing.T) {
t.Fatalf("SMTP 繁忙恢复后无法认证:%v", err)
}
}
func TestSMTPAuthenticationWireSeparatesBusyAndInvalidCredentials(t *testing.T) {
engine, _, code := newSMTPProtocolAuthFixture(t)
oldDB, oldConfig := db.Instance, config.Instance
db.Instance, config.Instance = engine, &config.Config{Domain: "example.com"}
t.Cleanup(func() { db.Instance, config.Instance = oldDB, oldConfig })
certificate := newTestCertificate(t)
server := smtp.NewServer(&Backend{})
server.Domain = "localhost"
server.TLSConfig = &tls.Config{Certificates: []tls.Certificate{certificate}, MinVersion: tls.VersionTLS12}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() { _ = server.Close() })
conn, err := net.DialTimeout("tcp", listener.Addr().String(), time.Second)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if err := conn.SetDeadline(time.Now().Add(20 * time.Second)); err != nil {
t.Fatal(err)
}
plain := textproto.NewConn(conn)
if _, _, err := plain.ReadResponse(220); err != nil {
t.Fatal(err)
}
command := func(client *textproto.Conn, line string, status int, prefix string) {
t.Helper()
if err := client.PrintfLine("%s", line); err != nil {
t.Fatal(err)
}
_, message, err := client.ReadResponse(status)
if err != nil || !strings.HasPrefix(message, prefix) {
t.Fatalf("SMTP 响应错误:%q,预期 %d %q,错误 %v", message, status, prefix, err)
}
}
command(plain, "EHLO test.example", 250, "")
command(plain, "STARTTLS", 220, "")
leaf, err := x509.ParseCertificate(certificate.Certificate[0])
if err != nil {
t.Fatal(err)
}
roots := x509.NewCertPool()
roots.AddCert(leaf)
tlsConn := tls.Client(conn, &tls.Config{RootCAs: roots, ServerName: "localhost", MinVersion: tls.VersionTLS12})
if err := tlsConn.Handshake(); err != nil {
t.Fatal(err)
}
secure := textproto.NewConn(tlsConn)
command(secure, "EHLO test.example", 250, "")
authLine := func(password string) string {
return "AUTH PLAIN " + base64.StdEncoding.EncodeToString([]byte("\x00alice@example.com\x00"+password))
}
command(secure, authLine("invalid-code"), 535, "5.7.8 Authentication credentials invalid")
release := passwordtest.Hold(t)
command(secure, authLine(code), 454, "4.7.0 Temporary authentication failure")
release()
command(secure, authLine(code), 235, "2.0.0")
command(secure, "QUIT", 221, "")
}