Debian Codegraph @

pkg/services/email/smtp/smtp_test.go

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