git » chasquid » smarthost » tree

[smarthost] / internal / smtpsrv / server_test.go

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
package smtpsrv

import (
	"crypto/tls"
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"net/smtp"
	"os"
	"testing"
	"time"

	"blitiri.com.ar/go/chasquid/internal/aliases"
	"blitiri.com.ar/go/chasquid/internal/maillog"
	"blitiri.com.ar/go/chasquid/internal/testlib"
	"blitiri.com.ar/go/chasquid/internal/userdb"
)

// Flags.
var (
	externalSMTPAddr = flag.String("external_smtp_addr", "",
		"SMTP server address to test (defaults to use internal)")
	externalSubmissionAddr = flag.String("external_submission_addr", "",
		"submission server address to test (defaults to use internal)")
	externalSubmissionTLSAddr = flag.String("external_submission_tls_addr", "",
		"submission+TLS server address to test (defaults to use internal)")
)

var (
	// Server addresses. Will be filled in at init time.
	// We default to internal ones, but may get overridden via flags.
	smtpAddr          = ""
	submissionAddr    = ""
	submissionTLSAddr = ""

	// TLS configuration to use in the clients.
	// Will contain the generated server certificate as root CA.
	tlsConfig *tls.Config

	// Test couriers, so we can validate that emails got sent.
	localC  = testlib.NewTestCourier()
	remoteC = testlib.NewTestCourier()

	// Max data size, in MiB.
	maxDataSizeMiB = 5
)

//
// === Tests ===
//

func mustDial(tb testing.TB, mode SocketMode, startTLS bool) *smtp.Client {
	addr := ""
	switch mode {
	case ModeSMTP:
		addr = smtpAddr
	case ModeSubmission:
		addr = submissionAddr
	case ModeSubmissionTLS:
		addr = submissionTLSAddr
	}

	var err error
	var conn net.Conn
	if mode.TLS {
		conn, err = tls.Dial("tcp", addr, tlsConfig)
	} else {
		conn, err = net.Dial("tcp", addr)
	}
	if err != nil {
		tb.Fatalf("(net||tls).Dial: %v", err)
	}
	c, err := smtp.NewClient(conn, "127.0.0.1")
	if err != nil {
		tb.Fatalf("smtp.Dial: %v", err)
	}

	if err = c.Hello("test"); err != nil {
		tb.Fatalf("c.Hello: %v", err)
	}

	if startTLS {
		if ok, _ := c.Extension("STARTTLS"); !ok {
			tb.Fatalf("STARTTLS not advertised in EHLO")
		}

		if err = c.StartTLS(tlsConfig); err != nil {
			tb.Fatalf("StartTLS: %v", err)
		}
	}

	return c
}

func sendEmail(tb testing.TB, c *smtp.Client) {
	sendEmailWithAuth(tb, c, nil)
}

func sendEmailWithAuth(tb testing.TB, c *smtp.Client, auth smtp.Auth) {
	var err error
	from := "from@from"

	if auth != nil {
		if err = c.Auth(auth); err != nil {
			tb.Errorf("Auth: %v", err)
		}

		// If we authenticated, we must use the user as from, as the server
		// checks otherwise.
		from = "testuser@localhost"
	}

	if err = c.Mail(from); err != nil {
		tb.Errorf("Mail: %v", err)
	}

	if err = c.Rcpt("to@localhost"); err != nil {
		tb.Errorf("Rcpt: %v", err)
	}

	w, err := c.Data()
	if err != nil {
		tb.Fatalf("Data: %v", err)
	}

	msg := []byte("Subject: Hi!\n\n This is an email\n")
	if _, err = w.Write(msg); err != nil {
		tb.Errorf("Data write: %v", err)
	}

	localC.Expect(1)

	if err = w.Close(); err != nil {
		tb.Errorf("Data close: %v", err)
	}

	localC.Wait()
}

func TestSimple(t *testing.T) {
	c := mustDial(t, ModeSMTP, false)
	defer c.Close()
	sendEmail(t, c)
}

func TestSimpleTLS(t *testing.T) {
	c := mustDial(t, ModeSMTP, true)
	defer c.Close()
	sendEmail(t, c)
}

func TestManyEmails(t *testing.T) {
	c := mustDial(t, ModeSMTP, true)
	defer c.Close()
	sendEmail(t, c)
	sendEmail(t, c)
	sendEmail(t, c)
}

func TestAuth(t *testing.T) {
	c := mustDial(t, ModeSubmission, true)
	defer c.Close()

	auth := smtp.PlainAuth("", "testuser@localhost", "testpasswd", "127.0.0.1")
	sendEmailWithAuth(t, c, auth)
}

