Debian Codegraph @

pkg/services/email/smtp/smtp_message_test.go

raw
1 package smtp
2
3 import (
4 "mime"
5 "net/mail"
6 "strings"
7 "text/template"
8 "time"
9
10 ginkgo "github.com/onsi/ginkgo/v2"
11 gomega "github.com/onsi/gomega"
12
13 "github.com/nicholas-fedor/shoutrrr/internal/testutils"
14 typesmocks "github.com/nicholas-fedor/shoutrrr/pkg/types/mocks"
15 )
16
17 var _ = ginkgo.Describe("message", func() {
18 ginkgo.Describe("headers", func() {
19 ginkgo.When("the subject contains non-ASCII characters", func() {
20 ginkgo.It("should encode it as an RFC 2047 encoded-word", func() {
21 headerMap := headers(
22 &Config{FromAddress: "[email protected]", Subject: "Plan überschritten"},
23 "[email protected]",
24 "",
25 )
26
27 gomega.Expect(headerMap["Subject"]).
28 To(gomega.Equal("=?UTF-8?q?Plan_=C3=BCberschritten?="))
29 gomega.Expect(new(mime.WordDecoder).DecodeHeader(headerMap["Subject"])).
30 To(gomega.Equal("Plan überschritten"))
31 })
32 })
33
34 ginkgo.When("the subject is pure ASCII", func() {
35 ginkgo.It("should leave it unencoded", func() {
36 headerMap := headers(
37 &Config{FromAddress: "[email protected]", Subject: "Plan exceeded"},
38 "[email protected]",
39 "",
40 )
41
42 gomega.Expect(headerMap["Subject"]).To(gomega.Equal("Plan exceeded"))
43 })
44 })
45
46 ginkgo.When("the subject contains CR or LF", func() {
47 ginkgo.It("should encode them so they cannot inject a Bcc header", func() {
48 headerMap := headers(
49 &Config{FromAddress: "[email protected]", Subject: "Hello\r\nBcc: [email protected]"},
50 "[email protected]",
51 "",
52 )
53
54 gomega.Expect(headerMap["Subject"]).NotTo(gomega.ContainSubstring("\r"))
55 gomega.Expect(headerMap["Subject"]).NotTo(gomega.ContainSubstring("\n"))
56 decoded, err := new(mime.WordDecoder).DecodeHeader(headerMap["Subject"])
57 gomega.Expect(err).NotTo(gomega.HaveOccurred())
58 gomega.Expect(decoded).To(gomega.Equal("Hello\r\nBcc: [email protected]"))
59
60 writer := &captureWriter{}
61 gomega.Expect(writeHeaders(writer, map[string]string{
62 "Subject": headerMap["Subject"],
63 "From": headerMap["From"],
64 })).To(gomega.Succeed())
65 gomega.Expect(writer.String()).NotTo(gomega.ContainSubstring("\nBcc:"))
66 })
67 })
68
69 ginkgo.When("the sender name contains CR or LF", func() {
70 ginkgo.It("should encode them out of the From header value", func() {
71 headerMap := headers(&Config{
72 FromName: "Eve\r\nBcc: [email protected]",
73 FromAddress: "[email protected]",
74 Subject: "Subject",
75 }, "[email protected]", "")
76
77 gomega.Expect(headerMap["From"]).NotTo(gomega.ContainSubstring("\r"))
78 gomega.Expect(headerMap["From"]).NotTo(gomega.ContainSubstring("\n"))
79 })
80 })
81
82 ginkgo.When("an identifying header is already an encoded-word", func() {
83 ginkgo.It("should not wrap an ASCII encoded-word again", func() {
84 headerMap := headers(
85 &Config{FromAddress: "[email protected]", Subject: "=?UTF-8?q?Hello?="},
86 "[email protected]",
87 "",
88 )
89
90 gomega.Expect(headerMap["Subject"]).To(gomega.Equal("=?UTF-8?q?Hello?="))
91 })
92 })
93
94 ginkgo.When("the subject is longer than 998 octets", func() {
95 ginkgo.It("should fold the value so no physical line exceeds the RFC 5322 limit", func() {
96 subject := strings.Repeat("A", 1200)
97 headerMap := headers(
98 &Config{FromAddress: "[email protected]", Subject: subject},
99 "[email protected]",
100 "",
101 )
102
103 gomega.Expect(strings.ReplaceAll(headerMap["Subject"], "\n ", "")).
104 To(gomega.Equal(subject))
105 gomega.Expect(headerMap["Subject"]).NotTo(gomega.ContainSubstring("\r"))
106
107 for line := range strings.SplitSeq("Subject: "+headerMap["Subject"], "\n") {
108 gomega.Expect(len(line)).To(gomega.BeNumerically("<=", maxHeaderLineOctets))
109 }
110 })
111 })
112
113 ginkgo.When("the sender name contains non-ASCII characters", func() {
114 ginkgo.It("should encode it and keep the address parseable", func() {
115 headerMap := headers(&Config{
116 FromName: "Grüßer",
117 FromAddress: "[email protected]",
118 Subject: "Subject",
119 }, "[email protected]", "")
120
121 gomega.Expect(headerMap["From"]).
122 To(gomega.Equal("=?utf-8?q?Gr=C3=BC=C3=9Fer?= <[email protected]>"))
123
124 address, err := mail.ParseAddress(headerMap["From"])
125 gomega.Expect(err).NotTo(gomega.HaveOccurred())
126 gomega.Expect(address.Name).To(gomega.Equal("Grüßer"))
127 gomega.Expect(address.Address).To(gomega.Equal("[email protected]"))
128 })
129 })
130
131 ginkgo.When("the sender name or address requires quoting", func() {
132 ginkgo.It("should quote them", func() {
133 headerMap := headers(&Config{
134 FromName: "Doe, John",
135 FromAddress: "odd [email protected]",
136 Subject: "Subject",
137 }, "[email protected]", "")
138
139 gomega.Expect(headerMap["From"]).
140 To(gomega.Equal(`"Doe, John" <"odd name"@example.com>`))
141 gomega.Expect(mail.ParseAddress(headerMap["From"])).
142 To(gomega.Equal(&mail.Address{
143 Name: "Doe, John",
144 Address: `odd [email protected]`,
145 }))
146 })
147 })
148
149 ginkgo.When("no sender name is configured", func() {
150 ginkgo.It("should only emit the address", func() {
151 headerMap := headers(
152 &Config{FromAddress: "[email protected]", Subject: "Subject"},
153 "[email protected]",
154 "",
155 )
156
157 gomega.Expect(headerMap["From"]).To(gomega.Equal("<[email protected]>"))
158 })
159 })
160
161 ginkgo.When("the message is HTML", func() {
162 ginkgo.It("should put the supplied boundary in the Content-Type header", func() {
163 headerMap := headers(&Config{
164 FromAddress: "[email protected]",
165 UseHTML: true,
166 }, "[email protected]", "abc123")
167
168 gomega.Expect(headerMap["Content-Type"]).
169 To(gomega.Equal(`multipart/alternative; boundary=abc123`))
170 _, hasCTE := headerMap["Content-Transfer-Encoding"]
171 gomega.Expect(hasCTE).To(gomega.BeFalse())
172 })
173 })
174
175 ginkgo.When("the message is plain text", func() {
176 ginkgo.It("should declare 8bit content-transfer-encoding", func() {
177 headerMap := headers(
178 &Config{FromAddress: "[email protected]"},
179 "[email protected]",
180 "",
181 )
182
183 gomega.Expect(headerMap["Content-Transfer-Encoding"]).To(gomega.Equal("8bit"))
184 })
185 })
186
187 ginkgo.When("constructing identifying headers", func() {
188 ginkgo.It("should generate a Message-ID using the sender domain", func() {
189 headerMap := headers(
190 &Config{FromAddress: "[email protected]"},
191 "[email protected]",
192 "",
193 )
194
195 gomega.Expect(headerMap["Message-ID"]).
196 To(gomega.MatchRegexp(`^<[0-9a-f]+@example\.com>$`))
197 })
198
199 ginkgo.It("should format the To address like From", func() {
200 headerMap := headers(
201 &Config{FromAddress: "[email protected]"},
202 "[email protected]",
203 "",
204 )
205
206 gomega.Expect(headerMap["To"]).To(gomega.Equal("<[email protected]>"))
207 })
208
209 ginkgo.It("should include a parseable Date and MIME-version", func() {
210 headerMap := headers(
211 &Config{FromAddress: "[email protected]"},
212 "[email protected]",
213 "",
214 )
215
216 gomega.Expect(headerMap["MIME-version"]).To(gomega.Equal("1.0"))
217 _, err := time.Parse(time.RFC1123Z, headerMap["Date"])
218 gomega.Expect(err).NotTo(gomega.HaveOccurred())
219 })
220
221 ginkgo.It("should encode a non-ASCII recipient local-part", func() {
222 headerMap := headers(
223 &Config{FromAddress: "[email protected]"},
224 "grüß@example.com",
225 "",
226 )
227
228 gomega.Expect(headerMap["To"]).NotTo(gomega.Equal("grüß@example.com"))
229 address, err := mail.ParseAddress(headerMap["To"])
230 gomega.Expect(err).NotTo(gomega.HaveOccurred())
231 gomega.Expect(address.Address).To(gomega.Equal("grüß@example.com"))
232 })
233 })
234 })
235
236 ginkgo.Describe("generateMessageID", func() {
237 ginkgo.It("should use the sender domain", func() {
238 gomega.Expect(generateMessageID("[email protected]")).
239 To(gomega.MatchRegexp(`^<[0-9a-f]{16}@example\.com>$`))
240 })
241
242 ginkgo.It("should fall back to localhost when the address has no host", func() {
243 gomega.Expect(generateMessageID("nodomain")).
244 To(gomega.MatchRegexp(`^<[0-9a-f]{16}@localhost>$`))
245 gomega.Expect(generateMessageID("user@")).
246 To(gomega.MatchRegexp(`^<[0-9a-f]{16}@localhost>$`))
247 })
248 })
249
250 ginkgo.Describe("generateBoundary", func() {
251 ginkgo.It("should return a unique hex token", func() {
252 first, err := generateBoundary()
253 gomega.Expect(err).NotTo(gomega.HaveOccurred())
254 second, err := generateBoundary()
255 gomega.Expect(err).NotTo(gomega.HaveOccurred())
256 gomega.Expect(first).To(gomega.MatchRegexp(`^[0-9a-f]{16}$`))
257 gomega.Expect(second).To(gomega.MatchRegexp(`^[0-9a-f]{16}$`))
258 gomega.Expect(first).NotTo(gomega.Equal(second))
259 })
260 })
261
262 ginkgo.Describe("writeHeaders", func() {
263 ginkgo.It("should write each header and a blank line", func() {
264 writer := &captureWriter{}
265 gomega.Expect(writeHeaders(writer, map[string]string{"Subject": "Hello"})).To(gomega.Succeed())
266 gomega.Expect(writer.String()).To(gomega.Equal("Subject: Hello\n\n"))
267 })
268
269 ginkgo.It("should write headers in sorted key order", func() {
270 writer := &captureWriter{}
271 gomega.Expect(writeHeaders(writer, map[string]string{
272 "Subject": "Hello",
273 "From": "<[email protected]>",
274 })).To(gomega.Succeed())
275 gomega.Expect(writer.String()).To(gomega.Equal("From: <[email protected]>\nSubject: Hello\n\n"))
276 })
277
278 ginkgo.It("should fold a long header value to the RFC 5322 line limit", func() {
279 writer := &captureWriter{}
280 gomega.Expect(writeHeaders(writer, map[string]string{
281 "Subject": strings.Repeat("B", 1200),
282 })).To(gomega.Succeed())
283
284 body := strings.TrimSuffix(writer.String(), "\n")
285 for line := range strings.SplitSeq(body, "\n") {
286 gomega.Expect(len(line)).To(gomega.BeNumerically("<=", maxHeaderLineOctets))
287 }
288
289 unfolded := strings.ReplaceAll(strings.TrimPrefix(strings.ReplaceAll(body, "\n ", ""), "Subject: "), "\n", "")
290 gomega.Expect(unfolded).To(gomega.Equal(strings.Repeat("B", 1200)))
291 })
292
293 ginkgo.When("the output stream is closed during header content", func() {
294 ginkgo.It("should fail with FailWriteHeaders", func() {
295 gomega.Expect(writeHeaders(testutils.CreateFailWriter(0), map[string]string{"key": "value"})).
296 To(matchFailure(FailWriteHeaders))
297 })
298 })
299
300 ginkgo.When("the output stream is closed after header content", func() {
301 ginkgo.It("should fail with FailWriteHeaders", func() {
302 gomega.Expect(writeHeaders(testutils.CreateFailWriter(1), map[string]string{"key": "value"})).
303 To(matchFailure(FailWriteHeaders))
304 })
305 })
306 })
307
308 ginkgo.Describe("writeAlternative", func() {
309 ginkgo.It("should write plain and HTML parts with the closing boundary", func() {
310 templater := typesmocks.NewMockTemplater(ginkgo.GinkgoT())
311 templater.On("GetTemplate", templatePlain).Return(nil, false)
312 templater.On("GetTemplate", templateHTML).Return(nil, false)
313
314 writer := &captureWriter{}
315 gomega.Expect(writeAlternative(writer, "hello", "abc", templater)).To(gomega.Succeed())
316
317 body := writer.String()
318 gomega.Expect(body).To(gomega.ContainSubstring("--abc\n"))
319 gomega.Expect(body).To(gomega.ContainSubstring("Content-Type: " + contentPlain))
320 gomega.Expect(body).To(gomega.ContainSubstring("Content-Type: " + contentHTML))
321 gomega.Expect(strings.Count(body, "hello")).To(gomega.Equal(2))
322 gomega.Expect(body).To(gomega.ContainSubstring("--abc--"))
323 })
324
325 ginkgo.When("the underlying stream stops working", func() {
326 ginkgo.It("should fail when writing multipart plain header", func() {
327 err := writeAlternative(testutils.CreateFailWriter(1), "", "boundary", &Service{})
328 gomega.Expect(err).To(matchFailure(FailPlainHeader))
329 })
330
331 ginkgo.It("should fail when writing multipart plain message", func() {
332 err := writeAlternative(testutils.CreateFailWriter(2), "", "boundary", &Service{})
333 gomega.Expect(err).To(matchFailure(FailMessageRaw))
334 })
335
336 ginkgo.It("should fail when writing multipart HTML header", func() {
337 err := writeAlternative(testutils.CreateFailWriter(4), "", "boundary", &Service{})
338 gomega.Expect(err).To(matchFailure(FailHTMLHeader))
339 })
340
341 ginkgo.It("should fail when writing multipart HTML message", func() {
342 err := writeAlternative(testutils.CreateFailWriter(5), "", "boundary", &Service{})
343 gomega.Expect(err).To(matchFailure(FailMessageRaw))
344 })
345
346 ginkgo.It("should fail when writing multipart end header", func() {
347 err := writeAlternative(testutils.CreateFailWriter(6), "", "boundary", &Service{})
348 gomega.Expect(err).To(matchFailure(FailMultiEndHeader))
349 })
350 })
351 })
352
353 ginkgo.Describe("writePart", func() {
354 ginkgo.It("should write the raw message when no template is registered", func() {
355 templater := typesmocks.NewMockTemplater(ginkgo.GinkgoT())
356 templater.On("GetTemplate", "HTML").Return(nil, false)
357
358 writer := &captureWriter{}
359 gomega.Expect(writePart(writer, "<p>styled</p>", "HTML", templater)).To(gomega.Succeed())
360 gomega.Expect(writer.String()).To(gomega.Equal("<p>styled</p>"))
361 })
362
363 ginkgo.It("should execute a registered template", func() {
364 tpl := template.Must(template.New("plain").Parse("wrapped {{.message}}"))
365 templater := typesmocks.NewMockTemplater(ginkgo.GinkgoT())
366 templater.On("GetTemplate", templatePlain).Return(tpl, true)
367
368 writer := &captureWriter{}
369 gomega.Expect(writePart(writer, "hello", templatePlain, templater)).To(gomega.Succeed())
370 gomega.Expect(writer.String()).To(gomega.Equal("wrapped hello"))
371 })
372
373 ginkgo.It("should fail when the template cannot be executed", func() {
374 tpl := template.Must(template.New("dummy").Parse("{{.message.Bogus}}"))
375 templater := typesmocks.NewMockTemplater(ginkgo.GinkgoT())
376 templater.On("GetTemplate", "dummy").Return(tpl, true)
377
378 err := writePart(&captureWriter{}, "hello", "dummy", templater)
379 gomega.Expect(err).To(matchFailure(FailMessageTemplate))
380 })
381
382 ginkgo.It("should fail when writing a template to a closed stream", func() {
383 service := Service{}
384 gomega.Expect(service.SetTemplateString("dummy", "dummy template content")).To(gomega.Succeed())
385
386 err := writePart(testutils.CreateFailWriter(0), "", "dummy", &service)
387 gomega.Expect(err).To(matchFailure(FailMessageTemplate))
388 })
389 })
390
391 ginkgo.Describe("writePartHeader", func() {
392 ginkgo.It("should write a part header with content type", func() {
393 writer := &captureWriter{}
394 gomega.Expect(writePartHeader(writer, "abc", contentPlain)).To(gomega.Succeed())
395 gomega.Expect(writer.String()).To(gomega.HavePrefix("\n\n--abc\n"))
396 gomega.Expect(writer.String()).To(gomega.ContainSubstring("Content-Type: " + contentPlain))
397 gomega.Expect(writer.String()).To(gomega.ContainSubstring("Content-Transfer-Encoding: 8bit"))
398 })
399
400 ginkgo.It("should write the closing boundary when content type is empty", func() {
401 writer := &captureWriter{}
402 gomega.Expect(writePartHeader(writer, "abc", "")).To(gomega.Succeed())
403 gomega.Expect(writer.String()).To(gomega.Equal("\n\n--abc--"))
404 })
405
406 ginkgo.It("should fail when the writer rejects the boundary", func() {
407 err := writePartHeader(testutils.CreateFailWriter(0), "abc", contentPlain)
408 gomega.Expect(err).To(gomega.HaveOccurred())
409 gomega.Expect(err.Error()).To(gomega.ContainSubstring("writing multipart boundary"))
410 })
411 })
412 })