Debian Codegraph @

pkg/services/email/smtp/smtp_test.go

raw
1 package smtp
2
3 import (
4 "bytes"
5 "context"
6 "log"
7 "net/smtp"
8 "net/url"
9 "time"
10
11 ginkgo "github.com/onsi/ginkgo/v2"
12 gomega "github.com/onsi/gomega"
13
14 "github.com/nicholas-fedor/shoutrrr/internal/testutils"
15 "github.com/nicholas-fedor/shoutrrr/pkg/format"
16 "github.com/nicholas-fedor/shoutrrr/pkg/types"
17 typesmocks "github.com/nicholas-fedor/shoutrrr/pkg/types/mocks"
18 )
19
20 var _ = ginkgo.Describe("Service", func() {
21 ginkgo.BeforeEach(func() {
22 service = &Service{}
23 })
24
25 ginkgo.Describe("GetID", func() {
26 ginkgo.It("should return smtp", func() {
27 gomega.Expect(service.GetID()).To(gomega.Equal(Scheme))
28 })
29 })
30
31 ginkgo.Describe("Initialize", func() {
32 ginkgo.It("should apply the default SMTP port and timeout when omitted", func() {
33 mockLogger := typesmocks.NewMockStdLogger(ginkgo.GinkgoT())
34 serviceURL := testutils.URLMust(
35 "smtp://example.com/[email protected]&[email protected]",
36 )
37
38 gomega.Expect(service.Initialize(serviceURL, mockLogger)).To(gomega.Succeed())
39 gomega.Expect(service.Config.Port).To(gomega.Equal(uint16(DefaultSMTPPort)))
40 gomega.Expect(service.Config.Timeout).To(gomega.Equal(defaultTimeout))
41 })
42
43 ginkgo.It("should infer AuthPlain when a username is present", func() {
44 serviceURL := testutils.URLMust(
45 "smtp://user:[email protected]/[email protected]&[email protected]",
46 )
47
48 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
49 gomega.Expect(service.Config.Auth).To(gomega.Equal(AuthTypes.Plain))
50 })
51
52 ginkgo.It("should infer AuthNone when no username is present", func() {
53 serviceURL := testutils.URLMust(
54 "smtp://example.com/[email protected]&[email protected]",
55 )
56
57 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
58 gomega.Expect(service.Config.Auth).To(gomega.Equal(AuthTypes.None))
59 })
60
61 ginkgo.It("should keep an explicit auth method", func() {
62 serviceURL := testutils.URLMust(
63 "smtp://user:[email protected]/?auth=Login&[email protected]&[email protected]",
64 )
65
66 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
67 gomega.Expect(service.Config.Auth).To(gomega.Equal(AuthTypes.Login))
68 })
69
70 ginkgo.It("should use the specified timeout", func() {
71 serviceURL := testutils.URLMust(modifyURL(baseNoAuthURL, map[string]string{"timeout": "5s"}))
72
73 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
74 gomega.Expect(service.Config.Timeout).To(gomega.Equal(5 * time.Second))
75 })
76
77 ginkgo.It("should report the URL timeout as the send budget", func() {
78 serviceURL := testutils.URLMust(modifyURL(baseNoAuthURL, map[string]string{"timeout": "30s"}))
79
80 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
81 gomega.Expect(service.ServiceTimeout(nil)).To(gomega.Equal(30 * time.Second))
82 gomega.Expect(service.Config.Timeout).To(gomega.Equal(30 * time.Second))
83 })
84
85 ginkgo.It("should report the default timeout when the URL omits it", func() {
86 serviceURL := testutils.URLMust(
87 "smtp://example.com/[email protected]&[email protected]",
88 )
89
90 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
91 gomega.Expect(service.ServiceTimeout(nil)).To(gomega.Equal(defaultTimeout))
92 })
93
94 ginkgo.It("should apply a timeout param without changing the stored config", func() {
95 serviceURL := testutils.URLMust(modifyURL(baseNoAuthURL, map[string]string{"timeout": "30s"}))
96
97 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
98
99 params := types.Params{"timeout": "1m"}
100 gomega.Expect(service.ServiceTimeout(&params)).To(gomega.Equal(time.Minute))
101 gomega.Expect(service.Config.Timeout).To(gomega.Equal(30 * time.Second))
102 })
103
104 ginkgo.It("should fail when the configuration URL is invalid", func() {
105 serviceURL := testutils.URLMust("smtp://example.com/")
106
107 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.MatchError(ErrFromAddressMissing))
108 })
109
110 ginkgo.It("should keep the default port when the URL port is out of range", func() {
111 serviceURL := testutils.URLMust(
112 "smtp://example.com:99999/[email protected]&[email protected]",
113 )
114
115 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
116 gomega.Expect(service.Config.Port).To(gomega.Equal(uint16(DefaultSMTPPort)))
117 })
118 })
119
120 ginkgo.Describe("Send", func() {
121 ginkgo.It("should use the default timeout when Timeout is non-positive", func() {
122 gomega.Expect(effectiveTimeout(0)).To(gomega.Equal(defaultTimeout))
123 gomega.Expect(effectiveTimeout(-time.Second)).To(gomega.Equal(defaultTimeout))
124 gomega.Expect(effectiveTimeout(5 * time.Second)).To(gomega.Equal(5 * time.Second))
125 })
126
127 ginkgo.It("should fail when the service is not configured with a reachable host", func() {
128 svc := Service{Config: &Config{Host: "127.0.0.1", Port: 1, Timeout: time.Millisecond}}
129 gomega.Expect(svc.Send("test message", nil)).To(matchFailure(FailGetSMTPClient))
130
131 svc.Config.Encryption = EncMethods.ImplicitTLS
132 gomega.Expect(svc.Send("test message", nil)).To(matchFailure(FailGetSMTPClient))
133 })
134
135 ginkgo.It("should fail when an invalid param is passed", func() {
136 svc := Service{Config: &Config{}}
137 gomega.Expect(svc.Send("test message", &types.Params{"invalid": "value"})).
138 To(matchFailure(FailApplySendParams))
139 })
140
141 ginkgo.It("should log a warning when SkipTLSVerify is enabled", func() {
142 var buf bytes.Buffer
143
144 testLogger := log.New(&buf, "", 0)
145 svc := &Service{}
146 gomega.Expect(svc.Initialize(testutils.URLMust(baseNoAuthURL), testLogger)).To(gomega.Succeed())
147 svc.Config.SkipTLSVerify = true
148 svc.Config.Host = "127.0.0.1"
149 svc.Config.Port = 1
150 svc.Config.Timeout = time.Millisecond
151
152 gomega.Expect(svc.Send("test message", nil)).To(matchFailure(FailGetSMTPClient))
153 gomega.Expect(buf.String()).
154 To(gomega.ContainSubstring("Warning: TLS verification is disabled, making connections insecure"))
155 })
156
157 ginkgo.It("should apply send params before dialing", func() {
158 address, firstByte, stop := startGreetingServer()
159 defer stop()
160
161 serviceURL := testutils.URLMust(
162 "smtp://" + address + "/?encryption=ImplicitTLS&auth=none&usestarttls=no" +
163 "&[email protected]&[email protected]&timeout=5s",
164 )
165 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
166
167 gomega.Expect(service.Send("test message", &types.Params{"encryption": "None"})).
168 To(matchFailure(FailHandshake))
169 gomega.Eventually(firstByte).Should(gomega.Receive(gomega.Equal(byte('E'))))
170 })
171
172 ginkgo.It("should time out the handshake using the configured deadline", func() {
173 address, stop := startHangingGreetingServer()
174 defer stop()
175
176 sendTimeout := 200 * time.Millisecond
177 serviceURL := testutils.URLMust(
178 "smtp://" + address + "/?auth=none&usestarttls=no" +
179 "&[email protected]&[email protected]&timeout=" +
180 sendTimeout.String(),
181 )
182 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
183
184 start := time.Now()
185 err := service.Send("test message", nil)
186
187 gomega.Expect(time.Since(start)).To(gomega.BeNumerically("<", sendTimeout+2*time.Second))
188 gomega.Expect(err).To(matchFailure(FailHandshake))
189 })
190 })
191
192 ginkgo.Describe("SendContext", func() {
193 ginkgo.It("should fail when the caller context is already canceled", func() {
194 ctx, cancel := context.WithCancel(context.Background())
195 cancel()
196
197 svc := Service{Config: &Config{Host: "example.com", Port: 25, Timeout: time.Second}}
198 err := svc.SendContext(ctx, "test message", nil)
199 gomega.Expect(err).To(matchFailure(FailGetSMTPClient))
200 gomega.Expect(err).To(gomega.MatchError(context.Canceled))
201 })
202
203 ginkgo.It("should time out the handshake using the caller context deadline", func() {
204 address, stop := startHangingGreetingServer()
205 defer stop()
206
207 parentTimeout := 200 * time.Millisecond
208 serviceURL := testutils.URLMust(
209 "smtp://" + address + "/?auth=none&usestarttls=no" +
210 "&[email protected]&[email protected]&timeout=10s",
211 )
212 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
213
214 ctx, cancel := context.WithTimeout(context.Background(), parentTimeout)
215 defer cancel()
216
217 start := time.Now()
218 err := service.SendContext(ctx, "test message", nil)
219
220 gomega.Expect(time.Since(start)).To(gomega.BeNumerically("<", parentTimeout+2*time.Second))
221 gomega.Expect(err).To(matchFailure(FailHandshake))
222 })
223 })
224
225 ginkgo.When("SkipTLSVerify is enabled on the parsed URL", func() {
226 ginkgo.It("should log a security warning when Send is called", func() {
227 localService := &Service{}
228 testURL := modifyURL(baseNoAuthURL, map[string]string{"skiptlsverify": "yes"})
229
230 var buf bytes.Buffer
231
232 testLogger := log.New(&buf, "", 0)
233 gomega.Expect(localService.Initialize(testutils.URLMust(testURL), testLogger)).To(gomega.Succeed())
234 localService.Config.Host = "127.0.0.1"
235 localService.Config.Port = 1
236 localService.Config.Timeout = time.Millisecond
237
238 gomega.Expect(localService.Send("test message", nil)).To(matchFailure(FailGetSMTPClient))
239 gomega.Expect(buf.String()).
240 To(gomega.ContainSubstring("Warning: TLS verification is disabled, making connections insecure"))
241 })
242 })
243
244 ginkgo.When("send params change the message content", func() {
245 ginkgo.It("should build the headers from the params", func() {
246 gomega.Expect(service.Initialize(testutils.URLMust(baseNoAuthURL), logger)).To(gomega.Succeed())
247
248 config := service.Config.Clone()
249 gomega.Expect(service.propKeyResolver.UpdateConfigFromParams(&config, &types.Params{
250 "fromaddress": "[email protected]",
251 "fromname": "Override",
252 "subject": "Overridden",
253 "usehtml": "yes",
254 })).To(gomega.Succeed())
255
256 textCon, tcfaker := testutils.CreateTextConFaker([]string{
257 "250-mx.google.com at your service",
258 "250 8BITMIME",
259 "250 Sender OK",
260 "250 Receiver OK",
261 "354 Go ahead",
262 "250 Data OK",
263 "221 OK",
264 }, "\r\n")
265 client := &smtp.Client{Text: textCon}
266 fakeTLSEnabled(client, "example.com")
267
268 gomega.Expect(runSMTPSession(service, client, &config)).To(gomega.Succeed())
269
270 received := tcfaker.GetClientSentences()
271 gomega.Expect(received).To(gomega.ContainElement("MAIL FROM:<[email protected]> BODY=8BITMIME"))
272 gomega.Expect(received).To(gomega.ContainElement(`From: "Override" <[email protected]>`))
273 gomega.Expect(received).To(gomega.ContainElement("Subject: Overridden"))
274 gomega.Expect(received).
275 To(gomega.ContainElement(gomega.HavePrefix("Content-Type: multipart/alternative; boundary=")))
276 })
277 })
278
279 ginkgo.When("running E2E tests", func() {
280 ginkgo.It("should work without errors", func() {
281 if envSMTPURL == "" {
282 ginkgo.Skip("environment not set up for E2E testing")
283 }
284
285 serviceURL, err := url.Parse(envSMTPURL)
286 gomega.Expect(err).NotTo(gomega.HaveOccurred())
287 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
288 gomega.Expect(service.Send("this is an integration test", nil)).To(gomega.Succeed())
289 })
290 })
291
292 ginkgo.When("configuring timeout via params", func() {
293 ginkgo.It("should use the specified timeout", func() {
294 config := &Config{}
295 resolver := format.NewPropKeyResolver(config)
296 params := types.Params{"timeout": "1h2m3s"}
297
298 gomega.Expect(resolver.UpdateConfigFromParams(config, &params)).To(gomega.Succeed())
299 gomega.Expect(config.Timeout).To(gomega.Equal(1*time.Hour + 2*time.Minute + 3*time.Second))
300 })
301
302 ginkgo.It("should reject a bare non-zero timeout value", func() {
303 config := &Config{Timeout: 5 * time.Second}
304 resolver := format.NewPropKeyResolver(config)
305 params := types.Params{"timeout": "10"}
306
307 gomega.Expect(resolver.UpdateConfigFromParams(config, &params)).
308 To(gomega.MatchError(format.ErrParseDurationFailed))
309 gomega.Expect(config.Timeout).To(gomega.Equal(5 * time.Second))
310 })
311 })
312 })