func TestSubmissionWithoutAuth(t *testing.T) {
	c := mustDial(t, ModeSubmission, true)
	defer c.Close()

	if err := c.Mail("from@from"); err == nil {
		t.Errorf("Mail not failed as expected")
	}
}

func TestAuthOnTLS(t *testing.T) {
	c := mustDial(t, ModeSubmissionTLS, false)
	defer c.Close()

	auth := smtp.PlainAuth("", "testuser@localhost", "testpasswd", "127.0.0.1")
	sendEmailWithAuth(t, c, auth)
}

func TestAuthOnSMTP(t *testing.T) {
	c := mustDial(t, ModeSMTP, true)
	defer c.Close()

	auth := smtp.PlainAuth("", "testuser@localhost", "testpasswd", "127.0.0.1")

	// At least for now, we allow AUTH over the SMTP port to avoid unnecessary
	// complexity, so we expect it to work.
	sendEmailWithAuth(t, c, auth)
}

func TestBrokenAuth(t *testing.T) {
	c := mustDial(t, ModeSubmission, true)
	defer c.Close()

	auth := smtp.PlainAuth("", "user@broken", "passwd", "127.0.0.1")
	err := c.Auth(auth)
	if err == nil {
		t.Errorf("Broken auth succeeded")
	} else if err.Error() != "454 4.7.0 Temporary authentication failure" {
		t.Errorf("Broken auth returned unexpected error %q", err.Error())
	}
}

func TestWrongMailParsing(t *testing.T) {
	addrs := []string{"from", "a b c", "a @ b", "<x>", "<x y>", "><"}
	for _, addr := range addrs {
		c := mustDial(t, ModeSMTP, false)

		if err := c.Mail(addr); err == nil {
			t.Errorf("Mail not failed as expected with %q", addr)
		}

		if err := c.Mail("from@plain"); err != nil {
			t.Errorf("Mail: %v", err)
		}

		for _, addr := range addrs {
			if err := c.Rcpt(addr); err == nil {
				t.Errorf("Rcpt not failed as expected with %q", addr)
			}
		}

		c.Close()
	}
}

func TestNullMailFrom(t *testing.T) {
	c := mustDial(t, ModeSMTP, false)
	defer c.Close()

	addrs := []string{"<>", "  <>", "<> OPTION"}
	for _, addr := range addrs {
		simpleCmd(t, c, fmt.Sprintf("MAIL FROM:%s", addr), 250)
	}
}

func TestRcptBeforeMail(t *testing.T) {
	c := mustDial(t, ModeSMTP, false)
	defer c.Close()

	if err := c.Rcpt("to@to"); err == nil {
		t.Errorf("Rcpt not failed as expected")
	}
}

func TestRcptOption(t *testing.T) {
	c := mustDial(t, ModeSMTP, true)
	defer c.Close()

	if err := c.Mail("from@localhost"); err != nil {
		t.Fatalf("Mail: %v", err)
	}

	params := []string{
		"<to@localhost>", "  <to@localhost>", "<to@localhost> OPTION"}
	for _, p := range params {
		simpleCmd(t, c, fmt.Sprintf("RCPT TO:%s", p), 250)
	}
}

func TestRelayForbidden(t *testing.T) {
	c := mustDial(t, ModeSMTP, false)
	defer c.Close()

	if err := c.Mail("from@somewhere"); err != nil {
		t.Errorf("Mail: %v", err)
	}

	if err := c.Rcpt("to@somewhere"); err == nil {
		t.Errorf("Accepted relay email")
	}
}

func TestTooManyRecipients(t *testing.T) {
	c := mustDial(t, ModeSubmission, true)
	defer c.Close()

	auth := smtp.PlainAuth("", "testuser@localhost", "testpasswd", "127.0.0.1")
	if err := c.Auth(auth); err != nil {
		t.Fatalf("Auth: %v", err)
	}

	if err := c.Mail("testuser@localhost"); err != nil {
		t.Fatalf("Mail: %v", err)
	}

	for i := 0; i < 101; i++ {
		if err := c.Rcpt(fmt.Sprintf("to%d@somewhere", i)); err != nil {
			t.Fatalf("Rcpt: %v", err)
		}
	}

	err := c.Rcpt("to102@somewhere")
	if err == nil || err.Error() != "452 4.5.3 Too many recipients" {
		t.Errorf("Expected too many recipients, got: %v", err)
	}
}

func TestRcptBrokenExists(t *testing.T) {
	c := mustDial(t, ModeSMTP, true)
	defer c.Close()

	if err := c.Mail("from@localhost"); err != nil {
		t.Fatalf("Mail: %v", err)
	}

	err := c.Rcpt("to@broken")
	if err == nil {
		t.Errorf("Accepted RCPT with broken Exists")
	}
	expect := "451 4.4.3 Temporary error checking address"
	if err.Error() != expect {
		t.Errorf("RCPT returned unexpected error %q", err.Error())
	}
}

