package qawemail import ( "bufio" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "math/big" "net" "strings" "sync" "testing" "time" ) // smtpStub is a real TCP/TLS SMTP server for tests: it exercises the production SMTPMailer // instead of mocking the Mailer interface, so the DATA-phase classification is proven end to end. type smtpStub struct { ln net.Listener cert tls.Certificate mu sync.Mutex mode string datas int rejected int closed chan struct{} once sync.Once } const ( smtpStubAccept = "accept" smtpStubRejectRcpt = "reject_rcpt" smtpStubLostAck = "lost_ack" smtpStubStall = "stall" ) func newSMTPStub(t *testing.T) *smtpStub { t.Helper() listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } stub := &smtpStub{ln: listener, cert: stubCertificate(t), mode: smtpStubAccept, closed: make(chan struct{})} go stub.serve() t.Cleanup(stub.Close) return stub } func (s *smtpStub) Close() { s.once.Do(func() { close(s.closed) _ = s.ln.Close() }) } func (s *smtpStub) port() int { return s.ln.Addr().(*net.TCPAddr).Port } func (s *smtpStub) setMode(mode string) { s.mu.Lock() s.mode = mode s.mu.Unlock() } func (s *smtpStub) currentMode() string { s.mu.Lock() defer s.mu.Unlock() return s.mode } // deliveries counts completed DATA uploads, whether or not the final 250 was delivered. func (s *smtpStub) deliveries() int { s.mu.Lock() defer s.mu.Unlock() return s.datas } func (s *smtpStub) rejections() int { s.mu.Lock() defer s.mu.Unlock() return s.rejected } func (s *smtpStub) serve() { for { conn, err := s.ln.Accept() if err != nil { return } go s.handle(conn) } } func (s *smtpStub) handle(raw net.Conn) { defer raw.Close() conn := raw reader := bufio.NewReader(conn) writer := bufio.NewWriter(conn) reply := func(line string) error { if _, err := writer.WriteString(line + "\r\n"); err != nil { return err } return writer.Flush() } if reply("220 stub ESMTP") != nil { return } secured := false for { line, err := reader.ReadString('\n') if err != nil { return } upper := strings.ToUpper(strings.TrimSpace(line)) switch { case strings.HasPrefix(upper, "EHLO"), strings.HasPrefix(upper, "HELO"): lines := []string{"250-stub"} if !secured { lines = append(lines, "250-STARTTLS") } lines = append(lines, "250 OK") for _, item := range lines { if reply(item) != nil { return } } case upper == "STARTTLS": if reply("220 ready to start TLS") != nil { return } securedConn := tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{s.cert}, MinVersion: tls.VersionTLS12}) if err := securedConn.Handshake(); err != nil { return } conn = securedConn reader = bufio.NewReader(conn) writer = bufio.NewWriter(conn) secured = true case strings.HasPrefix(upper, "MAIL FROM"): _ = reply("250 OK") case strings.HasPrefix(upper, "RCPT TO"): if s.currentMode() == smtpStubRejectRcpt { s.mu.Lock() s.rejected++ s.mu.Unlock() _ = reply("550 5.1.1 mailbox unavailable") continue } _ = reply("250 OK") case upper == "DATA": if reply("354 end data with .") != nil { return } if err := readSMTPData(reader); err != nil { return } s.mu.Lock() s.datas++ s.mu.Unlock() switch s.currentMode() { case smtpStubLostAck: // Drop the connection instead of the final 250: the client cannot know whether // the server queued the message. return case smtpStubStall: select { case <-s.closed: case <-time.After(30 * time.Second): } return default: if reply("250 2.0.0 Ok: queued as stub-1") != nil { return } } case upper == "QUIT": _ = reply("221 Bye") return default: _ = reply("250 OK") } } } func readSMTPData(reader *bufio.Reader) error { for { line, err := reader.ReadString('\n') if err != nil { return err } if strings.TrimRight(line, "\r\n") == "." { return nil } } } // stubCertificate builds a throwaway self-signed cert for 127.0.0.1. Tests trust it explicitly; // production never sees it. func stubCertificate(t *testing.T) tls.Certificate { t.Helper() key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } template := x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "kg-smtp-stub"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, IsCA: true, BasicConstraintsValid: true, } der, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) if err != nil { t.Fatal(err) } return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} }