7 cryptorand "crypto/rand"
25 "github.com/mjl-/mox/dns"
26 "github.com/mjl-/mox/mlog"
27 "github.com/mjl-/mox/sasl"
28 "github.com/mjl-/mox/scram"
29 "github.com/mjl-/mox/smtp"
32var zerohost dns.Domain
33var localhost = dns.Domain{ASCII: "localhost"}
35func TestClient(t *testing.T) {
36 ctx := context.Background()
37 log := mlog.New("smtpclient", nil)
39 mlog.SetConfig(map[string]slog.Level{"": mlog.LevelTrace})
51 auths []string // Allowed mechanisms.
53 nodeliver bool // For server, whether client will attempt a delivery.
59 tlsHostname dns.Domain
63 recipients []string // If nil, mjl@mox.example is used.
64 resps []Response // Checked only if non-nil.
67 // Make fake cert, and make it trusted.
68 cert := fakeCert(t, false)
69 roots := x509.NewCertPool()
70 roots.AddCert(cert.Leaf)
71 tlsConfig := tls.Config{
72 Certificates: []tls.Certificate{cert},
75 cleanupResp := func(resps []Response) []Response {
76 for i, r := range resps {
77 resps[i] = Response{Code: r.Code, Secode: r.Secode}
82 test := func(msg string, opts options, auth func(l []string, cs *tls.ConnectionState) (sasl.Client, error), expClientErr, expDeliverErr, expServerErr error) {
85 if opts.tlsMode == "" {
86 opts.tlsMode = TLSOpportunistic
89 clientConn, serverConn := net.Pipe()
90 defer serverConn.Close()
92 result := make(chan error, 2)
97 if x != nil && x != "stop" {
101 fail := func(format string, args ...any) {
102 err := fmt.Errorf("server: %w", fmt.Errorf(format, args...))
103 log.Errorx("failure", err)
104 if err != nil && expServerErr != nil && (errors.Is(err, expServerErr) || errors.As(err, reflect.New(reflect.ValueOf(expServerErr).Type()).Interface())) {
111 br := bufio.NewReader(serverConn)
112 readline := func(prefix string) string {
113 s, err := br.ReadString('\n')
115 fail("expected command: %v", err)
117 if !strings.HasPrefix(strings.ToLower(s), strings.ToLower(prefix)) {
118 fail("expected command %q, got: %s", prefix, s)
121 return strings.TrimSuffix(s, "\r\n")
123 writeline := func(s string) {
124 fmt.Fprintf(serverConn, "%s\r\n", s)
129 ehlo := true // Initially we expect EHLO.
134 writeline("250 mox.example")
141 // Client will try again with HELO.
142 writeline("500 bad syntax")
148 writeline("250-mox.example")
150 writeline("250-PIPELINING")
152 if opts.maxSize > 0 {
153 writeline(fmt.Sprintf("250-SIZE %d", opts.maxSize))
156 writeline("250-ENHANCEDSTATUSCODES")
158 if opts.starttls && !haveTLS {
159 writeline("250-STARTTLS")
161 if opts.eightbitmime {
162 writeline("250-8BITMIME")
165 writeline("250-SMTPUTF8")
167 if opts.requiretls && haveTLS {
168 writeline("250-REQUIRETLS")
170 if opts.auths != nil {
171 writeline("250-AUTH " + strings.Join(opts.auths, " "))
173 writeline("250-LIMITS MAILMAX=10 RCPTMAX=100 RCPTDOMAINMAX=1")
174 writeline("250 UNKNOWN") // To be ignored.
177 writeline("220 mox.example ESMTP test")
184 tlsConn := tls.Server(serverConn, &tlsConfig)
185 nctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
187 err := tlsConn.HandshakeContext(nctx)
189 fail("tls handshake: %w", err)
192 br = bufio.NewReader(serverConn)
198 if opts.auths != nil {
199 more := readline("AUTH ")
200 t := strings.SplitN(more, " ", 2)
203 writeline("235 2.7.0 auth ok")
205 writeline("334 " + base64.StdEncoding.EncodeToString([]byte("<123.1234@host>")))
206 readline("") // Proof
207 writeline("235 2.7.0 auth ok")
208 case "SCRAM-SHA-256-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-1":
209 // Cannot fake/hardcode scram interactions.
210 var h func() hash.Hash
211 salt := scram.MakeRandom()
214 case "SCRAM-SHA-1-PLUS", "SCRAM-SHA-1":
216 iterations = 2 * 4096
217 case "SCRAM-SHA-256-PLUS", "SCRAM-SHA-256":
221 panic("missing case for scram")
223 var cs *tls.ConnectionState
224 if strings.HasSuffix(t[0], "-PLUS") {
226 writeline("501 scram plus without tls not possible")
232 xcs := serverConn.(*tls.Conn).ConnectionState()
235 saltedPassword := scram.SaltPassword(h, "test", salt, iterations)
237 clientFirst, err := base64.StdEncoding.DecodeString(t[1])
239 fail("bad base64: %w", err)
241 s, err := scram.NewServer(h, clientFirst, cs, cs != nil)
243 fail("scram new server: %w", err)
245 serverFirst, err := s.ServerFirst(iterations, salt)
247 fail("scram server first: %w", err)
249 writeline("334 " + base64.StdEncoding.EncodeToString([]byte(serverFirst)))
251 xclientFinal := readline("")
252 clientFinal, err := base64.StdEncoding.DecodeString(xclientFinal)
254 fail("bad base64: %w", err)
256 serverFinal, err := s.Finish([]byte(clientFinal), saltedPassword)
258 fail("scram finish: %w", err)
260 writeline("334 " + base64.StdEncoding.EncodeToString([]byte(serverFinal)))
262 writeline("235 2.7.0 auth ok")
264 writeline("501 unknown mechanism")
268 if expClientErr == nil && !opts.nodeliver {
269 readline("MAIL FROM:")
271 n := len(opts.recipients)
275 for i := 0; i < n; i++ {
278 if i < len(opts.resps) {
279 resp = fmt.Sprintf("%d maybe", opts.resps[i].Code)
284 writeline("354 continue")
285 reader := smtp.NewDataReader(br)
286 io.Copy(io.Discard, reader)
289 if expDeliverErr == nil {
293 readline("MAIL FROM:")
295 for i := 0; i < n; i++ {
298 if i < len(opts.resps) {
299 resp = fmt.Sprintf("%d maybe", opts.resps[i].Code)
304 writeline("354 continue")
305 reader = smtp.NewDataReader(br)
306 io.Copy(io.Discard, reader)
316 // todo: should abort tests more properly. on client failures, we may be left with hanging test.
320 if x != nil && x != "stop" {
324 fail := func(format string, args ...any) {
325 err := fmt.Errorf("client: %w", fmt.Errorf(format, args...))
326 log.Errorx("failure", err)
330 client, err := New(ctx, log.Logger, clientConn, opts.tlsMode, opts.tlsPKIX, localhost, opts.tlsHostname, Opts{Auth: auth, RootCAs: opts.roots})
331 if (err == nil) != (expClientErr == nil) || err != nil && !errors.As(err, reflect.New(reflect.ValueOf(expClientErr).Type()).Interface()) && !errors.Is(err, expClientErr) {
332 fail("new client: got err %v, expected %#v", err, expClientErr)
338 rcptTo := opts.recipients
339 if len(rcptTo) == 0 {
340 rcptTo = []string{"mjl@mox.example"}
342 resps, err := client.DeliverMultiple(ctx, "postmaster@mox.example", rcptTo, int64(len(msg)), strings.NewReader(msg), opts.need8bitmime, opts.needsmtputf8, opts.needsrequiretls)
343 if (err == nil) != (expDeliverErr == nil) || err != nil && !errors.Is(err, expDeliverErr) && !reflect.DeepEqual(err, expDeliverErr) {
344 fail("first deliver: got err %#v (%s), expected %#v (%s)", err, err, expDeliverErr, expDeliverErr)
345 } else if opts.resps != nil && !reflect.DeepEqual(cleanupResp(resps), opts.resps) {
346 fail("first deliver: got resps %v, expected %v", resps, opts.resps)
351 fail("reset: %v", err)
353 resps, err = client.DeliverMultiple(ctx, "postmaster@mox.example", rcptTo, int64(len(msg)), strings.NewReader(msg), opts.need8bitmime, opts.needsmtputf8, opts.needsrequiretls)
354 if (err == nil) != (expDeliverErr == nil) || err != nil && !errors.Is(err, expDeliverErr) && !reflect.DeepEqual(err, expDeliverErr) {
355 fail("second deliver: got err %#v (%s), expected %#v (%s)", err, err, expDeliverErr, expDeliverErr)
356 } else if opts.resps != nil && !reflect.DeepEqual(cleanupResp(resps), opts.resps) {
357 fail("second: got resps %v, expected %v", resps, opts.resps)
362 fail("close client: %v", err)
368 for i := 0; i < 2; i++ {
371 errs = append(errs, err)
379 msg := strings.ReplaceAll(`From: <postmaster@mox.example>
396 tlsMode: TLSRequiredStartTLS,
399 tlsHostname: dns.Domain{ASCII: "mox.example"},
402 needsrequiretls: true,
405 test(msg, options{}, nil, nil, nil, nil)
406 test(msg, allopts, nil, nil, nil, nil)
407 test(msg, options{ehlo: true, eightbitmime: true}, nil, nil, nil, nil)
408 test(msg, options{ehlo: true, eightbitmime: false, need8bitmime: true, nodeliver: true}, nil, nil, Err8bitmimeUnsupported, nil)
409 test(msg, options{ehlo: true, smtputf8: false, needsmtputf8: true, nodeliver: true}, nil, nil, ErrSMTPUTF8Unsupported, nil)
411 // Server TLS handshake is a net.OpError with "remote error" as text.
412 test(msg, options{ehlo: true, starttls: true, tlsMode: TLSRequiredStartTLS, tlsPKIX: true, tlsHostname: dns.Domain{ASCII: "mismatch.example"}, nodeliver: true}, nil, ErrTLS, nil, &net.OpError{})
414 test(msg, options{ehlo: true, maxSize: len(msg) - 1, nodeliver: true}, nil, nil, ErrSize, nil)
416 // Multiple recipients, not pipelined.
421 recipients: []string{"mjl@mox.example", "mjl2@mox.example", "mjl3@mox.example"},
423 {Code: smtp.C250Completed},
424 {Code: smtp.C250Completed},
425 {Code: smtp.C250Completed},
428 test(msg, multi1, nil, nil, nil, nil)
429 multi1.pipelining = true
430 test(msg, multi1, nil, nil, nil, nil)
432 // Multiple recipients with 452 and other error, not pipelined
436 recipients: []string{"xmjl@mox.example", "xmjl2@mox.example", "xmjl3@mox.example"},
438 {Code: smtp.C250Completed},
439 {Code: smtp.C554TransactionFailed}, // Will continue when not pipelined.
440 {Code: smtp.C452StorageFull}, // Will stop sending further recipients.
443 test(msg, multi2, nil, nil, nil, nil)
444 multi2.pipelining = true
445 test(msg, multi2, nil, nil, nil, nil)
446 multi2.pipelining = false
447 multi2.resps[2].Code = smtp.C552MailboxFull
448 test(msg, multi2, nil, nil, nil, nil)
449 multi2.pipelining = true
450 test(msg, multi2, nil, nil, nil, nil)
452 // Single recipient with error and pipelining is an error.
457 recipients: []string{"xmjl@mox.example"},
458 resps: []Response{{Code: smtp.C452StorageFull}},
460 test(msg, multi3, nil, nil, Error{Code: smtp.C452StorageFull, Command: "rcptto", Line: "452 maybe"}, nil)
462 authPlain := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
463 return sasl.NewClientPlain("test", "test"), nil
465 test(msg, options{ehlo: true, auths: []string{"PLAIN"}}, authPlain, nil, nil, nil)
467 authCRAMMD5 := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
468 return sasl.NewClientCRAMMD5("test", "test"), nil
470 test(msg, options{ehlo: true, auths: []string{"CRAM-MD5"}}, authCRAMMD5, nil, nil, nil)
472 // todo: add tests for failing authentication, also at various stages in SCRAM
474 authSCRAMSHA1 := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
475 return sasl.NewClientSCRAMSHA1("test", "test", false), nil
477 test(msg, options{ehlo: true, auths: []string{"SCRAM-SHA-1"}}, authSCRAMSHA1, nil, nil, nil)
479 authSCRAMSHA1PLUS := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
480 return sasl.NewClientSCRAMSHA1PLUS("test", "test", *cs), nil
482 test(msg, options{ehlo: true, starttls: true, auths: []string{"SCRAM-SHA-1-PLUS"}}, authSCRAMSHA1PLUS, nil, nil, nil)
484 authSCRAMSHA256 := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
485 return sasl.NewClientSCRAMSHA256("test", "test", false), nil
487 test(msg, options{ehlo: true, auths: []string{"SCRAM-SHA-256"}}, authSCRAMSHA256, nil, nil, nil)
489 authSCRAMSHA256PLUS := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
490 return sasl.NewClientSCRAMSHA256PLUS("test", "test", *cs), nil
492 test(msg, options{ehlo: true, starttls: true, auths: []string{"SCRAM-SHA-256-PLUS"}}, authSCRAMSHA256PLUS, nil, nil, nil)
494 test(msg, options{ehlo: true, requiretls: false, needsrequiretls: true, nodeliver: true}, nil, nil, ErrRequireTLSUnsupported, nil)
496 // Set an expired certificate. For non-strict TLS, we should still accept it.
498 cert = fakeCert(t, true)
499 roots = x509.NewCertPool()
500 roots.AddCert(cert.Leaf)
501 tlsConfig = tls.Config{
502 Certificates: []tls.Certificate{cert},
504 test(msg, options{ehlo: true, starttls: true, roots: roots}, nil, nil, nil, nil)
506 // Again with empty cert pool so it isn't trusted in any way.
507 roots = x509.NewCertPool()
508 tlsConfig = tls.Config{
509 Certificates: []tls.Certificate{cert},
511 test(msg, options{ehlo: true, starttls: true, roots: roots}, nil, nil, nil, nil)
514func TestErrors(t *testing.T) {
515 ctx := context.Background()
516 log := mlog.New("smtpclient", nil)
519 run(t, func(s xserver) {
520 s.writeline("bogus") // Invalid, should be "220 <hostname>".
521 }, func(conn net.Conn) {
522 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
524 if err == nil || !errors.Is(err, ErrProtocol) || !errors.As(err, &xerr) || xerr.Permanent {
525 panic(fmt.Errorf("got %#v, expected ErrProtocol without Permanent", err))
529 // Server just closes connection.
530 run(t, func(s xserver) {
532 }, func(conn net.Conn) {
533 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
535 if err == nil || !errors.Is(err, io.ErrUnexpectedEOF) || !errors.As(err, &xerr) || xerr.Permanent {
536 panic(fmt.Errorf("got %#v (%v), expected ErrUnexpectedEOF without Permanent", err, err))
540 // Server does not want to speak SMTP.
541 run(t, func(s xserver) {
542 s.writeline("521 not accepting connections")
543 }, func(conn net.Conn) {
544 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
546 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
547 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
551 // Server has invalid code in greeting.
552 run(t, func(s xserver) {
553 s.writeline("2200 mox.example") // Invalid, too many digits.
554 }, func(conn net.Conn) {
555 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
557 if err == nil || !errors.Is(err, ErrProtocol) || !errors.As(err, &xerr) || xerr.Permanent {
558 panic(fmt.Errorf("got %#v, expected ErrProtocol without Permanent", err))
562 // Server sends multiline response, but with different codes.
563 run(t, func(s xserver) {
564 s.writeline("220 mox.example")
566 s.writeline("250-mox.example")
567 s.writeline("500 different code") // Invalid.
568 }, func(conn net.Conn) {
569 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
571 if err == nil || !errors.Is(err, ErrProtocol) || !errors.As(err, &xerr) || xerr.Permanent {
572 panic(fmt.Errorf("got %#v, expected ErrProtocol without Permanent", err))
576 // Server permanently refuses MAIL FROM.
577 run(t, func(s xserver) {
578 s.writeline("220 mox.example")
580 s.writeline("250-mox.example")
581 s.writeline("250 ENHANCEDSTATUSCODES")
582 s.readline("MAIL FROM:")
583 s.writeline("550 5.7.0 not allowed")
584 }, func(conn net.Conn) {
585 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
590 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
592 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
593 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
597 // Server temporarily refuses MAIL FROM.
598 run(t, func(s xserver) {
599 s.writeline("220 mox.example")
601 s.writeline("250 mox.example")
602 s.readline("MAIL FROM:")
603 s.writeline("451 bad sender")
604 }, func(conn net.Conn) {
605 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
610 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
612 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || xerr.Permanent {
613 panic(fmt.Errorf("got %#v, expected ErrStatus with not-Permanent", err))
617 // Server temporarily refuses RCPT TO.
618 run(t, func(s xserver) {
619 s.writeline("220 mox.example")
621 s.writeline("250 mox.example")
622 s.readline("MAIL FROM:")
623 s.writeline("250 ok")
624 s.readline("RCPT TO:")
626 }, func(conn net.Conn) {
627 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
632 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
634 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || xerr.Permanent {
635 panic(fmt.Errorf("got %#v, expected ErrStatus with not-Permanent", err))
639 // Server permanently refuses DATA.
640 run(t, func(s xserver) {
641 s.writeline("220 mox.example")
643 s.writeline("250 mox.example")
644 s.readline("MAIL FROM:")
645 s.writeline("250 ok")
646 s.readline("RCPT TO:")
647 s.writeline("250 ok")
649 s.writeline("550 no!")
650 }, func(conn net.Conn) {
651 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
656 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
658 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
659 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
663 // TLS is required, so we attempt it regardless of whether it is advertised.
664 run(t, func(s xserver) {
665 s.writeline("220 mox.example")
667 s.writeline("250 mox.example")
668 s.readline("STARTTLS")
669 s.writeline("502 command not implemented")
670 }, func(conn net.Conn) {
671 _, err := New(ctx, log.Logger, conn, TLSRequiredStartTLS, true, localhost, dns.Domain{ASCII: "mox.example"}, Opts{})
673 if err == nil || !errors.Is(err, ErrTLS) || !errors.As(err, &xerr) || !xerr.Permanent {
674 panic(fmt.Errorf("got %#v, expected ErrTLS with Permanent", err))
678 // If TLS is available, but we don't want to use it, client should skip it.
679 run(t, func(s xserver) {
680 s.writeline("220 mox.example")
682 s.writeline("250-mox.example")
683 s.writeline("250 STARTTLS")
684 s.readline("MAIL FROM:")
685 s.writeline("451 enough")
686 }, func(conn net.Conn) {
687 c, err := New(ctx, log.Logger, conn, TLSSkip, false, localhost, dns.Domain{ASCII: "mox.example"}, Opts{})
692 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
694 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || xerr.Permanent {
695 panic(fmt.Errorf("got %#v, expected ErrStatus with non-Permanent", err))
699 // A transaction is aborted. If we try another one, we should send a RSET.
700 run(t, func(s xserver) {
701 s.writeline("220 mox.example")
703 s.writeline("250 mox.example")
704 s.readline("MAIL FROM:")
705 s.writeline("250 ok")
706 s.readline("RCPT TO:")
707 s.writeline("451 not now")
709 s.writeline("250 ok")
710 s.readline("MAIL FROM:")
711 s.writeline("250 ok")
712 s.readline("RCPT TO:")
713 s.writeline("250 ok")
715 s.writeline("550 not now")
716 }, func(conn net.Conn) {
717 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
723 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
725 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || xerr.Permanent {
726 panic(fmt.Errorf("got %#v, expected ErrStatus with non-Permanent", err))
730 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
731 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
732 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
736 // Remote closes connection after 550 response to MAIL FROM in pipelined
737 // connection. Should result in permanent error, not temporary read error.
738 // E.g. outlook.com that has your IP blocklisted.
739 run(t, func(s xserver) {
740 s.writeline("220 mox.example")
742 s.writeline("250-mox.example")
743 s.writeline("250 PIPELINING")
744 s.readline("MAIL FROM:")
745 s.writeline("550 ok")
746 }, func(conn net.Conn) {
747 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
753 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
755 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
756 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
760 // If we try multiple recipients and first is 452, it is an error and a
761 // non-pipelined deliver will be aborted.
762 run(t, func(s xserver) {
763 s.writeline("220 mox.example")
765 s.writeline("250 mox.example")
766 s.readline("MAIL FROM:")
767 s.writeline("250 ok")
768 s.readline("RCPT TO:")
769 s.writeline("451 not now")
770 s.readline("RCPT TO:")
771 s.writeline("451 not now")
773 s.writeline("250 ok")
774 }, func(conn net.Conn) {
775 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
781 _, err = c.DeliverMultiple(ctx, "postmaster@other.example", []string{"mjl@mox.example", "mjl@mox.example"}, int64(len(msg)), strings.NewReader(msg), false, false, false)
783 if err == nil || !errors.Is(err, errNoRecipients) || !errors.As(err, &xerr) || xerr.Permanent {
784 panic(fmt.Errorf("got %#v (%s) expected errNoRecipients with non-Permanent", err, err))
789 // If we try multiple recipients and first is 452, it is an error and a pipelined
790 // deliver will abort an allowed DATA.
791 run(t, func(s xserver) {
792 s.writeline("220 mox.example")
794 s.writeline("250-mox.example")
795 s.writeline("250 PIPELINING")
796 s.readline("MAIL FROM:")
797 s.writeline("250 ok")
798 s.readline("RCPT TO:")
799 s.writeline("451 not now")
800 s.readline("RCPT TO:")
801 s.writeline("451 not now")
803 s.writeline("354 ok")
805 s.writeline("503 no recipient")
807 s.writeline("250 ok")
808 }, func(conn net.Conn) {
809 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
815 _, err = c.DeliverMultiple(ctx, "postmaster@other.example", []string{"mjl@mox.example", "mjl@mox.example"}, int64(len(msg)), strings.NewReader(msg), false, false, false)
817 if err == nil || !errors.Is(err, errNoRecipientsPipelined) || !errors.As(err, &xerr) || xerr.Permanent {
818 panic(fmt.Errorf("got %#v (%s), expected errNoRecipientsPipelined with non-Permanent", err, err))
829func (s xserver) check(err error, msg string) {
831 panic(fmt.Errorf("%s: %w", msg, err))
835func (s xserver) errorf(format string, args ...any) {
836 panic(fmt.Errorf(format, args...))
839func (s xserver) writeline(line string) {
840 _, err := fmt.Fprintf(s.conn, "%s\r\n", line)
841 s.check(err, "write")
844func (s xserver) readline(prefix string) {
845 line, err := s.br.ReadString('\n')
846 s.check(err, "reading command")
847 if !strings.HasPrefix(strings.ToLower(line), strings.ToLower(prefix)) {
848 s.errorf("expected command %q, got: %s", prefix, line)
852func run(t *testing.T, server func(s xserver), client func(conn net.Conn)) {
855 result := make(chan error, 2)
856 clientConn, serverConn := net.Pipe()
862 result <- fmt.Errorf("server: %v", x)
867 server(xserver{serverConn, bufio.NewReader(serverConn)})
874 result <- fmt.Errorf("client: %v", x)
882 for i := 0; i < 2; i++ {
885 errs = append(errs, err)
889 t.Fatalf("errors: %v", errs)
893func TestLimits(t *testing.T) {
894 check := func(s string, expLimits map[string]string, expMailMax, expRcptMax, expRcptDomainMax int) {
896 limits, mailmax, rcptMax, rcptDomainMax := parseLimits([]byte(s))
897 if !reflect.DeepEqual(limits, expLimits) || mailmax != expMailMax || rcptMax != expRcptMax || rcptDomainMax != expRcptDomainMax {
898 t.Errorf("bad limits, got %v %d %d %d, expected %v %d %d %d, for %q", limits, mailmax, rcptMax, rcptDomainMax, expLimits, expMailMax, expRcptMax, expRcptDomainMax, s)
901 check(" unknown=a=b -_1oK=xY", map[string]string{"UNKNOWN": "a=b", "-_1OK": "xY"}, 0, 0, 0)
902 check(" MAILMAX=123 OTHER=ignored RCPTDOMAINMAX=1 RCPTMAX=321", map[string]string{"MAILMAX": "123", "OTHER": "ignored", "RCPTDOMAINMAX": "1", "RCPTMAX": "321"}, 123, 321, 1)
903 check(" MAILMAX=invalid", map[string]string{"MAILMAX": "invalid"}, 0, 0, 0)
904 check(" invalid syntax", nil, 0, 0, 0)
905 check(" DUP=1 DUP=2", nil, 0, 0, 0)
908// Just a cert that appears valid. SMTP client will not verify anything about it
909// (that is opportunistic TLS for you, "better some than none"). Let's enjoy this
910// one moment where it makes life easier.
911func fakeCert(t *testing.T, expired bool) tls.Certificate {
912 notAfter := time.Now()
914 notAfter = notAfter.Add(-time.Hour)
916 notAfter = notAfter.Add(time.Hour)
919 privKey := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize)) // Fake key, don't use this for real!
920 template := &x509.Certificate{
921 SerialNumber: big.NewInt(1), // Required field...
922 DNSNames: []string{"mox.example"},
923 NotBefore: time.Now().Add(-time.Hour),
926 localCertBuf, err := x509.CreateCertificate(cryptorand.Reader, template, template, privKey.Public(), privKey)
928 t.Fatalf("making certificate: %s", err)
930 cert, err := x509.ParseCertificate(localCertBuf)
932 t.Fatalf("parsing generated certificate: %s", err)
934 c := tls.Certificate{
935 Certificate: [][]byte{localCertBuf},