Debian Codegraph @

pkg/services/incident/pagerduty/pagerduty_test.go

raw
1 package pagerduty
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "log"
9 "net"
10 "net/http"
11 "net/http/httptest"
12 "net/url"
13 "strings"
14 "testing"
15 "time"
16
17 "github.com/onsi/ginkgo/v2"
18 "github.com/onsi/gomega"
19
20 "github.com/nicholas-fedor/shoutrrr/pkg/types"
21 )
22
23 const (
24 mockIntegrationKey = "a1b2c3d4e5f678901234567890abcdef"
25 mockHost = "events.pagerduty.com"
26 )
27
28 var _ = ginkgo.Describe("the PagerDuty service", func() {
29 var (
30 // a simulated http server to mock out PagerDuty itself
31 mockServer *httptest.Server
32 // the host of our mock server
33 mockHost string
34 // the port of our mock server
35 mockPort string
36 // function to check if the http request received by the mock server is as expected
37 checkRequest func(body string, header http.Header)
38 // the shoutrrr PagerDuty service
39 service *Service
40 // just a mock logger
41 mockLogger *log.Logger
42 // test-scoped HTTP client that trusts the mock server's certificate
43 mockHTTPClient *http.Client
44 )
45
46 ginkgo.BeforeEach(func() {
47 // Initialize a mock http server
48 httpHandler := func(_ http.ResponseWriter, r *http.Request) {
49 body, err := io.ReadAll(r.Body)
50 gomega.Expect(err).ToNot(gomega.HaveOccurred())
51
52 defer func() { _ = r.Body.Close() }()
53
54 checkRequest(string(body), r.Header)
55 }
56 mockServer = httptest.NewTLSServer(http.HandlerFunc(httpHandler))
57
58 // Create a test-scoped HTTP client that trusts the mock server's self-signed certificate
59 mockHTTPClient = mockServer.Client()
60
61 // Determine the host and port of our mock http server
62 mockServerURL, err := url.Parse(mockServer.URL)
63 gomega.Expect(err).ToNot(gomega.HaveOccurred())
64 mockHost, mockPort, err = net.SplitHostPort(mockServerURL.Host)
65 gomega.Expect(err).ToNot(gomega.HaveOccurred())
66
67 // Initialize a mock logger
68 var buf bytes.Buffer
69
70 mockLogger = log.New(&buf, "", 0)
71 })
72
73 ginkgo.AfterEach(func() {
74 mockServer.Close()
75 })
76
77 ginkgo.Context("without query parameters", func() {
78 ginkgo.BeforeEach(func() {
79 // Initialize service
80 serviceURL, err := url.Parse(
81 fmt.Sprintf(
82 "pagerduty://%s/%s",
83 net.JoinHostPort(mockHost, mockPort),
84 mockIntegrationKey,
85 ),
86 )
87 gomega.Expect(err).ToNot(gomega.HaveOccurred())
88
89 service = &Service{}
90 err = service.Initialize(serviceURL, mockLogger)
91 gomega.Expect(err).ToNot(gomega.HaveOccurred())
92 service.SetHTTPClient(mockHTTPClient)
93 })
94
95 ginkgo.When("sending a simple alert", func() {
96 ginkgo.It(
97 "should send a request to our mock PagerDuty server with default values",
98 func() {
99 checkRequest = func(body string, header http.Header) {
100 gomega.Expect(header["Content-Type"][0]).
101 To(gomega.Equal("application/json"))
102 gomega.Expect(body).To(gomega.Equal(`{` +
103 `"payload":{` +
104 `"summary":"hello world",` +
105 `"severity":"error",` +
106 `"source":"default"` +
107 `},` +
108 `"routing_key":"a1b2c3d4e5f678901234567890abcdef",` +
109 `"event_action":"trigger"` +
110 `}`))
111 }
112
113 err := service.Send("hello world", &types.Params{})
114 gomega.Expect(err).ToNot(gomega.HaveOccurred())
115 },
116 )
117 })
118
119 ginkgo.Context("message truncation", func() {
120 ginkgo.BeforeEach(func() {
121 serviceURL, err := url.Parse(
122 fmt.Sprintf(
123 "pagerduty://%s/%s",
124 net.JoinHostPort(mockHost, mockPort),
125 mockIntegrationKey,
126 ),
127 )
128 gomega.Expect(err).ToNot(gomega.HaveOccurred())
129
130 service = &Service{}
131 err = service.Initialize(serviceURL, mockLogger)
132 gomega.Expect(err).ToNot(gomega.HaveOccurred())
133 service.SetHTTPClient(mockHTTPClient)
134 })
135
136 ginkgo.When("sending a message longer than 1024 characters", func() {
137 ginkgo.It("should truncate the message to 1024 characters", func() {
138 longMessage := strings.Repeat("a", 1100)
139 checkRequest = func(body string, header http.Header) {
140 gomega.Expect(header["Content-Type"][0]).
141 To(gomega.Equal("application/json"))
142
143 var payload EventPayload
144
145 err := json.Unmarshal([]byte(body), &payload)
146 gomega.Expect(err).ToNot(gomega.HaveOccurred())
147 gomega.Expect(payload.Payload.Summary).To(gomega.HaveLen(1024))
148 gomega.Expect(payload.Payload.Summary).
149 To(gomega.Equal(strings.Repeat("a", 1024)))
150 }
151
152 err := service.Send(longMessage, &types.Params{})
153 gomega.Expect(err).ToNot(gomega.HaveOccurred())
154 })
155 })
156 })
157
158 ginkgo.Context("integration key validation", func() {
159 ginkgo.When("using an invalid integration key", func() {
160 ginkgo.It("should return an error during initialization", func() {
161 invalidKey := "invalid-key"
162 serviceURL, err := url.Parse(
163 fmt.Sprintf("pagerduty://%s/%s", mockHost, invalidKey),
164 )
165 gomega.Expect(err).ToNot(gomega.HaveOccurred())
166
167 service = &Service{}
168 err = service.Initialize(serviceURL, mockLogger)
169 gomega.Expect(err).To(gomega.HaveOccurred())
170 gomega.Expect(err.Error()).
171 To(gomega.ContainSubstring("invalid integration key format"))
172 })
173 })
174 })
175
176 ginkgo.Context("HTTP timeout scenarios", func() {
177 ginkgo.BeforeEach(func() {
178 serviceURL, err := url.Parse(
179 fmt.Sprintf(
180 "pagerduty://%s/%s",
181 net.JoinHostPort(mockHost, mockPort),
182 mockIntegrationKey,
183 ),
184 )
185 gomega.Expect(err).ToNot(gomega.HaveOccurred())
186
187 service = &Service{}
188 err = service.Initialize(serviceURL, mockLogger)
189 gomega.Expect(err).ToNot(gomega.HaveOccurred())
190 service.SetHTTPClient(mockHTTPClient)
191 })
192
193 ginkgo.When("HTTP client has a timeout", func() {
194 ginkgo.It("should use the configured timeout", func() {
195 // The test setup already uses a timeout, so we just verify the service works
196 checkRequest = func(_ string, header http.Header) {
197 gomega.Expect(header["Content-Type"][0]).
198 To(gomega.Equal("application/json"))
199 }
200
201 err := service.Send("test message", &types.Params{})
202 gomega.Expect(err).ToNot(gomega.HaveOccurred())
203 })
204 })
205 })
206
207 ginkgo.Context("optional fields support", func() {
208 ginkgo.BeforeEach(func() {
209 serviceURL, err := url.Parse(
210 fmt.Sprintf(
211 "pagerduty://%s/%s?client=my-monitor&client_url=https://example.com&details=%%7B%%22key%%22%%3A%%22value%%22%%7D",
212 net.JoinHostPort(mockHost, mockPort),
213 mockIntegrationKey,
214 ),
215 )
216 gomega.Expect(err).ToNot(gomega.HaveOccurred())
217
218 service = &Service{}
219 err = service.Initialize(serviceURL, mockLogger)
220 gomega.Expect(err).ToNot(gomega.HaveOccurred())
221 service.SetHTTPClient(mockHTTPClient)
222 })
223
224 ginkgo.When("sending with optional fields", func() {
225 ginkgo.It("should include optional fields in the payload", func() {
226 checkRequest = func(body string, header http.Header) {
227 gomega.Expect(header["Content-Type"][0]).
228 To(gomega.Equal("application/json"))
229
230 var payload EventPayload
231
232 err := json.Unmarshal([]byte(body), &payload)
233 gomega.Expect(err).ToNot(gomega.HaveOccurred())
234 gomega.Expect(payload.Client).To(gomega.Equal("my-monitor"))
235 gomega.Expect(payload.ClientURL).To(gomega.Equal("https://example.com"))
236 gomega.Expect(payload.Details).
237 To(gomega.Equal(map[string]any{"key": "value"}))
238 }
239
240 err := service.Send("test message", &types.Params{})
241 gomega.Expect(err).ToNot(gomega.HaveOccurred())
242 })
243 })
244 })
245
246 ginkgo.Context("contexts support", func() {
247 ginkgo.BeforeEach(func() {
248 serviceURL, err := url.Parse(
249 fmt.Sprintf(
250 "pagerduty://%s/%s?contexts=link:http://example.com,text:Additional+context,image:http://example.com/img.png",
251 net.JoinHostPort(mockHost, mockPort),
252 mockIntegrationKey,
253 ),
254 )
255 gomega.Expect(err).ToNot(gomega.HaveOccurred())
256
257 service = &Service{}
258 err = service.Initialize(serviceURL, mockLogger)
259 gomega.Expect(err).ToNot(gomega.HaveOccurred())
260 service.SetHTTPClient(mockHTTPClient)
261 })
262
263 ginkgo.When("sending with contexts", func() {
264 ginkgo.It("should include contexts in the payload", func() {
265 checkRequest = func(body string, header http.Header) {
266 gomega.Expect(header["Content-Type"][0]).
267 To(gomega.Equal("application/json"))
268
269 var payload EventPayload
270
271 err := json.Unmarshal([]byte(body), &payload)
272 gomega.Expect(err).ToNot(gomega.HaveOccurred())
273 gomega.Expect(payload.Contexts).To(gomega.HaveLen(2))
274 gomega.Expect(
275 payload.Contexts[0],
276 ).To(gomega.Equal(PagerDutyContext{Type: "link", Href: "http://example.com"}))
277 gomega.Expect(
278 payload.Contexts[1],
279 ).To(gomega.Equal(PagerDutyContext{Type: "image", Src: "http://example.com/img.png"}))
280 }
281
282 err := service.Send("test message", &types.Params{})
283 gomega.Expect(err).ToNot(gomega.HaveOccurred())
284 })
285 })
286 })
287
288 ginkgo.Context("custom HTTP client", func() {
289 ginkgo.BeforeEach(func() {
290 serviceURL, err := url.Parse(
291 fmt.Sprintf(
292 "pagerduty://%s/%s",
293 net.JoinHostPort(mockHost, mockPort),
294 mockIntegrationKey,
295 ),
296 )
297 gomega.Expect(err).ToNot(gomega.HaveOccurred())
298
299 service = &Service{}
300 err = service.Initialize(serviceURL, mockLogger)
301 gomega.Expect(err).ToNot(gomega.HaveOccurred())
302
303 // Set a custom HTTP client with timeout, based on the mock client for TLS trust
304 customClient := mockServer.Client()
305 customClient.Timeout = 10 * time.Second
306 service.SetHTTPClient(customClient)
307 })
308
309 ginkgo.When("using a custom HTTP client", func() {
310 ginkgo.It("should use the custom client for requests", func() {
311 checkRequest = func(_ string, header http.Header) {
312 gomega.Expect(header["Content-Type"][0]).
313 To(gomega.Equal("application/json"))
314 }
315
316 err := service.Send("test message", &types.Params{})
317 gomega.Expect(err).ToNot(gomega.HaveOccurred())
318 })
319 })
320 })
321 })
322
323 ginkgo.Context("with query parameters", func() {
324 ginkgo.BeforeEach(func() {
325 // Initialize service
326 serviceURL, err := url.Parse(
327 fmt.Sprintf(
328 `pagerduty://%s/%s?severity=critical&source=beszel&action=resolve`,
329 net.JoinHostPort(mockHost, mockPort),
330 mockIntegrationKey,
331 ),
332 )
333 gomega.Expect(err).ToNot(gomega.HaveOccurred())
334
335 service = &Service{}
336 err = service.Initialize(serviceURL, mockLogger)
337 gomega.Expect(err).ToNot(gomega.HaveOccurred())
338 service.SetHTTPClient(mockHTTPClient)
339 })
340
341 ginkgo.When("sending a simple alert", func() {
342 ginkgo.It(
343 "should send a request to our mock PagerDuty server with all fields populated from query parameters",
344 func() {
345 checkRequest = func(body string, header http.Header) {
346 gomega.Expect(header["Content-Type"][0]).
347 To(gomega.Equal("application/json"))
348 gomega.Expect(body).To(gomega.Equal(`{` +
349 `"payload":{` +
350 `"summary":"An example alert message",` +
351 `"severity":"critical",` +
352 `"source":"beszel"` +
353 `},` +
354 `"routing_key":"a1b2c3d4e5f678901234567890abcdef",` +
355 `"event_action":"resolve"` +
356 `}`))
357 }
358
359 err := service.Send("An example alert message", &types.Params{})
360 gomega.Expect(err).ToNot(gomega.HaveOccurred())
361 },
362 )
363 })
364 })
365 })
366
367 var _ = ginkgo.Describe("parseContexts function", func() {
368 ginkgo.When("parsing valid context strings", func() {
369 ginkgo.It("should parse link contexts correctly", func() {
370 contexts, err := parseContexts("link:http://example.com")
371 gomega.Expect(err).ToNot(gomega.HaveOccurred())
372 gomega.Expect(contexts).To(gomega.HaveLen(1))
373 gomega.Expect(
374 contexts[0],
375 ).To(gomega.Equal(PagerDutyContext{Type: "link", Href: "http://example.com"}))
376 })
377
378 ginkgo.It("should parse image contexts correctly", func() {
379 contexts, err := parseContexts("image:http://example.com/img.png")
380 gomega.Expect(err).ToNot(gomega.HaveOccurred())
381 gomega.Expect(contexts).To(gomega.HaveLen(1))
382 gomega.Expect(
383 contexts[0],
384 ).To(gomega.Equal(PagerDutyContext{Type: "image", Src: "http://example.com/img.png"}))
385 })
386
387 ginkgo.It("should skip text contexts", func() {
388 contexts, err := parseContexts("text:Some description")
389 gomega.Expect(err).ToNot(gomega.HaveOccurred())
390 gomega.Expect(contexts).To(gomega.BeEmpty())
391 })
392
393 ginkgo.It("should parse multiple contexts correctly", func() {
394 contexts, err := parseContexts(
395 "link:http://example.com,text:Additional context,image:http://example.com/img.png",
396 )
397 gomega.Expect(err).ToNot(gomega.HaveOccurred())
398 gomega.Expect(contexts).To(gomega.HaveLen(2))
399 gomega.Expect(
400 contexts[0],
401 ).To(gomega.Equal(PagerDutyContext{Type: "link", Href: "http://example.com"}))
402 gomega.Expect(
403 contexts[1],
404 ).To(gomega.Equal(PagerDutyContext{Type: "image", Src: "http://example.com/img.png"}))
405 })
406
407 ginkgo.It("should handle empty string", func() {
408 contexts, err := parseContexts("")
409 gomega.Expect(err).ToNot(gomega.HaveOccurred())
410 gomega.Expect(contexts).To(gomega.BeNil())
411 })
412
413 ginkgo.It("should skip empty contexts", func() {
414 contexts, err := parseContexts("link:http://example.com,,text:Some text")
415 gomega.Expect(err).ToNot(gomega.HaveOccurred())
416 gomega.Expect(contexts).To(gomega.HaveLen(1))
417 gomega.Expect(
418 contexts[0],
419 ).To(gomega.Equal(PagerDutyContext{Type: "link", Href: "http://example.com"}))
420 })
421 })
422
423 ginkgo.When("parsing invalid context strings", func() {
424 ginkgo.It("should return error for invalid format", func() {
425 _, err := parseContexts("invalid")
426 gomega.Expect(err).To(gomega.HaveOccurred())
427 gomega.Expect(err.Error()).To(gomega.ContainSubstring("invalid context format"))
428 })
429
430 ginkgo.It("should return error for empty type", func() {
431 _, err := parseContexts(":value")
432 gomega.Expect(err).To(gomega.HaveOccurred())
433 gomega.Expect(err.Error()).To(gomega.ContainSubstring("type and value cannot be empty"))
434 })
435
436 ginkgo.It("should return error for empty value", func() {
437 _, err := parseContexts("type:")
438 gomega.Expect(err).To(gomega.HaveOccurred())
439 gomega.Expect(err.Error()).To(gomega.ContainSubstring("type and value cannot be empty"))
440 })
441
442 ginkgo.It("should return error for missing colon", func() {
443 _, err := parseContexts("typevalue")
444 gomega.Expect(err).To(gomega.HaveOccurred())
445 gomega.Expect(err.Error()).To(gomega.ContainSubstring("invalid context format"))
446 })
447 })
448 })
449
450 var _ = ginkgo.Describe("the PagerDuty Config struct", func() {
451 ginkgo.When("generating a Config from a simple URL", func() {
452 ginkgo.It("should populate the Config with host and integration key", func() {
453 url, err := url.Parse(fmt.Sprintf("pagerduty://%s/%s", mockHost, mockIntegrationKey))
454 gomega.Expect(err).ToNot(gomega.HaveOccurred())
455
456 config := Config{}
457 err = config.SetURL(url)
458 gomega.Expect(err).ToNot(gomega.HaveOccurred())
459
460 gomega.Expect(config.IntegrationKey).To(gomega.Equal(mockIntegrationKey))
461 gomega.Expect(config.Host).To(gomega.Equal(mockHost))
462 })
463 })
464
465 ginkgo.When("generating a Config from a url with port", func() {
466 ginkgo.It("should populate the port field", func() {
467 url, err := url.Parse(
468 fmt.Sprintf(
469 "pagerduty://%s/%s",
470 net.JoinHostPort(mockHost, "12345"),
471 mockIntegrationKey,
472 ),
473 )
474 gomega.Expect(err).ToNot(gomega.HaveOccurred())
475
476 config := Config{}
477 err = config.SetURL(url)
478 gomega.Expect(err).ToNot(gomega.HaveOccurred())
479
480 gomega.Expect(config.Port).To(gomega.Equal(uint16(12345)))
481 })
482 })
483
484 ginkgo.When("generating a Config from a url with query parameters", func() {
485 ginkgo.It("should populate the Config fields with the query parameter values", func() {
486 queryParams := `severity=critical&source=my-app&action=trigger`
487 url, err := url.Parse(
488 fmt.Sprintf(
489 "pagerduty://%s/%s?%s",
490 net.JoinHostPort(mockHost, "12345"),
491 mockIntegrationKey,
492 queryParams,
493 ),
494 )
495 gomega.Expect(err).ToNot(gomega.HaveOccurred())
496
497 config := Config{}
498 err = config.SetURL(url)
499 gomega.Expect(err).ToNot(gomega.HaveOccurred())
500
501 gomega.Expect(config.Severity).To(gomega.Equal("critical"))
502 gomega.Expect(config.Source).To(gomega.Equal("my-app"))
503 gomega.Expect(config.Action).To(gomega.Equal("trigger"))
504 })
505 })
506
507 ginkgo.When("generating a Config from a url with differently escaped spaces", func() {
508 ginkgo.It("should parse the escaped spaces correctly", func() {
509 // Use: '%20', '+' and a normal space
510 queryParams := `source=my app`
511 url, err := url.Parse(
512 fmt.Sprintf(
513 "pagerduty://%s/%s?%s",
514 net.JoinHostPort(mockHost, "12345"),
515 mockIntegrationKey,
516 queryParams,
517 ),
518 )
519 gomega.Expect(err).ToNot(gomega.HaveOccurred())
520
521 config := Config{}
522 err = config.SetURL(url)
523 gomega.Expect(err).ToNot(gomega.HaveOccurred())
524
525 gomega.Expect(config.Source).To(gomega.Equal("my app"))
526 })
527 })
528 })
529
530 func TestPagerDuty(t *testing.T) {
531 t.Parallel()
532 gomega.RegisterFailHandler(ginkgo.Fail)
533 ginkgo.RunSpecs(t, "Shoutrrr Pagerduty Suite")
534 }