统一邮件协议加密方式与端口联动

This commit is contained in:
xuans committed 2026-09-07 22:39:34 +08:00
1 parent 0975e26762
commit b7a4614e5b
13 files changed
+369 -118

No files matched your search

+63 -5
View File
@@ -1,10 +1,17 @@
package config
// 邮件监听与发信中继相互独立。零值表示沿用兼容默认值,不表示关闭服务。
const (
MailSecurityBoth = "both"
MailSecuritySTARTTLS = "starttls"
MailSecurityImplicitTLS = "implicit_tls"
)
// 邮件监听与发信中继相互独立。未设置加密模式的旧配置继续同时开放两套监听。
type SMTPListenerConfig struct {
Port int `json:"port"`
STARTTLSPort int `json:"starttlsPort"`
TLSPort int `json:"tlsPort"`
Port int `json:"port"`
STARTTLSPort int `json:"starttlsPort"`
TLSPort int `json:"tlsPort"`
Security string `json:"security,omitempty"`
}
type IMAPListenerConfig struct {
@@ -16,6 +23,32 @@ type POP3ListenerConfig struct {
TLSPort int `json:"tlsPort"`
}
func ResolveMailSecurity(listener SMTPListenerConfig) string {
switch NormalizeMailSecurity(listener.Security) {
case MailSecuritySTARTTLS:
return MailSecuritySTARTTLS
case MailSecurityImplicitTLS:
return MailSecurityImplicitTLS
case "", MailSecurityBoth:
return MailSecurityBoth
default:
return listener.Security
}
}
// NormalizeMailSecurity 保留空值及未知值,只将旧版 TLS 名称规范为当前名称。
func NormalizeMailSecurity(value string) string {
if value == "tls" {
return MailSecurityImplicitTLS
}
return value
}
// PublicMailSecurity 保留旧配置的空值,只规范公开视图中的旧版名称。
func PublicMailSecurity(listener SMTPListenerConfig) string {
return NormalizeMailSecurity(listener.Security)
}
// ResolveMailPorts 是公开配置视图、冲突校验及真实监听的共同端口来源。
func ResolveMailPorts(smtp SMTPSectionConfig, email EmailSectionConfig) MailPorts {
portOr := func(port, fallback int) int {
@@ -24,7 +57,7 @@ func ResolveMailPorts(smtp SMTPSectionConfig, email EmailSectionConfig) MailPort
}
return fallback
}
return MailPorts{
ports := MailPorts{
SMTP: portOr(smtp.Listener.Port, portOr(email.Policy.SMTPPort, 25)),
SMTPSTARTTLS: portOr(smtp.Listener.STARTTLSPort, 587),
SMTPTLS: portOr(smtp.Listener.TLSPort, 465),
@@ -33,9 +66,34 @@ func ResolveMailPorts(smtp SMTPSectionConfig, email EmailSectionConfig) MailPort
POP3: portOr(email.POP3.Port, portOr(email.Policy.POP3Port, 110)),
POP3TLS: portOr(email.POP3.TLSPort, 995),
}
switch ResolveMailSecurity(smtp.Listener) {
case MailSecuritySTARTTLS:
ports.SMTPTLS = 0
ports.IMAP = portOr(email.IMAP.TLSPort, 143)
ports.POP3TLS = 0
case MailSecurityImplicitTLS:
ports.SMTPSTARTTLS = 0
ports.IMAP = portOr(email.IMAP.TLSPort, 993)
ports.POP3 = 0
}
return ports
}
func validateMailListeners(smtp SMTPSectionConfig, email EmailSectionConfig) error {
if smtp.Listener.Security == MailSecurityBoth {
return ErrInvalidRuntimeConfig
}
security := ResolveMailSecurity(smtp.Listener)
if security != MailSecurityBoth && security != MailSecuritySTARTTLS && security != MailSecurityImplicitTLS {
return ErrInvalidRuntimeConfig
}
relayConfigured := smtpRelayConfigured(smtp.Relay)
if relayConfigured && security != MailSecurityBoth {
relaySecurity := NormalizeMailSecurity(smtp.Relay.Security)
if relaySecurity != security {
return ErrInvalidSMTP
}
}
for _, port := range []int{
smtp.Listener.Port, smtp.Listener.STARTTLSPort, smtp.Listener.TLSPort,
email.IMAP.TLSPort, email.POP3.Port, email.POP3.TLSPort,
+64
View File
@@ -146,3 +146,67 @@ func TestOldPartitionPayloadsKeepExistingListenerDefaults(t *testing.T) {
t.Fatalf("legacy listeners changed: %+v", got)
}
}
func TestUnifiedMailSecurityResolvesOnlySelectedClientListeners(t *testing.T) {
for _, test := range []struct {
security string
want MailPorts
}{
{MailSecuritySTARTTLS, MailPorts{SMTP: 25, SMTPSTARTTLS: 587, IMAP: 143, POP3: 110}},
{MailSecurityImplicitTLS, MailPorts{SMTP: 25, SMTPTLS: 465, IMAP: 993, POP3TLS: 995}},
} {
smtp := SMTPSectionConfig{Listener: SMTPListenerConfig{Security: test.security}}
if got := ResolveMailPorts(smtp, EmailSectionConfig{}); got != test.want {
t.Fatalf("%s ports = %+v, want %+v", test.security, got, test.want)
}
}
}
func TestLegacyMailSecurityKeepsExistingListeners(t *testing.T) {
smtp := SMTPSectionConfig{Listener: SMTPListenerConfig{Port: 2525, STARTTLSPort: 2587, TLSPort: 2465}}
email := EmailSectionConfig{IMAP: IMAPListenerConfig{TLSPort: 2993}, POP3: POP3ListenerConfig{Port: 2110, TLSPort: 2995}}
want := MailPorts{SMTP: 2525, SMTPSTARTTLS: 2587, SMTPTLS: 2465, IMAP: 2993, POP3: 2110, POP3TLS: 2995}
if got := ResolveMailPorts(smtp, email); got != want {
t.Fatalf("legacy ports = %+v, want %+v", got, want)
}
if got := ResolveMailSecurity(smtp.Listener); got != MailSecurityBoth {
t.Fatalf("legacy security = %q, want %q", got, MailSecurityBoth)
}
if got := PublicMailSecurity(smtp.Listener); got != "" {
t.Fatalf("legacy public security = %q, want empty", got)
}
if got := PublicMailSecurity(SMTPListenerConfig{Security: "tls"}); got != MailSecurityImplicitTLS {
t.Fatalf("legacy TLS public security = %q, want %q", got, MailSecurityImplicitTLS)
}
if got := NormalizeMailSecurity("tls"); got != MailSecurityImplicitTLS {
t.Fatalf("legacy relay security = %q, want %q", got, MailSecurityImplicitTLS)
}
}
func TestMailListenerValidationAcceptsMatchingLegacyTLSNames(t *testing.T) {
runtime := validRuntimeConfig()
runtime.SMTP.Listener.Security = "tls"
runtime.SMTP.Relay.Security = "tls"
if err := ValidateRuntimeConfig(runtime, RuntimeValidationOptions{HasSuperAdmin: true}); err != nil {
t.Fatalf("matching legacy TLS validation = %v", err)
}
}
func TestMailListenerValidationRejectsUnknownSecurity(t *testing.T) {
runtime := validRuntimeConfig()
runtime.SMTP.Listener.Security = "unknown"
if err := ValidateRuntimeConfig(runtime, RuntimeValidationOptions{HasSuperAdmin: true}); !errors.Is(err, ErrInvalidRuntimeConfig) {
t.Fatalf("validation = %v, want invalid runtime configuration", err)
}
}
func TestMailListenerValidationAllowsLegacyEmptySecurityButRejectsExplicitBoth(t *testing.T) {
runtime := validRuntimeConfig()
if err := ValidateRuntimeConfig(runtime, RuntimeValidationOptions{HasSuperAdmin: true}); err != nil {
t.Fatalf("legacy empty security validation = %v", err)
}
runtime.SMTP.Listener.Security = MailSecurityBoth
if err := ValidateRuntimeConfig(runtime, RuntimeValidationOptions{HasSuperAdmin: true}); !errors.Is(err, ErrInvalidRuntimeConfig) {
t.Fatalf("explicit both validation = %v, want invalid runtime configuration", err)
}
}
+9
View File
@@ -289,6 +289,15 @@ func CurrentMailPorts() MailPorts {
// 旧版 SMTPPort 属于发信中继,不能用作本机监听端口。
return ResolveMailPorts(SMTPSectionConfig{}, EmailSectionConfig{})
}
func CurrentMailSecurity() string {
if manager := CurrentManager(); manager != nil {
if runtime := manager.Snapshot(); runtime.Generation != 0 {
return ResolveMailSecurity(runtime.SMTP.Listener)
}
}
return MailSecurityBoth
}
func cloneHTTPConfig(source HTTPConfig) HTTPConfig {
clone := source
clone.TrustedProxyCIDRs = append([]string(nil), source.TrustedProxyCIDRs...)
+7 -2
View File
@@ -149,8 +149,7 @@ func validateSMTP(smtp SMTPConfig) error {
return ErrInvalidSMTP
}
}
relayConfigured := smtp.RelayHost != "" || smtp.RelayPort != 0 || smtp.Username != "" ||
smtp.Password.Configured() || smtp.Security != "" || smtp.From != ""
relayConfigured := smtpRelayConfigured(smtp)
if !relayConfigured {
return nil
}
@@ -167,6 +166,12 @@ func validateSMTP(smtp SMTPConfig) error {
return nil
}
// smtpRelayConfigured 只把实际连接或发件身份字段视为启用中继。
// 推荐端口、统一加密方式和默认发件域名单独存在时,中继仍保持可选状态。
func smtpRelayConfigured(smtp SMTPConfig) bool {
return smtp.RelayHost != "" || smtp.Username != "" || smtp.Password.Configured() || smtp.From != ""
}
func validateSSL(ssl SSLConfig) error {
if !isControlledRelativePath(ssl.DefaultDirectory) {
return ErrInvalidSSL
@@ -183,6 +183,15 @@ func TestValidateSMTPKeepsLoginVerificationIndependentFromRelay(t *testing.T) {
},
valid: true,
},
{
name: "unified defaults without relay host",
smtp: SMTPConfig{
RelayPort: 587,
Security: "starttls",
FromDomain: "example.com",
},
valid: true,
},
{
name: "partially configured relay",
smtp: SMTPConfig{
+4 -4
View File
@@ -449,12 +449,12 @@ func publicConfigSection(runtime config.RuntimeConfig, section config.Section) (
ports := config.ResolveMailPorts(runtime.SMTP, runtime.Email)
return map[string]any{
"meta": runtime.SMTP.Meta,
"listener": config.SMTPListenerConfig{Port: ports.SMTP, STARTTLSPort: ports.SMTPSTARTTLS, TLSPort: ports.SMTPTLS},
"listener": config.SMTPListenerConfig{Port: ports.SMTP, STARTTLSPort: ports.SMTPSTARTTLS, TLSPort: ports.SMTPTLS, Security: config.PublicMailSecurity(runtime.SMTP.Listener)},
"relay": map[string]any{
"relayHost": runtime.SMTP.Relay.RelayHost,
"relayPort": runtime.SMTP.Relay.RelayPort,
"username": runtime.SMTP.Relay.Username,
"security": runtime.SMTP.Relay.Security,
"security": config.NormalizeMailSecurity(runtime.SMTP.Relay.Security),
"from": runtime.SMTP.Relay.From,
"fromDomain": runtime.SMTP.Relay.FromDomain,
"verificationEnabled": runtime.SMTP.Relay.VerificationEnabled,
@@ -467,12 +467,12 @@ func publicConfigSection(runtime config.RuntimeConfig, section config.Section) (
ports := config.ResolveMailPorts(runtime.SMTP, runtime.Email)
return map[string]any{
"meta": runtime.SMTP.Meta,
"listener": config.SMTPListenerConfig{Port: ports.SMTP, STARTTLSPort: ports.SMTPSTARTTLS, TLSPort: ports.SMTPTLS},
"listener": config.SMTPListenerConfig{Port: ports.SMTP, STARTTLSPort: ports.SMTPSTARTTLS, TLSPort: ports.SMTPTLS, Security: config.PublicMailSecurity(runtime.SMTP.Listener)},
"relay": map[string]any{
"relayHost": runtime.SMTP.Relay.RelayHost,
"relayPort": runtime.SMTP.Relay.RelayPort,
"username": runtime.SMTP.Relay.Username,
"security": runtime.SMTP.Relay.Security,
"security": config.NormalizeMailSecurity(runtime.SMTP.Relay.Security),
"from": runtime.SMTP.Relay.From,
"fromDomain": runtime.SMTP.Relay.FromDomain,
"verificationEnabled": runtime.SMTP.Relay.VerificationEnabled,
@@ -44,6 +44,9 @@ func TestPublicMailPortsMatchListenersWithoutChangingSnapshot(t *testing.T) {
if mail.Listener.Port != want.SMTP || mail.Listener.STARTTLSPort != want.SMTPSTARTTLS || mail.Listener.TLSPort != want.SMTPTLS || mail.IMAP.TLSPort != want.IMAP || mail.POP3.Port != want.POP3 || mail.POP3.TLSPort != want.POP3TLS {
t.Fatal("combined public mail ports differ from listener configuration")
}
if mail.Listener.Security != runtime.SMTP.Listener.Security {
t.Fatal("public mail view changed legacy security state")
}
smtpPublic, err := publicConfigSection(runtime, config.SectionSMTP)
if err != nil {
t.Fatal(err)
@@ -71,3 +74,36 @@ func TestPublicMailPortsMatchListenersWithoutChangingSnapshot(t *testing.T) {
}
}
}
func TestPublicMailSecurityNormalizesLegacyTLSNames(t *testing.T) {
runtime := config.RuntimeConfig{
SMTP: config.SMTPSectionConfig{
Listener: config.SMTPListenerConfig{Security: "tls"},
Relay: config.SMTPConfig{Security: "tls"},
},
}
for _, section := range []config.Section{config.SectionSMTP, config.SectionMail} {
public, err := publicConfigSection(runtime, section)
if err != nil {
t.Fatal(err)
}
data, err := json.Marshal(public)
if err != nil {
t.Fatal(err)
}
var value struct {
Listener config.SMTPListenerConfig `json:"listener"`
Relay config.SMTPConfig `json:"relay"`
}
if err := json.Unmarshal(data, &value); err != nil {
t.Fatal(err)
}
if value.Listener.Security != config.MailSecurityImplicitTLS {
t.Fatalf("%s listener security = %q, want %q", section, value.Listener.Security, config.MailSecurityImplicitTLS)
}
if value.Relay.Security != config.MailSecurityImplicitTLS {
t.Fatalf("%s relay security = %q, want %q", section, value.Relay.Security, config.MailSecurityImplicitTLS)
}
}
}
+22
View File
@@ -9,9 +9,16 @@ import (
log "github.com/sirupsen/logrus"
)
var instance *imapserver.Server
var instanceTLS *imapserver.Server
func Stop() {
if instance != nil {
if err := instance.Close(); err != nil {
log.WithError(err).Warn("close IMAP STARTTLS server failed")
}
instance = nil
}
if instanceTLS != nil {
if err := instanceTLS.Close(); err != nil {
log.WithError(err).Warn("close IMAP server failed")
@@ -20,6 +27,21 @@ func Stop() {
}
}
// Start 启动普通 IMAP 监听,认证前必须通过 STARTTLS 升级连接。
func Start() error {
server, err := newIMAPServer()
if err != nil {
return err
}
instance = server
imapPort := config.CurrentMailPorts().IMAP
log.Infof("IMAP With STARTTLS Server Start On Port :%d", imapPort)
if err := instance.ListenAndServe(fmt.Sprintf(":%d", imapPort)); err != nil {
return fmt.Errorf("serve IMAP STARTTLS: %w", err)
}
return nil
}
// StarTLS 启动隐式 TLS 监听,不提供明文认证入口。
func StarTLS() error {
server, err := newIMAPServer()
+19 -8
View File
@@ -194,10 +194,15 @@ func Init(serverVersion string) error {
}()
}
hooks.Init(serverVersion)
// smtp server start
mailSecurity := config.CurrentMailSecurity()
// SMTP 25 用于服务器间投递,始终保留并支持机会性 STARTTLS。
startService(serviceErrors, "SMTP", smtp_server.Start)
startService(serviceErrors, "SMTP TLS", smtp_server.StartWithTLS)
startService(serviceErrors, "SMTP STARTTLS", smtp_server.StartWithTLSNew)
if mailSecurity == config.MailSecurityBoth || mailSecurity == config.MailSecurityImplicitTLS {
startService(serviceErrors, "SMTP TLS", smtp_server.StartWithTLS)
}
if mailSecurity == config.MailSecurityBoth || mailSecurity == config.MailSecuritySTARTTLS {
startService(serviceErrors, "SMTP STARTTLS", smtp_server.StartWithTLSNew)
}
// http server start
startService(serviceErrors, "HTTPS", http_server.HttpsStart)
startService(serviceErrors, "HTTP", http_server.HttpStart)
@@ -211,11 +216,17 @@ func Init(serverVersion string) error {
// 更新 SSL 配置。
ssl.Update(false)
// pop3 server start
startService(serviceErrors, "POP3", pop3_server.Start)
startService(serviceErrors, "POP3 TLS", pop3_server.StartWithTls)
// imap server start
startService(serviceErrors, "IMAP TLS", imap_server.StarTLS)
if mailSecurity == config.MailSecurityBoth || mailSecurity == config.MailSecuritySTARTTLS {
startService(serviceErrors, "POP3 STLS", pop3_server.Start)
}
if mailSecurity == config.MailSecurityBoth || mailSecurity == config.MailSecurityImplicitTLS {
startService(serviceErrors, "POP3 TLS", pop3_server.StartWithTls)
}
if mailSecurity == config.MailSecuritySTARTTLS {
startService(serviceErrors, "IMAP STARTTLS", imap_server.Start)
} else {
startService(serviceErrors, "IMAP TLS", imap_server.StarTLS)
}
log.Info("邮箱服务已启动")
restart.SetCurrent(restart.NewSignalTrigger(signal.RestartChan))