feat: import Sea vHost single-server testing release

This commit is contained in:
canglan committed 2026-10-30 08:39:10 +08:00
commit 248badd33e
441 files changed
+63221

No files matched your search

+244
View File
@@ -0,0 +1,244 @@
package notify
import (
"bufio"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"mime"
"net"
"net/mail"
"net/smtp"
"strconv"
"strings"
"time"
"sea-vhost/internal/secrets"
"sea-vhost/internal/store"
)
type smtpConfig struct {
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Secret string `json:"secret"`
From string `json:"from"`
AdminRecipients string `json:"adminRecipients"`
StartTLS bool `json:"startTls"`
Enabled bool `json:"enabled"`
}
type Dispatcher struct {
store *store.Store
box *secrets.Box
}
func New(database *store.Store, secret string) *Dispatcher {
return &Dispatcher{store: database, box: secrets.New(secret)}
}
func (d *Dispatcher) Run(ctx context.Context, interval time.Duration) {
if interval <= 0 {
interval = time.Minute
}
d.dispatch(ctx)
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
d.dispatch(ctx)
}
}
}
func (d *Dispatcher) dispatch(ctx context.Context) {
cfg, err := d.config(ctx)
if err != nil || !cfg.Enabled {
return
}
items, err := d.store.PendingAdminNotifications(ctx, time.Now(), 25)
if err != nil {
return
}
for _, item := range items {
operation, cancel := context.WithTimeout(ctx, 30*time.Second)
err = send(operation, cfg, item)
cancel()
if err == nil {
_ = d.store.CompleteAdminNotification(context.WithoutCancel(ctx), item.ID)
continue
}
delay := time.Duration(1<<min(item.Attempts, 6)) * 5 * time.Minute
_ = d.store.FailAdminNotification(context.WithoutCancel(ctx), item.ID, err.Error(), time.Now().Add(delay))
}
}
func (d *Dispatcher) config(ctx context.Context) (smtpConfig, error) {
raw := d.store.Setting(ctx, "smtp_config", "{}")
var cfg smtpConfig
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
return cfg, err
}
if cfg.Secret != "" {
ciphertext, err := base64.RawStdEncoding.DecodeString(cfg.Secret)
if err != nil {
return cfg, err
}
cfg.Secret, err = d.box.Open("system/smtp_config", ciphertext)
if err != nil {
return cfg, err
}
}
return cfg, validateConfig(cfg)
}
func validateConfig(cfg smtpConfig) error {
if !cfg.Enabled {
return nil
}
if net.ParseIP(cfg.Host) == nil && !validDNSName(cfg.Host) {
return errors.New("invalid SMTP host")
}
if cfg.Port < 1 || cfg.Port > 65535 {
return errors.New("invalid SMTP port")
}
from, err := mail.ParseAddress(cfg.From)
if err != nil || from.Address != cfg.From {
return errors.New("invalid SMTP sender")
}
if len(recipients(cfg.AdminRecipients)) == 0 {
return errors.New("SMTP recipients are empty")
}
if cfg.Username != "" && cfg.Secret == "" {
return errors.New("SMTP password is empty")
}
return nil
}
func send(ctx context.Context, cfg smtpConfig, item store.AdminNotification) error {
address := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
dialer := &net.Dialer{Timeout: 10 * time.Second}
var connection net.Conn
var err error
implicitTLS := cfg.Port == 465
if implicitTLS {
connection, err = tls.DialWithDialer(dialer, "tcp", address, &tls.Config{MinVersion: tls.VersionTLS12, ServerName: cfg.Host})
} else {
connection, err = dialer.DialContext(ctx, "tcp", address)
}
if err != nil {
return fmt.Errorf("connect SMTP: %w", err)
}
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(25 * time.Second))
client, err := smtp.NewClient(connection, cfg.Host)
if err != nil {
return err
}
defer client.Close()
secure := implicitTLS
if !implicitTLS && cfg.StartTLS {
if ok, _ := client.Extension("STARTTLS"); !ok {
return errors.New("SMTP server does not support STARTTLS")
}
if err = client.StartTLS(&tls.Config{MinVersion: tls.VersionTLS12, ServerName: cfg.Host}); err != nil {
return err
}
secure = true
}
if cfg.Username != "" {
if !secure {
return errors.New("SMTP authentication requires TLS")
}
if err = client.Auth(smtp.PlainAuth("", cfg.Username, cfg.Secret, cfg.Host)); err != nil {
return err
}
}
if err = client.Mail(cfg.From); err != nil {
return err
}
to := recipients(cfg.AdminRecipients)
for _, recipient := range to {
if err = client.Rcpt(recipient); err != nil {
return err
}
}
writer, err := client.Data()
if err != nil {
return err
}
buffer := bufio.NewWriter(writer)
subject := "[Sea vHost][" + strings.ToUpper(item.Severity) + "] " + sanitizeHeader(item.Title)
headers := []string{
"From: " + cfg.From,
"To: " + strings.Join(to, ", "),
"Subject: " + mime.QEncoding.Encode("UTF-8", subject),
"Date: " + time.Now().Format(time.RFC1123Z),
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: base64",
"",
}
for _, header := range headers {
if _, err = buffer.WriteString(header + "\r\n"); err != nil {
return err
}
}
body := fmt.Sprintf("类型:%s\n级别:%s\n时间:%s\n\n%s\n", item.Category, item.Severity, time.Now().Format(time.RFC3339), item.Detail)
encoded := base64.StdEncoding.EncodeToString([]byte(body))
for len(encoded) > 76 {
_, _ = buffer.WriteString(encoded[:76] + "\r\n")
encoded = encoded[76:]
}
_, _ = buffer.WriteString(encoded + "\r\n")
if err = buffer.Flush(); err != nil {
return err
}
if err = writer.Close(); err != nil {
return err
}
return client.Quit()
}
func recipients(value string) []string {
fields := strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ';' || r == '\n' })
result := make([]string, 0, len(fields))
seen := map[string]bool{}
for _, field := range fields {
address := strings.TrimSpace(field)
parsed, err := mail.ParseAddress(address)
if err == nil && parsed.Address == address && !seen[strings.ToLower(address)] {
seen[strings.ToLower(address)] = true
result = append(result, address)
}
}
return result
}
func sanitizeHeader(value string) string {
return strings.ReplaceAll(strings.ReplaceAll(value, "\r", " "), "\n", " ")
}
func validDNSName(value string) bool {
value = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), "."))
if value == "" || len(value) > 253 {
return false
}
for _, label := range strings.Split(value, ".") {
if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
return false
}
for _, character := range label {
if !(character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '-') {
return false
}
}
}
return true
}
+137
View File
@@ -0,0 +1,137 @@
package notify
import (
"bufio"
"context"
"encoding/base64"
"fmt"
"mime"
"net"
"net/mail"
"strconv"
"strings"
"testing"
"time"
"sea-vhost/internal/store"
)
func TestSMTPDeliveryAndHeaderSafety(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
message := make(chan string, 1)
go func() {
connection, e := listener.Accept()
if e != nil {
return
}
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(10 * time.Second))
reader := bufio.NewReader(connection)
fmt.Fprint(connection, "220 localhost test SMTP\r\n")
for {
line, e := reader.ReadString('\n')
if e != nil {
return
}
switch {
case strings.HasPrefix(line, "EHLO"):
fmt.Fprint(connection, "250 localhost\r\n")
case strings.HasPrefix(line, "MAIL FROM:"), strings.HasPrefix(line, "RCPT TO:"):
fmt.Fprint(connection, "250 accepted\r\n")
case strings.HasPrefix(line, "DATA"):
fmt.Fprint(connection, "354 continue\r\n")
var data strings.Builder
for {
line, e = reader.ReadString('\n')
if e != nil {
return
}
if line == ".\r\n" {
break
}
data.WriteString(line)
}
message <- data.String()
fmt.Fprint(connection, "250 queued\r\n")
case strings.HasPrefix(line, "QUIT"):
fmt.Fprint(connection, "221 bye\r\n")
return
default:
fmt.Fprint(connection, "500 unexpected\r\n")
}
}
}()
host, port, _ := net.SplitHostPort(listener.Addr().String())
number, _ := strconv.Atoi(port)
err = send(context.Background(), smtpConfig{Host: host, Port: number, From: "sender@seavhost.test", AdminRecipients: "admin@seavhost.test"}, store.AdminNotification{Title: "主机超额\r\nBcc: attacker@example.test", Category: "quota", Severity: "critical", Detail: "仅本机测试字符串 SEA-SMTP-CANARY"})
if err != nil {
t.Fatal(err)
}
select {
case raw := <-message:
parsed, e := mail.ReadMessage(strings.NewReader(raw))
if e != nil {
t.Fatal(e)
}
if parsed.Header.Get("Bcc") != "" {
t.Fatal("header injection")
}
subject, e := new(mime.WordDecoder).DecodeHeader(parsed.Header.Get("Subject"))
if e != nil || !strings.Contains(subject, "主机超额") {
t.Fatalf("invalid Unicode subject: %v", e)
}
body := base64.NewDecoder(base64.StdEncoding, parsed.Body)
scanner := bufio.NewScanner(body)
var text strings.Builder
for scanner.Scan() {
text.WriteString(scanner.Text())
}
if !strings.Contains(text.String(), "SEA-SMTP-CANARY") {
t.Fatal("notification body lost")
}
case <-time.After(5 * time.Second):
t.Fatal("message not delivered")
}
}
func TestSMTPDoesNotSendCredentialsWithoutTLS(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
commands := make(chan string, 1)
go func() {
connection, e := listener.Accept()
if e != nil {
return
}
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(5 * time.Second))
fmt.Fprint(connection, "220 local\r\n")
reader := bufio.NewReader(connection)
var all strings.Builder
for {
line, e := reader.ReadString('\n')
if e != nil {
commands <- all.String()
return
}
all.WriteString(line)
fmt.Fprint(connection, "250 localhost\r\n")
}
}()
host, port, _ := net.SplitHostPort(listener.Addr().String())
number, _ := strconv.Atoi(port)
err = send(context.Background(), smtpConfig{Host: host, Port: number, Username: "test", Secret: "must-not-transmit"}, store.AdminNotification{})
if err == nil || !strings.Contains(err.Error(), "requires TLS") {
t.Fatalf("insecure authentication allowed: %v", err)
}
if command := <-commands; strings.Contains(command, "AUTH") || strings.Contains(command, "must-not-transmit") {
t.Fatal("plaintext credential sent")
}
}