Files
tenant-registry/internal/mail/plain_test.go
T
sharang 69c15be333
ci / shared (push) Successful in 12s
ci / test (push) Successful in 9m8s
ci / image (push) Successful in 36s
feat(onprem): APP_ENV=onprem with directory users and installation mail (#146)
2026-11-20 16:31:11 +00:00

102 lines
2.7 KiB
Go

package mail
import (
"bufio"
"context"
"net"
"strconv"
"strings"
"testing"
)
// plainRelay is a minimal SMTP server without STARTTLS (an internal relay on
// port 25). It records the commands it saw.
func plainRelay(t *testing.T) (host string, port int, cmds chan string) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
cmds = make(chan string, 64)
go func() {
conn, err := ln.Accept()
if err != nil {
return
}
defer func() { _ = conn.Close() }()
r := bufio.NewReader(conn)
say := func(s string) { _, _ = conn.Write([]byte(s + "\r\n")) }
say("220 relay.onprem.test ESMTP")
data := false
for {
line, err := r.ReadString('\n')
if err != nil {
return
}
line = strings.TrimRight(line, "\r\n")
if data {
if line == "." {
data = false
say("250 queued")
}
continue
}
verb := strings.ToUpper(strings.SplitN(line, " ", 2)[0])
cmds <- verb
switch verb {
case "EHLO", "HELO":
say("250-relay.onprem.test")
say("250 8BITMIME")
case "MAIL", "RCPT":
say("250 ok")
case "DATA":
data = true
say("354 go ahead")
case "QUIT":
say("221 bye")
return
default:
say("502 not implemented")
}
}
}()
h, p, _ := net.SplitHostPort(ln.Addr().String())
port, _ = strconv.Atoi(p)
return h, port, cmds
}
func TestSMTP_plainRelay(t *testing.T) {
host, port, cmds := plainRelay(t)
s := &SMTP{Cfg: Config{Host: host, Port: port, From: "breakpilot@onprem.test", TLS: "none"}}
if err := s.Send(context.Background(), Message{To: "anna@onprem.test", Subject: "Test", Text: "hi", HTML: "<p>hi</p>"}); err != nil {
t.Fatal(err)
}
close(cmds)
var seen []string
for c := range cmds {
seen = append(seen, c)
}
if got := strings.Join(seen, " "); got != "EHLO MAIL RCPT DATA QUIT" {
t.Errorf("commands = %s", got)
}
}
func TestSMTP_starttlsStillRequiredByDefault(t *testing.T) {
host, port, _ := plainRelay(t)
s := &SMTP{Cfg: Config{Host: host, Port: port, From: "breakpilot@onprem.test"}}
err := s.Send(context.Background(), Message{To: "anna@onprem.test", Subject: "Test", Text: "hi"})
if err == nil || !strings.Contains(err.Error(), "STARTTLS") {
t.Errorf("err = %v, want the STARTTLS refusal", err)
}
}
func TestSMTP_noAuthInPlainText(t *testing.T) {
host, port, _ := plainRelay(t)
s := &SMTP{Cfg: Config{Host: host, Port: port, From: "breakpilot@onprem.test", TLS: "none", User: "u", Password: "p"}}
err := s.Send(context.Background(), Message{To: "anna@onprem.test", Subject: "Test", Text: "hi"})
if err == nil || !strings.Contains(err.Error(), "unencrypted") {
t.Errorf("err = %v, want the plain-text AUTH refusal", err)
}
}