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})
40 defer mlog.SetConfig(map[string]slog.Level{"": mlog.LevelDebug})
52 auths []string // Allowed mechanisms.
54 nodeliver bool // For server, whether client will attempt a delivery.
60 tlsHostname dns.Domain
64 recipients []string // If nil, mjl@mox.example is used.
65 resps []Response // Checked only if non-nil.
68 // Make fake cert, and make it trusted.
69 cert := fakeCert(t, false)
70 roots := x509.NewCertPool()
71 roots.AddCert(cert.Leaf)
72 tlsConfig := tls.Config{
73 Certificates: []tls.Certificate{cert},
76 cleanupResp := func(resps []Response) []Response {
77 for i, r := range resps {
78 resps[i] = Response{Code: r.Code, Secode: r.Secode}
83 test := func(msg string, opts options, auth func(l []string, cs *tls.ConnectionState) (sasl.Client, error), expClientErr, expDeliverErr, expServerErr error) {
86 if opts.tlsMode == "" {
87 opts.tlsMode = TLSOpportunistic
90 clientConn, serverConn := net.Pipe()
91 defer serverConn.Close()
93 result := make(chan error, 2)
98 if x != nil && x != "stop" {
102 fail := func(format string, args ...any) {
103 err := fmt.Errorf("server: %w", fmt.Errorf(format, args...))
104 log.Errorx("failure", err)
105 if err != nil && expServerErr != nil && (errors.Is(err, expServerErr) || errors.As(err, reflect.New(reflect.ValueOf(expServerErr).Type()).Interface())) {
112 br := bufio.NewReader(serverConn)
113 readline := func(prefix string) string {
114 s, err := br.ReadString('\n')
116 fail("expected command: %v", err)
118 if !strings.HasPrefix(strings.ToLower(s), strings.ToLower(prefix)) {
119 fail("expected command %q, got: %s", prefix, s)
122 return strings.TrimSuffix(s, "\r\n")
124 writeline := func(s string) {
125 fmt.Fprintf(serverConn, "%s\r\n", s)
130 ehlo := true // Initially we expect EHLO.
135 writeline("250 mox.example")
142 // Client will try again with HELO.
143 writeline("500 bad syntax")
149 writeline("250-mox.example")
151 writeline("250-PIPELINING")
153 if opts.maxSize > 0 {
154 writeline(fmt.Sprintf("250-SIZE %d", opts.maxSize))
157 writeline("250-ENHANCEDSTATUSCODES")
159 if opts.starttls && !haveTLS {
160 writeline("250-STARTTLS")
162 if opts.eightbitmime {
163 writeline("250-8BITMIME")
166 writeline("250-SMTPUTF8")
168 if opts.requiretls && haveTLS {
169 writeline("250-REQUIRETLS")
171 if opts.auths != nil {
172 writeline("250-AUTH " + strings.Join(opts.auths, " "))
174 writeline("250-LIMITS MAILMAX=10 RCPTMAX=100 RCPTDOMAINMAX=1")
175 writeline("250 UNKNOWN") // To be ignored.
178 writeline("220 mox.example ESMTP test")
185 tlsConn := tls.Server(serverConn, &tlsConfig)
186 nctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
188 err := tlsConn.HandshakeContext(nctx)
190 fail("tls handshake: %w", err)
193 br = bufio.NewReader(serverConn)
199 if opts.auths != nil {
200 more := readline("AUTH ")
201 t := strings.SplitN(more, " ", 2)
204 writeline("235 2.7.0 auth ok")
206 writeline("334 " + base64.StdEncoding.EncodeToString([]byte("<123.1234@host>")))
207 readline("") // Proof
208 writeline("235 2.7.0 auth ok")
209 case "SCRAM-SHA-256-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-1":
210 // Cannot fake/hardcode scram interactions.
211 var h func() hash.Hash
212 salt := scram.MakeRandom()
215 case "SCRAM-SHA-1-PLUS", "SCRAM-SHA-1":
217 iterations = 2 * 4096
218 case "SCRAM-SHA-256-PLUS", "SCRAM-SHA-256":
222 panic("missing case for scram")
224 var cs *tls.ConnectionState
225 if strings.HasSuffix(t[0], "-PLUS") {
227 writeline("501 scram plus without tls not possible")
233 xcs := serverConn.(*tls.Conn).ConnectionState()
236 saltedPassword, err := scram.SaltPassword(h, "test", salt, iterations)
238 fail("scram salt password: %w", err)
241 clientFirst, err := base64.StdEncoding.DecodeString(t[1])
243 fail("bad base64: %w", err)
245 s, err := scram.NewServer(h, clientFirst, cs, cs != nil)
247 fail("scram new server: %w", err)
249 serverFirst, err := s.ServerFirst(iterations, salt)
251 fail("scram server first: %w", err)
253 writeline("334 " + base64.StdEncoding.EncodeToString([]byte(serverFirst)))
255 xclientFinal := readline("")
256 clientFinal, err := base64.StdEncoding.DecodeString(xclientFinal)
258 fail("bad base64: %w", err)
260 serverFinal, err := s.Finish([]byte(clientFinal), saltedPassword)
262 fail("scram finish: %w", err)
264 writeline("334 " + base64.StdEncoding.EncodeToString([]byte(serverFinal)))
266 writeline("235 2.7.0 auth ok")
268 writeline("501 unknown mechanism")
272 if expClientErr == nil && !opts.nodeliver {
273 readline("MAIL FROM:")
275 n := len(opts.recipients)
282 if i < len(opts.resps) {
283 resp = fmt.Sprintf("%d maybe", opts.resps[i].Code)
288 writeline("354 continue")
289 reader := smtp.NewDataReader(br)
290 io.Copy(io.Discard, reader)
293 if expDeliverErr == nil {
297 readline("MAIL FROM:")
302 if i < len(opts.resps) {
303 resp = fmt.Sprintf("%d maybe", opts.resps[i].Code)
308 writeline("354 continue")
309 reader = smtp.NewDataReader(br)
310 io.Copy(io.Discard, reader)
320 // todo: should abort tests more properly. on client failures, we may be left with hanging test.
324 if x != nil && x != "stop" {
328 fail := func(format string, args ...any) {
329 err := fmt.Errorf("client: %w", fmt.Errorf(format, args...))
330 log.Errorx("failure", err)
334 client, err := New(ctx, log.Logger, clientConn, opts.tlsMode, opts.tlsPKIX, localhost, opts.tlsHostname, Opts{Auth: auth, RootCAs: opts.roots})
335 if (err == nil) != (expClientErr == nil) || err != nil && !errors.As(err, reflect.New(reflect.ValueOf(expClientErr).Type()).Interface()) && !errors.Is(err, expClientErr) {
336 fail("new client: got err %v, expected %#v", err, expClientErr)
342 rcptTo := opts.recipients
343 if len(rcptTo) == 0 {
344 rcptTo = []string{"mjl@mox.example"}
346 resps, err := client.DeliverMultiple(ctx, "postmaster@mox.example", rcptTo, int64(len(msg)), strings.NewReader(msg), opts.need8bitmime, opts.needsmtputf8, opts.needsrequiretls)
347 if (err == nil) != (expDeliverErr == nil) || err != nil && !errors.Is(err, expDeliverErr) && !reflect.DeepEqual(err, expDeliverErr) {
348 fail("first deliver: got err %#v (%s), expected %#v (%s)", err, err, expDeliverErr, expDeliverErr)
349 } else if opts.resps != nil && !reflect.DeepEqual(cleanupResp(resps), opts.resps) {
350 fail("first deliver: got resps %v, expected %v", resps, opts.resps)
355 fail("reset: %v", err)
357 resps, err = client.DeliverMultiple(ctx, "postmaster@mox.example", rcptTo, int64(len(msg)), strings.NewReader(msg), opts.need8bitmime, opts.needsmtputf8, opts.needsrequiretls)
358 if (err == nil) != (expDeliverErr == nil) || err != nil && !errors.Is(err, expDeliverErr) && !reflect.DeepEqual(err, expDeliverErr) {
359 fail("second deliver: got err %#v (%s), expected %#v (%s)", err, err, expDeliverErr, expDeliverErr)
360 } else if opts.resps != nil && !reflect.DeepEqual(cleanupResp(resps), opts.resps) {
361 fail("second: got resps %v, expected %v", resps, opts.resps)
366 fail("close client: %v", err)
375 errs = append(errs, err)
383 msg := strings.ReplaceAll(`From: <postmaster@mox.example>
400 tlsMode: TLSRequiredStartTLS,
403 tlsHostname: dns.Domain{ASCII: "mox.example"},
406 needsrequiretls: true,
409 test(msg, options{}, nil, nil, nil, nil)
410 test(msg, allopts, nil, nil, nil, nil)
411 test(msg, options{ehlo: true, eightbitmime: true}, nil, nil, nil, nil)
412 test(msg, options{ehlo: true, eightbitmime: false, need8bitmime: true, nodeliver: true}, nil, nil, Err8bitmimeUnsupported, nil)
413 test(msg, options{ehlo: true, smtputf8: false, needsmtputf8: true, nodeliver: true}, nil, nil, ErrSMTPUTF8Unsupported, nil)
415 // Server TLS handshake is a net.OpError with "remote error" as text.
416 test(msg, options{ehlo: true, starttls: true, tlsMode: TLSRequiredStartTLS, tlsPKIX: true, tlsHostname: dns.Domain{ASCII: "mismatch.example"}, nodeliver: true}, nil, ErrTLS, nil, &net.OpError{})
418 test(msg, options{ehlo: true, maxSize: len(msg) - 1, nodeliver: true}, nil, nil, ErrSize, nil)
420 // Multiple recipients, not pipelined.
425 recipients: []string{"mjl@mox.example", "mjl2@mox.example", "mjl3@mox.example"},
427 {Code: smtp.C250Completed},
428 {Code: smtp.C250Completed},
429 {Code: smtp.C250Completed},
432 test(msg, multi1, nil, nil, nil, nil)
433 multi1.pipelining = true
434 test(msg, multi1, nil, nil, nil, nil)
436 // Multiple recipients with 452 and other error, not pipelined
440 recipients: []string{"xmjl@mox.example", "xmjl2@mox.example", "xmjl3@mox.example"},
442 {Code: smtp.C250Completed},
443 {Code: smtp.C554TransactionFailed}, // Will continue when not pipelined.
444 {Code: smtp.C452StorageFull}, // Will stop sending further recipients.
447 test(msg, multi2, nil, nil, nil, nil)
448 multi2.pipelining = true
449 test(msg, multi2, nil, nil, nil, nil)
450 multi2.pipelining = false
451 multi2.resps[2].Code = smtp.C552MailboxFull
452 test(msg, multi2, nil, nil, nil, nil)
453 multi2.pipelining = true
454 test(msg, multi2, nil, nil, nil, nil)
456 // Single recipient with error and pipelining is an error.
461 recipients: []string{"xmjl@mox.example"},
462 resps: []Response{{Code: smtp.C452StorageFull}},
464 test(msg, multi3, nil, nil, Error{Code: smtp.C452StorageFull, Command: "rcptto", Line: "452 maybe"}, nil)
466 authPlain := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
467 return sasl.NewClientPlain("test", "test"), nil
469 test(msg, options{ehlo: true, auths: []string{"PLAIN"}}, authPlain, nil, nil, nil)
471 authCRAMMD5 := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
472 return sasl.NewClientCRAMMD5("test", "test"), nil
474 test(msg, options{ehlo: true, auths: []string{"CRAM-MD5"}}, authCRAMMD5, nil, nil, nil)
476 // todo: add tests for failing authentication, also at various stages in SCRAM
478 authSCRAMSHA1 := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
479 return sasl.NewClientSCRAMSHA1("test", "test", false), nil
481 test(msg, options{ehlo: true, auths: []string{"SCRAM-SHA-1"}}, authSCRAMSHA1, nil, nil, nil)
483 authSCRAMSHA1PLUS := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
484 return sasl.NewClientSCRAMSHA1PLUS("test", "test", *cs), nil
486 test(msg, options{ehlo: true, starttls: true, auths: []string{"SCRAM-SHA-1-PLUS"}}, authSCRAMSHA1PLUS, nil, nil, nil)
488 authSCRAMSHA256 := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
489 return sasl.NewClientSCRAMSHA256("test", "test", false), nil
491 test(msg, options{ehlo: true, auths: []string{"SCRAM-SHA-256"}}, authSCRAMSHA256, nil, nil, nil)
493 authSCRAMSHA256PLUS := func(l []string, cs *tls.ConnectionState) (sasl.Client, error) {
494 return sasl.NewClientSCRAMSHA256PLUS("test", "test", *cs), nil
496 test(msg, options{ehlo: true, starttls: true, auths: []string{"SCRAM-SHA-256-PLUS"}}, authSCRAMSHA256PLUS, nil, nil, nil)
498 test(msg, options{ehlo: true, requiretls: false, needsrequiretls: true, nodeliver: true}, nil, nil, ErrRequireTLSUnsupported, nil)
500 // Set an expired certificate. For non-strict TLS, we should still accept it.
502 cert = fakeCert(t, true)
503 roots = x509.NewCertPool()
504 roots.AddCert(cert.Leaf)
505 tlsConfig = tls.Config{
506 Certificates: []tls.Certificate{cert},
508 test(msg, options{ehlo: true, starttls: true, roots: roots}, nil, nil, nil, nil)
510 // Again with empty cert pool so it isn't trusted in any way.
511 roots = x509.NewCertPool()
512 tlsConfig = tls.Config{
513 Certificates: []tls.Certificate{cert},
515 test(msg, options{ehlo: true, starttls: true, roots: roots}, nil, nil, nil, nil)
518func TestErrors(t *testing.T) {
519 ctx := context.Background()
520 log := mlog.New("smtpclient", nil)
523 run(t, func(s xserver) {
524 s.writeline("bogus") // Invalid, should be "220 <hostname>".
525 }, func(conn net.Conn) {
526 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
528 if err == nil || !errors.Is(err, ErrProtocol) || !errors.As(err, &xerr) || xerr.Permanent {
529 panic(fmt.Errorf("got %#v, expected ErrProtocol without Permanent", err))
533 // Server just closes connection.
534 run(t, func(s xserver) {
536 }, func(conn net.Conn) {
537 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
539 if err == nil || !errors.Is(err, io.ErrUnexpectedEOF) || !errors.As(err, &xerr) || xerr.Permanent {
540 panic(fmt.Errorf("got %#v (%v), expected ErrUnexpectedEOF without Permanent", err, err))
544 // Server does not want to speak SMTP.
545 run(t, func(s xserver) {
546 s.writeline("521 not accepting connections")
547 }, func(conn net.Conn) {
548 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
550 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
551 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
555 // Server has invalid code in greeting.
556 run(t, func(s xserver) {
557 s.writeline("2200 mox.example") // Invalid, too many digits.
558 }, func(conn net.Conn) {
559 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
561 if err == nil || !errors.Is(err, ErrProtocol) || !errors.As(err, &xerr) || xerr.Permanent {
562 panic(fmt.Errorf("got %#v, expected ErrProtocol without Permanent", err))
566 // Server sends multiline response, but with different codes.
567 run(t, func(s xserver) {
568 s.writeline("220 mox.example")
570 s.writeline("250-mox.example")
571 s.writeline("500 different code") // Invalid.
572 }, func(conn net.Conn) {
573 _, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
575 if err == nil || !errors.Is(err, ErrProtocol) || !errors.As(err, &xerr) || xerr.Permanent {
576 panic(fmt.Errorf("got %#v, expected ErrProtocol without Permanent", err))
580 // Server permanently refuses MAIL FROM.
581 run(t, func(s xserver) {
582 s.writeline("220 mox.example")
584 s.writeline("250-mox.example")
585 s.writeline("250 ENHANCEDSTATUSCODES")
586 s.readline("MAIL FROM:")
587 s.writeline("550 5.7.0 not allowed")
588 }, func(conn net.Conn) {
589 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
594 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
596 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
597 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
601 // Server temporarily refuses MAIL FROM.
602 run(t, func(s xserver) {
603 s.writeline("220 mox.example")
605 s.writeline("250 mox.example")
606 s.readline("MAIL FROM:")
607 s.writeline("451 bad sender")
608 }, func(conn net.Conn) {
609 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
614 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
616 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || xerr.Permanent {
617 panic(fmt.Errorf("got %#v, expected ErrStatus with not-Permanent", err))
621 // Server temporarily refuses RCPT TO.
622 run(t, func(s xserver) {
623 s.writeline("220 mox.example")
625 s.writeline("250 mox.example")
626 s.readline("MAIL FROM:")
627 s.writeline("250 ok")
628 s.readline("RCPT TO:")
630 }, func(conn net.Conn) {
631 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
636 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
638 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || xerr.Permanent {
639 panic(fmt.Errorf("got %#v, expected ErrStatus with not-Permanent", err))
643 // Server permanently refuses DATA.
644 run(t, func(s xserver) {
645 s.writeline("220 mox.example")
647 s.writeline("250 mox.example")
648 s.readline("MAIL FROM:")
649 s.writeline("250 ok")
650 s.readline("RCPT TO:")
651 s.writeline("250 ok")
653 s.writeline("550 no!")
654 }, func(conn net.Conn) {
655 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
660 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
662 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
663 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
667 // TLS is required, so we attempt it regardless of whether it is advertised.
668 run(t, func(s xserver) {
669 s.writeline("220 mox.example")
671 s.writeline("250 mox.example")
672 s.readline("STARTTLS")
673 s.writeline("502 command not implemented")
674 }, func(conn net.Conn) {
675 _, err := New(ctx, log.Logger, conn, TLSRequiredStartTLS, true, localhost, dns.Domain{ASCII: "mox.example"}, Opts{})
677 if err == nil || !errors.Is(err, ErrTLS) || !errors.As(err, &xerr) || !xerr.Permanent {
678 panic(fmt.Errorf("got %#v, expected ErrTLS with Permanent", err))
682 // If TLS is available, but we don't want to use it, client should skip it.
683 run(t, func(s xserver) {
684 s.writeline("220 mox.example")
686 s.writeline("250-mox.example")
687 s.writeline("250 STARTTLS")
688 s.readline("MAIL FROM:")
689 s.writeline("451 enough")
690 }, func(conn net.Conn) {
691 c, err := New(ctx, log.Logger, conn, TLSSkip, false, localhost, dns.Domain{ASCII: "mox.example"}, Opts{})
696 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
698 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || xerr.Permanent {
699 panic(fmt.Errorf("got %#v, expected ErrStatus with non-Permanent", err))
703 // A transaction is aborted. If we try another one, we should send a RSET.
704 run(t, func(s xserver) {
705 s.writeline("220 mox.example")
707 s.writeline("250 mox.example")
708 s.readline("MAIL FROM:")
709 s.writeline("250 ok")
710 s.readline("RCPT TO:")
711 s.writeline("451 not now")
713 s.writeline("250 ok")
714 s.readline("MAIL FROM:")
715 s.writeline("250 ok")
716 s.readline("RCPT TO:")
717 s.writeline("250 ok")
719 s.writeline("550 not now")
720 }, func(conn net.Conn) {
721 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
727 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
729 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || xerr.Permanent {
730 panic(fmt.Errorf("got %#v, expected ErrStatus with non-Permanent", err))
734 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
735 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
736 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
740 // Remote closes connection after 550 response to MAIL FROM in pipelined
741 // connection. Should result in permanent error, not temporary read error.
742 // E.g. outlook.com that has your IP blocklisted.
743 run(t, func(s xserver) {
744 s.writeline("220 mox.example")
746 s.writeline("250-mox.example")
747 s.writeline("250 PIPELINING")
748 s.readline("MAIL FROM:")
749 s.writeline("550 ok")
750 }, func(conn net.Conn) {
751 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
757 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
759 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
760 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
764 // Remote closes connection after 554 response to RCPT TO in pipelined
765 // connection. Should result in permanent error, not temporary read error.
766 // E.g. icloud.com that has your IP blocklisted.
767 run(t, func(s xserver) {
768 s.writeline("220 mox.example")
770 s.writeline("250-mox.example")
771 s.writeline("250-ENHANCEDSTATUSCODES")
772 s.writeline("250 PIPELINING")
773 s.readline("MAIL FROM:")
774 s.writeline("250 2.1.0 ok")
775 s.readline("RCPT TO:")
776 s.writeline("554 5.7.0 Blocked")
777 }, func(conn net.Conn) {
778 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
784 err = c.Deliver(ctx, "postmaster@other.example", "mjl@mox.example", int64(len(msg)), strings.NewReader(msg), false, false, false)
786 if err == nil || !errors.Is(err, ErrStatus) || !errors.As(err, &xerr) || !xerr.Permanent {
787 panic(fmt.Errorf("got %#v, expected ErrStatus with Permanent", err))
791 // If we try multiple recipients and first is 452, it is an error and a
792 // non-pipelined deliver will be aborted.
793 run(t, func(s xserver) {
794 s.writeline("220 mox.example")
796 s.writeline("250 mox.example")
797 s.readline("MAIL FROM:")
798 s.writeline("250 ok")
799 s.readline("RCPT TO:")
800 s.writeline("451 not now")
801 s.readline("RCPT TO:")
802 s.writeline("451 not now")
804 s.writeline("250 ok")
805 }, func(conn net.Conn) {
806 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
812 _, err = c.DeliverMultiple(ctx, "postmaster@other.example", []string{"mjl@mox.example", "mjl@mox.example"}, int64(len(msg)), strings.NewReader(msg), false, false, false)
814 if err == nil || !errors.Is(err, errNoRecipients) || !errors.As(err, &xerr) || xerr.Permanent {
815 panic(fmt.Errorf("got %#v (%s) expected errNoRecipients with non-Permanent", err, err))
820 // If we try multiple recipients and first is 452, it is an error and a pipelined
821 // deliver will abort an allowed DATA.
822 run(t, func(s xserver) {
823 s.writeline("220 mox.example")
825 s.writeline("250-mox.example")
826 s.writeline("250 PIPELINING")
827 s.readline("MAIL FROM:")
828 s.writeline("250 ok")
829 s.readline("RCPT TO:")
830 s.writeline("451 not now")
831 s.readline("RCPT TO:")
832 s.writeline("451 not now")
834 s.writeline("354 ok")
836 s.writeline("503 no recipient")
838 s.writeline("250 ok")
839 }, func(conn net.Conn) {
840 c, err := New(ctx, log.Logger, conn, TLSOpportunistic, false, localhost, zerohost, Opts{})
846 _, err = c.DeliverMultiple(ctx, "postmaster@other.example", []string{"mjl@mox.example", "mjl@mox.example"}, int64(len(msg)), strings.NewReader(msg), false, false, false)
848 if err == nil || !errors.Is(err, errNoRecipientsPipelined) || !errors.As(err, &xerr) || xerr.Permanent {
849 panic(fmt.Errorf("got %#v (%s), expected errNoRecipientsPipelined with non-Permanent", err, err))
860func (s xserver) check(err error, msg string) {
862 panic(fmt.Errorf("%s: %w", msg, err))
866func (s xserver) errorf(format string, args ...any) {
867 panic(fmt.Errorf(format, args...))
870func (s xserver) writeline(line string) {
871 _, err := fmt.Fprintf(s.conn, "%s\r\n", line)
872 s.check(err, "write")
875func (s xserver) readline(prefix string) {
876 line, err := s.br.ReadString('\n')
877 s.check(err, "reading command")
878 if !strings.HasPrefix(strings.ToLower(line), strings.ToLower(prefix)) {
879 s.errorf("expected command %q, got: %s", prefix, line)
883func run(t *testing.T, server func(s xserver), client func(conn net.Conn)) {
886 result := make(chan error, 2)
887 clientConn, serverConn := net.Pipe()
893 result <- fmt.Errorf("server: %v", x)
898 server(xserver{serverConn, bufio.NewReader(serverConn)})
905 result <- fmt.Errorf("client: %v", x)
916 errs = append(errs, err)
920 t.Fatalf("errors: %v", errs)
924func TestLimits(t *testing.T) {
925 check := func(s string, expLimits map[string]string, expMailMax, expRcptMax, expRcptDomainMax int) {
927 limits, mailmax, rcptMax, rcptDomainMax := parseLimits([]byte(s))
928 if !reflect.DeepEqual(limits, expLimits) || mailmax != expMailMax || rcptMax != expRcptMax || rcptDomainMax != expRcptDomainMax {
929 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)
932 check(" unknown=a=b -_1oK=xY", map[string]string{"UNKNOWN": "a=b", "-_1OK": "xY"}, 0, 0, 0)
933 check(" MAILMAX=123 OTHER=ignored RCPTDOMAINMAX=1 RCPTMAX=321", map[string]string{"MAILMAX": "123", "OTHER": "ignored", "RCPTDOMAINMAX": "1", "RCPTMAX": "321"}, 123, 321, 1)
934 check(" MAILMAX=invalid", map[string]string{"MAILMAX": "invalid"}, 0, 0, 0)
935 check(" invalid syntax", nil, 0, 0, 0)
936 check(" DUP=1 DUP=2", nil, 0, 0, 0)
939// Just a cert that appears valid. SMTP client will not verify anything about it
940// (that is opportunistic TLS for you, "better some than none"). Let's enjoy this
941// one moment where it makes life easier.
942func fakeCert(t *testing.T, expired bool) tls.Certificate {
943 notAfter := time.Now()
945 notAfter = notAfter.Add(-time.Hour)
947 notAfter = notAfter.Add(time.Hour)
950 privKey := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize)) // Fake key, don't use this for real!
951 template := &x509.Certificate{
952 SerialNumber: big.NewInt(1), // Required field...
953 DNSNames: []string{"mox.example"},
954 NotBefore: time.Now().Add(-time.Hour),
957 localCertBuf, err := x509.CreateCertificate(cryptorand.Reader, template, template, privKey.Public(), privKey)
959 t.Fatalf("making certificate: %s", err)
961 cert, err := x509.ParseCertificate(localCertBuf)
963 t.Fatalf("parsing generated certificate: %s", err)
965 c := tls.Certificate{
966 Certificate: [][]byte{localCertBuf},