handler_correlation_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package webhooks
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "strings"
  6. "testing"
  7. "github.com/OliveTin/OliveTin/internal/config"
  8. "github.com/google/uuid"
  9. log "github.com/sirupsen/logrus"
  10. "github.com/sirupsen/logrus/hooks/test"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/require"
  13. )
  14. func postWebhook(t *testing.T, cfg *config.Config) (*httptest.ResponseRecorder, *test.Hook) {
  15. t.Helper()
  16. hook := test.NewGlobal()
  17. t.Cleanup(func() { log.StandardLogger().ReplaceHooks(make(log.LevelHooks)) })
  18. req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks?source=ci", strings.NewReader(`{"ref":"main"}`))
  19. rec := httptest.NewRecorder()
  20. NewWebhookHandler(cfg, nil).HandleWebhook(rec, req)
  21. return rec, hook
  22. }
  23. func requireCorrelationID(t *testing.T, rec *httptest.ResponseRecorder) string {
  24. t.Helper()
  25. id := rec.Header().Get(CorrelationIDHeader)
  26. _, err := uuid.Parse(id)
  27. require.NoError(t, err, "header should be a bare UUID, got %q", id)
  28. return id
  29. }
  30. func findLogEntry(hook *test.Hook, message string) *log.Entry {
  31. for _, entry := range hook.AllEntries() {
  32. if entry.Message == message {
  33. return entry
  34. }
  35. }
  36. return nil
  37. }
  38. func TestWebhookNoMatchReturnsCorrelationIDInHeaderAndLog(t *testing.T) {
  39. rec, hook := postWebhook(t, config.DefaultConfig())
  40. assert.Equal(t, http.StatusOK, rec.Code)
  41. id := requireCorrelationID(t, rec)
  42. entry := findLogEntry(hook, "Webhook: no matching actions")
  43. require.NotNil(t, entry)
  44. assert.Equal(t, id, entry.Data["correlationId"])
  45. }
  46. func TestWebhookMatchUsesSameCorrelationIDForEveryLogLine(t *testing.T) {
  47. cfg := config.DefaultConfig()
  48. cfg.Actions = []*config.Action{{
  49. Title: "Deploy",
  50. ExecOnWebhook: []config.WebhookConfig{{
  51. AuthType: "bearer",
  52. Secret: "not-sent-by-this-request",
  53. }},
  54. }}
  55. rec, hook := postWebhook(t, cfg)
  56. id := requireCorrelationID(t, rec)
  57. matched := findLogEntry(hook, "Webhook: matched")
  58. require.NotNil(t, matched)
  59. assert.Equal(t, id, matched.Data["correlationId"])
  60. authFailed := findLogEntry(hook, "Webhook authentication failed")
  61. require.NotNil(t, authFailed)
  62. assert.Equal(t, id, authFailed.Data["correlationId"])
  63. }
  64. func TestWebhookCorrelationIDIsUniquePerRequest(t *testing.T) {
  65. first, _ := postWebhook(t, config.DefaultConfig())
  66. second, _ := postWebhook(t, config.DefaultConfig())
  67. assert.NotEqual(t, requireCorrelationID(t, first), requireCorrelationID(t, second))
  68. }