Browse Source

fix(webhooks): log matcher diagnostics with the request's correlation ID

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread 1 day ago
parent
commit
43b714a6ac

+ 6 - 6
service/internal/webhooks/handler.go

@@ -48,7 +48,7 @@ func (h *WebhookHandler) HandleWebhook(w http.ResponseWriter, r *http.Request) {
 		return
 		return
 	}
 	}
 
 
-	matchingActions := h.findMatchingActions(r, payload)
+	matchingActions := h.findMatchingActions(r, payload, reqLog)
 	if len(matchingActions) == 0 {
 	if len(matchingActions) == 0 {
 		reqLog.Infof("Webhook: no matching actions")
 		reqLog.Infof("Webhook: no matching actions")
 		h.writeOKResponse(w, "no matching webhook actions")
 		h.writeOKResponse(w, "no matching webhook actions")
@@ -103,17 +103,17 @@ func (h *WebhookHandler) processMatchingActions(matchingActions []ActionWebhookC
 	return processed
 	return processed
 }
 }
 
 
-func (h *WebhookHandler) findMatchingActions(r *http.Request, payload []byte) []ActionWebhookConfig {
+func (h *WebhookHandler) findMatchingActions(r *http.Request, payload []byte, reqLog *log.Entry) []ActionWebhookConfig {
 	var matches []ActionWebhookConfig
 	var matches []ActionWebhookConfig
 
 
 	for _, action := range h.cfg.Actions {
 	for _, action := range h.cfg.Actions {
-		matches = append(matches, h.findMatchingWebhooksForAction(action, r, payload)...)
+		matches = append(matches, h.findMatchingWebhooksForAction(action, r, payload, reqLog)...)
 	}
 	}
 
 
 	return matches
 	return matches
 }
 }
 
 
-func (h *WebhookHandler) findMatchingWebhooksForAction(action *config.Action, r *http.Request, payload []byte) []ActionWebhookConfig {
+func (h *WebhookHandler) findMatchingWebhooksForAction(action *config.Action, r *http.Request, payload []byte, reqLog *log.Entry) []ActionWebhookConfig {
 	var matches []ActionWebhookConfig
 	var matches []ActionWebhookConfig
 
 
 	for _, webhookConfig := range action.ExecOnWebhook {
 	for _, webhookConfig := range action.ExecOnWebhook {
@@ -123,7 +123,7 @@ func (h *WebhookHandler) findMatchingWebhooksForAction(action *config.Action, r
 			ApplyGitHubTemplate(&webhookConfigCopy, webhookConfigCopy.Template)
 			ApplyGitHubTemplate(&webhookConfigCopy, webhookConfigCopy.Template)
 		}
 		}
 
 
-		matcher := NewWebhookMatcher(webhookConfigCopy, r, payload)
+		matcher := NewWebhookMatcher(webhookConfigCopy, r, payload).WithLogger(reqLog)
 		if matcher.Matches() {
 		if matcher.Matches() {
 			matches = append(matches, ActionWebhookConfig{
 			matches = append(matches, ActionWebhookConfig{
 				Action: action,
 				Action: action,
@@ -145,7 +145,7 @@ func (h *WebhookHandler) processWebhook(actionConfig ActionWebhookConfig, r *htt
 		return false
 		return false
 	}
 	}
 
 
-	matcher := NewWebhookMatcher(actionConfig.Config, r, payload)
+	matcher := NewWebhookMatcher(actionConfig.Config, r, payload).WithLogger(reqLog)
 
 
 	args, err := matcher.ExtractArguments()
 	args, err := matcher.ExtractArguments()
 	if err != nil {
 	if err != nil {

+ 19 - 0
service/internal/webhooks/handler_correlation_test.go

@@ -83,3 +83,22 @@ func TestWebhookCorrelationIDIsUniquePerRequest(t *testing.T) {
 
 
 	assert.NotEqual(t, requireCorrelationID(t, first), requireCorrelationID(t, second))
 	assert.NotEqual(t, requireCorrelationID(t, first), requireCorrelationID(t, second))
 }
 }
+
+func TestWebhookMatcherDiagnosticsUseTheCorrelationID(t *testing.T) {
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{{
+		Title: "Deploy",
+		ExecOnWebhook: []config.WebhookConfig{{
+			AuthType:     "bearer",
+			Secret:       "not-sent-by-this-request",
+			MatchHeaders: map[string]string{"X-Event": "regex:("},
+		}},
+	}}
+
+	rec, hook := postWebhook(t, cfg)
+
+	id := requireCorrelationID(t, rec)
+	entry := findLogEntry(hook, "Invalid regex pattern")
+	require.NotNil(t, entry)
+	assert.Equal(t, id, entry.Data["correlationId"])
+}

+ 17 - 8
service/internal/webhooks/matcher.go

@@ -12,6 +12,7 @@ import (
 type WebhookMatcher struct {
 type WebhookMatcher struct {
 	config    config.WebhookConfig
 	config    config.WebhookConfig
 	req       *http.Request
 	req       *http.Request
+	log       *log.Entry
 	bodyBytes []byte
 	bodyBytes []byte
 }
 }
 
 
@@ -20,9 +21,17 @@ func NewWebhookMatcher(cfg config.WebhookConfig, r *http.Request, bodyBytes []by
 		config:    cfg,
 		config:    cfg,
 		req:       r,
 		req:       r,
 		bodyBytes: bodyBytes,
 		bodyBytes: bodyBytes,
+		log:       log.NewEntry(log.StandardLogger()),
 	}
 	}
 }
 }
 
 
+// WithLogger makes the matcher log through the request's logger, so that its
+// diagnostics carry the request's correlation ID.
+func (m *WebhookMatcher) WithLogger(entry *log.Entry) *WebhookMatcher {
+	m.log = entry
+	return m
+}
+
 func (m *WebhookMatcher) Matches() bool {
 func (m *WebhookMatcher) Matches() bool {
 	if !m.matchHeaders() {
 	if !m.matchHeaders() {
 		return false
 		return false
@@ -47,7 +56,7 @@ func (m *WebhookMatcher) matchHeaders() bool {
 	for key, expectedValue := range m.config.MatchHeaders {
 	for key, expectedValue := range m.config.MatchHeaders {
 		actualValue := m.req.Header.Get(key)
 		actualValue := m.req.Header.Get(key)
 		if !m.compareValues(actualValue, expectedValue) {
 		if !m.compareValues(actualValue, expectedValue) {
-			log.WithFields(log.Fields{
+			m.log.WithFields(log.Fields{
 				"header":   key,
 				"header":   key,
 				"expected": expectedValue,
 				"expected": expectedValue,
 				"actual":   actualValue,
 				"actual":   actualValue,
@@ -67,7 +76,7 @@ func (m *WebhookMatcher) matchQuery() bool {
 	for key, expectedValue := range m.config.MatchQuery {
 	for key, expectedValue := range m.config.MatchQuery {
 		actualValue := query.Get(key)
 		actualValue := query.Get(key)
 		if !m.compareValues(actualValue, expectedValue) {
 		if !m.compareValues(actualValue, expectedValue) {
-			log.WithFields(log.Fields{
+			m.log.WithFields(log.Fields{
 				"query":    key,
 				"query":    key,
 				"expected": expectedValue,
 				"expected": expectedValue,
 				"actual":   actualValue,
 				"actual":   actualValue,
@@ -86,7 +95,7 @@ func (m *WebhookMatcher) matchPath() bool {
 	jsonPath, expectedValue := m.parseMatchPath()
 	jsonPath, expectedValue := m.parseMatchPath()
 	matcher, err := NewJSONMatcher(m.bodyBytes)
 	matcher, err := NewJSONMatcher(m.bodyBytes)
 	if err != nil {
 	if err != nil {
-		log.WithFields(log.Fields{
+		m.log.WithFields(log.Fields{
 			"error": err,
 			"error": err,
 		}).Debugf("Failed to create JSON matcher")
 		}).Debugf("Failed to create JSON matcher")
 		return false
 		return false
@@ -107,13 +116,13 @@ func (m *WebhookMatcher) parseMatchPath() (string, string) {
 
 
 func (m *WebhookMatcher) matchPathValue(matcher *JSONMatcher, jsonPath, expectedValue string) bool {
 func (m *WebhookMatcher) matchPathValue(matcher *JSONMatcher, jsonPath, expectedValue string) bool {
 	if expectedValue == "" {
 	if expectedValue == "" {
-		_, err := matcher.ExtractValue(jsonPath)
-		return err == nil
+		found, err := matcher.HasValue(jsonPath)
+		return err == nil && found
 	}
 	}
 
 
 	matches, err := matcher.MatchPath(jsonPath, expectedValue)
 	matches, err := matcher.MatchPath(jsonPath, expectedValue)
 	if err != nil {
 	if err != nil {
-		log.WithFields(log.Fields{
+		m.log.WithFields(log.Fields{
 			"jsonPath": jsonPath,
 			"jsonPath": jsonPath,
 			"error":    err,
 			"error":    err,
 		}).Debugf("Failed to match JSONPath")
 		}).Debugf("Failed to match JSONPath")
@@ -126,7 +135,7 @@ func (m *WebhookMatcher) compareValues(actual, expected string) bool {
 	if pattern, hasRegex := strings.CutPrefix(expected, "regex:"); hasRegex {
 	if pattern, hasRegex := strings.CutPrefix(expected, "regex:"); hasRegex {
 		matched, err := regexp.MatchString(pattern, actual)
 		matched, err := regexp.MatchString(pattern, actual)
 		if err != nil {
 		if err != nil {
-			log.WithFields(log.Fields{
+			m.log.WithFields(log.Fields{
 				"pattern": pattern,
 				"pattern": pattern,
 				"error":   err,
 				"error":   err,
 			}).Warnf("Invalid regex pattern")
 			}).Warnf("Invalid regex pattern")
@@ -169,7 +178,7 @@ func (m *WebhookMatcher) extractJSONPathValues(matcher *JSONMatcher) map[string]
 	for argName, jsonPath := range m.config.Extract {
 	for argName, jsonPath := range m.config.Extract {
 		value, err := matcher.ExtractValue(jsonPath)
 		value, err := matcher.ExtractValue(jsonPath)
 		if err != nil {
 		if err != nil {
-			log.WithFields(log.Fields{
+			m.log.WithFields(log.Fields{
 				"argName":  argName,
 				"argName":  argName,
 				"jsonPath": jsonPath,
 				"jsonPath": jsonPath,
 				"error":    err,
 				"error":    err,