Debian Codegraph @

pkg/services/email/smtp/smtp_session_test.go

raw
1 package smtp
2
3 import (
4 "bytes"
5 "crypto/hmac"
6 "crypto/md5"
7 "encoding/base64"
8 "encoding/hex"
9 "io"
10 "log"
11 "mime"
12 "mime/multipart"
13 "net/mail"
14 "net/smtp"
15 "net/url"
16 "os"
17 "strings"
18 "time"
19
20 ginkgo "github.com/onsi/ginkgo/v2"
21 gomega "github.com/onsi/gomega"
22
23 "github.com/nicholas-fedor/shoutrrr/internal/testutils"
24 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
25 )
26
27 var _ = ginkgo.Describe("session", func() {
28 ginkgo.BeforeEach(func() {
29 service = &Service{}
30 })
31
32 ginkgo.Describe("ehloName", func() {
33 ginkgo.When("clienthost is set to auto", func() {
34 ginkgo.It("should return the os hostname", func() {
35 hostname, err := os.Hostname()
36 gomega.Expect(err).ToNot(gomega.HaveOccurred())
37 gomega.Expect((&session{config: &Config{ClientHost: "auto"}, svc: service}).ehloName()).
38 To(gomega.Equal(hostname))
39 })
40 })
41
42 ginkgo.When("clienthost is set to a custom value", func() {
43 ginkgo.It("should return that value", func() {
44 gomega.Expect((&session{config: &Config{ClientHost: "computah"}, svc: service}).ehloName()).
45 To(gomega.Equal("computah"))
46 })
47 })
48 })
49
50 ginkgo.Describe("auth", func() {
51 ginkgo.It("should succeed without AUTH when Auth is None", func() {
52 sess := &session{config: &Config{Auth: AuthTypes.None}, svc: service}
53 gomega.Expect(sess.auth()).To(gomega.Succeed())
54 })
55
56 ginkgo.It("should fail when Auth is Unknown", func() {
57 sess := &session{config: &Config{Auth: AuthTypes.Unknown}, svc: service}
58 gomega.Expect(sess.auth()).To(matchFailure(FailAuthType))
59 })
60 })
61
62 ginkgo.Describe("closeIfOpen", func() {
63 ginkgo.It("should not close an already closed session", func() {
64 textCon, _ := testutils.CreateTextConFaker(nil, "\r\n")
65 client := &smtp.Client{Text: textCon}
66 mock := &mockConn{}
67 injectConn(client, mock)
68
69 sess := &session{closed: true, client: client, svc: service}
70 sess.closeIfOpen()
71 gomega.Expect(mock.closeCount).To(gomega.BeZero())
72
73 sess.closed = false
74 sess.closeIfOpen()
75 gomega.Expect(mock.closeCount).To(gomega.Equal(1))
76 gomega.Expect(sess.closed).To(gomega.BeTrue())
77 })
78 })
79
80 ginkgo.When("sending an HTML message", func() {
81 ginkgo.It("should use the same multipart boundary in the Content-Type header and body", func() {
82 gomega.Expect(service.Initialize(testutils.URLMust(baseNoAuthURL), logger)).To(gomega.Succeed())
83
84 textCon, tcfaker := testutils.CreateTextConFaker([]string{
85 "250-mx.google.com at your service",
86 "250 8BITMIME",
87 "250 Sender OK",
88 "250 Receiver OK",
89 "354 Go ahead",
90 "250 Data OK",
91 "221 OK",
92 }, "\r\n")
93 client := &smtp.Client{Text: textCon}
94 fakeTLSEnabled(client, "example.com")
95
96 config := service.Config.Clone()
97 config.UseHTML = true
98 gomega.Expect(runSMTPSession(service, client, &config)).To(gomega.Succeed())
99
100 received := tcfaker.GetClientSentences()
101 boundary := ""
102
103 for _, line := range received {
104 if rest, ok := strings.CutPrefix(line, "Content-Type: multipart/alternative; boundary="); ok {
105 boundary = rest
106
107 break
108 }
109 }
110
111 gomega.Expect(boundary).NotTo(gomega.BeEmpty())
112 gomega.Expect(received).To(gomega.ContainElement("--" + boundary))
113 gomega.Expect(received).To(gomega.ContainElement("--" + boundary + "--"))
114
115 payload := dataPayload(received)
116 msg, err := mail.ReadMessage(strings.NewReader(payload))
117 gomega.Expect(err).NotTo(gomega.HaveOccurred())
118 gomega.Expect(msg.Header.Get("MIME-Version")).To(gomega.Equal("1.0"))
119 _, parseErr := time.Parse(time.RFC1123Z, msg.Header.Get("Date"))
120 gomega.Expect(parseErr).NotTo(gomega.HaveOccurred())
121
122 mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
123 gomega.Expect(err).NotTo(gomega.HaveOccurred())
124 gomega.Expect(mediaType).To(gomega.Equal("multipart/alternative"))
125
126 mr := multipart.NewReader(msg.Body, params["boundary"])
127 plainPart, err := mr.NextPart()
128 gomega.Expect(err).NotTo(gomega.HaveOccurred())
129 plainBody, err := io.ReadAll(plainPart)
130 gomega.Expect(err).NotTo(gomega.HaveOccurred())
131 gomega.Expect(string(plainBody)).To(gomega.ContainSubstring("Test message"))
132
133 htmlPart, err := mr.NextPart()
134 gomega.Expect(err).NotTo(gomega.HaveOccurred())
135 htmlBody, err := io.ReadAll(htmlPart)
136 gomega.Expect(err).NotTo(gomega.HaveOccurred())
137 gomega.Expect(string(htmlBody)).To(gomega.ContainSubstring("Test message"))
138 })
139 })
140
141 ginkgo.Describe("message body", func() {
142 ginkgo.It("should send an empty body without error", func() {
143 gomega.Expect(service.Initialize(testutils.URLMust(baseNoAuthURL), logger)).To(gomega.Succeed())
144
145 textCon, tcfaker := testutils.CreateTextConFaker([]string{
146 "250-mx.google.com at your service",
147 "250 8BITMIME",
148 "250 Sender OK",
149 "250 Receiver OK",
150 "354 Go ahead",
151 "250 Data OK",
152 "221 OK",
153 }, "\r\n")
154 client := &smtp.Client{Text: textCon}
155 fakeTLSEnabled(client, "example.com")
156 gomega.Expect(runSMTPSessionMessage(service, client, service.Config, "")).To(gomega.Succeed())
157 gomega.Expect(tcfaker.GetClientSentences()).To(gomega.ContainElement("DATA"))
158 })
159 })
160
161 ginkgo.Describe("recipient headers", func() {
162 ginkgo.It("should not emit Cc or Bcc headers for envelope-only recipients", func() {
163 gomega.Expect(service.Initialize(testutils.URLMust(baseAuthURL), logger)).To(gomega.Succeed())
164
165 textCon, tcfaker := testutils.CreateTextConFaker([]string{
166 "250-mx.google.com at your service",
167 "250-AUTH LOGIN PLAIN",
168 "250 8BITMIME",
169 "235 Accepted",
170 "250 Sender OK",
171 "250 Receiver OK",
172 "354 Go ahead",
173 "250 Data OK",
174 "250 Reset OK",
175 "250 Sender OK",
176 "250 Receiver OK",
177 "354 Go ahead",
178 "250 Data OK",
179 "221 OK",
180 }, "\r\n")
181 client := &smtp.Client{Text: textCon}
182 fakeTLSEnabled(client, "example.com")
183 gomega.Expect(runSMTPSession(service, client, service.Config)).To(gomega.Succeed())
184
185 received := tcfaker.GetClientSentences()
186 gomega.Expect(headerLines(received, "To")).To(gomega.Equal([]string{
187 "To: <[email protected]>",
188 "To: <[email protected]>",
189 }))
190 gomega.Expect(headerLines(received, "Cc")).To(gomega.BeEmpty())
191 gomega.Expect(headerLines(received, "Bcc")).To(gomega.BeEmpty())
192 })
193 })
194
195 ginkgo.When("running integration tests", func() {
196 ginkgo.When("given a typical usage case configuration URL", func() {
197 ginkgo.It("should send notifications without any errors", func() {
198 err := testIntegration(baseAuthURL, []string{
199 "250-mx.google.com at your service",
200 "250-SIZE 35651584",
201 "250-AUTH LOGIN PLAIN",
202 "250 8BITMIME",
203 "235 Accepted",
204 "250 Sender OK",
205 "250 Receiver OK",
206 "354 Go ahead",
207 "250 Data OK",
208 "250 Reset OK",
209 "250 Sender OK",
210 "250 Receiver OK",
211 "354 Go ahead",
212 "250 Data OK",
213 "221 OK",
214 }, "<pre>{{ .message }}</pre>", "{{ .message }}",
215 "AUTH PLAIN AHVzZXIAcGFzc3dvcmQ=",
216 "To: <[email protected]>",
217 "To: <[email protected]>",
218 )
219 skipIfTestSetup(err)
220 gomega.Expect(err).NotTo(gomega.HaveOccurred())
221 })
222 })
223
224 ginkgo.When("given auth=Login", func() {
225 ginkgo.It("should complete the multi-step AUTH LOGIN dialog", func() {
226 testURL := modifyURL(baseAuthURL, map[string]string{
227 "auth": "Login",
228 "useHTML": "no",
229 })
230
231 err := testIntegration(testURL, []string{
232 "250-mx.google.com at your service",
233 "250-SIZE 35651584",
234 "250-AUTH LOGIN PLAIN",
235 "250 8BITMIME",
236 "334 VXNlciBOYW1lAA==",
237 "334 UGFzc3dvcmQ=",
238 "235 Accepted",
239 "250 Sender OK",
240 "250 Receiver OK",
241 "354 Go ahead",
242 "250 Data OK",
243 "250 Reset OK",
244 "250 Sender OK",
245 "250 Receiver OK",
246 "354 Go ahead",
247 "250 Data OK",
248 "221 OK",
249 }, "", "",
250 "AUTH LOGIN",
251 "dXNlcg==",
252 "cGFzc3dvcmQ=",
253 )
254 skipIfTestSetup(err)
255 gomega.Expect(err).NotTo(gomega.HaveOccurred())
256 })
257
258 ginkgo.It("should fail when the server rejects LOGIN with 535", func() {
259 testURL := modifyURL(baseAuthURL, map[string]string{
260 "auth": "Login",
261 "useHTML": "no",
262 })
263
264 err := testIntegration(testURL, []string{
265 "250-mx.google.com at your service",
266 "250-AUTH LOGIN PLAIN",
267 "250 8BITMIME",
268 "334 VXNlciBOYW1lAA==",
269 "334 UGFzc3dvcmQ=",
270 "535 5.7.8 Authentication failed",
271 }, "", "")
272 skipIfTestSetup(err)
273 gomega.Expect(err).To(matchFailure(FailAuthenticating))
274 })
275 })
276
277 ginkgo.When("given auth=OAuth2", func() {
278 ginkgo.It("should send AUTH XOAUTH2 with the Bearer token and succeed on 235", func() {
279 testURL := modifyURL(baseAuthURL, map[string]string{
280 "auth": "OAuth2",
281 "useHTML": "no",
282 })
283
284 err := testIntegration(testURL, []string{
285 "250-mx.google.com at your service",
286 "250-AUTH XOAUTH2",
287 "250 8BITMIME",
288 "235 Accepted",
289 "250 Sender OK",
290 "250 Receiver OK",
291 "354 Go ahead",
292 "250 Data OK",
293 "250 Reset OK",
294 "250 Sender OK",
295 "250 Receiver OK",
296 "354 Go ahead",
297 "250 Data OK",
298 "221 OK",
299 }, "", "",
300 "AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIHBhc3N3b3JkAQE=",
301 )
302 skipIfTestSetup(err)
303 gomega.Expect(err).NotTo(gomega.HaveOccurred())
304 })
305
306 ginkgo.It("should fail AUTH when the server returns 334 then 535", func() {
307 testURL := modifyURL(baseAuthURL, map[string]string{
308 "auth": "OAuth2",
309 "useHTML": "no",
310 })
311
312 err := testIntegration(testURL, []string{
313 "250-mx.google.com at your service",
314 "250-AUTH XOAUTH2",
315 "250 8BITMIME",
316 "334 eyJzdGF0dXMiOiI0MDAifQ==",
317 "535 5.7.8 Username and Password not accepted",
318 }, "", "")
319 skipIfTestSetup(err)
320 gomega.Expect(err).To(matchFailure(FailAuthenticating))
321 gomega.Expect(err.Error()).NotTo(gomega.ContainSubstring("password"))
322 })
323 })
324
325 ginkgo.When("given auth=CRAMMD5", func() {
326 ginkgo.It("should respond to the challenge with an HMAC-MD5 digest", func() {
327 testURL := modifyURL(baseAuthURL, map[string]string{
328 "auth": "CRAMMD5",
329 "useHTML": "no",
330 })
331 challenge := "<[email protected]>"
332 mac := hmac.New(md5.New, []byte("password"))
333 _, _ = mac.Write([]byte(challenge))
334 digest := hex.EncodeToString(mac.Sum(nil))
335 response := base64.StdEncoding.EncodeToString([]byte("user " + digest))
336
337 err := testIntegration(testURL, []string{
338 "250-mx.google.com at your service",
339 "250-AUTH CRAM-MD5",
340 "250 8BITMIME",
341 "334 " + base64.StdEncoding.EncodeToString([]byte(challenge)),
342 "235 Accepted",
343 "250 Sender OK",
344 "250 Receiver OK",
345 "354 Go ahead",
346 "250 Data OK",
347 "250 Reset OK",
348 "250 Sender OK",
349 "250 Receiver OK",
350 "354 Go ahead",
351 "250 Data OK",
352 "221 OK",
353 }, "", "",
354 "AUTH CRAM-MD5",
355 response,
356 )
357 skipIfTestSetup(err)
358 gomega.Expect(err).NotTo(gomega.HaveOccurred())
359 })
360 })
361
362 ginkgo.When("AUTH is not advertised", func() {
363 ginkgo.It("should still attempt AUTH and fail when the server rejects it", func() {
364 err := testIntegration(baseAuthURL, []string{
365 "250-mx.google.com at your service",
366 "250 8BITMIME",
367 "503 5.5.1 AUTH not advertised",
368 }, "", "")
369 skipIfTestSetup(err)
370 gomega.Expect(err).To(matchFailure(FailAuthenticating))
371 })
372 })
373
374 ginkgo.When("credentials are empty", func() {
375 ginkgo.It("should send AUTH PLAIN with an empty identity payload", func() {
376 testURL := "smtp://example.com:2225/?auth=Plain&useStartTLS=no" +
377 "&[email protected]&[email protected]&timeout=10s"
378
379 err := testIntegration(testURL, []string{
380 "250-mx.google.com at your service",
381 "250-AUTH PLAIN",
382 "250 8BITMIME",
383 "535 5.7.8 empty credentials",
384 }, "", "",
385 "AUTH PLAIN AAA=",
386 )
387 skipIfTestSetup(err)
388 gomega.Expect(err).To(matchFailure(FailAuthenticating))
389 })
390 })
391
392 ginkgo.When("PLAIN is used without TLS on a remote host", func() {
393 ginkgo.It("should refuse to send credentials", func() {
394 err := testIntegrationWithoutTLS(baseAuthURL, []string{
395 "250-mx.google.com at your service",
396 "250-AUTH PLAIN",
397 "250 8BITMIME",
398 })
399 skipIfTestSetup(err)
400 gomega.Expect(err).To(matchFailure(FailAuthenticating))
401 })
402 })
403
404 ginkgo.When("encryption is None", func() {
405 ginkgo.It("should still issue STARTTLS when usestarttls is yes", func() {
406 testURL := modifyURL(baseNoAuthURL, map[string]string{
407 "encryption": "None",
408 "useStartTLS": "yes",
409 })
410
411 err := testIntegration(testURL, []string{
412 "250-mx.google.com at your service",
413 "250-STARTTLS",
414 "250 8BITMIME",
415 "502 That's too hard",
416 }, "", "",
417 "STARTTLS",
418 )
419 skipIfTestSetup(err)
420 gomega.Expect(err).To(matchFailure(FailEnableStartTLS))
421 })
422
423 ginkgo.It("should not issue STARTTLS when usestarttls is no", func() {
424 testURL := modifyURL(baseNoAuthURL, map[string]string{
425 "encryption": "None",
426 "useStartTLS": "no",
427 })
428
429 gomega.Expect(service.Initialize(testutils.URLMust(testURL), logger)).To(gomega.Succeed())
430
431 textCon, tcfaker := testutils.CreateTextConFaker([]string{
432 "250-mx.google.com at your service",
433 "250-STARTTLS",
434 "250 8BITMIME",
435 "250 Sender OK",
436 "250 Receiver OK",
437 "354 Go ahead",
438 "250 Data OK",
439 "221 OK",
440 }, "\r\n")
441 client := &smtp.Client{Text: textCon}
442 fakeTLSEnabled(client, "example.com")
443 gomega.Expect(runSMTPSession(service, client, service.Config)).To(gomega.Succeed())
444 gomega.Expect(tcfaker.GetClientSentences()).NotTo(gomega.ContainElement("STARTTLS"))
445 })
446 })
447
448 ginkgo.When("no recipients are configured at send time", func() {
449 ginkgo.It("should fail with ErrToAddressMissing", func() {
450 gomega.Expect(service.Initialize(testutils.URLMust(baseNoAuthURL), logger)).To(gomega.Succeed())
451
452 textCon, _ := testutils.CreateTextConFaker(nil, "\r\n")
453 client := &smtp.Client{Text: textCon}
454 config := service.Config.Clone()
455 config.ToAddresses = nil
456 err := runSMTPSession(service, client, &config)
457 gomega.Expect(err).To(matchFailure(FailSendRecipient))
458 gomega.Expect(err).To(gomega.MatchError(ErrToAddressMissing))
459 })
460 })
461
462 ginkgo.When("given e-mail addresses with pluses in the configuration URL", func() {
463 ginkgo.It("should send notifications without any errors", func() {
464 err := testIntegration(basePlusURL, []string{
465 "250-mx.google.com at your service",
466 "250-SIZE 35651584",
467 "250-AUTH LOGIN PLAIN",
468 "250 8BITMIME",
469 "235 Accepted",
470 "250 Sender OK",
471 "250 Receiver OK",
472 "354 Go ahead",
473 "250 Data OK",
474 "250 Reset OK",
475 "250 Sender OK",
476 "250 Receiver OK",
477 "354 Go ahead",
478 "250 Data OK",
479 "221 OK",
480 }, "<pre>{{ .message }}</pre>", "{{ .message }}",
481 "RCPT TO:<[email protected]>",
482 "To: <[email protected]>",
483 "From: <[email protected]>")
484 skipIfTestSetup(err)
485 gomega.Expect(err).NotTo(gomega.HaveOccurred())
486 })
487 })
488
489 ginkgo.When("given a configuration URL with authentication disabled", func() {
490 ginkgo.It("should send notifications without any errors", func() {
491 err := testIntegration(baseNoAuthURL, []string{
492 "250-mx.google.com at your service",
493 "250-SIZE 35651584",
494 "250-AUTH LOGIN PLAIN",
495 "250 8BITMIME",
496 "250 Sender OK",
497 "250 Receiver OK",
498 "354 Go ahead",
499 "250 Data OK",
500 "221 OK",
501 }, "", "")
502 skipIfTestSetup(err)
503 gomega.Expect(err).NotTo(gomega.HaveOccurred())
504 })
505 })
506
507 ginkgo.When("given a configuration URL with StartTLS but it is not supported", func() {
508 ginkgo.It("should send notifications without any errors", func() {
509 testURL := modifyURL(baseNoAuthURL, map[string]string{"useStartTLS": "yes"})
510
511 err := testIntegration(testURL, []string{
512 "250-mx.google.com at your service",
513 "250-SIZE 35651584",
514 "250-AUTH LOGIN PLAIN",
515 "250 8BITMIME",
516 "250 Sender OK",
517 "250 Receiver OK",
518 "354 Go ahead",
519 "250 Data OK",
520 "221 OK",
521 }, "", "")
522 skipIfTestSetup(err)
523 gomega.Expect(err).NotTo(gomega.HaveOccurred())
524 })
525 })
526
527 ginkgo.When("StartTLS is required but unsupported", func() {
528 ginkgo.It("should fail with FailEnableStartTLS", func() {
529 testURL := modifyURL(baseNoAuthURL, map[string]string{
530 "useStartTLS": "yes",
531 "requirestarttls": "yes",
532 })
533
534 err := testIntegration(testURL, []string{
535 "250-mx.google.com at your service",
536 "250-SIZE 35651584",
537 "250-AUTH LOGIN PLAIN",
538 "250 8BITMIME",
539 }, "", "")
540 skipIfTestSetup(err)
541 gomega.Expect(err).To(matchFailure(FailEnableStartTLS))
542 })
543 })
544
545 ginkgo.When("server communication fails", func() {
546 ginkgo.It("should fail when initial handshake is not accepted", func() {
547 testURL := modifyURL(
548 baseNoAuthURL,
549 map[string]string{"useStartTLS": "yes", "clienthost": "spammer"},
550 )
551
552 err := testIntegration(testURL, []string{
553 "421 4.7.0 Try again later, closing connection. (EHLO) r20-20020a50d694000000b004588af8956dsm771862edi.9 - gsmtp",
554 }, "", "")
555 skipIfTestSetup(err)
556 gomega.Expect(err).To(matchFailure(FailHandshake))
557 })
558
559 ginkgo.It("should fail when not being able to enable StartTLS", func() {
560 testURL := modifyURL(baseNoAuthURL, map[string]string{"useStartTLS": "yes"})
561
562 err := testIntegration(testURL, []string{
563 "250-mx.google.com at your service",
564 "250-SIZE 35651584",
565 "250-STARTTLS",
566 "250-AUTH LOGIN PLAIN",
567 "250 8BITMIME",
568 "502 That's too hard",
569 }, "", "")
570 skipIfTestSetup(err)
571 gomega.Expect(err).To(matchFailure(FailEnableStartTLS))
572 })
573
574 ginkgo.It("should fail when authentication type is invalid", func() {
575 testURL := modifyURL(baseNoAuthURL, map[string]string{"auth": "bad"})
576
577 err := testIntegration(testURL, []string{}, "", "")
578 skipIfTestSetup(err)
579 gomega.Expect(err).To(matchFailure(standard.FailServiceInit))
580 })
581
582 ginkgo.It("should fail when not being able to use authentication type", func() {
583 testURL := modifyURL(baseNoAuthURL, map[string]string{"auth": "crammd5"})
584
585 err := testIntegration(testURL, []string{
586 "250-mx.google.com at your service",
587 "250-SIZE 35651584",
588 "250-AUTH LOGIN PLAIN",
589 "250 8BITMIME",
590 "504 Liar",
591 }, "", "")
592 skipIfTestSetup(err)
593 gomega.Expect(err).To(matchFailure(FailAuthenticating))
594 })
595
596 ginkgo.It("should fail MAIL FROM with FailSetSender", func() {
597 err := testSendRecipient([]string{
598 "250 mx.google.com at your service",
599 "550 sender rejected",
600 })
601 skipIfTestSetup(err)
602 gomega.Expect(err).To(matchFailure(FailSetSender))
603 })
604
605 ginkgo.It("should reject a From address that contains CR or LF", func() {
606 gomega.Expect(service.Initialize(testutils.URLMust(baseNoAuthURL), logger)).To(gomega.Succeed())
607
608 textCon, _ := testutils.CreateTextConFaker([]string{
609 "250 mx.google.com at your service",
610 }, "\r\n")
611 client := &smtp.Client{Text: textCon}
612 config := service.Config.Clone()
613 config.FromAddress = "[email protected]\r\nBcc: [email protected]"
614 err := (&session{client: client, config: &config, svc: service}).
615 sendMessage("[email protected]", "body", "")
616 gomega.Expect(err).To(matchFailure(FailSetSender))
617 gomega.Expect(err).To(gomega.MatchError(errHeaderBreak))
618 })
619
620 ginkgo.It("should reject a recipient address that contains CR or LF", func() {
621 gomega.Expect(service.Initialize(testutils.URLMust(baseNoAuthURL), logger)).To(gomega.Succeed())
622
623 textCon, _ := testutils.CreateTextConFaker([]string{
624 "250 mx.google.com at your service",
625 }, "\r\n")
626 client := &smtp.Client{Text: textCon}
627 config := service.Config.Clone()
628 err := (&session{client: client, config: &config, svc: service}).
629 sendMessage("[email protected]\r\nBcc: [email protected]", "body", "")
630 gomega.Expect(err).To(matchFailure(FailSetRecipient))
631 gomega.Expect(err).To(gomega.MatchError(errHeaderBreak))
632 })
633
634 ginkgo.It("should fail when not being able to send to recipient", func() {
635 err := testIntegration(baseNoAuthURL, []string{
636 "250-mx.google.com at your service",
637 "250-SIZE 35651584",
638 "250-AUTH LOGIN PLAIN",
639 "250 8BITMIME",
640 "551 I don't know you",
641 }, "", "")
642 skipIfTestSetup(err)
643 gomega.Expect(err).To(matchFailure(FailSendRecipient))
644 })
645
646 ginkgo.It("should fail when the recipient is not accepted", func() {
647 err := testSendRecipient([]string{
648 "250 mx.google.com at your service",
649 "250 Sender OK",
650 "553 She doesn't want to be disturbed",
651 })
652 skipIfTestSetup(err)
653 gomega.Expect(err).To(matchFailure(FailSetRecipient))
654 })
655
656 ginkgo.It("should fail when the server does not accept the data stream", func() {
657 err := testSendRecipient([]string{
658 "250 mx.google.com at your service",
659 "250 Sender OK",
660 "250 Receiver OK",
661 "554 Nah I'm fine thanks",
662 })
663 skipIfTestSetup(err)
664 gomega.Expect(err).To(matchFailure(FailOpenDataStream))
665 })
666
667 ginkgo.It("should fail when the server does not accept the data stream content", func() {
668 err := testSendRecipient([]string{
669 "250 mx.google.com at your service",
670 "250 Sender OK",
671 "250 Receiver OK",
672 "354 Go ahead",
673 "554 Such garbage!",
674 })
675 skipIfTestSetup(err)
676 gomega.Expect(err).To(matchFailure(FailCloseDataStream))
677 })
678
679 ginkgo.It("should fail when the server does not close the connection gracefully", func() {
680 err := testIntegration(baseNoAuthURL, []string{
681 "250-mx.google.com at your service",
682 "250-SIZE 35651584",
683 "250-AUTH LOGIN PLAIN",
684 "250 8BITMIME",
685 "250 Sender OK",
686 "250 Receiver OK",
687 "354 Go ahead",
688 "250 Data OK",
689 "502 You can't quit, you're fired!",
690 }, "", "")
691 skipIfTestSetup(err)
692 gomega.Expect(err).To(matchFailure(FailClosingSession))
693 })
694
695 ginkgo.It("should ignore short response errors on QUIT and log warning", func() {
696 serviceURL, _ := url.Parse(baseNoAuthURL)
697 localService := &Service{}
698 gomega.Expect(localService.Initialize(serviceURL, logger)).To(gomega.Succeed())
699
700 var buf bytes.Buffer
701
702 testLogger := log.New(&buf, "", 0)
703 localService.SetLogger(testLogger)
704
705 responses := []string{
706 "250-mx.google.com at your service",
707 "250-SIZE 35651584",
708 "250-AUTH LOGIN PLAIN",
709 "250 8BITMIME",
710 "250 Sender OK",
711 "250 Receiver OK",
712 "354 Go ahead",
713 "250 Data OK",
714 "22",
715 }
716 textCon, _ := testutils.CreateTextConFaker(responses, "\r\n")
717 client := &smtp.Client{Text: textCon}
718 fakeTLSEnabled(client, serviceURL.Hostname())
719
720 gomega.Expect(runSMTPSession(localService, client, localService.Config)).To(gomega.Succeed())
721 gomega.Expect(buf.String()).
722 To(gomega.ContainSubstring("Warning: Ignoring session closure error (delivery succeeded)"))
723 })
724
725 ginkgo.It("should not close again after a successful QUIT", func() {
726 serviceURL, _ := url.Parse(baseNoAuthURL)
727 localService := &Service{}
728 gomega.Expect(localService.Initialize(serviceURL, logger)).To(gomega.Succeed())
729
730 var buf bytes.Buffer
731
732 testLogger := log.New(&buf, "", 0)
733 localService.SetLogger(testLogger)
734
735 responses := []string{
736 "250-mx.google.com at your service",
737 "250-SIZE 35651584",
738 "250-AUTH LOGIN PLAIN",
739 "250 8BITMIME",
740 "250 Sender OK",
741 "250 Receiver OK",
742 "354 Go ahead",
743 "250 Data OK",
744 "221 OK",
745 }
746 textCon, _ := testutils.CreateTextConFaker(responses, "\r\n")
747 client := &smtp.Client{Text: textCon}
748 fakeTLSEnabled(client, serviceURL.Hostname())
749
750 mock := &mockConn{}
751 injectConn(client, mock)
752
753 gomega.Expect(runSMTPSession(localService, client, localService.Config)).To(gomega.Succeed())
754 gomega.Expect(buf.String()).
755 NotTo(gomega.ContainSubstring("Failed to close SMTP client connection"))
756 gomega.Expect(mock.closeCount).To(gomega.Equal(1))
757 })
758
759 ginkgo.It("should close the client when the handshake fails", func() {
760 serviceURL, _ := url.Parse(baseNoAuthURL)
761 localService := &Service{}
762 gomega.Expect(localService.Initialize(serviceURL, logger)).To(gomega.Succeed())
763
764 responses := []string{
765 "421 4.7.0 Try again later, closing connection. (EHLO)",
766 }
767 textCon, _ := testutils.CreateTextConFaker(responses, "\r\n")
768 client := &smtp.Client{Text: textCon}
769 fakeTLSEnabled(client, serviceURL.Hostname())
770
771 mock := &mockConn{}
772 injectConn(client, mock)
773
774 err := runSMTPSession(localService, client, localService.Config)
775 gomega.Expect(err).To(matchFailure(FailHandshake))
776 gomega.Expect(mock.closeCount).To(gomega.BeNumerically(">=", 1))
777 })
778
779 ginkgo.It("should attempt all recipients and collect errors", func() {
780 serviceURL, _ := url.Parse(baseAuthURL)
781 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
782
783 responses := []string{
784 "250-mx.google.com at your service",
785 "250-SIZE 35651584",
786 "250-AUTH LOGIN PLAIN",
787 "250 8BITMIME",
788 "235 Accepted",
789 "250 Sender OK",
790 "553 Recipient1 not found",
791 "250 Reset OK",
792 "250 Sender OK",
793 "250 Receiver OK",
794 "354 Go ahead",
795 "250 Data OK",
796 "221 OK",
797 }
798 textCon, tcfaker := testutils.CreateTextConFaker(responses, "\r\n")
799 client := &smtp.Client{Text: textCon}
800 fakeTLSEnabled(client, serviceURL.Hostname())
801
802 config := service.Config
803 config.ToAddresses = []string{"[email protected]", "[email protected]"}
804 err := runSMTPSession(service, client, config)
805 gomega.Expect(err).To(matchFailure(FailSendRecipient))
806 gomega.Expect(err.Error()).
807 To(gomega.ContainSubstring("error sending message to recipient \"[email protected]\""))
808
809 received := tcfaker.GetClientSentences()
810 gomega.Expect(received).To(gomega.ContainElement("RSET"))
811 gomega.Expect(received).To(gomega.ContainElement("RCPT TO:<[email protected]>"))
812 gomega.Expect(received).To(gomega.ContainElement("QUIT"))
813 logger.Printf("\n%s", tcfaker.GetConversation(false))
814 })
815
816 ginkgo.It("should fail when RSET is rejected between recipients", func() {
817 serviceURL, _ := url.Parse(baseAuthURL)
818 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
819
820 responses := []string{
821 "250-mx.google.com at your service",
822 "250-SIZE 35651584",
823 "250-AUTH LOGIN PLAIN",
824 "250 8BITMIME",
825 "235 Accepted",
826 "250 Sender OK",
827 "250 Receiver OK",
828 "354 Go ahead",
829 "250 Data OK",
830 "502 cannot reset",
831 }
832 textCon, _ := testutils.CreateTextConFaker(responses, "\r\n")
833 client := &smtp.Client{Text: textCon}
834 fakeTLSEnabled(client, serviceURL.Hostname())
835
836 config := service.Config
837 config.ToAddresses = []string{"[email protected]", "[email protected]"}
838 err := runSMTPSession(service, client, config)
839 gomega.Expect(err).To(gomega.HaveOccurred())
840 gomega.Expect(err.Error()).To(gomega.ContainSubstring("error resetting session between recipients"))
841 })
842 })
843 })
844 })