精简初始化通知设置并默认使用Smail系统通知身份发信
This commit is contained in:
1 parent
229d150a08
commit
a9937c3e6a
16 files changed
+186
-48
No files matched your search
@@ -97,6 +97,13 @@ func (completer *Completer) prepareNotification(ctx context.Context, current con
|
||||
return candidate, nil, completeError(CompleteErrorInput, "SMTP 通知主机、账号、密码或连接安全参数无效", nil)
|
||||
}
|
||||
credentials := make(map[string]map[string]string)
|
||||
if candidate.SMTPEnabled {
|
||||
name, email, err := candidate.SenderIdentity()
|
||||
if err != nil {
|
||||
return candidate, nil, completeError(CompleteErrorInput, "SMTP 发件账号无效,请使用 Smail 系统通知页提供的完整用户名", err)
|
||||
}
|
||||
candidate.SenderName, candidate.SenderEmail = name, email
|
||||
}
|
||||
if candidate.HTTPEnabled && candidate.HTTPAuthMode != "none" {
|
||||
values, err := notificationCredentials(candidate.HTTPAuthMode, input.HTTPCredentials)
|
||||
if err != nil {
|
||||
|
||||
@@ -15,7 +15,7 @@ func completionNotificationInput() *NotificationInput {
|
||||
return &NotificationInput{
|
||||
HTTPEnabled: true, Endpoint: "https://mail.example.test", HTTPAuthMode: "session",
|
||||
HTTPCredentials: map[string]string{"account": "mail-owner", "password": "private-http-password"},
|
||||
SMTPEnabled: true, SMTPHost: "smtp.example.test", SMTPUsername: "smtp-owner", SMTPPassword: "private-smtp-password",
|
||||
SMTPEnabled: true, SMTPHost: "smtp.example.test", SMTPUsername: "notify:smtp-owner@example.test", SMTPPassword: "private-smtp-password",
|
||||
IncludeManagementURL: true, IncludeCertificateSerial: true,
|
||||
Recipients: []string{"notify@example.test"}, TimeoutSecs: 15, RetryCount: 0, RetryIntervalsSecs: []int{},
|
||||
}
|
||||
@@ -59,6 +59,9 @@ func TestCompleterStoresNotificationCredentialsWithoutPlaintext(t *testing.T) {
|
||||
t.Fatalf("通知选项未完整保存:%+v", stored.Notification)
|
||||
}
|
||||
httpCredentials, err := fixture.store.Get(t.Context(), stored.Notification.HTTPCredentialRef)
|
||||
if stored.Notification.SenderEmail != "notification+system@example.test" || stored.Notification.SenderName != "系统通知" {
|
||||
t.Fatal("初始化没有保存 Smail 系统通知发件人")
|
||||
}
|
||||
if err != nil || httpCredentials["password"] != "private-http-password" {
|
||||
t.Fatalf("HTTP 通知凭据未进入敏感存储:%v", err)
|
||||
}
|
||||
|
||||
@@ -235,7 +235,7 @@ func newInitCommandWithDependencies(firewallManager firewall.Manager, issue init
|
||||
command.Flags().StringVar(&emailHTTPHeaders, "email-http-headers", "", "HTTP 自定义请求头 JSON")
|
||||
command.Flags().StringVar(&emailEventMode, "email-event-mode", "detailed", "通知事件模式:detailed、unified")
|
||||
command.Flags().StringVar(&emailSenderName, "email-sender-name", "Scert", "通知发件人名称")
|
||||
command.Flags().StringVar(&emailSenderEmail, "email-sender-email", "", "通知发件人地址,留空使用管理员邮箱")
|
||||
command.Flags().StringVar(&emailSenderEmail, "email-sender-email", "", "兼容通知发件人地址;Smail 系统通知账号自动确定,其他 SMTP 留空使用完整邮箱账号")
|
||||
command.Flags().BoolVar(&emailIncludeDeploymentDetails, "email-include-deployment-details", true, "是否发送服务器部署明细")
|
||||
command.Flags().BoolVar(&emailIncludeCertificateSerial, "email-include-certificate-serial", true, "是否发送证书序列号")
|
||||
command.Flags().BoolVar(&emailIncludeManagementURL, "email-include-management-url", true, "是否发送管理后台链接")
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/mail"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SenderIdentity 根据系统通知账号确定发件人,不能将管理员邮箱当作 SMTP 发件人。
|
||||
func (c NotificationConfig) SenderIdentity() (string, string, error) {
|
||||
name := strings.TrimSpace(c.SenderName)
|
||||
email := strings.TrimSpace(c.SenderEmail)
|
||||
if !c.SMTPEnabled {
|
||||
return name, email, nil
|
||||
}
|
||||
username := strings.ToLower(strings.TrimSpace(c.SMTPUsername))
|
||||
if strings.HasPrefix(username, "notify:") {
|
||||
account := strings.TrimPrefix(username, "notify:")
|
||||
parsed, err := mail.ParseAddress(account)
|
||||
parts := strings.Split(account, "@")
|
||||
if err != nil || parsed.Address != account || parsed.Name != "" || len(parts) != 2 ||
|
||||
strings.ContainsAny(account, "\r\n<>()") {
|
||||
return "", "", errors.New("Smail 系统通知用户名必须使用 notify:账号@邮件域名 格式")
|
||||
}
|
||||
// Smail 保留该发件地址;不能使用登录账号、管理员邮箱或自定义名称替代。
|
||||
return "系统通知", "notification+system@" + parts[1], nil
|
||||
}
|
||||
if email == "" {
|
||||
parsed, err := mail.ParseAddress(username)
|
||||
if err != nil || parsed.Address != username || parsed.Name != "" {
|
||||
return "", "", errors.New("请填写 Smail 系统通知用户名;兼容 SMTP 账号必须是完整邮箱地址")
|
||||
}
|
||||
email = username
|
||||
}
|
||||
return name, email, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNotificationSenderIdentity(t *testing.T) {
|
||||
for _, item := range []struct {
|
||||
name, username, sender, wantName, wantEmail string
|
||||
}{
|
||||
{"system", "notify:scert@example.test", "", "系统通知", "notification+system@example.test"},
|
||||
{"stale_admin", "notify:scert@example.test", "admin@other.test", "系统通知", "notification+system@example.test"},
|
||||
{"normalized", " NOTIFY:SCERT@EXAMPLE.TEST ", "", "系统通知", "notification+system@example.test"},
|
||||
{"smtp_compatibility", "sender@example.test", "", "Scert", "sender@example.test"},
|
||||
{"explicit_legacy", "smtp-login", "sender@example.test", "Scert", "sender@example.test"},
|
||||
} {
|
||||
t.Run(item.name, func(t *testing.T) {
|
||||
cfg := NotificationConfig{SMTPEnabled: true, SMTPUsername: item.username, SenderName: "Scert", SenderEmail: item.sender}
|
||||
name, email, err := cfg.SenderIdentity()
|
||||
if err != nil || name != item.wantName || email != item.wantEmail {
|
||||
t.Fatalf("发件身份不匹配:name=%q email=%q err=%v", name, email, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationSenderRejectsInvalidSystemAccount(t *testing.T) {
|
||||
for _, username := range []string{"notify:", "notify:user", "notify:@example.test", "notify:a@b@example.test", "notify:User <a@example.test>", "notify:a@example.test\r\nBcc:other@example.test", "smtp-login", ""} {
|
||||
cfg := NotificationConfig{SMTPEnabled: true, SMTPUsername: username}
|
||||
if _, _, err := cfg.SenderIdentity(); err == nil {
|
||||
t.Fatal("无效账号不得回退到管理员邮箱")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationSenderPreservesHTTPIdentity(t *testing.T) {
|
||||
cfg := NotificationConfig{SMTPUsername: "notify:unused@example.test", SenderName: "兼容通知", SenderEmail: "sender@example.test"}
|
||||
name, email, err := cfg.SenderIdentity()
|
||||
if err != nil || name != cfg.SenderName || email != cfg.SenderEmail {
|
||||
t.Fatal("未启用 SMTP 时不得改写原有 HTTP 发件人")
|
||||
}
|
||||
}
|
||||
@@ -716,7 +716,7 @@ func TestSetupLateFailureDeletesNewNotificationCredentials(t *testing.T) {
|
||||
"email_smtp_enabled":true,
|
||||
"email_smtp_host":"smtp.example.test",
|
||||
"email_smtp_port":587,
|
||||
"email_smtp_username":"smtp-user",
|
||||
"email_smtp_username":"notify:smtp-user@example.test",
|
||||
"email_smtp_password":"smtp-secret",
|
||||
"email_smtp_mode":"starttls",`, 1)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"html"
|
||||
"net/mail"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SendSecurityCode 仅向绑定邮箱发送验证码,不使用证书通知的收件人列表。
|
||||
@@ -24,7 +23,10 @@ func (s *Service) SendSecurityCode(ctx context.Context, recipient, code string)
|
||||
return errors.New("验证码格式无效")
|
||||
}
|
||||
}
|
||||
from := strings.TrimSpace(s.config.SenderEmail)
|
||||
fromName, from, err := s.config.SenderIdentity()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, value := range []string{from, recipient} {
|
||||
parsed, err := mail.ParseAddress(value)
|
||||
if err != nil || parsed.Address != value {
|
||||
@@ -34,7 +36,7 @@ func (s *Service) SendSecurityCode(ctx context.Context, recipient, code string)
|
||||
text := "有人正在部署服务器上重置 Scert 超级管理员密码。\n验证码:" + code +
|
||||
"\n验证码仅在当前本机重置会话中有效,有效期不超过两分钟。\n如果不是您本人操作,请勿提供此验证码,并检查服务器访问权限。"
|
||||
payload := mailPayload{
|
||||
From: address{Name: s.config.SenderName, Email: from},
|
||||
From: address{Name: fromName, Email: from},
|
||||
To: []address{{Email: recipient}},
|
||||
Subject: "[Scert] 超级管理员密码重置验证",
|
||||
Text: text, HTML: "<pre>" + html.EscapeString(text) + "</pre>",
|
||||
|
||||
@@ -371,7 +371,10 @@ func (s *Service) loadCredentials(ctx context.Context) (map[string]string, error
|
||||
}
|
||||
|
||||
func (s *Service) buildPayload(event Event) (mailPayload, error) {
|
||||
fromEmail := strings.TrimSpace(s.config.SenderEmail)
|
||||
fromName, fromEmail, err := s.config.SenderIdentity()
|
||||
if err != nil {
|
||||
return mailPayload{}, err
|
||||
}
|
||||
if fromEmail == "" {
|
||||
return mailPayload{}, errors.New("通知发件人地址不能为空")
|
||||
}
|
||||
@@ -410,7 +413,7 @@ func (s *Service) buildPayload(event Event) (mailPayload, error) {
|
||||
}
|
||||
text := buildText(event, title, status, domainName)
|
||||
return mailPayload{
|
||||
From: address{Name: s.config.SenderName, Email: fromEmail},
|
||||
From: address{Name: fromName, Email: fromEmail},
|
||||
To: recipients,
|
||||
Subject: fmt.Sprintf("[Scert] %s:%s(%s)", title, domainName, status),
|
||||
Text: text,
|
||||
|
||||
@@ -28,6 +28,7 @@ type smtpTestServer struct {
|
||||
rejectAuth bool
|
||||
mu sync.Mutex
|
||||
messages [][]byte
|
||||
mailFrom string
|
||||
connections int
|
||||
}
|
||||
|
||||
@@ -121,6 +122,7 @@ func (s *smtpTestServer) handle(connection net.Conn, startTLS bool) {
|
||||
}
|
||||
case strings.HasPrefix(upper, "MAIL FROM:"):
|
||||
s.mu.Lock()
|
||||
s.mailFrom = command
|
||||
fail := s.failMailOnce
|
||||
s.failMailOnce = false
|
||||
s.mu.Unlock()
|
||||
@@ -275,6 +277,42 @@ func TestSMTPSendsUTF8WithAllowedPlainAuthentication(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSmailSystemSenderUsesSameEnvelopeAndHeader(t *testing.T) {
|
||||
for _, security := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "notification", true: "security_code"}[security], func(t *testing.T) {
|
||||
server := newSMTPTestServer(t, false, true)
|
||||
host, port := server.address()
|
||||
cfg := smtpTestConfig(host, port, "starttls")
|
||||
cfg.SMTPUsername = "notify:scert@example.test"
|
||||
cfg.SenderEmail = "admin@other.test"
|
||||
service := New(cfg, credentialReaderStub{values: map[string]string{"password": "test-only-notification-credential"}})
|
||||
service.smtpTLSConfig = server.clientTLSConfig
|
||||
var err error
|
||||
if security {
|
||||
err = service.SendSecurityCode(t.Context(), "bound@example.test", "01234567")
|
||||
} else {
|
||||
err = service.Send(t.Context(), Event{Type: "certificate_issue", Status: "success", Domain: "example.test"})
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server.mu.Lock()
|
||||
envelope := server.mailFrom
|
||||
server.mu.Unlock()
|
||||
if !strings.HasPrefix(envelope, "MAIL FROM:<notification+system@example.test>") {
|
||||
t.Fatal("SMTP 信封没有使用系统通知地址")
|
||||
}
|
||||
message := string(server.message())
|
||||
if !strings.Contains(message, formatSMTPAddress(address{Name: "系统通知", Email: "notification+system@example.test"})) || strings.Contains(message, "admin@other.test") {
|
||||
t.Fatal("邮件头没有使用固定系统通知身份,或泄漏旧管理员发件地址")
|
||||
}
|
||||
if security && strings.Contains(message, "receiver@example.com") {
|
||||
t.Fatal("验证码不得发送给普通通知收件人")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPStartTLS(t *testing.T) {
|
||||
server := newSMTPTestServer(t, false, true)
|
||||
host, port := server.address()
|
||||
|
||||
@@ -170,8 +170,17 @@ func Apply(cfg *config.Config, input Input) error {
|
||||
}
|
||||
if strings.TrimSpace(input.EmailSenderEmail) != "" {
|
||||
cfg.Notification.SenderEmail = strings.ToLower(strings.TrimSpace(input.EmailSenderEmail))
|
||||
} else {
|
||||
} else if !cfg.Notification.SMTPEnabled {
|
||||
cfg.Notification.SenderEmail = adminEmail
|
||||
} else {
|
||||
cfg.Notification.SenderEmail = ""
|
||||
}
|
||||
if cfg.Notification.SMTPEnabled {
|
||||
name, email, err := cfg.Notification.SenderIdentity()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Notification.SenderName, cfg.Notification.SenderEmail = name, email
|
||||
}
|
||||
if input.EmailTimeoutSecs > 0 {
|
||||
cfg.Notification.TimeoutSecs = input.EmailTimeoutSecs
|
||||
|
||||
Reference in new issue
Block a user