SMTPServerSTARTTLS starts a server listening on the specified addr with the STARTTLS extension supported. Returned *tls.Config is for the client and is set to trust the server certificate.
(t *testing.T, addr string, fn ...SMTPServerConfigureFunc)
| 274 | // Returned *tls.Config is for the client and is set to trust the server |
| 275 | // certificate. |
| 276 | func SMTPServerSTARTTLS(t *testing.T, addr string, fn ...SMTPServerConfigureFunc) (*tls.Config, *SMTPBackend, *smtp.Server) { |
| 277 | t.Helper() |
| 278 | |
| 279 | cert, err := tls.X509KeyPair([]byte(testServerCert), []byte(testServerKey)) |
| 280 | if err != nil { |
| 281 | panic(err) |
| 282 | } |
| 283 | |
| 284 | l, err := net.Listen("tcp", addr) |
| 285 | if err != nil { |
| 286 | t.Fatal(err) |
| 287 | } |
| 288 | |
| 289 | be := new(SMTPBackend) |
| 290 | s := smtp.NewServer(be) |
| 291 | s.Domain = "localhost" |
| 292 | s.AllowInsecureAuth = true |
| 293 | s.TLSConfig = &tls.Config{ |
| 294 | Certificates: []tls.Certificate{cert}, |
| 295 | } |
| 296 | for _, f := range fn { |
| 297 | f(s) |
| 298 | } |
| 299 | |
| 300 | pool := x509.NewCertPool() |
| 301 | pool.AppendCertsFromPEM([]byte(testServerCert)) |
| 302 | |
| 303 | clientCfg := &tls.Config{ |
| 304 | ServerName: "127.0.0.1", |
| 305 | Time: func() time.Time { |
| 306 | return time.Date(2019, time.November, 18, 17, 59, 41, 0, time.UTC) |
| 307 | }, |
| 308 | RootCAs: pool, |
| 309 | } |
| 310 | |
| 311 | go func() { |
| 312 | if err := s.Serve(l); err != nil { |
| 313 | t.Error(err) |
| 314 | } |
| 315 | }() |
| 316 | |
| 317 | // Dial it once it make sure Server completes its initialization before |
| 318 | // we try to use it. Notably, if test fails before connecting to the server, |
| 319 | // it will call Server.Close which will call Server.listener.Close with a |
| 320 | // nil Server.listener (Serve sets it to a non-nil value, so it is racy and |
| 321 | // happens only sometimes). |
| 322 | testConn, err := net.Dial("tcp", addr) |
| 323 | require.NoError(t, err) |
| 324 | require.NoError(t, testConn.Close()) |
| 325 | |
| 326 | return clientCfg, be, s |
| 327 | } |
| 328 | |
| 329 | // SMTPServerTLS starts a SMTP server listening on the specified addr with |
| 330 | // Implicit TLS. |