fix(submission): 调整 SMTP 提交与发件授权逻辑。
- 启用 SMTP submission 时改为强制使用可读证书文件,并禁止使用容器自带测试证书。 - 收紧发件人校验,拒绝未授权的 From 地址,并支持别名多目标授权。 - 优化发送队列重入与重复消息处理,避免重复记录冲突。 - 让提交证书按需热加载,并稳定 MIME 头序列化顺序。 - 更新部署示例与文档,明确 submission 的证书配置要求。
This commit is contained in:
@@ -462,6 +462,30 @@ func (a *App) migrateSendQueueMessageID(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := a.db.ExecContext(ctx, `DELETE FROM send_queue
|
||||
WHERE id IN (
|
||||
SELECT id FROM (
|
||||
SELECT id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY mailbox_id, source, message_id
|
||||
ORDER BY
|
||||
CASE status
|
||||
WHEN 'queued' THEN 0
|
||||
WHEN 'sending' THEN 1
|
||||
WHEN 'failed' THEN 2
|
||||
WHEN 'delivered' THEN 3
|
||||
ELSE 4
|
||||
END,
|
||||
created_at DESC,
|
||||
id DESC
|
||||
) AS row_num
|
||||
FROM send_queue
|
||||
WHERE message_id <> ''
|
||||
)
|
||||
WHERE row_num > 1
|
||||
)`); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = a.db.ExecContext(ctx, `CREATE UNIQUE INDEX IF NOT EXISTS idx_send_queue_mailbox_source_message_id ON send_queue(mailbox_id, source, message_id) WHERE message_id <> ''`)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -4,14 +4,21 @@ import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/textproto"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -60,6 +67,49 @@ func defaultAdminUserAndMailbox(t *testing.T, a *App) (*User, *Mailbox) {
|
||||
return user, mb
|
||||
}
|
||||
|
||||
func writeTestCertificateFiles(t *testing.T, hostname string) (string, string) {
|
||||
t.Helper()
|
||||
if strings.TrimSpace(hostname) == "" {
|
||||
hostname = "localhost"
|
||||
}
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
tmpl := x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{
|
||||
CommonName: hostname,
|
||||
},
|
||||
NotBefore: now.Add(-time.Hour),
|
||||
NotAfter: now.Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
DNSNames: []string{hostname, "localhost"},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
certPath := filepath.Join(t.TempDir(), "cert.pem")
|
||||
keyPath := filepath.Join(filepath.Dir(certPath), "key.pem")
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
||||
if err := os.WriteFile(certPath, certPEM, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, keyPEM, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return certPath, keyPath
|
||||
}
|
||||
|
||||
func startFakeSMTP(t *testing.T) (string, string, <-chan string) {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
@@ -829,6 +879,27 @@ func TestMailSendQueuesSMTPFailureForRetry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailSendRejectsUnauthorizedFrom(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
ts := httptest.NewServer(a.Router())
|
||||
defer ts.Close()
|
||||
admin := &testClient{t: t, server: ts}
|
||||
|
||||
var login map[string]any
|
||||
if code := admin.do("POST", "/api/auth/login", map[string]string{"email": "admin@lanqin.local", "password": "ChangeMe123!"}, &login); code != http.StatusOK {
|
||||
t.Fatalf("login code=%d body=%v", code, login)
|
||||
}
|
||||
var errBody map[string]any
|
||||
if code := admin.do("POST", "/api/mail/send", map[string]any{
|
||||
"from": "attacker@example.com",
|
||||
"to": []string{"person@example.com"},
|
||||
"subject": "bad from",
|
||||
"text": "hello",
|
||||
}, &errBody); code != http.StatusForbidden {
|
||||
t.Fatalf("unauthorized from code=%d body=%v", code, errBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailSendRollsBackSentCopyWhenQueueInsertFails(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
a.cfg.SMTPHost = "postfix"
|
||||
@@ -1023,6 +1094,25 @@ func TestSubmissionRejectsMismatchedSender(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerializeMessageUsesStableHeaderOrder(t *testing.T) {
|
||||
header := textproto.MIMEHeader{
|
||||
"Subject": {"stable"},
|
||||
"From": {"admin@lanqin.local"},
|
||||
"Message": {"custom"},
|
||||
"X-Zebra": {"z"},
|
||||
"X-Answer": {"a"},
|
||||
}
|
||||
first := string(serializeMessage(header, []byte("body")))
|
||||
for i := 0; i < 20; i++ {
|
||||
if got := string(serializeMessage(header, []byte("body"))); got != first {
|
||||
t.Fatalf("serializeMessage is not stable:\nfirst=%q\ngot=%q", first, got)
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(first, "From: admin@lanqin.local\r\n") {
|
||||
t.Fatalf("unexpected header order: %q", first)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmissionRelayFailureKeepsSentCopyAndRetries(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
a.cfg.SMTPHost = "127.0.0.1"
|
||||
@@ -1129,6 +1219,48 @@ func TestSubmissionRequeuesTerminalFailedDuplicateMessageID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmissionRequeuesDeliveredDuplicateMessageID(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
host, port, received := startCapturingSMTP(t, 2)
|
||||
a.cfg.SMTPHost = host
|
||||
a.cfg.SMTPPort = port
|
||||
user, mb, err := a.authenticateSubmission(context.Background(), "admin@lanqin.local", "ChangeMe123!")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := "From: admin@lanqin.local\r\nTo: person@example.com\r\nSubject: resend\r\nMessage-ID: <delivered-requeue@example.test>\r\n\r\nbody"
|
||||
if err := a.submitSMTPMessage(context.Background(), user, mb, mb.Address, []string{"person@example.com"}, strings.NewReader(raw)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.processDueSendQueue(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-received:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("first delivery not received")
|
||||
}
|
||||
if err := a.submitSMTPMessage(context.Background(), user, mb, mb.Address, []string{"person@example.com"}, strings.NewReader(raw)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.processDueSendQueue(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-received:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("requeued delivered message was not relayed")
|
||||
}
|
||||
var status string
|
||||
var attemptCount int
|
||||
if err := a.db.QueryRow(`SELECT status,attempt_count FROM send_queue WHERE mailbox_id=? AND message_id=?`, mb.ID, "<delivered-requeue@example.test>").Scan(&status, &attemptCount); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != sendQueueStatusDelivered || attemptCount != 1 {
|
||||
t.Fatalf("queue status=%q attempts=%d, want delivered attempts=1", status, attemptCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmissionAllowsAuthorizedAliasSendAs(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
ctx := context.Background()
|
||||
@@ -1156,6 +1288,22 @@ func TestSubmissionAllowsAuthorizedAliasSendAs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmissionAllowsMultiDestinationAliasSendAs(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
ctx := context.Background()
|
||||
if _, err := a.db.ExecContext(ctx, `INSERT INTO aliases(id,domain_id,source,destination,enabled,created_at,updated_at) VALUES(?,?,?,?,?,?,?)`, newID("als"), mustDefaultDomainID(t, a), "team-many@lanqin.local", "other@lanqin.local, admin@lanqin.local", 1, a.now().UTC().Format(time.RFC3339Nano), a.now().UTC().Format(time.RFC3339Nano)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user, mb, err := a.authenticateSubmission(ctx, "admin@lanqin.local", "ChangeMe123!")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := "From: Team <team-many@lanqin.local>\r\nTo: person@example.com\r\nSubject: alias send-as\r\nMessage-ID: <multi-alias-send-as@example.test>\r\n\r\nbody"
|
||||
if err := a.submitSMTPMessage(ctx, user, mb, "team-many@lanqin.local", []string{"person@example.com"}, strings.NewReader(raw)); err != nil {
|
||||
t.Fatalf("authorized multi-destination alias send-as should submit: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmissionAllowsExplicitSendAsGrant(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
ctx := context.Background()
|
||||
@@ -1195,11 +1343,101 @@ func TestSentMessageDedupeTableExists(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendQueueMessageIDMigrationDropsDuplicatesBeforeUniqueIndex(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
user, mb := defaultAdminUserAndMailbox(t, a)
|
||||
if _, err := a.db.Exec(`DROP INDEX IF EXISTS idx_send_queue_mailbox_source_message_id`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.db.Exec(`INSERT INTO send_queue(id,user_id,mailbox_id,sent_message_id,message_id,source,mail_from,header_from,recipients_json,mime_base64,status,next_attempt_at,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
"dup_old", user.ID, mb.ID, "sent1", "<dup@example.test>", sendSourceSubmission, "admin@lanqin.local", "admin@lanqin.local", "[]", "bWVzc2FnZQ==", sendQueueStatusDelivered, a.now().UTC().Format(time.RFC3339Nano), "2026-06-24T00:00:00Z", "2026-06-24T00:00:00Z"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.db.Exec(`INSERT INTO send_queue(id,user_id,mailbox_id,sent_message_id,message_id,source,mail_from,header_from,recipients_json,mime_base64,status,next_attempt_at,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
"dup_keep", user.ID, mb.ID, "sent2", "<dup@example.test>", sendSourceSubmission, "admin@lanqin.local", "admin@lanqin.local", "[]", "bWVzc2FnZQ==", sendQueueStatusQueued, a.now().UTC().Format(time.RFC3339Nano), "2026-06-24T00:01:00Z", "2026-06-24T00:01:00Z"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.migrateSendQueueMessageID(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int
|
||||
if err := a.db.QueryRow(`SELECT COUNT(1) FROM send_queue WHERE mailbox_id=? AND source=? AND message_id='<dup@example.test>'`, mb.ID, sendSourceSubmission).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("duplicate queue rows count=%d, want 1", count)
|
||||
}
|
||||
var keptID string
|
||||
if err := a.db.QueryRow(`SELECT id FROM send_queue WHERE mailbox_id=? AND source=? AND message_id='<dup@example.test>'`, mb.ID, sendSourceSubmission).Scan(&keptID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if keptID != "dup_keep" {
|
||||
t.Fatalf("kept queue id=%q, want dup_keep", keptID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmissionTLSConfigRequiresCertificateFiles(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
a.cfg.SubmissionAddr = ":587"
|
||||
a.cfg.SubmissionTLSAddr = ":465"
|
||||
if _, err := LoadServerTLSConfig(a.cfg); err == nil {
|
||||
t.Fatal("submission TLS config should require certificate files")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmissionTLSConfigReloadsCertificateFiles(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
certPath, keyPath := writeTestCertificateFiles(t, "first.example.test")
|
||||
a.cfg.TLSCertFile = certPath
|
||||
a.cfg.TLSKeyFile = keyPath
|
||||
tlsConfig, err := LoadServerTLSConfig(a.cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := tlsConfig.GetCertificate(&tls.ClientHelloInfo{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstLeaf, err := x509.ParseCertificate(first.Certificate[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCertPath, nextKeyPath := writeTestCertificateFiles(t, "second.example.test")
|
||||
nextCert, err := os.ReadFile(nextCertPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextKey, err := os.ReadFile(nextKeyPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(certPath, nextCert, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, nextKey, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := tlsConfig.GetCertificate(&tls.ClientHelloInfo{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secondLeaf, err := x509.ParseCertificate(second.Certificate[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if firstLeaf.Subject.CommonName != "first.example.test" || secondLeaf.Subject.CommonName != "second.example.test" {
|
||||
t.Fatalf("cert reload common names first=%q second=%q", firstLeaf.Subject.CommonName, secondLeaf.Subject.CommonName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmissionServersAcceptStartTLSAndImplicitTLS(t *testing.T) {
|
||||
a := newTestApp(t)
|
||||
host, port, received := startCapturingSMTP(t, 2)
|
||||
a.cfg.SMTPHost = host
|
||||
a.cfg.SMTPPort = port
|
||||
certPath, keyPath := writeTestCertificateFiles(t, "mail.example.test")
|
||||
a.cfg.TLSCertFile = certPath
|
||||
a.cfg.TLSKeyFile = keyPath
|
||||
tlsConfig, err := LoadServerTLSConfig(a.cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -416,6 +416,10 @@ func (a *App) handleMailSend(w http.ResponseWriter, r *http.Request) {
|
||||
respondError(w, http.StatusTooManyRequests, err.Error())
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errSenderNotAuthorized) {
|
||||
respondError(w, http.StatusForbidden, err.Error())
|
||||
return
|
||||
}
|
||||
respondError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -426,6 +430,7 @@ var errNoRecipients = errors.New("at least one recipient is required")
|
||||
var errInvalidMIME = errors.New("invalid mime message")
|
||||
var errAttachmentTooLarge = errors.New("attachment size exceeds permission limit")
|
||||
var errSMTPRateLimited = errors.New("smtp send rate limit exceeded")
|
||||
var errSenderNotAuthorized = errors.New("sender address is not authorized")
|
||||
|
||||
func (a *App) sendMailNow(ctx context.Context, user *User, mb *Mailbox, req mailComposeInput) (*MailMessage, error) {
|
||||
if err := validateAttachmentLimit(req.Attachments, userLimits(user)); err != nil {
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -25,7 +24,8 @@ const (
|
||||
sendSourceWebmail = "webmail"
|
||||
sendSourceSubmission = "submission"
|
||||
|
||||
sendQueueStaleAfter = 15 * time.Minute
|
||||
sendQueueStaleAfter = 15 * time.Minute
|
||||
sendQueueConcurrency = 4
|
||||
)
|
||||
|
||||
type sendQueueInput struct {
|
||||
@@ -81,9 +81,9 @@ func (a *App) enqueueSend(ctx context.Context, in sendQueueInput) (string, error
|
||||
return "", err
|
||||
}
|
||||
if existingID != id {
|
||||
if status == sendQueueStatusFailed && attemptCount >= maxAttempts {
|
||||
_, err := a.db.ExecContext(ctx, `UPDATE send_queue SET user_id=?,sent_message_id=?,mail_from=?,header_from=?,recipients_json=?,mime_base64=?,status=?,attempt_count=0,next_attempt_at=?,last_error='',updated_at=?,delivered_at=NULL WHERE id=? AND status=? AND attempt_count>=max_attempts`,
|
||||
in.UserID, in.SentMessageID, normalizeEmail(in.MailFrom), normalizeEmail(in.HeaderFrom), recipientsJSON, mimeBase64, sendQueueStatusQueued, now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), existingID, sendQueueStatusFailed)
|
||||
if status == sendQueueStatusDelivered || (status == sendQueueStatusFailed && attemptCount >= maxAttempts) {
|
||||
_, err := a.db.ExecContext(ctx, `UPDATE send_queue SET user_id=?,sent_message_id=?,mail_from=?,header_from=?,recipients_json=?,mime_base64=?,status=?,attempt_count=0,next_attempt_at=?,last_error='',updated_at=?,delivered_at=NULL WHERE id=? AND status=?`,
|
||||
in.UserID, in.SentMessageID, normalizeEmail(in.MailFrom), normalizeEmail(in.HeaderFrom), recipientsJSON, mimeBase64, sendQueueStatusQueued, now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), existingID, status)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -154,8 +154,28 @@ func (a *App) processDueSendQueue(ctx context.Context) error {
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
sem := make(chan struct{}, sendQueueConcurrency)
|
||||
done := make(chan struct{}, len(ids))
|
||||
for _, id := range ids {
|
||||
a.processSendQueueItem(ctx, id)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case sem <- struct{}{}:
|
||||
}
|
||||
go func(id string) {
|
||||
defer func() {
|
||||
<-sem
|
||||
done <- struct{}{}
|
||||
}()
|
||||
a.processSendQueueItem(ctx, id)
|
||||
}(id)
|
||||
}
|
||||
for range ids {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-done:
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -322,7 +342,7 @@ func (a *App) authorizedSender(ctx context.Context, mb *Mailbox, from string) (s
|
||||
err := a.db.QueryRowContext(ctx, `SELECT display_name,enabled FROM send_as_grants WHERE mailbox_id=? AND address=?`, mb.ID, from).Scan(&displayName, &enabled)
|
||||
if err == nil {
|
||||
if enabled == 0 {
|
||||
return "", "", fmt.Errorf("send-as address is disabled")
|
||||
return "", "", errSenderNotAuthorized
|
||||
}
|
||||
return from, strings.TrimSpace(displayName), nil
|
||||
}
|
||||
@@ -331,8 +351,12 @@ func (a *App) authorizedSender(ctx context.Context, mb *Mailbox, from string) (s
|
||||
}
|
||||
var aliasDestination string
|
||||
err = a.db.QueryRowContext(ctx, `SELECT destination FROM aliases WHERE source=? AND enabled=1`, from).Scan(&aliasDestination)
|
||||
if err == nil && normalizeEmail(aliasDestination) == normalizeEmail(mb.Address) {
|
||||
return from, mb.DisplayName, nil
|
||||
if err == nil {
|
||||
for _, destination := range strings.Split(aliasDestination, ",") {
|
||||
if normalizeEmail(destination) == normalizeEmail(mb.Address) {
|
||||
return from, mb.DisplayName, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", "", fmt.Errorf("send-as address is not authorized")
|
||||
return "", "", errSenderNotAuthorized
|
||||
}
|
||||
|
||||
@@ -3,20 +3,15 @@ package app
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"database/sql"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/big"
|
||||
netmail "net/mail"
|
||||
"net/textproto"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -25,7 +20,9 @@ import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const defaultSubmissionMaxRecipients = 200
|
||||
const (
|
||||
defaultSubmissionMaxRecipients = 200
|
||||
)
|
||||
|
||||
type SubmissionServers struct {
|
||||
Plain *smtpserver.Server
|
||||
@@ -76,59 +73,20 @@ func (a *App) newSubmissionServer(addr string, tlsConfig *tls.Config) *smtpserve
|
||||
}
|
||||
|
||||
func LoadServerTLSConfig(cfg Config) (*tls.Config, error) {
|
||||
cert, err := loadOrGenerateCertificate(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
certFile, keyFile := strings.TrimSpace(cfg.TLSCertFile), strings.TrimSpace(cfg.TLSKeyFile)
|
||||
if certFile == "" || keyFile == "" {
|
||||
return nil, errors.New("LANQIN_TLS_CERT_FILE and LANQIN_TLS_KEY_FILE are required when SMTP submission is enabled")
|
||||
}
|
||||
return &tls.Config{
|
||||
Certificates: []tls.Certificate{cert},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func loadOrGenerateCertificate(cfg Config) (tls.Certificate, error) {
|
||||
certFile, keyFile := strings.TrimSpace(cfg.TLSCertFile), strings.TrimSpace(cfg.TLSKeyFile)
|
||||
if certFile != "" || keyFile != "" {
|
||||
if certFile == "" || keyFile == "" {
|
||||
return tls.Certificate{}, errors.New("both TLS certificate and key files are required")
|
||||
}
|
||||
return tls.LoadX509KeyPair(certFile, keyFile)
|
||||
}
|
||||
return generateSelfSignedCertificate(cfg.PublicHostname)
|
||||
}
|
||||
|
||||
func generateSelfSignedCertificate(hostname string) (tls.Certificate, error) {
|
||||
if strings.TrimSpace(hostname) == "" {
|
||||
hostname = "localhost"
|
||||
}
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
tmpl := x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{
|
||||
CommonName: hostname,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cert, nil
|
||||
},
|
||||
NotBefore: now.Add(-time.Hour),
|
||||
NotAfter: now.Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
DNSNames: []string{hostname, "localhost"},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
||||
return tls.X509KeyPair(certPEM, keyPEM)
|
||||
}, nil
|
||||
}
|
||||
|
||||
type submissionLogWriter struct {
|
||||
@@ -434,7 +392,15 @@ func readMessageHeader(raw []byte) (textproto.MIMEHeader, []byte, error) {
|
||||
|
||||
func serializeMessage(header textproto.MIMEHeader, body []byte) []byte {
|
||||
var buf bytes.Buffer
|
||||
for key, values := range header {
|
||||
keys := make([]string, 0, len(header))
|
||||
for key := range header {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.SliceStable(keys, func(i, j int) bool {
|
||||
return textproto.CanonicalMIMEHeaderKey(keys[i]) < textproto.CanonicalMIMEHeaderKey(keys[j])
|
||||
})
|
||||
for _, key := range keys {
|
||||
values := header[key]
|
||||
canonical := textproto.CanonicalMIMEHeaderKey(key)
|
||||
for _, value := range values {
|
||||
fmt.Fprintf(&buf, "%s: %s\r\n", canonical, strings.ReplaceAll(strings.ReplaceAll(value, "\r", ""), "\n", " "))
|
||||
|
||||
Reference in New Issue
Block a user