Debian Codegraph @

pkg/services/push/ntfy/ntfy_test.go

raw
1 package ntfy
2
3 import (
4 "crypto/rand"
5 "crypto/rsa"
6 "crypto/tls"
7 "crypto/x509"
8 "crypto/x509/pkix"
9 "encoding/json"
10 "fmt"
11 "log"
12 "math/big"
13 "net"
14 "net/http"
15 "net/http/httptest"
16 "net/url"
17 "os"
18 "testing"
19 "time"
20
21 "github.com/jarcoal/httpmock"
22 "github.com/onsi/ginkgo/v2"
23 "github.com/onsi/gomega"
24
25 gomegaformat "github.com/onsi/gomega/format"
26
27 "github.com/nicholas-fedor/shoutrrr/internal/testutils"
28 "github.com/nicholas-fedor/shoutrrr/pkg/format"
29 "github.com/nicholas-fedor/shoutrrr/pkg/util/jsonclient"
30 )
31
32 var (
33 service = &Service{}
34 envBarkURL *url.URL
35 logger *log.Logger = testutils.TestLogger()
36 _ = ginkgo.BeforeSuite(func() {
37 envBarkURL, _ = url.Parse(os.Getenv("SHOUTRRR_NTFY_URL"))
38 })
39 )
40
41 var _ = ginkgo.Describe("the ntfy service", func() {
42 ginkgo.When("running integration tests", func() {
43 ginkgo.It("should not error out", func() {
44 if envBarkURL.String() == "" {
45 ginkgo.Skip("No integration test ENV URL was set")
46
47 return
48 }
49
50 serviceURL := testutils.URLMust(envBarkURL.String())
51 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
52 gomega.Expect(service.Send("This is an integration test message", nil)).
53 To(gomega.Succeed())
54 })
55 })
56
57 ginkgo.Describe("the config", func() {
58 ginkgo.When("getting a API URL", func() {
59 ginkgo.It("should return the expected URL", func() {
60 gomega.Expect((&Config{
61 Host: "host:8080",
62 Scheme: "http",
63 Topic: "topic",
64 }).GetAPIURL()).To(gomega.Equal("http://host:8080/topic"))
65 })
66 })
67 ginkgo.When("only required fields are set", func() {
68 ginkgo.It("should set the optional fields to the defaults", func() {
69 serviceURL := testutils.URLMust("ntfy://hostname/topic")
70 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
71 gomega.Expect(*service.Config).To(gomega.Equal(Config{
72 Host: "hostname",
73 Topic: "topic",
74 Scheme: "https",
75 Tags: []string{""},
76 Actions: []string{""},
77 Priority: 3,
78 Firebase: true,
79 Cache: true,
80 DisableTLSVerification: false,
81 DisableTLS: false,
82 }))
83 })
84 })
85 ginkgo.When("parsing the configuration URL", func() {
86 ginkgo.It("should be identical after de-/serialization", func() {
87 testURL := "ntfy://user:[email protected]:2225/topic?cache=No&click=CLICK&disabletls=No&disabletlsverification=No&firebase=No&icon=ICON&priority=Max&scheme=http&title=TITLE"
88 config := &Config{}
89 service.client = jsonclient.NewWithHTTPClient(service.httpClient)
90 pkr := format.NewPropKeyResolver(config)
91 gomega.Expect(config.setURL(&pkr, testutils.URLMust(testURL))).
92 To(gomega.Succeed(), "verifying")
93 gomega.Expect(config.GetURL().String()).To(gomega.Equal(testURL))
94 })
95 })
96 })
97
98 ginkgo.When("sending the push payload", func() {
99 ginkgo.BeforeEach(func() {
100 serviceURL := testutils.URLMust("ntfy://:devicekey@hostname/testtopic")
101 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
102 httpmock.ActivateNonDefault(service.httpClient)
103 })
104 ginkgo.AfterEach(func() {
105 httpmock.DeactivateAndReset()
106 })
107
108 ginkgo.It("should not report an error if the server accepts the payload", func() {
109 httpmock.RegisterResponder(
110 "POST",
111 service.Config.GetAPIURL(),
112 testutils.JSONRespondMust(200, apiResponseError{
113 Code: http.StatusOK,
114 Message: "OK",
115 }),
116 )
117 gomega.Expect(service.Send("Message", nil)).To(gomega.Succeed())
118 })
119
120 ginkgo.It("should not panic if a server error occurs", func() {
121 httpmock.RegisterResponder(
122 "POST",
123 service.Config.GetAPIURL(),
124 testutils.JSONRespondMust(500, apiResponseError{
125 Code: 500,
126 Message: "someone turned off the internet",
127 }),
128 )
129 gomega.Expect(service.Send("Message", nil)).To(gomega.HaveOccurred())
130 })
131
132 ginkgo.It("should not panic if a communication error occurs", func() {
133 httpmock.DeactivateAndReset()
134
135 serviceURL := testutils.URLMust("ntfy://:devicekey@nonresolvablehostname/testtopic")
136 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
137 gomega.Expect(service.Send("Message", nil)).To(gomega.HaveOccurred())
138 })
139 })
140
141 ginkgo.Describe("the basic service API", func() {
142 ginkgo.Describe("the service config", func() {
143 ginkgo.It("should implement basic service config API methods correctly", func() {
144 testutils.TestConfigGetInvalidQueryValue(&Config{})
145 testutils.TestConfigSetInvalidQueryValue(&Config{}, "ntfy://host/topic?foo=bar")
146 testutils.TestConfigSetDefaultValues(&Config{})
147 testutils.TestConfigGetEnumsCount(&Config{}, 1)
148 testutils.TestConfigGetFieldsCount(&Config{}, 17)
149 })
150 })
151 ginkgo.Describe("the service instance", func() {
152 ginkgo.BeforeEach(func() {
153 serviceURL := testutils.URLMust("ntfy://:devicekey@hostname/testtopic")
154 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
155 httpmock.ActivateNonDefault(service.httpClient)
156 })
157 ginkgo.AfterEach(func() {
158 httpmock.DeactivateAndReset()
159 })
160 ginkgo.It("should implement basic service API methods correctly", func() {
161 serviceURL := testutils.URLMust("ntfy://:devicekey@hostname/testtopic")
162 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
163 testutils.TestServiceSetInvalidParamValue(service, "foo", "bar")
164 })
165 })
166 })
167
168 ginkgo.Describe("TLS certificate verification", func() {
169 ginkgo.It(
170 "should fail with TLS certificate verification error when RootCAs is empty",
171 func() {
172 // Generate a self-signed certificate that is not trusted by Go's default RootCAs
173 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
174 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
175
176 template := x509.Certificate{
177 SerialNumber: big.NewInt(1),
178 Subject: pkix.Name{
179 Organization: []string{"Test Organization"},
180 },
181 NotBefore: time.Now(),
182 NotAfter: time.Now().Add(time.Hour),
183 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
184 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
185 BasicConstraintsValid: true,
186 IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
187 }
188
189 derBytes, err := x509.CreateCertificate(
190 rand.Reader,
191 &template,
192 &template,
193 &privKey.PublicKey,
194 privKey,
195 )
196 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
197
198 // Create a test server with the self-signed certificate
199 server := httptest.NewUnstartedServer(
200 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
201 w.WriteHeader(http.StatusOK)
202 _, _ = w.Write([]byte("OK"))
203 }),
204 )
205 server.TLS = &tls.Config{
206 Certificates: []tls.Certificate{
207 {
208 Certificate: [][]byte{derBytes},
209 PrivateKey: privKey,
210 },
211 },
212 }
213
214 server.StartTLS()
215 defer server.Close()
216
217 // Create an HTTP client with empty RootCAs to simulate the problematic configuration
218 client := &http.Client{
219 Transport: &http.Transport{
220 TLSClientConfig: &tls.Config{
221 RootCAs: x509.NewCertPool(), // Empty cert pool
222 },
223 },
224 }
225
226 // Attempt to make a request to the test server
227 resp, err := client.Get(server.URL)
228
229 // Assert that the request fails with the exact error message
230 gomega.Expect(err).To(gomega.HaveOccurred())
231 gomega.Expect(err.Error()).
232 To(gomega.ContainSubstring("tls: failed to verify certificate: x509: certificate signed by unknown authority"))
233
234 // Ensure response is nil since the request failed
235 gomega.Expect(resp).To(gomega.BeNil())
236 },
237 )
238
239 ginkgo.It("should succeed when RootCAs is properly configured", func() {
240 // Create a test server with a valid TLS certificate
241 server := httptest.NewTLSServer(
242 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
243 w.WriteHeader(http.StatusOK)
244 _, _ = w.Write([]byte("OK"))
245 }),
246 )
247 defer server.Close()
248
249 // Create a dedicated HTTP client with the test server's certificate in RootCAs
250 certPool := x509.NewCertPool()
251 certPool.AddCert(server.Certificate())
252
253 transport := &http.Transport{
254 TLSClientConfig: &tls.Config{
255 RootCAs: certPool,
256 },
257 }
258 client := &http.Client{Transport: transport}
259
260 // Attempt to make a request to the test server
261 resp, err := client.Get(server.URL)
262
263 // Assert that the request succeeds
264 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
265 gomega.Expect(resp.StatusCode).To(gomega.Equal(http.StatusOK))
266
267 _ = resp.Body.Close()
268 })
269
270 ginkgo.It(
271 "should fail when using the actual ntfy service with an untrusted certificate",
272 func() {
273 // Generate a self-signed certificate that is not trusted by Go's default RootCAs
274 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
275 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
276
277 template := x509.Certificate{
278 SerialNumber: big.NewInt(1),
279 Subject: pkix.Name{
280 Organization: []string{"Test Organization"},
281 },
282 NotBefore: time.Now(),
283 NotAfter: time.Now().Add(time.Hour),
284 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
285 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
286 BasicConstraintsValid: true,
287 IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
288 }
289
290 derBytes, err := x509.CreateCertificate(
291 rand.Reader,
292 &template,
293 &template,
294 &privKey.PublicKey,
295 privKey,
296 )
297 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
298
299 // Create a test server with the self-signed certificate
300 server := httptest.NewUnstartedServer(
301 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
302 // Simulate successful ntfy API response
303 response := apiResponseError{
304 Code: http.StatusOK,
305 Message: "OK",
306 }
307
308 w.Header().Set("Content-Type", "application/json")
309 w.WriteHeader(http.StatusOK)
310 _ = json.NewEncoder(w).Encode(response)
311 }),
312 )
313 server.TLS = &tls.Config{
314 Certificates: []tls.Certificate{
315 {
316 Certificate: [][]byte{derBytes},
317 PrivateKey: privKey,
318 },
319 },
320 }
321
322 server.StartTLS()
323 defer server.Close()
324
325 // Parse the test server URL to extract host and construct ntfy URL
326 serverURL, err := url.Parse(server.URL)
327 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
328
329 // Create ntfy service URL pointing to the test server
330 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
331
332 // Initialize the ntfy service with the test server URL
333 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
334
335 // Attempt to send a message using the actual service.Send method
336 // This should fail due to untrusted certificate
337 gomega.Expect(service.Send("Test message", nil)).To(gomega.HaveOccurred())
338 },
339 )
340 ginkgo.It(
341 "should fail with Let's Encrypt certificate when RootCAs is empty (GitHub Issue #410 scenario)",
342 func() {
343 // This test simulates the exact scenario from GitHub Issue #410:
344 // Attempting to send to an ntfy server with a valid Let's Encrypt certificate
345 // but failing due to TLS verification issues caused by empty RootCAs
346
347 // Generate a certificate that mimics Let's Encrypt structure (self-signed for testing)
348 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
349 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
350
351 // Create a certificate with Let's Encrypt-like subject
352 template := x509.Certificate{
353 SerialNumber: big.NewInt(1),
354 Subject: pkix.Name{
355 CommonName: "ntfy.sh",
356 Organization: []string{"Let's Encrypt"},
357 },
358 NotBefore: time.Now(),
359 NotAfter: time.Now().Add(time.Hour),
360 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
361 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
362 BasicConstraintsValid: true,
363 DNSNames: []string{"ntfy.sh"},
364 }
365
366 derBytes, err := x509.CreateCertificate(
367 rand.Reader,
368 &template,
369 &template,
370 &privKey.PublicKey,
371 privKey,
372 )
373 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
374
375 // Create a test server simulating ntfy.sh with Let's Encrypt-like certificate
376 server := httptest.NewUnstartedServer(
377 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
378 // Simulate successful ntfy API response
379 response := apiResponseError{
380 Code: http.StatusOK,
381 Message: "OK",
382 }
383
384 w.Header().Set("Content-Type", "application/json")
385 w.WriteHeader(http.StatusOK)
386 _ = json.NewEncoder(w).Encode(response)
387 }),
388 )
389 server.TLS = &tls.Config{
390 Certificates: []tls.Certificate{
391 {
392 Certificate: [][]byte{derBytes},
393 PrivateKey: privKey,
394 },
395 },
396 }
397
398 server.StartTLS()
399 defer server.Close()
400
401 // Parse the test server URL to extract host and construct ntfy URL
402 serverURL, err := url.Parse(server.URL)
403 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
404
405 // Create ntfy service URL pointing to the test server
406 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
407
408 // Initialize the ntfy service with the test server URL
409 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
410
411 // Attempt to send a message - this should fail because the certificate
412 // is not in the default RootCAs (simulating the issue where RootCAs is empty)
413 err = service.Send("Test message", nil)
414 gomega.Expect(err).To(gomega.HaveOccurred())
415 gomega.Expect(err.Error()).
416 To(gomega.ContainSubstring("tls: failed to verify certificate"))
417 },
418 )
419
420 ginkgo.It("should fail with outdated RootCAs that don't include Let's Encrypt", func() {
421 // This test demonstrates failure when using RootCAs that predate Let's Encrypt
422 // (before 2016 when Let's Encrypt became widely available)
423
424 // Generate a certificate signed by a CA that represents an outdated RootCAs
425 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
426 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
427
428 // Create a CA certificate (representing an old CA that doesn't know about Let's Encrypt)
429 caTemplate := x509.Certificate{
430 SerialNumber: big.NewInt(1),
431 Subject: pkix.Name{
432 CommonName: "Old CA",
433 Organization: []string{"Pre-2016 Certificate Authority"},
434 },
435 NotBefore: time.Now().AddDate(-10, 0, 0), // 10 years ago
436 NotAfter: time.Now().AddDate(10, 0, 0),
437 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
438 BasicConstraintsValid: true,
439 IsCA: true,
440 }
441
442 caPrivKey, err := rsa.GenerateKey(rand.Reader, 2048)
443 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
444
445 caDerBytes, err := x509.CreateCertificate(
446 rand.Reader,
447 &caTemplate,
448 &caTemplate,
449 &caPrivKey.PublicKey,
450 caPrivKey,
451 )
452 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
453
454 // Generate a second CA (modern/Let's Encrypt-like)
455 caTemplateModern := x509.Certificate{
456 SerialNumber: big.NewInt(3),
457 Subject: pkix.Name{
458 CommonName: "Let's Encrypt Authority X3",
459 Organization: []string{"Let's Encrypt"},
460 },
461 NotBefore: time.Now().AddDate(-2, 0, 0), // 2 years ago
462 NotAfter: time.Now().AddDate(5, 0, 0),
463 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
464 BasicConstraintsValid: true,
465 IsCA: true,
466 }
467
468 caPrivKeyModern, err := rsa.GenerateKey(rand.Reader, 2048)
469 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
470
471 modernCaDerBytes, err := x509.CreateCertificate(
472 rand.Reader,
473 &caTemplateModern,
474 &caTemplateModern,
475 &caPrivKeyModern.PublicKey,
476 caPrivKeyModern,
477 )
478 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
479
480 // Create server certificate signed by the modern CA
481 serverTemplate := x509.Certificate{
482 SerialNumber: big.NewInt(2),
483 Subject: pkix.Name{
484 CommonName: "ntfy.sh",
485 Organization: []string{"Let's Encrypt"},
486 },
487 NotBefore: time.Now(),
488 NotAfter: time.Now().Add(time.Hour),
489 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
490 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
491 BasicConstraintsValid: true,
492 DNSNames: []string{"ntfy.sh"},
493 }
494
495 serverDerBytes, err := x509.CreateCertificate(
496 rand.Reader,
497 &serverTemplate,
498 &caTemplateModern,
499 &privKey.PublicKey,
500 caPrivKeyModern,
501 )
502 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
503
504 // Create a test server with the certificate signed by modern CA
505 server := httptest.NewUnstartedServer(
506 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
507 response := apiResponseError{
508 Code: http.StatusOK,
509 Message: "OK",
510 }
511
512 w.Header().Set("Content-Type", "application/json")
513 w.WriteHeader(http.StatusOK)
514 _ = json.NewEncoder(w).Encode(response)
515 }),
516 )
517 server.TLS = &tls.Config{
518 Certificates: []tls.Certificate{
519 {
520 Certificate: [][]byte{serverDerBytes, modernCaDerBytes},
521 PrivateKey: privKey,
522 },
523 },
524 MinVersion: tls.VersionTLS13,
525 }
526
527 server.StartTLS()
528 defer server.Close()
529
530 // Create RootCAs that only contains the old CA (simulating outdated trust store)
531 outdatedRootCAs := x509.NewCertPool()
532 caCert, err := x509.ParseCertificate(caDerBytes)
533 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
534 outdatedRootCAs.AddCert(caCert)
535
536 // Create a dedicated HTTP client with outdated RootCAs
537 transport := &http.Transport{
538 TLSClientConfig: &tls.Config{
539 RootCAs: outdatedRootCAs,
540 },
541 }
542 client := &http.Client{Transport: transport}
543 service.SetHTTPClient(client)
544
545 // Parse the test server URL to extract host and construct ntfy URL
546 serverURL, err := url.Parse(server.URL)
547 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
548
549 // Create ntfy service URL pointing to the test server
550 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
551
552 // Initialize the ntfy service with the test server URL
553 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
554
555 // Attempt to send a message - this should fail because the certificate
556 // is signed by a CA not in the outdated RootCAs
557 err = service.Send("Test message", nil)
558 gomega.Expect(err).To(gomega.HaveOccurred())
559 gomega.Expect(err.Error()).
560 To(gomega.ContainSubstring("tls: failed to verify certificate"))
561 })
562
563 ginkgo.It("should fail with missing intermediate certificates", func() {
564 // This test demonstrates failure when intermediate certificates are missing
565 // from the certificate chain, which is common with Let's Encrypt certificates
566 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
567 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
568
569 // Create an intermediate CA certificate
570 intermediateTemplate := x509.Certificate{
571 SerialNumber: big.NewInt(1),
572 Subject: pkix.Name{
573 CommonName: "R3",
574 Organization: []string{"Let's Encrypt"},
575 },
576 NotBefore: time.Now().AddDate(-1, 0, 0),
577 NotAfter: time.Now().AddDate(1, 0, 0),
578 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
579 BasicConstraintsValid: true,
580 IsCA: true,
581 }
582
583 intermediatePrivKey, err := rsa.GenerateKey(rand.Reader, 2048)
584 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
585
586 // Create root CA certificate
587 rootTemplate := x509.Certificate{
588 SerialNumber: big.NewInt(0),
589 Subject: pkix.Name{
590 CommonName: "ISRG Root X1",
591 Organization: []string{"Internet Security Research Group"},
592 },
593 NotBefore: time.Now().AddDate(-2, 0, 0),
594 NotAfter: time.Now().AddDate(10, 0, 0),
595 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
596 BasicConstraintsValid: true,
597 IsCA: true,
598 }
599
600 rootPrivKey, err := rsa.GenerateKey(rand.Reader, 2048)
601 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
602
603 rootDerBytes, err := x509.CreateCertificate(
604 rand.Reader,
605 &rootTemplate,
606 &rootTemplate,
607 &rootPrivKey.PublicKey,
608 rootPrivKey,
609 )
610 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
611
612 intermediateDerBytes, err := x509.CreateCertificate(
613 rand.Reader,
614 &intermediateTemplate,
615 &rootTemplate,
616 &intermediatePrivKey.PublicKey,
617 rootPrivKey,
618 )
619 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
620
621 // Create server certificate signed by intermediate CA
622 serverTemplate := x509.Certificate{
623 SerialNumber: big.NewInt(2),
624 Subject: pkix.Name{
625 CommonName: "ntfy.sh",
626 },
627 NotBefore: time.Now(),
628 NotAfter: time.Now().Add(time.Hour),
629 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
630 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
631 BasicConstraintsValid: true,
632 DNSNames: []string{"ntfy.sh"},
633 }
634
635 serverDerBytes, err := x509.CreateCertificate(
636 rand.Reader,
637 &serverTemplate,
638 &intermediateTemplate,
639 &privKey.PublicKey,
640 intermediatePrivKey,
641 )
642 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
643
644 // Create a test server with ONLY the server certificate (missing intermediate)
645 server := httptest.NewUnstartedServer(
646 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
647 response := apiResponseError{
648 Code: http.StatusOK,
649 Message: "OK",
650 }
651
652 w.Header().Set("Content-Type", "application/json")
653 w.WriteHeader(http.StatusOK)
654 _ = json.NewEncoder(w).Encode(response)
655 }),
656 )
657 server.TLS = &tls.Config{
658 Certificates: []tls.Certificate{
659 {
660 Certificate: [][]byte{
661 serverDerBytes,
662 },
663 PrivateKey: privKey,
664 },
665 },
666 }
667 // Reference intermediateDerBytes to avoid unused variable warning
668 _ = intermediateDerBytes
669
670 server.StartTLS()
671 defer server.Close()
672
673 // Create RootCAs that only contains the root CA (not the intermediate)
674 rootCAs := x509.NewCertPool()
675 rootCert, err := x509.ParseCertificate(rootDerBytes)
676 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
677 rootCAs.AddCert(rootCert)
678
679 // Create a dedicated HTTP client with root CAs only
680 transport := &http.Transport{
681 TLSClientConfig: &tls.Config{
682 RootCAs: rootCAs,
683 },
684 }
685 client := &http.Client{Transport: transport}
686 service.SetHTTPClient(client)
687
688 // Parse the test server URL to extract host and construct ntfy URL
689 serverURL, err := url.Parse(server.URL)
690 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
691
692 // Create ntfy service URL pointing to the test server
693 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
694
695 // Initialize the ntfy service with the test server URL
696 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
697
698 // Attempt to send a message - this should fail because the intermediate
699 // certificate is missing from the chain
700 err = service.Send("Test message", nil)
701 gomega.Expect(err).To(gomega.HaveOccurred())
702 gomega.Expect(err.Error()).
703 To(gomega.ContainSubstring("tls: failed to verify certificate"))
704 })
705
706 ginkgo.It("should fail with network/proxy interference scenarios", func() {
707 // This test demonstrates failure when network proxies or middleboxes
708 // interfere with TLS connections by performing MITM attacks
709 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
710 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
711
712 // Create a certificate that represents what a proxy might present
713 // (different from the expected ntfy.sh certificate)
714 template := x509.Certificate{
715 SerialNumber: big.NewInt(1),
716 Subject: pkix.Name{
717 CommonName: "proxy.example.com", // Different hostname
718 Organization: []string{"Proxy Authority"},
719 },
720 NotBefore: time.Now(),
721 NotAfter: time.Now().Add(time.Hour),
722 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
723 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
724 BasicConstraintsValid: true,
725 DNSNames: []string{"proxy.example.com"},
726 }
727
728 derBytes, err := x509.CreateCertificate(
729 rand.Reader,
730 &template,
731 &template,
732 &privKey.PublicKey,
733 privKey,
734 )
735 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
736
737 // Create a test server with the proxy certificate
738 server := httptest.NewUnstartedServer(
739 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
740 // Simulate proxy interference - might return different response
741 response := apiResponseError{
742 Code: http.StatusOK,
743 Message: "Intercepted by proxy",
744 }
745
746 w.Header().Set("Content-Type", "application/json")
747 w.WriteHeader(http.StatusOK)
748 _ = json.NewEncoder(w).Encode(response)
749 }),
750 )
751 server.TLS = &tls.Config{
752 Certificates: []tls.Certificate{
753 {
754 Certificate: [][]byte{derBytes},
755 PrivateKey: privKey,
756 },
757 },
758 }
759
760 server.StartTLS()
761 defer server.Close()
762
763 // Parse the test server URL to extract host and construct ntfy URL
764 serverURL, err := url.Parse(server.URL)
765 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
766
767 // Create ntfy service URL pointing to the test server
768 // Note: We're connecting to proxy.example.com but expecting ntfy.sh
769 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
770
771 // Initialize the ntfy service with the test server URL
772 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
773
774 // Attempt to send a message - this should fail because the certificate
775 // doesn't match the expected hostname (simulating proxy interference)
776 err = service.Send("Test message", nil)
777 gomega.Expect(err).To(gomega.HaveOccurred())
778 gomega.Expect(err.Error()).
779 To(gomega.ContainSubstring("tls: failed to verify certificate"))
780 })
781
782 ginkgo.It(
783 "should succeed with properly configured TLS and valid certificate chain",
784 func() {
785 // This test demonstrates what SHOULD work - proper TLS configuration
786 // with a complete certificate chain that includes all intermediates
787 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
788 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
789
790 // Create root CA certificate
791 rootTemplate := x509.Certificate{
792 SerialNumber: big.NewInt(0),
793 Subject: pkix.Name{
794 CommonName: "Test Root CA",
795 Organization: []string{"Test Certificate Authority"},
796 },
797 NotBefore: time.Now().AddDate(-1, 0, 0),
798 NotAfter: time.Now().AddDate(5, 0, 0),
799 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
800 BasicConstraintsValid: true,
801 IsCA: true,
802 }
803
804 rootPrivKey, err := rsa.GenerateKey(rand.Reader, 2048)
805 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
806
807 rootDerBytes, err := x509.CreateCertificate(
808 rand.Reader,
809 &rootTemplate,
810 &rootTemplate,
811 &rootPrivKey.PublicKey,
812 rootPrivKey,
813 )
814 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
815
816 // Create intermediate CA certificate
817 intermediateTemplate := x509.Certificate{
818 SerialNumber: big.NewInt(1),
819 Subject: pkix.Name{
820 CommonName: "Test Intermediate CA",
821 Organization: []string{"Test Certificate Authority"},
822 },
823 NotBefore: time.Now().AddDate(-1, 0, 0),
824 NotAfter: time.Now().AddDate(2, 0, 0),
825 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
826 BasicConstraintsValid: true,
827 IsCA: true,
828 }
829
830 intermediatePrivKey, err := rsa.GenerateKey(rand.Reader, 2048)
831 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
832
833 intermediateDerBytes, err := x509.CreateCertificate(
834 rand.Reader,
835 &intermediateTemplate,
836 &rootTemplate,
837 &intermediatePrivKey.PublicKey,
838 rootPrivKey,
839 )
840 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
841
842 // Create server certificate signed by intermediate CA
843 serverTemplate := x509.Certificate{
844 SerialNumber: big.NewInt(2),
845 Subject: pkix.Name{
846 CommonName: "127.0.0.1",
847 },
848 NotBefore: time.Now(),
849 NotAfter: time.Now().Add(time.Hour),
850 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
851 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
852 BasicConstraintsValid: true,
853 IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
854 }
855
856 serverDerBytes, err := x509.CreateCertificate(
857 rand.Reader,
858 &serverTemplate,
859 &intermediateTemplate,
860 &privKey.PublicKey,
861 intermediatePrivKey,
862 )
863 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
864
865 // Create a test server with the complete certificate chain
866 server := httptest.NewUnstartedServer(
867 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
868 response := apiResponseError{
869 Code: http.StatusOK,
870 Message: "OK",
871 }
872
873 w.Header().Set("Content-Type", "application/json")
874 w.WriteHeader(http.StatusOK)
875 _ = json.NewEncoder(w).Encode(response)
876 }),
877 )
878 server.TLS = &tls.Config{
879 Certificates: []tls.Certificate{
880 {
881 Certificate: [][]byte{
882 serverDerBytes,
883 intermediateDerBytes,
884 rootDerBytes,
885 }, // Complete chain
886 PrivateKey: privKey,
887 },
888 },
889 }
890
891 server.StartTLS()
892 defer server.Close()
893
894 // Create a dedicated HTTP client with minimum TLS version 1.2 and proper RootCAs
895 rootCAs := x509.NewCertPool()
896 rootCert, err := x509.ParseCertificate(rootDerBytes)
897 // Add debug logging for the test setup
898 service.Logf(
899 "DEBUG: Test setup - server certificate chain length: %d",
900 len(server.TLS.Certificates[0].Certificate),
901 )
902
903 if len(server.TLS.Certificates[0].Certificate) > 0 {
904 cert, err := x509.ParseCertificate(server.TLS.Certificates[0].Certificate[0])
905 if err == nil {
906 service.Logf(
907 "DEBUG: Server cert subject: %s, issuer: %s",
908 cert.Subject.CommonName,
909 cert.Issuer.CommonName,
910 )
911 }
912 }
913
914 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
915 rootCAs.AddCert(rootCert)
916
917 transport := &http.Transport{
918 TLSClientConfig: &tls.Config{
919 MinVersion: tls.VersionTLS12,
920 RootCAs: rootCAs,
921 },
922 }
923 client := &http.Client{Transport: transport}
924
925 // Parse the test server URL to extract host and construct ntfy URL
926 serverURL, err := url.Parse(server.URL)
927 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
928
929 // Create ntfy service URL pointing to the test server
930 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
931
932 // Initialize the ntfy service with the test server URL
933 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
934
935 service.SetHTTPClient(client)
936
937 // Attempt to send a message - this should succeed because we have
938 // the complete certificate chain and proper RootCAs configured
939 gomega.Expect(service.Send("Test message", nil)).To(gomega.Succeed())
940 },
941 )
942
943 ginkgo.It(
944 "should succeed with default Go RootCAs when certificate is properly trusted",
945 func() {
946 // This test demonstrates success with Go's default RootCAs
947 // using httptest.NewTLSServer which provides a properly trusted certificate
948 server := httptest.NewTLSServer(
949 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
950 response := apiResponseError{
951 Code: http.StatusOK,
952 Message: "OK",
953 }
954
955 w.Header().Set("Content-Type", "application/json")
956 w.WriteHeader(http.StatusOK)
957 _ = json.NewEncoder(w).Encode(response)
958 }),
959 )
960 defer server.Close()
961
962 // Parse the test server URL to extract host and construct ntfy URL
963 serverURL, err := url.Parse(server.URL)
964 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
965
966 // Create ntfy service URL pointing to the test server
967 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
968
969 // Initialize the ntfy service with the test server URL
970 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
971
972 // Configure HTTP client to trust the test server's certificate
973 certPool := x509.NewCertPool()
974 certPool.AddCert(server.Certificate())
975 transport := &http.Transport{
976 TLSClientConfig: &tls.Config{
977 RootCAs: certPool,
978 },
979 }
980 client := &http.Client{Transport: transport}
981 service.SetHTTPClient(client)
982
983 // Attempt to send a message - this should succeed because the certificate is now trusted
984 gomega.Expect(service.Send("Test message", nil)).To(gomega.Succeed())
985 },
986 )
987
988 ginkgo.It(
989 "should fail when server uses TLS 1.0 and client requires minimum TLS 1.2",
990 func() {
991 // This test demonstrates that TLS certificate verification can fail even with valid certificates
992 // when the server uses a TLS version below the client's minimum required version.
993 // This highlights another aspect of TLS issues that can cause certificate verification failures.
994 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
995 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
996
997 template := x509.Certificate{
998 SerialNumber: big.NewInt(1),
999 Subject: pkix.Name{
1000 Organization: []string{"Test Organization"},
1001 },
1002 NotBefore: time.Now(),
1003 NotAfter: time.Now().Add(time.Hour),
1004 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
1005 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
1006 BasicConstraintsValid: true,
1007 IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
1008 }
1009
1010 derBytes, err := x509.CreateCertificate(
1011 rand.Reader,
1012 &template,
1013 &template,
1014 &privKey.PublicKey,
1015 privKey,
1016 )
1017 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1018
1019 // Create a test server that only supports TLS 1.0
1020 server := httptest.NewUnstartedServer(
1021 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
1022 response := apiResponseError{
1023 Code: http.StatusOK,
1024 Message: "OK",
1025 }
1026
1027 w.Header().Set("Content-Type", "application/json")
1028 w.WriteHeader(http.StatusOK)
1029 _ = json.NewEncoder(w).Encode(response)
1030 }),
1031 )
1032 server.TLS = &tls.Config{
1033 Certificates: []tls.Certificate{
1034 {
1035 Certificate: [][]byte{derBytes},
1036 PrivateKey: privKey,
1037 },
1038 },
1039 // Force server to use only TLS 1.0
1040 MinVersion: tls.VersionTLS10,
1041 MaxVersion: tls.VersionTLS10,
1042 }
1043
1044 server.StartTLS()
1045 defer server.Close()
1046
1047 // Create a dedicated HTTP client with minimum TLS version 1.2
1048 transport := &http.Transport{
1049 TLSClientConfig: &tls.Config{
1050 MinVersion: tls.VersionTLS12,
1051 },
1052 }
1053 client := &http.Client{Transport: transport}
1054 service.SetHTTPClient(client)
1055
1056 // Parse the test server URL to extract host and construct ntfy URL
1057 serverURL, err := url.Parse(server.URL)
1058 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1059
1060 // Create ntfy service URL pointing to the test server
1061 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
1062
1063 // Initialize the ntfy service with the test server URL
1064 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1065
1066 // Attempt to send a message - this should fail because the server only supports TLS 1.0
1067 // but the client requires minimum TLS 1.2
1068 err = service.Send("Test message", nil)
1069 gomega.Expect(err).To(gomega.HaveOccurred())
1070 gomega.Expect(err.Error()).
1071 To(gomega.ContainSubstring("tls: protocol version not supported"))
1072 },
1073 )
1074
1075 ginkgo.It(
1076 "should fail when server uses TLS 1.1 and client requires minimum TLS 1.2",
1077 func() {
1078 // This test demonstrates that TLS certificate verification can fail even with valid certificates
1079 // when the server uses TLS 1.1 but the client requires minimum TLS 1.2.
1080 // This is another common cause of TLS handshake failures that appear as certificate verification errors.
1081 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
1082 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1083
1084 template := x509.Certificate{
1085 SerialNumber: big.NewInt(1),
1086 Subject: pkix.Name{
1087 Organization: []string{"Test Organization"},
1088 },
1089 NotBefore: time.Now(),
1090 NotAfter: time.Now().Add(time.Hour),
1091 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
1092 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
1093 BasicConstraintsValid: true,
1094 IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
1095 }
1096
1097 derBytes, err := x509.CreateCertificate(
1098 rand.Reader,
1099 &template,
1100 &template,
1101 &privKey.PublicKey,
1102 privKey,
1103 )
1104 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1105
1106 // Create a test server that only supports TLS 1.1
1107 server := httptest.NewUnstartedServer(
1108 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
1109 response := apiResponseError{
1110 Code: http.StatusOK,
1111 Message: "OK",
1112 }
1113
1114 w.Header().Set("Content-Type", "application/json")
1115 w.WriteHeader(http.StatusOK)
1116 _ = json.NewEncoder(w).Encode(response)
1117 }),
1118 )
1119 server.TLS = &tls.Config{
1120 Certificates: []tls.Certificate{
1121 {
1122 Certificate: [][]byte{derBytes},
1123 PrivateKey: privKey,
1124 },
1125 },
1126 // Force server to use only TLS 1.1
1127 MinVersion: tls.VersionTLS11,
1128 MaxVersion: tls.VersionTLS11,
1129 }
1130
1131 server.StartTLS()
1132 defer server.Close()
1133
1134 // Create a dedicated HTTP client with minimum TLS version 1.2
1135 certPool := x509.NewCertPool()
1136 certPool.AddCert(server.Certificate())
1137 transport := &http.Transport{
1138 TLSClientConfig: &tls.Config{
1139 MinVersion: tls.VersionTLS12,
1140 RootCAs: certPool,
1141 },
1142 }
1143 client := &http.Client{Transport: transport}
1144
1145 // Parse the test server URL to extract host and construct ntfy URL
1146 serverURL, err := url.Parse(server.URL)
1147 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1148
1149 // Create ntfy service URL pointing to the test server
1150 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
1151
1152 // Initialize the ntfy service with the test server URL
1153 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1154
1155 service.SetHTTPClient(client)
1156
1157 // Attempt to send a message - this should fail because the server only supports TLS 1.1
1158 // but the client requires minimum TLS 1.2
1159 err = service.Send("Test message", nil)
1160 gomega.Expect(err).To(gomega.HaveOccurred())
1161 gomega.Expect(err.Error()).
1162 To(gomega.ContainSubstring("tls: protocol version not supported"))
1163 },
1164 )
1165
1166 ginkgo.It(
1167 "should succeed when server uses TLS 1.2 and client requires minimum TLS 1.2",
1168 func() {
1169 // This test demonstrates successful TLS connection when both server and client
1170 // support TLS 1.2 as the minimum version requirement.
1171 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
1172 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1173
1174 template := x509.Certificate{
1175 SerialNumber: big.NewInt(1),
1176 Subject: pkix.Name{
1177 Organization: []string{"Test Organization"},
1178 },
1179 NotBefore: time.Now(),
1180 NotAfter: time.Now().Add(time.Hour),
1181 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
1182 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
1183 BasicConstraintsValid: true,
1184 IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
1185 }
1186
1187 derBytes, err := x509.CreateCertificate(
1188 rand.Reader,
1189 &template,
1190 &template,
1191 &privKey.PublicKey,
1192 privKey,
1193 )
1194 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1195
1196 // Create a test server that supports TLS 1.2
1197 server := httptest.NewUnstartedServer(
1198 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
1199 response := apiResponseError{
1200 Code: http.StatusOK,
1201 Message: "OK",
1202 }
1203
1204 w.Header().Set("Content-Type", "application/json")
1205 w.WriteHeader(http.StatusOK)
1206 _ = json.NewEncoder(w).Encode(response)
1207 }),
1208 )
1209 server.TLS = &tls.Config{
1210 Certificates: []tls.Certificate{
1211 {
1212 Certificate: [][]byte{derBytes},
1213 PrivateKey: privKey,
1214 },
1215 },
1216 // Server supports TLS 1.2 and above
1217 MinVersion: tls.VersionTLS12,
1218 }
1219
1220 server.StartTLS()
1221 defer server.Close()
1222
1223 // Create a dedicated HTTP client with minimum TLS version 1.2
1224 certPool := x509.NewCertPool()
1225 certPool.AddCert(server.Certificate())
1226 transport := &http.Transport{
1227 TLSClientConfig: &tls.Config{
1228 MinVersion: tls.VersionTLS12,
1229 RootCAs: certPool,
1230 },
1231 }
1232 client := &http.Client{Transport: transport}
1233
1234 // Parse the test server URL to extract host and construct ntfy URL
1235 serverURL, err := url.Parse(server.URL)
1236 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1237
1238 // Create ntfy service URL pointing to the test server
1239 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
1240
1241 // Initialize the ntfy service with the test server URL
1242 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1243
1244 service.SetHTTPClient(client)
1245
1246 // Attempt to send a message - this should succeed because both server and client
1247 // support TLS 1.2 as the minimum version
1248 gomega.Expect(service.Send("Test message", nil)).To(gomega.Succeed())
1249 },
1250 )
1251
1252 ginkgo.It(
1253 "should succeed when server supports TLS 1.2+ and client requires minimum TLS 1.2",
1254 func() {
1255 // This test demonstrates successful TLS connection when the server supports TLS 1.2+
1256 // and the client requires minimum TLS 1.2 (TLS 1.3 is negotiated when available).
1257 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
1258 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1259
1260 template := x509.Certificate{
1261 SerialNumber: big.NewInt(1),
1262 Subject: pkix.Name{
1263 Organization: []string{"Test Organization"},
1264 },
1265 NotBefore: time.Now(),
1266 NotAfter: time.Now().Add(time.Hour),
1267 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
1268 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
1269 BasicConstraintsValid: true,
1270 IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
1271 }
1272
1273 derBytes, err := x509.CreateCertificate(
1274 rand.Reader,
1275 &template,
1276 &template,
1277 &privKey.PublicKey,
1278 privKey,
1279 )
1280 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1281
1282 // Create a test server that supports TLS 1.2+
1283 server := httptest.NewUnstartedServer(
1284 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
1285 response := apiResponseError{
1286 Code: http.StatusOK,
1287 Message: "OK",
1288 }
1289
1290 w.Header().Set("Content-Type", "application/json")
1291 w.WriteHeader(http.StatusOK)
1292 _ = json.NewEncoder(w).Encode(response)
1293 }),
1294 )
1295 server.TLS = &tls.Config{
1296 Certificates: []tls.Certificate{
1297 {
1298 Certificate: [][]byte{derBytes},
1299 PrivateKey: privKey,
1300 },
1301 },
1302 // Server supports TLS 1.2 and above, negotiating to 1.3 when available
1303 MinVersion: tls.VersionTLS12,
1304 }
1305
1306 server.StartTLS()
1307 defer server.Close()
1308
1309 // Create a dedicated HTTP client with InsecureSkipVerify to allow version negotiation
1310 transport := &http.Transport{
1311 TLSClientConfig: &tls.Config{
1312 InsecureSkipVerify: true,
1313 },
1314 }
1315 client := &http.Client{Transport: transport}
1316
1317 // Parse the test server URL to extract host and construct ntfy URL
1318 serverURL, err := url.Parse(server.URL)
1319 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1320
1321 // Create ntfy service URL pointing to the test server
1322 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
1323
1324 // Initialize the ntfy service with the test server URL
1325 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1326
1327 service.SetHTTPClient(client)
1328
1329 // Attempt to send a message - this should succeed because TLS 1.3 is compatible
1330 // with a minimum requirement of TLS 1.2
1331 gomega.Expect(service.Send("Test message", nil)).To(gomega.Succeed())
1332 },
1333 )
1334
1335 ginkgo.It(
1336 "should demonstrate the impact of different MinVersion settings on TLS connections",
1337 func() {
1338 // This test demonstrates how different MinVersion settings affect TLS connections.
1339 // It shows that even with valid certificates, TLS version requirements can cause
1340 // connection failures that manifest as certificate verification errors.
1341 privKey, err := rsa.GenerateKey(rand.Reader, 2048)
1342 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1343
1344 template := x509.Certificate{
1345 SerialNumber: big.NewInt(1),
1346 Subject: pkix.Name{
1347 Organization: []string{"Test Organization"},
1348 },
1349 NotBefore: time.Now(),
1350 NotAfter: time.Now().Add(time.Hour),
1351 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
1352 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
1353 BasicConstraintsValid: true,
1354 IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
1355 }
1356
1357 derBytes, err := x509.CreateCertificate(
1358 rand.Reader,
1359 &template,
1360 &template,
1361 &privKey.PublicKey,
1362 privKey,
1363 )
1364 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1365
1366 // Create a test server that supports only TLS 1.2
1367 server := httptest.NewUnstartedServer(
1368 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
1369 response := apiResponseError{
1370 Code: http.StatusOK,
1371 Message: "OK",
1372 }
1373
1374 w.Header().Set("Content-Type", "application/json")
1375 w.WriteHeader(http.StatusOK)
1376 _ = json.NewEncoder(w).Encode(response)
1377 }),
1378 )
1379 server.TLS = &tls.Config{
1380 Certificates: []tls.Certificate{
1381 {
1382 Certificate: [][]byte{derBytes},
1383 PrivateKey: privKey,
1384 },
1385 },
1386 // Server supports only TLS 1.2
1387 MinVersion: tls.VersionTLS12,
1388 MaxVersion: tls.VersionTLS12,
1389 }
1390
1391 server.StartTLS()
1392 defer server.Close()
1393
1394 // Parse the test server URL to extract host and construct ntfy URL
1395 serverURL, err := url.Parse(server.URL)
1396 gomega.Expect(err).To(gomega.Not(gomega.HaveOccurred()))
1397
1398 serviceURL := testutils.URLMust(fmt.Sprintf("ntfy://%s/testtopic", serverURL.Host))
1399
1400 // Test 1: MinVersion = TLS 1.3 should fail against TLS 1.2 server
1401 certPool := x509.NewCertPool()
1402 certPool.AddCert(server.Certificate())
1403 transport13 := &http.Transport{
1404 TLSClientConfig: &tls.Config{
1405 MinVersion: tls.VersionTLS13,
1406 RootCAs: certPool,
1407 },
1408 }
1409 // Add debug logging for TLS version test
1410 service.Logf(
1411 "DEBUG: TLS version test - client MinVersion: %v, server MinVersion: %v, MaxVersion: %v",
1412 transport13.TLSClientConfig.MinVersion,
1413 server.TLS.MinVersion,
1414 server.TLS.MaxVersion,
1415 )
1416 client13 := &http.Client{Transport: transport13}
1417
1418 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1419 service.SetHTTPClient(client13)
1420 err = service.Send("Test message with TLS 1.3 min requirement", nil)
1421 gomega.Expect(err).To(gomega.HaveOccurred())
1422 gomega.Expect(err.Error()).
1423 To(gomega.ContainSubstring("tls: protocol version not supported"))
1424
1425 // Test 2: MinVersion = TLS 1.2 should succeed against TLS 1.2 server
1426 transport12 := &http.Transport{
1427 TLSClientConfig: &tls.Config{
1428 MinVersion: tls.VersionTLS12,
1429 RootCAs: certPool,
1430 },
1431 }
1432 client12 := &http.Client{Transport: transport12}
1433
1434 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1435 service.SetHTTPClient(client12)
1436 gomega.Expect(service.Send("Test message with TLS 1.2 min requirement", nil)).
1437 To(gomega.Succeed())
1438 },
1439 )
1440 })
1441
1442 ginkgo.Describe("service identification", func() {
1443 ginkgo.It("should return the correct service ID", func() {
1444 service := &Service{}
1445 gomega.Expect(service.GetID()).To(gomega.Equal("ntfy"))
1446 })
1447 })
1448
1449 ginkgo.Describe("TLS configuration", func() {
1450 ginkgo.Describe("DisableTLSVerification", func() {
1451 ginkgo.It(
1452 "should set InsecureSkipVerify when DisableTLSVerification is true",
1453 func() {
1454 serviceURL := testutils.URLMust(
1455 "ntfy://example.com/test?disabletlsverification=yes",
1456 )
1457 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1458
1459 transport := service.httpClient.Transport.(*http.Transport)
1460 gomega.Expect(transport.TLSClientConfig.InsecureSkipVerify).To(gomega.BeTrue())
1461 },
1462 )
1463
1464 ginkgo.It("should log warning when DisableTLSVerification is enabled", func() {
1465 // This test verifies that a warning is logged when TLS verification is disabled
1466 serviceURL := testutils.URLMust(
1467 "ntfy://example.com/test?disabletlsverification=yes",
1468 )
1469 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1470 gomega.Expect(service.Config.DisableTLSVerification).To(gomega.BeTrue())
1471 })
1472
1473 ginkgo.It(
1474 "should not set InsecureSkipVerify when DisableTLSVerification is false",
1475 func() {
1476 serviceURL := testutils.URLMust("ntfy://example.com/test")
1477 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1478
1479 // Check that the HTTP client does not have InsecureSkipVerify set
1480 transport := service.httpClient.Transport.(*http.Transport)
1481 gomega.Expect(transport.TLSClientConfig == nil || transport.TLSClientConfig.InsecureSkipVerify == false).
1482 To(gomega.BeTrue())
1483 },
1484 )
1485 })
1486
1487 ginkgo.Describe("DisableTLS", func() {
1488 ginkgo.It("should use HTTP scheme when DisableTLS is true", func() {
1489 serviceURL := testutils.URLMust("ntfy://example.com/test?disabletls=yes")
1490 gomega.Expect(service.Initialize(serviceURL, logger)).To(gomega.Succeed())
1491
1492 gomega.Expect(service.Config.GetAPIURL()).
1493 To(gomega.Equal("http://example.com/test"))
1494 })
1495
1496 ginkgo.It("should use HTTPS scheme when DisableTLS is false", func() {
1497 config := &Config{
1498 Host: "example.com",
1499 Topic: "test",
1500 Scheme: "https",
1501 DisableTLS: false,
1502 }
1503 gomega.Expect(config.GetAPIURL()).To(gomega.Equal("https://example.com/test"))
1504 })
1505 })
1506 })
1507 })
1508
1509 func TestNtfy(t *testing.T) {
1510 t.Parallel()
1511
1512 gomegaformat.CharactersAroundMismatchToInclude = 20
1513
1514 gomega.RegisterFailHandler(ginkgo.Fail)
1515 ginkgo.RunSpecs(t, "Shoutrrr Ntfy Suite")
1516 }