Debian Codegraph @

pkg/services/email/smtp/smtp_test.go

raw
1 package smtp
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "log"
8 "net"
9 "net/smtp"
10 "net/url"
11 "os"
12 "reflect"
13 "testing"
14 "time"
15 "unsafe"
16
17 "github.com/onsi/ginkgo/v2"
18 "github.com/onsi/gomega"
19
20 gomegaTypes "github.com/onsi/gomega/types"
21
22 "github.com/nicholas-fedor/shoutrrr/internal/failures"
23 "github.com/nicholas-fedor/shoutrrr/internal/testutils"
24 "github.com/nicholas-fedor/shoutrrr/pkg/format"
25 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
26 "github.com/nicholas-fedor/shoutrrr/pkg/types"
27 )
28
29 // mockConn is a mock implementation of net.Conn that fails on Close for testing purposes.
30 type mockConn struct {
31 closeCount int
32 }
33
34 var tt *testing.T
35
36 var (
37 service *Service
38 envSMTPURL string
39 logger *log.Logger
40 _ = ginkgo.BeforeSuite(func() {
41 envSMTPURL = os.Getenv("SHOUTRRR_SMTP_URL")
42 logger = testutils.TestLogger()
43 })
44 urlWithAllProps = "smtp://user:[email protected]:2225/?auth=None&clienthost=testhost&encryption=ExplicitTLS&fromaddress=sender%40example.com&fromname=Sender&subject=Subject&toaddresses=rec1%40example.com%2Crec2%40example.com&usehtml=Yes&usestarttls=No&timeout=10s"
45 // BaseNoAuthURL is a minimal SMTP config without authentication.
46 BaseNoAuthURL = "smtp://example.com:2225/?useStartTLS=no&auth=none&[email protected]&[email protected]&useHTML=no&timeout=10s"
47 // BaseAuthURL is a typical config with authentication.
48 BaseAuthURL = "smtp://user:[email protected]:2225/?useStartTLS=no&[email protected]&[email protected],[email protected]&useHTML=yes&timeout=10s"
49 // BasePlusURL is a config with plus signs in email addresses.
50 BasePlusURL = "smtp://user:[email protected]:2225/?useStartTLS=no&[email protected]&[email protected],[email protected]&useHTML=yes&timeout=10s"
51 )
52
53 var _ = ginkgo.Describe("the SMTP service", func() {
54 ginkgo.BeforeEach(func() {
55 service = &Service{}
56 })
57 ginkgo.When("parsing the configuration URL", func() {
58 ginkgo.It("should be identical after de-/serialization", func() {
59 url := testutils.URLMust(urlWithAllProps)
60 config := &Config{}
61 pkr := format.NewPropKeyResolver(config)
62 err := config.setURL(&pkr, url)
63 gomega.Expect(err).NotTo(gomega.HaveOccurred(), "verifying")
64
65 outputURL := config.GetURL()
66 ginkgo.GinkgoT().Logf("\n\n%s\n%s\n\n-", outputURL, urlWithAllProps)
67 gomega.Expect(outputURL.String()).To(gomega.Equal(urlWithAllProps))
68 })
69 ginkgo.When("skiptlsverify is set to yes", func() {
70 ginkgo.It("should set SkipTLSVerify to true", func() {
71 testURL := testutils.URLMust(
72 "smtp://user:[email protected]:2225/[email protected]&[email protected]&skiptlsverify=yes",
73 )
74 config := &Config{}
75 err := config.SetURL(testURL)
76 gomega.Expect(err).NotTo(gomega.HaveOccurred())
77 gomega.Expect(config.SkipTLSVerify).To(gomega.BeTrue())
78 })
79 })
80 ginkgo.When("skiptlsverify is set to no", func() {
81 ginkgo.It("should set SkipTLSVerify to false", func() {
82 testURL := testutils.URLMust(
83 "smtp://user:[email protected]:2225/[email protected]&[email protected]&skiptlsverify=no",
84 )
85 config := &Config{}
86 err := config.SetURL(testURL)
87 gomega.Expect(err).NotTo(gomega.HaveOccurred())
88 gomega.Expect(config.SkipTLSVerify).To(gomega.BeFalse())
89 })
90 })
91 ginkgo.When("SkipTLSVerify is enabled", func() {
92 ginkgo.It("should log a security warning", func() {
93 localService := &Service{}
94 testURL := modifyURL(BaseNoAuthURL, map[string]string{"skiptlsverify": "yes"})
95 serviceURL := testutils.URLMust(testURL)
96
97 var buf bytes.Buffer
98
99 testLogger := log.New(&buf, "", 0)
100 err := localService.Initialize(serviceURL, testLogger)
101 gomega.Expect(err).NotTo(gomega.HaveOccurred())
102 // Simulate the logging that happens in Send without attempting network connection
103 config := localService.Config.Clone()
104 if config.SkipTLSVerify {
105 localService.Log(
106 "Warning: TLS verification is disabled, making connections insecure",
107 )
108 }
109
110 gomega.Expect(buf.String()).
111 To(gomega.ContainSubstring("Warning: TLS verification is disabled, making connections insecure"))
112 })
113 })
114 ginkgo.When("resolving client host", func() {
115 ginkgo.When("clienthost is set to auto", func() {
116 ginkgo.It("should return the os hostname", func() {
117 hostname, err := os.Hostname()
118 gomega.Expect(err).ToNot(gomega.HaveOccurred())
119 gomega.Expect(service.resolveClientHost(&Config{ClientHost: "auto"})).
120 To(gomega.Equal(hostname))
121 })
122 })
123 ginkgo.When("clienthost is set to a custom value", func() {
124 ginkgo.It("should return that value", func() {
125 gomega.Expect(service.resolveClientHost(&Config{ClientHost: "computah"})).
126 To(gomega.Equal("computah"))
127 })
128 })
129 })
130 ginkgo.When("fromAddress is missing", func() {
131 ginkgo.It("should return an error", func() {
132 testURL := testutils.URLMust(
133 "smtp://user:[email protected]:2225/[email protected],[email protected]",
134 )
135 gomega.Expect((&Config{}).SetURL(testURL)).ToNot(gomega.Succeed())
136 })
137 })
138 ginkgo.When("toAddresses are missing", func() {
139 ginkgo.It("should return an error", func() {
140 testURL := testutils.URLMust(
141 "smtp://user:[email protected]:2225/[email protected]",
142 )
143 gomega.Expect((&Config{}).SetURL(testURL)).ToNot(gomega.Succeed())
144 })
145 })
146 })
147
148 ginkgo.Context("basic service API methods", func() {
149 var config *Config
150
151 ginkgo.BeforeEach(func() {
152 config = &Config{}
153 })
154 ginkgo.It("should not allow getting invalid query values", func() {
155 testutils.TestConfigGetInvalidQueryValue(config)
156 })
157 ginkgo.It("should not allow setting invalid query values", func() {
158 testutils.TestConfigSetInvalidQueryValue(
159 config,
160 "smtp://example.com/[email protected]&[email protected]&foo=bar",
161 )
162 })
163 ginkgo.It("should have the expected number of fields and enums", func() {
164 testutils.TestConfigGetEnumsCount(config, 2)
165 testutils.TestConfigGetFieldsCount(config, 16)
166 })
167 })
168
169 ginkgo.When("cloning a config", func() {
170 ginkgo.It("should be identical to the original", func() {
171 config := &Config{}
172 gomega.Expect(config.SetURL(testutils.URLMust(urlWithAllProps))).To(gomega.Succeed())
173 gomega.Expect(config.Clone()).To(gomega.Equal(*config))
174 })
175 })
176
177 ginkgo.When("sending a message", func() {
178 ginkgo.When("the service is not configured correctly", func() {
179 ginkgo.It("should fail to send messages", func() {
180 service := Service{Config: &Config{}}
181 gomega.Expect(service.Send("test message", nil)).To(matchFailure(FailGetSMTPClient))
182 service.Config.Encryption = EncMethods.ImplicitTLS
183 gomega.Expect(service.Send("test message", nil)).To(matchFailure(FailGetSMTPClient))
184 })
185 })
186 ginkgo.When("an invalid param is passed", func() {
187 ginkgo.It("should fail to send messages", func() {
188 service := Service{Config: &Config{}}
189 gomega.Expect(service.Send("test message", &types.Params{"invalid": "value"})).
190 To(matchFailure(FailApplySendParams))
191 })
192 })
193 })
194
195 ginkgo.When("the underlying stream stops working", func() {
196 var (
197 service Service
198 message string
199 )
200
201 ginkgo.BeforeEach(func() {
202 service = Service{}
203 message = ""
204 })
205 ginkgo.It("should fail when writing multipart plain header", func() {
206 writer := testutils.CreateFailWriter(1)
207 err := service.writeMultipartMessage(writer, message)
208 gomega.Expect(err).To(gomega.HaveOccurred())
209 gomega.Expect(err).To(matchFailure(FailPlainHeader))
210 })
211 ginkgo.It("should fail when writing multipart plain message", func() {
212 writer := testutils.CreateFailWriter(2)
213 err := service.writeMultipartMessage(writer, message)
214 gomega.Expect(err).To(gomega.HaveOccurred())
215 gomega.Expect(err).To(matchFailure(FailMessageRaw))
216 })
217 ginkgo.It("should fail when writing multipart HTML header", func() {
218 writer := testutils.CreateFailWriter(4)
219 err := service.writeMultipartMessage(writer, message)
220 gomega.Expect(err).To(gomega.HaveOccurred())
221 gomega.Expect(err).To(matchFailure(FailHTMLHeader))
222 })
223 ginkgo.It("should fail when writing multipart HTML message", func() {
224 writer := testutils.CreateFailWriter(5)
225 err := service.writeMultipartMessage(writer, message)
226 gomega.Expect(err).To(gomega.HaveOccurred())
227 gomega.Expect(err).To(matchFailure(FailMessageRaw))
228 })
229 ginkgo.It("should fail when writing multipart end header", func() {
230 writer := testutils.CreateFailWriter(6)
231 err := service.writeMultipartMessage(writer, message)
232 gomega.Expect(err).To(gomega.HaveOccurred())
233 gomega.Expect(err).To(matchFailure(FailMultiEndHeader))
234 })
235 ginkgo.It("should fail when writing message template", func() {
236 writer := testutils.CreateFailWriter(0)
237 e := service.SetTemplateString("dummy", "dummy template content")
238 gomega.Expect(e).ToNot(gomega.HaveOccurred())
239
240 err := service.writeMessagePart(writer, message, "dummy")
241 gomega.Expect(err).To(gomega.HaveOccurred())
242 gomega.Expect(err).To(matchFailure(FailMessageTemplate))
243 })
244 })
245
246 ginkgo.When("running E2E tests", func() {
247 ginkgo.It("should work without errors", func() {
248 if envSMTPURL == "" {
249 ginkgo.Skip("environment not set up for E2E testing")
250
251 return
252 }
253
254 serviceURL, err := url.Parse(envSMTPURL)
255 gomega.Expect(err).NotTo(gomega.HaveOccurred())
256 err = service.Initialize(serviceURL, logger)
257 gomega.Expect(err).NotTo(gomega.HaveOccurred())
258 err = service.Send("this is an integration test", nil)
259 gomega.Expect(err).NotTo(gomega.HaveOccurred())
260 })
261 })
262
263 ginkgo.When("running integration tests", func() {
264 ginkgo.When("given a typical usage case configuration URL", func() {
265 ginkgo.It("should send notifications without any errors", func() {
266 testURL := BaseAuthURL
267
268 err := testIntegration(testURL, []string{
269 "250-mx.google.com at your service",
270 "250-SIZE 35651584",
271 "250-AUTH LOGIN PLAIN",
272 "250 8BITMIME",
273 "235 Accepted",
274 "250 Sender OK",
275 "250 Receiver OK",
276 "354 Go ahead",
277 "250 Data OK",
278 "250 Sender OK",
279 "250 Receiver OK",
280 "354 Go ahead",
281 "250 Data OK",
282 "221 OK",
283 }, "<pre>{{ .message }}</pre>", "{{ .message }}")
284 if msg, test := standard.IsTestSetupFailure(err); test {
285 ginkgo.Skip(msg)
286
287 return
288 }
289
290 gomega.Expect(err).NotTo(gomega.HaveOccurred())
291 })
292 })
293 ginkgo.When("given e-mail addresses with pluses in the configuration URL", func() {
294 ginkgo.It("should send notifications without any errors", func() {
295 testURL := BasePlusURL
296
297 err := testIntegration(testURL, []string{
298 "250-mx.google.com at your service",
299 "250-SIZE 35651584",
300 "250-AUTH LOGIN PLAIN",
301 "250 8BITMIME",
302 "235 Accepted",
303 "250 Sender OK",
304 "250 Receiver OK",
305 "354 Go ahead",
306 "250 Data OK",
307 "250 Sender OK",
308 "250 Receiver OK",
309 "354 Go ahead",
310 "250 Data OK",
311 "221 OK",
312 }, "<pre>{{ .message }}</pre>", "{{ .message }}",
313 "RCPT TO:<[email protected]>",
314 "To: [email protected]",
315 "From: <[email protected]>")
316 if msg, test := standard.IsTestSetupFailure(err); test {
317 ginkgo.Skip(msg)
318
319 return
320 }
321
322 gomega.Expect(err).NotTo(gomega.HaveOccurred())
323 })
324 })
325 ginkgo.When("given a configuration URL with authentication disabled", func() {
326 ginkgo.It("should send notifications without any errors", func() {
327 testURL := BaseNoAuthURL
328
329 err := testIntegration(testURL, []string{
330 "250-mx.google.com at your service",
331 "250-SIZE 35651584",
332 "250-AUTH LOGIN PLAIN",
333 "250 8BITMIME",
334 "250 Sender OK",
335 "250 Receiver OK",
336 "354 Go ahead",
337 "250 Data OK",
338 "221 OK",
339 }, "", "")
340 if msg, test := standard.IsTestSetupFailure(err); test {
341 ginkgo.Skip(msg)
342
343 return
344 }
345
346 gomega.Expect(err).NotTo(gomega.HaveOccurred())
347 })
348 })
349 ginkgo.When("given a configuration URL with StartTLS but it is not supported", func() {
350 ginkgo.It("should send notifications without any errors", func() {
351 testURL := modifyURL(BaseNoAuthURL, map[string]string{"useStartTLS": "yes"})
352
353 err := testIntegration(testURL, []string{
354 "250-mx.google.com at your service",
355 "250-SIZE 35651584",
356 "250-AUTH LOGIN PLAIN",
357 "250 8BITMIME",
358 "250 Sender OK",
359 "250 Receiver OK",
360 "354 Go ahead",
361 "250 Data OK",
362 "221 OK",
363 }, "", "")
364 if msg, test := standard.IsTestSetupFailure(err); test {
365 ginkgo.Skip(msg)
366
367 return
368 }
369
370 gomega.Expect(err).NotTo(gomega.HaveOccurred())
371 })
372 })
373 ginkgo.When("server communication fails", func() {
374 ginkgo.It("should fail when initial handshake is not accepted", func() {
375 testURL := modifyURL(
376 BaseNoAuthURL,
377 map[string]string{"useStartTLS": "yes", "clienthost": "spammer"},
378 )
379
380 err := testIntegration(testURL, []string{
381 "421 4.7.0 Try again later, closing connection. (EHLO) r20-20020a50d694000000b004588af8956dsm771862edi.9 - gsmtp",
382 }, "", "")
383 if msg, test := standard.IsTestSetupFailure(err); test {
384 ginkgo.Skip(msg)
385
386 return
387 }
388
389 gomega.Expect(err).To(matchFailure(FailHandshake))
390 })
391 ginkgo.It("should fail when not being able to enable StartTLS", func() {
392 testURL := modifyURL(BaseNoAuthURL, map[string]string{"useStartTLS": "yes"})
393
394 err := testIntegration(testURL, []string{
395 "250-mx.google.com at your service",
396 "250-SIZE 35651584",
397 "250-STARTTLS",
398 "250-AUTH LOGIN PLAIN",
399 "250 8BITMIME",
400 "502 That's too hard",
401 }, "", "")
402 if msg, test := standard.IsTestSetupFailure(err); test {
403 ginkgo.Skip(msg)
404
405 return
406 }
407
408 gomega.Expect(err).To(matchFailure(FailEnableStartTLS))
409 })
410 ginkgo.It("should fail when authentication type is invalid", func() {
411 testURL := modifyURL(BaseNoAuthURL, map[string]string{"auth": "bad"})
412
413 err := testIntegration(testURL, []string{}, "", "")
414 if msg, test := standard.IsTestSetupFailure(err); test {
415 ginkgo.Skip(msg)
416
417 return
418 }
419
420 gomega.Expect(err).To(matchFailure(standard.FailServiceInit))
421 })
422 ginkgo.It("should fail when not being able to use authentication type", func() {
423 testURL := modifyURL(BaseNoAuthURL, map[string]string{"auth": "crammd5"})
424
425 err := testIntegration(testURL, []string{
426 "250-mx.google.com at your service",
427 "250-SIZE 35651584",
428 "250-AUTH LOGIN PLAIN",
429 "250 8BITMIME",
430 "504 Liar",
431 }, "", "")
432 if msg, test := standard.IsTestSetupFailure(err); test {
433 ginkgo.Skip(msg)
434
435 return
436 }
437
438 gomega.Expect(err).To(matchFailure(FailAuthenticating))
439 })
440 ginkgo.It("should fail when not being able to send to recipient", func() {
441 testURL := BaseNoAuthURL
442
443 err := testIntegration(testURL, []string{
444 "250-mx.google.com at your service",
445 "250-SIZE 35651584",
446 "250-AUTH LOGIN PLAIN",
447 "250 8BITMIME",
448 "551 I don't know you",
449 }, "", "")
450 if msg, test := standard.IsTestSetupFailure(err); test {
451 ginkgo.Skip(msg)
452
453 return
454 }
455
456 gomega.Expect(err).To(matchFailure(FailSendRecipient))
457 })
458 ginkgo.It("should fail when the recipient is not accepted", func() {
459 testURL := BaseNoAuthURL
460
461 err := testSendRecipient(testURL, []string{
462 "250 mx.google.com at your service",
463 "250 Sender OK",
464 "553 She doesn't want to be disturbed",
465 })
466 if msg, test := standard.IsTestSetupFailure(err); test {
467 ginkgo.Skip(msg)
468
469 return
470 }
471
472 gomega.Expect(err).To(matchFailure(FailSetRecipient))
473 })
474 ginkgo.It("should fail when the server does not accept the data stream", func() {
475 testURL := BaseNoAuthURL
476
477 err := testSendRecipient(testURL, []string{
478 "250 mx.google.com at your service",
479 "250 Sender OK",
480 "250 Receiver OK",
481 "554 Nah I'm fine thanks",
482 })
483 if msg, test := standard.IsTestSetupFailure(err); test {
484 ginkgo.Skip(msg)
485
486 return
487 }
488
489 gomega.Expect(err).To(matchFailure(FailOpenDataStream))
490 })
491 ginkgo.It(
492 "should fail when the server does not accept the data stream content",
493 func() {
494 testURL := BaseNoAuthURL
495
496 err := testSendRecipient(testURL, []string{
497 "250 mx.google.com at your service",
498 "250 Sender OK",
499 "250 Receiver OK",
500 "354 Go ahead",
501 "554 Such garbage!",
502 })
503 if msg, test := standard.IsTestSetupFailure(err); test {
504 ginkgo.Skip(msg)
505
506 return
507 }
508
509 gomega.Expect(err).To(matchFailure(FailCloseDataStream))
510 },
511 )
512 ginkgo.It(
513 "should fail when the server does not close the connection gracefully",
514 func() {
515 testURL := BaseNoAuthURL
516
517 err := testIntegration(testURL, []string{
518 "250-mx.google.com at your service",
519 "250-SIZE 35651584",
520 "250-AUTH LOGIN PLAIN",
521 "250 8BITMIME",
522 "250 Sender OK",
523 "250 Receiver OK",
524 "354 Go ahead",
525 "250 Data OK",
526 "502 You can't quit, you're fired!",
527 }, "", "")
528 if msg, test := standard.IsTestSetupFailure(err); test {
529 ginkgo.Skip(msg)
530
531 return
532 }
533
534 gomega.Expect(err).To(matchFailure(FailClosingSession))
535 },
536 )
537 ginkgo.It("should ignore short response errors on QUIT and log warning", func() {
538 testURL := BaseNoAuthURL
539 serviceURL, _ := url.Parse(testURL)
540 localService := &Service{}
541 err := localService.Initialize(serviceURL, logger)
542 gomega.Expect(err).NotTo(gomega.HaveOccurred())
543
544 var buf bytes.Buffer
545
546 testLogger := log.New(&buf, "", 0)
547 localService.SetLogger(testLogger)
548
549 responses := []string{
550 "250-mx.google.com at your service",
551 "250-SIZE 35651584",
552 "250-AUTH LOGIN PLAIN",
553 "250 8BITMIME",
554 "250 Sender OK",
555 "250 Receiver OK",
556 "354 Go ahead",
557 "250 Data OK",
558 "22", // Short response on QUIT
559 }
560 textCon, _ := testutils.CreateTextConFaker(responses, "\r\n")
561 client := &smtp.Client{Text: textCon}
562 fakeTLSEnabled(client, serviceURL.Hostname())
563
564 config := localService.Config
565 err = localService.doSend(client, "Test message", config)
566 gomega.Expect(err).ToNot(gomega.HaveOccurred())
567 gomega.Expect(buf.String()).
568 To(gomega.ContainSubstring("Warning: Ignoring session closure error (delivery succeeded)"))
569 })
570 ginkgo.It("should log warning when QUIT succeeds but Close fails", func() {
571 testURL := BaseNoAuthURL
572 serviceURL, _ := url.Parse(testURL)
573 localService := &Service{}
574 err := localService.Initialize(serviceURL, logger)
575 gomega.Expect(err).NotTo(gomega.HaveOccurred())
576
577 var buf bytes.Buffer
578
579 testLogger := log.New(&buf, "", 0)
580 localService.SetLogger(testLogger)
581
582 responses := []string{
583 "250-mx.google.com at your service",
584 "250-SIZE 35651584",
585 "250-AUTH LOGIN PLAIN",
586 "250 8BITMIME",
587 "250 Sender OK",
588 "250 Receiver OK",
589 "354 Go ahead",
590 "250 Data OK",
591 "221 OK", // QUIT succeeds
592 }
593 textCon, _ := testutils.CreateTextConFaker(responses, "\r\n")
594 client := &smtp.Client{Text: textCon}
595 fakeTLSEnabled(client, serviceURL.Hostname())
596 // Mock the underlying connection to fail on Close
597 cr := reflect.ValueOf(client).Elem().FieldByName("Text").Elem().FieldByName("conn")
598 cr = reflect.NewAt(cr.Type(), unsafe.Pointer(cr.UnsafeAddr())).Elem()
599 cr.Set(reflect.ValueOf(&mockConn{}))
600
601 config := localService.Config
602 err = localService.doSend(client, "Test message", config)
603 gomega.Expect(err).ToNot(gomega.HaveOccurred())
604 gomega.Expect(buf.String()).
605 To(gomega.ContainSubstring("Warning: Failed to close SMTP client connection: mock close error"))
606 })
607 ginkgo.It("should fail when context is canceled during connection", func() {
608 ctx, cancel := context.WithCancel(context.Background())
609 cancel()
610
611 config := &Config{
612 Host: "example.com",
613 Port: 25,
614 FromAddress: "[email protected]",
615 ToAddresses: []string{"[email protected]"},
616 }
617 _, err := getClientConnection(ctx, config)
618 gomega.Expect(err).To(gomega.MatchError(context.Canceled))
619 })
620 ginkgo.It("should attempt all recipients and collect errors", func() {
621 testURL := BaseAuthURL
622 serviceURL, _ := url.Parse(testURL)
623 err := service.Initialize(serviceURL, logger)
624 gomega.Expect(err).NotTo(gomega.HaveOccurred())
625
626 responses := []string{
627 "250-mx.google.com at your service",
628 "250-SIZE 35651584",
629 "250-AUTH LOGIN PLAIN",
630 "250 8BITMIME",
631 "235 Accepted",
632 "250 Sender OK",
633 "553 Recipient1 not found", // Fail first recipient
634 "250 Sender OK",
635 "250 Receiver OK",
636 "354 Go ahead",
637 "250 Data OK",
638 "221 OK",
639 }
640 textCon, tcfaker := testutils.CreateTextConFaker(responses, "\r\n")
641 client := &smtp.Client{Text: textCon}
642 fakeTLSEnabled(client, serviceURL.Hostname())
643
644 config := service.Config
645 config.ToAddresses = []string{"[email protected]", "[email protected]"}
646 err = service.doSend(client, "Test message", config)
647 gomega.Expect(err).To(gomega.HaveOccurred())
648 gomega.Expect(err).To(matchFailure(FailSendRecipient))
649 gomega.Expect(err.Error()).
650 To(gomega.ContainSubstring("error sending message to recipient \"[email protected]\""))
651
652 received := tcfaker.GetClientSentences()
653 gomega.Expect(received).
654 To(gomega.ContainElement("RCPT TO:<[email protected]>"))
655 // Verify second recipient attempted
656 gomega.Expect(received).
657 To(gomega.ContainElement("QUIT"))
658 // Verify connection closed
659 logger.Printf("\n%s", tcfaker.GetConversation(false))
660 })
661 })
662 })
663
664 ginkgo.When("writing headers and the output stream is closed", func() {
665 ginkgo.When("it's closed during header content", func() {
666 ginkgo.It("should fail with correct error", func() {
667 fw := testutils.CreateFailWriter(0)
668 gomega.Expect(writeHeaders(fw, map[string]string{"key": "value"})).
669 To(matchFailure(FailWriteHeaders))
670 })
671 })
672 ginkgo.When("it's closed after header content", func() {
673 ginkgo.It("should fail with correct error", func() {
674 fw := testutils.CreateFailWriter(1)
675 gomega.Expect(writeHeaders(fw, map[string]string{"key": "value"})).
676 To(matchFailure(FailWriteHeaders))
677 })
678 })
679 })
680
681 ginkgo.When("default port is not specified", func() {
682 ginkgo.It("should use the default SMTP port when not specified", func() {
683 testURL := "smtp://example.com/[email protected]&[email protected]"
684 serviceURL := testutils.URLMust(testURL)
685 err := service.Initialize(serviceURL, logger)
686 gomega.Expect(err).NotTo(gomega.HaveOccurred())
687 gomega.Expect(service.Config.Port).To(gomega.Equal(uint16(DefaultSMTPPort)))
688 gomega.Expect(service.Config.Timeout).To(gomega.Equal(10 * time.Second))
689 })
690 })
691
692 ginkgo.When("configuring timeout via URL", func() {
693 ginkgo.It("should use the specified timeout", func() {
694 testURL := modifyURL(BaseNoAuthURL, map[string]string{"timeout": "5s"})
695 serviceURL := testutils.URLMust(testURL)
696 err := service.Initialize(serviceURL, logger)
697 gomega.Expect(err).NotTo(gomega.HaveOccurred())
698 gomega.Expect(service.Config.Timeout).To(gomega.Equal(5 * time.Second))
699 })
700 })
701
702 ginkgo.It("returns the correct service identifier", func() {
703 gomega.Expect(service.GetID()).To(gomega.Equal("smtp"))
704 })
705 })
706
707 func (m *mockConn) Close() error {
708 m.closeCount++
709
710 _, _ = ginkgo.GinkgoWriter.Write([]byte("mockConn.Close called\n"))
711
712 if m.closeCount > 1 {
713 return errors.New("mock close error")
714 }
715
716 return nil
717 }
718 func (m *mockConn) LocalAddr() net.Addr { return nil }
719 func (m *mockConn) Read(_ []byte) (int, error) { return 0, nil }
720 func (m *mockConn) RemoteAddr() net.Addr { return nil }
721 func (m *mockConn) SetDeadline(_ time.Time) error { return nil }
722 func (m *mockConn) SetReadDeadline(_ time.Time) error { return nil }
723 func (m *mockConn) SetWriteDeadline(_ time.Time) error { return nil }
724 func (m *mockConn) Write(b []byte) (int, error) { return len(b), nil }
725
726 func TestSMTP(t *testing.T) {
727 t.Parallel()
728 gomega.RegisterFailHandler(ginkgo.Fail)
729
730 tt = t
731 ginkgo.RunSpecs(t, "Shoutrrr SMTP Suite")
732 }
733
734 // fakeTLSEnabled tricks a given client into believing that TLS is enabled even though it's not
735 // this is needed because the SMTP library won't allow plain authentication without TLS being turned on.
736 // having it turned on would of course mean that we cannot test the communication since it will be encrypted.
737 func fakeTLSEnabled(client *smtp.Client, hostname string) {
738 // set the "tls" flag on the client which indicates that TLS encryption is enabled (even though it's not)
739 cr := reflect.ValueOf(client).Elem().FieldByName("tls")
740 cr = reflect.NewAt(cr.Type(), unsafe.Pointer(cr.UnsafeAddr())).Elem()
741 cr.SetBool(true)
742 // set the serverName field on the client which is used to identify the server and has to equal the hostname
743 cr = reflect.ValueOf(client).Elem().FieldByName("serverName")
744 cr = reflect.NewAt(cr.Type(), unsafe.Pointer(cr.UnsafeAddr())).Elem()
745 cr.SetString(hostname)
746 }
747
748 // matchFailure is a simple wrapper around `fail` and `gomega.MatchError` to make it easier to use in tests.
749 func matchFailure(id failures.FailureID) gomegaTypes.GomegaMatcher {
750 return gomega.MatchError(fail(id, nil))
751 }
752
753 // modifyURL modifies a base URL by updating query parameters as specified.
754 func modifyURL(base string, params map[string]string) string {
755 u := testutils.URLMust(base)
756
757 q := u.Query()
758 for k, v := range params {
759 q.Set(k, v)
760 }
761
762 u.RawQuery = q.Encode()
763
764 return u.String()
765 }
766
767 func testIntegration(
768 testURL string,
769 responses []string,
770 htmlTemplate string,
771 plainTemplate string,
772 expectRec ...string,
773 ) failures.Failure {
774 serviceURL, err := url.Parse(testURL)
775 if err != nil {
776 return standard.Failure(standard.FailParseURL, err)
777 }
778
779 if err = service.Initialize(serviceURL, logger); err != nil {
780 return standard.Failure(standard.FailServiceInit, err)
781 }
782
783 if htmlTemplate != "" {
784 if err := service.SetTemplateString("HTML", htmlTemplate); err != nil {
785 return failures.Wrap("error setting HTML template", standard.FailTestSetup, err)
786 }
787 }
788
789 if plainTemplate != "" {
790 if err := service.SetTemplateString("plain", plainTemplate); err != nil {
791 return failures.Wrap("error setting plain template", standard.FailTestSetup, err)
792 }
793 }
794
795 textCon, tcfaker := testutils.CreateTextConFaker(responses, "\r\n")
796 client := &smtp.Client{Text: textCon}
797 fakeTLSEnabled(client, serviceURL.Hostname())
798 ferr := service.doSend(client, "Test message", service.Config)
799
800 received := tcfaker.GetClientSentences()
801 for _, expected := range expectRec {
802 gomega.Expect(received).To(gomega.ContainElement(expected))
803 }
804
805 logger.Printf("\n%s", tcfaker.GetConversation(false))
806
807 if ferr != nil {
808 return ferr
809 }
810
811 return nil
812 }
813
814 func testSendRecipient(testURL string, responses []string) failures.Failure {
815 serviceURL, err := url.Parse(testURL)
816 if err != nil {
817 return standard.Failure(standard.FailParseURL, err)
818 }
819
820 err = service.Initialize(serviceURL, logger)
821 if err != nil {
822 return failures.Wrap("error parsing URL", standard.FailTestSetup, err)
823 }
824
825 if err := service.SetTemplateString("plain", "{{.message}}"); err != nil {
826 return failures.Wrap("error setting plain template", standard.FailTestSetup, err)
827 }
828
829 textCon, tcfaker := testutils.CreateTextConFaker(responses, "\r\n")
830 client := &smtp.Client{Text: textCon}
831 fakeTLSEnabled(client, serviceURL.Hostname())
832
833 config := &Config{}
834 message := "message body"
835 ferr := service.sendToRecipient(client, "[email protected]", config, message)
836
837 logger.Printf("\n%s", tcfaker.GetConversation(false))
838
839 if ferr != nil {
840 return ferr
841 }
842
843 return nil
844 }