package email import ( "context" "fmt" "log/slog" "net" "net/smtp" "os" "strings" "testing" "time" "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/domain/messaging" ) type fakeChatContract struct { messaging.ChatContract routeFunc func(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) } func (f *fakeChatContract) Route(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) { if f.routeFunc != nil { return f.routeFunc(ctx, in) } return messaging.ChatReply{Text: "ok"}, nil } func TestName(t *testing.T) { g := New(":2525", "", slog.Default()) if g.Name() != "email" { t.Errorf("Name() = %q", g.Name()) } } func TestExtractAddr(t *testing.T) { tests := []struct { input string want string }{ {"MAIL FROM:", "user@example.com"}, {"RCPT TO:", "test@foo.bar"}, {"MAIL FROM: SIZE=1234", "user@example.com"}, {"garbage", "garbage"}, } for _, tt := range tests { if got := extractAddr(tt.input); got != tt.want { t.Errorf("extractAddr(%q) = %q, want %q", tt.input, got, tt.want) } } } func TestExtractBodyPlain(t *testing.T) { raw := "From: test@example.com\r\nSubject: Hello\r\n\r\nThis is the body text.\r\nMore text." if got := extractBody(raw); !strings.Contains(got, "This is the body") { t.Errorf("extractBody = %q", got) } } // TestExtractBodyMultiParagraph pins that a non-multipart plain-text body // keeps every paragraph. extractBody used to re-split the body on the // first "\r\n\r\n" it found -- intended to strip a stray content-header // block some MTAs emit -- but that heuristic can't tell a header block // from an ordinary blank line between paragraphs, so it silently dropped // the first paragraph of any multi-paragraph email. func TestExtractBodyMultiParagraph(t *testing.T) { raw := "From: test@example.com\r\nSubject: Hello\r\n\r\nFirst paragraph.\r\n\r\nSecond paragraph." got := extractBody(raw) if !strings.Contains(got, "First paragraph.") { t.Errorf("extractBody = %q, want it to contain %q", got, "First paragraph.") } if !strings.Contains(got, "Second paragraph.") { t.Errorf("extractBody = %q, want it to contain %q", got, "Second paragraph.") } } func TestExtractBodyMultipart(t *testing.T) { raw := "From: test@example.com\r\nContent-Type: multipart/alternative; boundary=abc123\r\n\r\n--abc123\r\nContent-Type: text/plain\r\n\r\nplain text here\r\n--abc123\r\nContent-Type: text/html\r\n\r\n\r\n--abc123--" if got := extractBody(raw); got != "plain text here" { t.Errorf("extractBody = %q, want 'plain text here'", got) } } func TestExtractBoundary(t *testing.T) { if got := extractBoundary(`boundary="abc123"`); got != "abc123" { t.Errorf("got %q", got) } if got := extractBoundary(`boundary=xyz`); got != "xyz" { t.Errorf("got %q", got) } } func TestSMTPReceiveAndRoute(t *testing.T) { log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})) g := New(":0", "", log) chat := &fakeChatContract{ routeFunc: func(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) { if in.Message.Sender != "sender@test.com" { return messaging.ChatReply{}, fmt.Errorf("unexpected sender: %s", in.Message.Sender) } if in.Message.SenderID != "sender@test.com" { return messaging.ChatReply{}, fmt.Errorf("unexpected SenderID: %s", in.Message.SenderID) } return messaging.ChatReply{Text: "got it"}, nil }, } ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() // Start the server to get the assigned port, then connect. var listenConfig net.ListenConfig ln, err := listenConfig.Listen(ctx, "tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } addr := ln.Addr().String() _ = ln.Close() g.ListenAddr = addr go func() { _ = g.Start(ctx, chat, channels.Lifecycle{}) }() time.Sleep(20 * time.Millisecond) defer func() { _ = g.Stop(context.Background()) }() // Connect via SMTP and send a message. dialer := net.Dialer{Timeout: 1 * time.Second} conn, err := dialer.DialContext(ctx, "tcp", addr) if err != nil { t.Fatal(err) } defer func() { _ = conn.Close() }() // Read greeting. buf := make([]byte, 1024) n, _ := conn.Read(buf) if !strings.HasPrefix(string(buf[:n]), "220") { t.Fatalf("unexpected greeting: %q", string(buf[:n])) } // Send a minimal SMTP transaction. send := func(s string) { _, _ = conn.Write([]byte(s + "\r\n")) time.Sleep(5 * time.Millisecond) } send("EHLO test") send("MAIL FROM:") send("RCPT TO:") send("DATA") send("Hello from email test.") send(".") send("QUIT") // Drain response. time.Sleep(50 * time.Millisecond) } func TestStopUnstarted(t *testing.T) { g := New(":2525", "", slog.Default()) if err := g.Stop(context.Background()); err != nil { t.Errorf("unexpected error: %v", err) } } func TestSendReplyNoRelay(t *testing.T) { g := New(":2525", "", slog.Default()) // Should not panic when relay is empty. if err := g.sendReply("to@x.com", "from@x.com", "test"); err == nil { t.Log("expected error with empty relay") } } func TestTruncateSubject(t *testing.T) { if got := truncateSubject("hello"); got != "hello" { t.Errorf("short: %q", got) } long := strings.Repeat("x", 100) if got := truncateSubject(long); len(got) > 60 { t.Errorf("long: %d chars", len(got)) } } // Compile-time guard. var ( _ channels.Channel = (*Gateway)(nil) _ = smtp.PlainAuth )