| 1 | package mailyak |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/rand" |
| 7 | "crypto/rsa" |
| 8 | "crypto/tls" |
| 9 | "crypto/x509" |
| 10 | "crypto/x509/pkix" |
| 11 | "encoding/hex" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "math/big" |
| 15 | "net" |
| 16 | "net/smtp" |
| 17 | "reflect" |
| 18 | "testing" |
| 19 | "time" |
| 20 | ) |
| 21 | |
| 22 | var ( |
| 23 | // Test RSA key & self-signed certificate populated by init() |
| 24 | testRSAKey *rsa.PrivateKey |
| 25 | testCertBytes []byte |
| 26 | testCert *x509.Certificate |
| 27 | ) |
| 28 | |
| 29 | // Initialise the TLS certificate and key material for TLS tests. |
| 30 | func init() { |
| 31 | key, err := rsa.GenerateKey(rand.Reader, 2048) |
| 32 | if err != nil { |
| 33 | panic(fmt.Sprintf("failed to generate RSA test key: %v", err)) |
| 34 | } |
| 35 | testRSAKey = key |
| 36 | |
| 37 | // Define the certificate template |
| 38 | self := &x509.Certificate{ |
| 39 | Version: 3, |
| 40 | SerialNumber: big.NewInt(42), |
| 41 | Issuer: pkix.Name{ |
| 42 | CommonName: "CA Bananas Inc", |
| 43 | }, |
| 44 | Subject: pkix.Name{ |
| 45 | CommonName: "The Banana Factory", |
| 46 | }, |
| 47 | NotBefore: time.Now().Add(-1 * time.Hour), |
| 48 | NotAfter: time.Now().Add(time.Hour), |
| 49 | IPAddresses: []net.IP{ |
| 50 | net.IPv4(127, 0, 0, 1), |
| 51 | }, |
| 52 | } |
| 53 | |
| 54 | // Sign the template certificate |
| 55 | cert, err := x509.CreateCertificate(rand.Reader, self, self, &testRSAKey.PublicKey, testRSAKey) |
| 56 | if err != nil { |
| 57 | panic(fmt.Sprintf("failed to generate self-signed test cert: %v", err)) |
| 58 | } |
| 59 | testCertBytes = cert |
| 60 | |
| 61 | // Parse the signed certificate |
| 62 | serverCert, err := x509.ParseCertificate(testCertBytes) |
| 63 | if err != nil { |
| 64 | panic(fmt.Sprintf("failed to bind to localhost: %v", err)) |
| 65 | } |
| 66 | testCert = serverCert |
| 67 | } |
| 68 | |
| 69 | // connAsserts wraps a net.Conn, performing writes and asserts responses within |
| 70 | // tests. |
| 71 | // |
| 72 | // Any errors cause the method to panic. |
| 73 | type connAsserts struct { |
| 74 | net.Conn |
| 75 | |
| 76 | t *testing.T |
| 77 | buf *bytes.Buffer |
| 78 | } |
| 79 | |
| 80 | func (c *connAsserts) Read(b []byte) (n int, err error) { |
| 81 | n, err = c.Conn.Read(b) |
| 82 | c.t.Logf("MailYak -> Server:\n%s\n", hex.Dump(b)) |
| 83 | return n, err |
| 84 | } |
| 85 | |
| 86 | func (c *connAsserts) Write(b []byte) (n int, err error) { |
| 87 | n, err = c.Conn.Write(b) |
| 88 | c.t.Logf("Server -> MailYak:\n%s\n", hex.Dump(b)) |
| 89 | return n, err |
| 90 | } |
| 91 | |
| 92 | func (c *connAsserts) Expect(want string) { |
| 93 | c.buf.Reset() |
| 94 | |
| 95 | n, err := io.CopyN(c.buf, c, int64(len(want))) |
| 96 | if err != nil { |
| 97 | c.t.Fatalf("got error %v after reading %d bytes (got %q, want %q)", err, n, c.buf.String(), want) |
| 98 | } |
| 99 | if c.buf.String() != want { |
| 100 | c.t.Fatalf("read %q, want %q", c.buf.String(), want) |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | func (c *connAsserts) Respond(put string) { |
| 105 | n, err := c.Write([]byte(put)) |
| 106 | if err != nil { |
| 107 | c.t.Fatalf("got error %v writing %q (wrote %d bytes)", err, put, n) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | func newConnAsserts(c net.Conn, t *testing.T) *connAsserts { |
| 112 | return &connAsserts{ |
| 113 | Conn: c, |
| 114 | t: t, |
| 115 | buf: &bytes.Buffer{}, |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | // mockMail provides the methods for a sendableMail, allowing for deterministic |
| 120 | // MIME content in tests. |
| 121 | type mockMail struct { |
| 122 | localName string |
| 123 | toAddrs []string |
| 124 | fromAddr string |
| 125 | auth smtp.Auth |
| 126 | mime string |
| 127 | } |
| 128 | |
| 129 | // getLocalName should return the sender domain to be used in the EHLO/HELO |
| 130 | // command. |
| 131 | func (m *mockMail) getLocalName() string { |
| 132 | return m.localName |
| 133 | } |
| 134 | |
| 135 | // toAddrs should return a slice of email addresses to be added to the RCPT |
| 136 | // TO command. |
| 137 | func (m *mockMail) getToAddrs() []string { |
| 138 | return stripNames(m.toAddrs) |
| 139 | } |
| 140 | |
| 141 | // fromAddr should return the address to be used in the MAIL FROM command. |
| 142 | func (m *mockMail) getFromAddr() string { |
| 143 | return m.fromAddr |
| 144 | } |
| 145 | |
| 146 | // auth should return the smtp.Auth if configured, nil if not. |
| 147 | func (m *mockMail) getAuth() smtp.Auth { |
| 148 | return m.auth |
| 149 | } |
| 150 | |
| 151 | // buildMime should write the generated MIME to w. |
| 152 | // |
| 153 | // The emailSender implementation is responsible for providing appropriate |
| 154 | // buffering of writes. |
| 155 | func (m *mockMail) buildMime(w io.Writer) error { |
| 156 | _, err := w.Write([]byte(m.mime)) |
| 157 | return err |
| 158 | } |
| 159 | |
| 160 | // TestSMTPProtocolExchange sends the same mock email over two different |
| 161 | // transports using two different sender implementations, ensuring parity |
| 162 | // between the two (specifically that both impleementations result in the same |
| 163 | // SMTP conversation). |
| 164 | // |
| 165 | // Because the mock server in the tests does not advertise STARTTLS support in, |
| 166 | // there is no upgrade. |
| 167 | func TestSMTPProtocolExchange(t *testing.T) { |
| 168 | t.Parallel() |
| 169 | |
| 170 | const testTimeout = 15 * time.Second |
| 171 | |
| 172 | tests := []struct { |
| 173 | name string |
| 174 | mail *mockMail |
| 175 | |
| 176 | // Called once the Send() method is invoked, impersonating and asserting |
| 177 | // the client/server conversation. |
| 178 | connFn func(c *connAsserts) |
| 179 | |
| 180 | // Error returned when sending over TLS |
| 181 | wantTLSErr error |
| 182 | |
| 183 | // Error returned when sending over plaintext |
| 184 | wantPlaintextErr error |
| 185 | }{ |
| 186 | { |
| 187 | name: "ok", |
| 188 | mail: &mockMail{ |
| 189 | toAddrs: []string{ |
| 190 | "[email protected]", |
| 191 | "[email protected]", |
| 192 | "Dom <[email protected]>", |
| 193 | }, |
| 194 | fromAddr: "[email protected]", |
| 195 | mime: "bananas", |
| 196 | }, |
| 197 | connFn: func(c *connAsserts) { |
| 198 | c.Respond("220 localhost ESMTP bananas\r\n") |
| 199 | |
| 200 | c.Expect("EHLO localhost\r\n") |
| 201 | c.Respond("250-localhost Hola\r\n") |
| 202 | c.Respond("250 AUTH LOGIN PLAIN\r\n") |
| 203 | |
| 204 | c.Expect("MAIL FROM:<[email protected]>\r\n") |
| 205 | c.Respond("250 OK\r\n") |
| 206 | |
| 207 | c.Expect("RCPT TO:<[email protected]>\r\n") |
| 208 | c.Respond("250 OK\r\n") |
| 209 | |
| 210 | c.Expect("RCPT TO:<[email protected]>\r\n") |
| 211 | c.Respond("250 OK\r\n") |
| 212 | |
| 213 | c.Expect("RCPT TO:<[email protected]>\r\n") |
| 214 | c.Respond("250 OK\r\n") |
| 215 | |
| 216 | c.Expect("DATA\r\n") |
| 217 | c.Respond("354 OK\r\n") |
| 218 | c.Expect("bananas\r\n.\r\n") |
| 219 | c.Respond("250 Will do friend\r\n") |
| 220 | |
| 221 | c.Expect("QUIT\r\n") |
| 222 | c.Respond("221 Adios\r\n") |
| 223 | }, |
| 224 | wantTLSErr: nil, |
| 225 | wantPlaintextErr: nil, |
| 226 | }, |
| 227 | { |
| 228 | name: "with auth", |
| 229 | mail: &mockMail{ |
| 230 | toAddrs: []string{ |
| 231 | "[email protected]", |
| 232 | "[email protected]", |
| 233 | "[email protected]", |
| 234 | }, |
| 235 | fromAddr: "[email protected]", |
| 236 | mime: "bananas", |
| 237 | auth: smtp.PlainAuth("ident", "user", "pass", "127.0.0.1"), |
| 238 | }, |
| 239 | connFn: func(c *connAsserts) { |
| 240 | c.Respond("220 localhost ESMTP bananas\r\n") |
| 241 | |
| 242 | c.Expect("EHLO localhost\r\n") |
| 243 | c.Respond("250-localhost Hola\r\n") |
| 244 | c.Respond("250 AUTH LOGIN PLAIN\r\n") |
| 245 | |
| 246 | c.Expect("AUTH PLAIN aWRlbnQAdXNlcgBwYXNz\r\n") |
| 247 | c.Respond("235 Looks good\r\n") |
| 248 | |
| 249 | c.Expect("MAIL FROM:<[email protected]>\r\n") |
| 250 | c.Respond("250 OK\r\n") |
| 251 | |
| 252 | c.Expect("RCPT TO:<[email protected]>\r\n") |
| 253 | c.Respond("250 OK\r\n") |
| 254 | |
| 255 | c.Expect("RCPT TO:<[email protected]>\r\n") |
| 256 | c.Respond("250 OK\r\n") |
| 257 | |
| 258 | c.Expect("RCPT TO:<[email protected]>\r\n") |
| 259 | c.Respond("250 OK\r\n") |
| 260 | |
| 261 | c.Expect("DATA\r\n") |
| 262 | c.Respond("354 OK\r\n") |
| 263 | c.Expect("bananas\r\n.\r\n") |
| 264 | c.Respond("250 Will do friend\r\n") |
| 265 | |
| 266 | c.Expect("QUIT\r\n") |
| 267 | c.Respond("221 Adios\r\n") |
| 268 | }, |
| 269 | wantTLSErr: nil, |
| 270 | wantPlaintextErr: nil, |
| 271 | }, |
| 272 | { |
| 273 | name: "with localname", |
| 274 | mail: &mockMail{ |
| 275 | toAddrs: []string{ |
| 276 | "[email protected]", |
| 277 | "[email protected]", |
| 278 | "Dom <[email protected]>", |
| 279 | }, |
| 280 | fromAddr: "[email protected]", |
| 281 | mime: "bananas", |
| 282 | localName: "example.com", |
| 283 | }, |
| 284 | connFn: func(c *connAsserts) { |
| 285 | c.Respond("220 localhost ESMTP bananas\r\n") |
| 286 | |
| 287 | c.Expect("EHLO example.com\r\n") |
| 288 | c.Respond("250-example.com Hola\r\n") |
| 289 | c.Respond("250 AUTH LOGIN PLAIN\r\n") |
| 290 | |
| 291 | c.Expect("MAIL FROM:<[email protected]>\r\n") |
| 292 | c.Respond("250 OK\r\n") |
| 293 | |
| 294 | c.Expect("RCPT TO:<[email protected]>\r\n") |
| 295 | c.Respond("250 OK\r\n") |
| 296 | |
| 297 | c.Expect("RCPT TO:<[email protected]>\r\n") |
| 298 | c.Respond("250 OK\r\n") |
| 299 | |
| 300 | c.Expect("RCPT TO:<[email protected]>\r\n") |
| 301 | c.Respond("250 OK\r\n") |
| 302 | |
| 303 | c.Expect("DATA\r\n") |
| 304 | c.Respond("354 OK\r\n") |
| 305 | c.Expect("bananas\r\n.\r\n") |
| 306 | c.Respond("250 Will do friend\r\n") |
| 307 | |
| 308 | c.Expect("QUIT\r\n") |
| 309 | c.Respond("221 Adios\r\n") |
| 310 | }, |
| 311 | wantTLSErr: nil, |
| 312 | wantPlaintextErr: nil, |
| 313 | }, |
| 314 | } |
| 315 | |
| 316 | // handleConn provides the accept loop for both the TLS server, and the |
| 317 | // plain-text server, passing the accepted connection to the test actor |
| 318 | // func. |
| 319 | // |
| 320 | // Once the actor func has finished, done is closed. |
| 321 | handleConn := func(t *testing.T, l net.Listener, done chan<- struct{}, actor func(c *connAsserts)) { |
| 322 | defer close(done) |
| 323 | |
| 324 | conn, err := l.Accept() |
| 325 | if err != nil { |
| 326 | panic(err) |
| 327 | } |
| 328 | defer conn.Close() |
| 329 | |
| 330 | actor(newConnAsserts(conn, t)) |
| 331 | } |
| 332 | |
| 333 | for _, tt := range tests { |
| 334 | tt := tt |
| 335 | t.Run(tt.name, func(t *testing.T) { |
| 336 | t.Parallel() |
| 337 | |
| 338 | // Send the mock email over each implementation of the sender |
| 339 | // interface, including initialisation with the respective MailYak |
| 340 | // constructor. |
| 341 | |
| 342 | t.Run("Explicit_TLS", func(t *testing.T) { |
| 343 | t.Parallel() |
| 344 | |
| 345 | ctx, cancel := context.WithTimeout(context.Background(), testTimeout) |
| 346 | defer cancel() |
| 347 | |
| 348 | // Initialise a server TLS config using the self-signed test |
| 349 | // certificate and key material. |
| 350 | serverConfig := &tls.Config{ |
| 351 | Certificates: []tls.Certificate{ |
| 352 | { |
| 353 | Certificate: [][]byte{testCertBytes}, |
| 354 | PrivateKey: testRSAKey, |
| 355 | }, |
| 356 | }, |
| 357 | } |
| 358 | |
| 359 | // Bind a TLS-enabled TCP socket to some random port |
| 360 | socket, err := tls.Listen("tcp", "127.0.0.1:0", serverConfig) |
| 361 | if err != nil { |
| 362 | t.Fatalf("failed to bind to localhost: %v", err) |
| 363 | } |
| 364 | defer socket.Close() |
| 365 | |
| 366 | handlerDone := make(chan struct{}) |
| 367 | go handleConn(t, socket, handlerDone, tt.connFn) |
| 368 | |
| 369 | // Build a root store for the self-signed certificate. |
| 370 | roots := x509.NewCertPool() |
| 371 | roots.AddCert(testCert) |
| 372 | |
| 373 | // Initialise a TLS mailyak using the root store. |
| 374 | m, err := NewWithTLS(socket.Addr().String(), nil, &tls.Config{ |
| 375 | RootCAs: roots, |
| 376 | ServerName: "127.0.0.1", |
| 377 | }) |
| 378 | if err != nil { |
| 379 | t.Fatal(err) |
| 380 | } |
| 381 | |
| 382 | // Call into the sender directly, giving it the mock |
| 383 | // sendableEmail |
| 384 | sendErr := make(chan error) |
| 385 | go func() { |
| 386 | sendErr <- m.sender.Send(tt.mail) |
| 387 | }() |
| 388 | |
| 389 | // Wait for the SMTP conversation to complete |
| 390 | select { |
| 391 | case <-ctx.Done(): |
| 392 | t.Fatal("timeout waiting for SMTP conversation to complete") |
| 393 | case <-handlerDone: |
| 394 | // The handler is complete, wait for the send error and |
| 395 | // check it matches the expected value. |
| 396 | select { |
| 397 | case <-ctx.Done(): |
| 398 | t.Fatal("timeout waiting for Send() to return") |
| 399 | |
| 400 | case err := <-sendErr: |
| 401 | if !reflect.DeepEqual(err, tt.wantTLSErr) { |
| 402 | t.Errorf("got %v, want %v", err, tt.wantTLSErr) |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | }) |
| 407 | |
| 408 | t.Run("Plaintext", func(t *testing.T) { |
| 409 | t.Parallel() |
| 410 | |
| 411 | ctx, cancel := context.WithTimeout(context.Background(), testTimeout) |
| 412 | defer cancel() |
| 413 | |
| 414 | // Start listening to a local plain-text socket |
| 415 | socket, err := net.Listen("tcp", "127.0.0.1:0") |
| 416 | if err != nil { |
| 417 | t.Fatalf("failed to bind to localhost: %v", err) |
| 418 | } |
| 419 | defer socket.Close() |
| 420 | |
| 421 | handlerDone := make(chan struct{}) |
| 422 | go handleConn(t, socket, handlerDone, tt.connFn) |
| 423 | |
| 424 | m := New(socket.Addr().String(), nil) |
| 425 | |
| 426 | // Call into the sender directly, giving it the mock |
| 427 | // sendableEmail |
| 428 | sendErr := make(chan error) |
| 429 | go func() { |
| 430 | sendErr <- m.sender.Send(tt.mail) |
| 431 | }() |
| 432 | |
| 433 | // Wait for the SMTP conversation to complete |
| 434 | select { |
| 435 | case <-ctx.Done(): |
| 436 | t.Fatal("timeout waiting for SMTP conversation to complete") |
| 437 | case <-handlerDone: |
| 438 | // The handler is complete, wait for the send error and |
| 439 | // check it matches the expected value. |
| 440 | select { |
| 441 | case <-ctx.Done(): |
| 442 | t.Fatal("timeout waiting for Send() to return") |
| 443 | |
| 444 | case err := <-sendErr: |
| 445 | if !reflect.DeepEqual(err, tt.wantPlaintextErr) { |
| 446 | t.Errorf("got %v, want %v", err, tt.wantPlaintextErr) |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | }) |
| 451 | }) |
| 452 | } |
| 453 | } |