func TestRcptUserDoesNotExist(t *testing.T) {
	c := mustDial(t, ModeSMTP, true)
	defer c.Close()

	if err := c.Mail("from@localhost"); err != nil {
		t.Fatalf("Mail: %v", err)
	}

	err := c.Rcpt("doesnotexist@localhost")
	if err == nil {
		t.Errorf("Accepted RCPT for non-existent user")
	}
	expect := "550 5.1.1 Destination address is unknown (user does not exist)"
	if err.Error() != expect {
		t.Errorf("RCPT returned unexpected error %q", err.Error())
	}
}

var str1MiB string

func sendLargeEmail(tb testing.TB, c *smtp.Client, sizeMiB int) error {
	tb.Helper()
	if err := c.Mail("from@from"); err != nil {
		tb.Fatalf("Mail: %v", err)
	}
	if err := c.Rcpt("to@localhost"); err != nil {
		tb.Fatalf("Rcpt: %v", err)
	}

	w, err := c.Data()
	if err != nil {
		tb.Fatalf("Data: %v", err)
	}

	if _, err := w.Write([]byte("Subject: I ate too much\n\n")); err != nil {
		tb.Fatalf("Data write: %v", err)
	}

	// Write the 1 MiB string sizeMiB times.
	for i := 0; i < sizeMiB; i++ {
		if _, err := w.Write([]byte(str1MiB)); err != nil {
			tb.Fatalf("Data write: %v", err)
		}
	}

	return w.Close()
}

func TestTooMuchData(t *testing.T) {
	c := mustDial(t, ModeSMTP, true)
	defer c.Close()

	localC.Expect(1)
	err := sendLargeEmail(t, c, maxDataSizeMiB-1)
	if err != nil {
		t.Errorf("Error sending large but ok email: %v", err)
	}
	localC.Wait()

	// Repeat the test - we want to check that the limit applies to each
	// message, not the entire connection.
	localC.Expect(1)
	err = sendLargeEmail(t, c, maxDataSizeMiB-1)
	if err != nil {
		t.Errorf("Error sending large but ok email: %v", err)
	}
	localC.Wait()

	err = sendLargeEmail(t, c, maxDataSizeMiB+1)
	if err == nil || err.Error() != "552 5.3.4 Message too big" {
		t.Fatalf("Expected message too big, got: %v", err)
	}

	// Repeat the test once again, the limit should not prevent connection
	// from continuing.
	localC.Expect(1)
	err = sendLargeEmail(t, c, maxDataSizeMiB-1)
	if err != nil {
		t.Errorf("Error sending large but ok email: %v", err)
	}
	localC.Wait()
}

func simpleCmd(t *testing.T, c *smtp.Client, cmd string, expected int) string {
	t.Helper()
	if err := c.Text.PrintfLine(cmd); err != nil {
		t.Fatalf("Failed to write %s: %v", cmd, err)
	}

	_, msg, err := c.Text.ReadResponse(expected)
	if err != nil {
		t.Errorf("Incorrect %s response: %v", cmd, err)
	}
	return msg
}

func TestSimpleCommands(t *testing.T) {
	c := mustDial(t, ModeSMTP, false)
	defer c.Close()
	simpleCmd(t, c, "HELP", 214)
	simpleCmd(t, c, "NOOP", 250)
	simpleCmd(t, c, "VRFY", 502)
	simpleCmd(t, c, "EXPN", 502)
}

func TestLongLines(t *testing.T) {
	c := mustDial(t, ModeSMTP, false)
	defer c.Close()

	// Send a not-too-long line.
	simpleCmd(t, c, fmt.Sprintf("%1000s", "x"), 500)

	// Send a very long line, expect an error.
	msg := simpleCmd(t, c, fmt.Sprintf("%1001s", "x"), 554)
	if msg != "error reading command: line too long" {
		t.Errorf("Expected 'line too long', got %v", msg)
	}
}

func TestReset(t *testing.T) {
	c := mustDial(t, ModeSMTP, false)
	defer c.Close()

	if err := c.Mail("from@plain"); err != nil {
		t.Fatalf("MAIL FROM: %v", err)
	}

	if err := c.Reset(); err != nil {
		t.Errorf("RSET: %v", err)
	}

	if err := c.Mail("from@plain"); err != nil {
		t.Errorf("MAIL after RSET: %v", err)
	}
}

func TestRepeatedStartTLS(t *testing.T) {
	c, err := smtp.Dial(smtpAddr)
	if err != nil {
		t.Fatalf("smtp.Dial: %v", err)
	}

	if err = c.StartTLS(tlsConfig); err != nil {
		t.Fatalf("StartTLS: %v", err)
	}

	if err = c.StartTLS(tlsConfig); err == nil {
		t.Errorf("Second STARTTLS did not fail as expected")
	}
}

// Test that STARTTLS fails on a TLS connection.
func TestStartTLSOnTLS(t *testing.T) {
	c := mustDial(t, ModeSubmissionTLS, false)
	defer c.Close()

	if err := c.StartTLS(tlsConfig); err == nil {
		t.Errorf("STARTTLS did not fail as expected")
	}
}

//
// === Benchmarks ===
//

func BenchmarkManyEmails(b *testing.B) {
	c := mustDial(b, ModeSMTP, false)
	defer c.Close()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		sendEmail(b, c)
	}
}

func BenchmarkManyEmailsParallel(b *testing.B) {
	b.RunParallel(func(pb *testing.PB) {
		c := mustDial(b, ModeSMTP, false)
		defer c.Close()

		for pb.Next() {
			sendEmail(b, c)
		}
	})
}

//
// === Test environment ===
//

// waitForServer waits 5 seconds for the server to start, and returns an error
// if it fails to do so.
// It does this by repeatedly connecting to the address until it either
// replies or times out. Note we do not do any validation of the reply.
func waitForServer(addr string) error {
	start := time.Now()
	for time.Since(start) < 10*time.Second {
		conn, err := net.Dial("tcp", addr)
		if err == nil {
			conn.Close()
			return nil
		}

		time.Sleep(100 * time.Millisecond)
	}

	return fmt.Errorf("not reachable")
}

type brokenAuthBE struct{}

func (b brokenAuthBE) Authenticate(user, password string) (bool, error) {
	return false, fmt.Errorf("failed to auth")
}

func (b brokenAuthBE) Exists(user string) (bool, error) {
	return false, fmt.Errorf("failed to check if user exists")
}

func (b brokenAuthBE) Reload() error {
	return fmt.Errorf("failed to reload")
}

// realMain is the real main function, which returns the value to pass to
// os.Exit(). We have to do this so we can use defer.
func realMain(m *testing.M) int {
	flag.Parse()

	// Create a 1MiB string, which the large message tests use.
	buf := make([]byte, 1024*1024)
	for i := 0; i < len(buf); i++ {
		buf[i] = 'a'
	}
	str1MiB = string(buf)

	// Set up the mail log to stdout, which is captured by the test runner,
	// so we have better debugging information on failures.
	maillog.Default = maillog.New(os.Stdout)

	if *externalSMTPAddr != "" {
		smtpAddr = *externalSMTPAddr
		submissionAddr = *externalSubmissionAddr
		submissionTLSAddr = *externalSubmissionTLSAddr
		tlsConfig = &tls.Config{
			InsecureSkipVerify: true,
		}
	} else {
		// Generate certificates in a temporary directory.
		tmpDir, err := ioutil.TempDir("", "chasquid_test:")
		if err != nil {
			fmt.Printf("Failed to create temp dir: %v\n", tmpDir)
			return 1
		}
		defer os.RemoveAll(tmpDir)

		tlsConfig, err = testlib.GenerateCert(tmpDir)
		if err != nil {
			fmt.Printf("Failed to generate cert for testing: %v\n", err)
			return 1
		}

		smtpAddr = testlib.GetFreePort()
		submissionAddr = testlib.GetFreePort()
		submissionTLSAddr = testlib.GetFreePort()

		s := NewServer()
		s.Hostname = "localhost"
		s.MaxDataSize = int64(maxDataSizeMiB) * 1024 * 1024
		s.AddCerts(tmpDir+"/cert.pem", tmpDir+"/key.pem")
		s.AddAddr(smtpAddr, ModeSMTP)
		s.AddAddr(submissionAddr, ModeSubmission)
		s.AddAddr(submissionTLSAddr, ModeSubmissionTLS)

		s.InitQueue(tmpDir+"/queue", localC, remoteC)
		s.InitDomainInfo(tmpDir + "/domaininfo")

		udb := userdb.New("/dev/null")
		udb.AddUser("testuser", "testpasswd")
		s.aliasesR.AddAliasForTesting(
			"to@localhost", "testuser@localhost", aliases.EMAIL)
		s.AddDomain("localhost")
		s.AddUserDB("localhost", udb)

		s.AddDomain("broken")
		s.authr.Register("broken", &brokenAuthBE{})

		// Disable SPF lookups, to avoid leaking DNS queries.
		disableSPFForTesting = true

		// Disable reloading.
		reloadEvery = nil

		go s.ListenAndServe()
	}

	waitForServer(smtpAddr)
	waitForServer(submissionAddr)
	waitForServer(submissionTLSAddr)
	return m.Run()
}

func TestMain(m *testing.M) {
	os.Exit(realMain(m))
}