Просмотр исходного кода

fix: address review comments on the release PR (#1191)

James Read 4 дней назад
Родитель
Сommit
4d08ee436a

+ 3 - 0
.github/workflows/release-upgrade-notes.yml

@@ -20,9 +20,12 @@ on:
 permissions:
   contents: read
 
+# A run that is waiting must not be replaced by a later one, or the notes for
+# the earlier tag would be moved under the later version instead.
 concurrency:
   group: release-upgrade-notes
   cancel-in-progress: false
+  queue: max
 
 jobs:
   label-upgrade-notes:

+ 1 - 1
SECURITY.md

@@ -99,7 +99,7 @@ A DoS report **is** considered a vulnerability when at least one of these is tru
 * **Amplification**: a small or cheap request makes OliveTin do disproportionately large work. For example a single request that allocates a large amount of memory, or a short input that causes a large amount of CPU work.
 * **Unbounded growth**: requests cause memory or other state to grow without limit, and it is not reclaimed after the requests stop. For example a map, slice or cache that has no cap, expiry or eviction.
 
-A DoS report is **not** considered a vulnerability when:
+A DoS report is **not** considered a vulnerability when none of the above is true, and:
 
 * the load is proportional to the number and size of requests sent, and the work done for each request is bounded;
 * OliveTin fails gracefully while busy, for example by returning HTTP 429 or `ResourceExhausted`, rather than crashing;

+ 3 - 2
docs/modules/ROOT/examples/solutions/single-button-toggle/config.yaml

@@ -8,13 +8,14 @@ actions:
     entity: water_valve
     shell: |
       set -e
-      if [ "{{ .CurrentEntity.state }}" = "open" ]; then
+      entity_file=/etc/OliveTin/entities/water_valve.yaml
+      if grep -Eq "^  state: +[\"']?open[\"']? *$" "$entity_file"; then
         next_state=closed
       else
         next_state=open
       fi
       echo "Setting {{ .CurrentEntity.title }} to $next_state"
-      printf -- '- title: %s\n  state: %s\n' "{{ .CurrentEntity.title }}" "$next_state" > /etc/OliveTin/entities/water_valve.yaml
+      sed -i "s/^  state: .*/  state: $next_state/" "$entity_file"
 
 dashboards:
   - title: Water Valve

+ 3 - 2
docs/modules/ROOT/images/solutions/single-button-toggle/config.yaml

@@ -15,13 +15,14 @@ actions:
     entity: water_valve
     shell: |
       set -e
-      if [ "{{ .CurrentEntity.state }}" = "open" ]; then
+      entity_file="${{ WATER_VALVE_ENTITY_FILE }}"
+      if grep -Eq "^  state: +[\"']?open[\"']? *$" "$entity_file"; then
         next_state=closed
       else
         next_state=open
       fi
       echo "Setting {{ .CurrentEntity.title }} to $next_state"
-      printf -- '- title: %s\n  state: %s\n' "{{ .CurrentEntity.title }}" "$next_state" > "${{ WATER_VALVE_ENTITY_FILE }}"
+      sed -i "s/^  state: .*/  state: $next_state/" "$entity_file"
 
 dashboards:
   - title: Water Valve

+ 4 - 2
docs/modules/ROOT/pages/solutions/single-button-toggle/index.adoc

@@ -22,7 +22,9 @@ a| image::solutions/single-button-toggle/dashboard-open.png[]
 * The entity file `/etc/OliveTin/entities/water_valve.yaml` holds the state of the valve (`open` or `closed`). It is the single source of truth for the dashboard.
 * The **Toggle valve** action's icon is an `<img>` tag that uses `{{ .CurrentEntity.state }}` as the file name, so state `closed` shows `closed.png` and state `open` shows `open.png`.
 * The action has no `enabledExpression`, so it is never disabled.
-* When it runs, the action reads the current state, works out the opposite state, and writes that back to the entity file. OliveTin watches entity files, so the dashboard and the icon update as soon as the file changes.
+* When it runs, the action reads the current state from the entity file, works out the opposite state, and changes the `state:` line in the file. OliveTin watches entity files, so the dashboard and the icon update as soon as the file changes.
+* Each execution reads the state from the file, not from the dashboard, so a press that runs straight after another still flips the valve, even before OliveTin has reloaded the entity. The state may be written as `open` or `"open"`.
+* OliveTin runs one execution of an action at a time by default (`maxConcurrent: 1`). A press while the action is still running is blocked, not queued, so it does not flip the valve. Press again once the first execution has finished.
 
 == Icons
 
@@ -61,7 +63,7 @@ include::example$solutions/single-button-toggle/config.yaml[]
 * Only write the new state to the entity file once the hardware command has succeeded. If the command fails, the shell exits before the state changes and the dashboard keeps showing the real state.
 * If something else can change the device (a physical switch, a schedule), have a script update the entity file too. The icon will then follow it.
 * The icon path starts with `/`, so it works from any dashboard. If OliveTin is served under a sub-path behind a reverse proxy, include that sub-path in the icon's `src`.
-* This action rewrites the whole entity file, so to control several valves, give each one its own entity file (or update the file in place with a tool such as `yq`).
+* This action changes every `state:` line in the entity file, so to control several valves, give each one its own entity file, or update the right entity with a YAML-aware tool such as `yq`.
 * Add ACLs if only certain users should be able to operate the valve.
 
 == See also

+ 18 - 0
docs/modules/ROOT/pages/upgrade/upgrade_notes.adoc

@@ -54,6 +54,24 @@ OliveTin now keeps up to 2000 execution logs in memory, and removes the oldest f
 
 If you want a longer history in the web interface, raise `logHistoryLimit` in your config. Logs saved to disk with `saveLogs` are not affected. See xref:logs/saving.adoc#log-history-limit[How many logs are kept in memory].
 
+[#restart-action-current-config]
+=== `RestartAction` uses the action as it is configured now
+
+Restarting an execution, with the Restart button or the `RestartAction` API method, now runs the action as it is in the current config, with the arguments and justification stored with the original run. Previously it ran the action as it was configured when the original run started.
+
+After a config change, restarting an old execution can therefore run the changed command.
+
+If the action has been removed, the restart fails with "is no longer in the configuration", and `StartAction` cannot start it either. To run it again, add the action back to your config, or use the action that replaced it.
+
+If the action still exists but now requires an argument or a justification that the original run did not have, the restart fails and asks you to use `StartAction` instead. Start the action again with `StartAction`, or from the dashboard, with the inputs it now needs.
+
+[#web-ui-cache-control]
+=== Web UI files are no longer cached by browsers without checking
+
+OliveTin now sends `Cache-Control: no-cache` with web UI files, so browsers check for a newer version every time, and get the new web interface straight after an upgrade.
+
+Browsers that loaded the web interface from an earlier version may still have those files cached without this header. If the web interface looks out of date or broken after you upgrade, force a reload (Ctrl+Shift+R, or Cmd+Shift+R on macOS), or clear the browser cache for your OliveTin site. You only need to do this once.
+
 [#start-action-by-get-justification]
 === `StartActionByGet` and `StartActionByGetAndWait` now check required justifications
 

+ 10 - 0
frontend/resources/vue/views/LogsCalendarView.vue

@@ -171,7 +171,17 @@ function handleMonthChange (month, year) {
   router.replace({ query: { ...route.query, month: formatCalendarMonthQuery(month, year) } })
 }
 
+// A missing or invalid month is written into the URL, so that bookmarking the
+// page keeps the month it showed.
+function writeDisplayedMonthToAddress () {
+  const month = formatCalendarMonthQuery(currentMonthIndex.value, currentYear.value)
+  if (route.query.month !== month) {
+    router.replace({ query: { ...route.query, month } })
+  }
+}
+
 onMounted(() => {
+  writeDisplayedMonthToAddress()
   fetchLogs()
 })
 </script>

+ 2 - 1
service/internal/api/api.go

@@ -265,7 +265,8 @@ func (api *oliveTinAPI) startActionAndWaitRun(binding *executor.ActionBinding, a
 	}
 	wg, _ := api.executor.ExecRequest(&execReq)
 	wg.Wait()
-	return api.executor.GetLog(execReq.TrackingID)
+	entry := execReq.LogEntry()
+	return entry, entry != nil
 }
 
 func (api *oliveTinAPI) findBindingOrNotFound(actionId string) (*executor.ActionBinding, error) {

+ 3 - 1
service/internal/configissues/health.go

@@ -176,8 +176,10 @@ func uniqueIssueViews(stored []health.IssueView) []health.IssueView {
 			out = append(out, view)
 			continue
 		}
+		// Only the severity is raised, so the issue keeps the position of the
+		// first source it was found in.
 		if severityRank(view.Severity) > severityRank(out[position].Severity) {
-			out[position] = view
+			out[position].Severity = view.Severity
 		}
 	}
 	return out

+ 31 - 0
service/internal/configissues/health_test.go

@@ -225,3 +225,34 @@ func TestIssueInTwoSourcesIsListedWithTheHighestSeverity(t *testing.T) {
 		assert.Equal(t, []Issue{failure}, List())
 	})
 }
+
+func TestDuplicateIssueIsLoggedOnceAsAnError(t *testing.T) {
+	resetIssues(t)
+	hook := captureLogs(t)
+
+	warning := testIssue(CodeConfigDecode, "bad value")
+	failure := warning
+	failure.Severity = SeverityError
+
+	Replace([]Issue{warning, failure})
+	Replace([]Issue{warning, failure})
+
+	entries := issueLogEntries(hook)
+	require.Len(t, entries, 1, "a duplicate issue must be logged once, and not again on an unchanged rebuild")
+	assert.Equal(t, log.ErrorLevel, entries[0].Level)
+}
+
+func TestIssueRaisedToAnErrorKeepsItsFirstPosition(t *testing.T) {
+	resetIssues(t)
+
+	warning := testIssue(CodeConfigDecode, "bad value")
+	failure := warning
+	failure.Severity = SeverityError
+
+	ReplaceLoadIssues([]Issue{warning})
+	ReportRuntime(testIssue(CodeDeprecatedAPICall, "runtime"))
+	Replace([]Issue{failure})
+
+	assert.Equal(t, []string{"bad value", "runtime"}, messages(List()))
+	assert.Equal(t, SeverityError, List()[0].Severity)
+}

+ 10 - 6
service/internal/configissues/store.go

@@ -121,7 +121,7 @@ func setSource(sourceID string, next []Issue) {
 	}
 
 	refreshSnapshot()
-	logNewIssues(before, next)
+	logNewIssues(before, copyCurrentSeverities(), next)
 }
 
 func raise(sourceID string, issue Issue) {
@@ -143,7 +143,7 @@ func raise(sourceID string, issue Issue) {
 	}
 
 	refreshSnapshot()
-	logNewIssues(before, []Issue{issue})
+	logNewIssues(before, copyCurrentSeverities(), []Issue{issue})
 }
 
 // refreshSnapshot rebuilds the list returned by List after a change, so that
@@ -182,14 +182,18 @@ func copyCurrentSeverities() map[string]string {
 // logNewIssues logs issues that were not open before, or whose severity changed,
 // in the order they were collected, so startup and reloads do not repeat the
 // same warnings.
-func logNewIssues(before map[string]string, issues []Issue) {
+// An issue is logged when the severity it is now listed with is new, and that
+// severity is the one it was reported with. The same problem reported as both a
+// warning and an error is listed once as an error, so only the error is logged,
+// and an unchanged rebuild logs nothing.
+func logNewIssues(before map[string]string, after map[string]string, issues []Issue) {
 	for _, issue := range issues {
 		key := issueKey(issue)
-		severity := string(healthSeverity(issue.Severity))
-		if before[key] == severity {
+		listed := after[key]
+		if listed == before[key] || listed != string(healthSeverity(issue.Severity)) {
 			continue
 		}
-		before[key] = severity
+		before[key] = listed
 		logNewIssue(issue)
 	}
 }

+ 14 - 0
service/internal/executor/executor.go

@@ -96,6 +96,20 @@ func (req *ExecutionRequest) mutateLogEntry(mutator func(*InternalLogEntry)) {
 	mutator(req.logEntry)
 }
 
+// LogEntry returns a copy of this request's own log entry. Callers that wait
+// for a request use it instead of looking the entry up in the history, because
+// a later run can evict a finished entry from the history before it is read.
+func (req *ExecutionRequest) LogEntry() *InternalLogEntry {
+	if req.executor == nil {
+		return cloneInternalLogEntry(req.logEntry)
+	}
+
+	req.executor.logmutex.RLock()
+	defer req.executor.logmutex.RUnlock()
+
+	return cloneInternalLogEntry(req.logEntry)
+}
+
 // LogEntrySnapshot is a copy of selected log entry fields for race-safe reads.
 type LogEntrySnapshot struct {
 	Output            string

+ 27 - 14
service/internal/executor/log_retention.go

@@ -1,7 +1,6 @@
 package executor
 
 import (
-	"slices"
 	"time"
 
 	config "github.com/OliveTin/OliveTin/internal/config"
@@ -36,10 +35,11 @@ func (e *Executor) evictOldLogsLocked(now time.Time) {
 	}
 
 	kept := make([]string, 0, len(e.logsTrackingIdsByDate)-excess)
+	evicted := make(map[*InternalLogEntry]bool, excess)
 
 	for _, trackingID := range e.logsTrackingIdsByDate {
 		if excess > 0 && canEvictLogEntry(e.logs[trackingID], now) {
-			e.removeLogLocked(trackingID)
+			e.removeLogLocked(trackingID, evicted)
 			excess--
 			continue
 		}
@@ -48,6 +48,7 @@ func (e *Executor) evictOldLogsLocked(now time.Time) {
 	}
 
 	e.logsTrackingIdsByDate = kept
+	e.removeEvictedFromBindingsLocked(evicted)
 }
 
 func canEvictLogEntry(entry *InternalLogEntry, now time.Time) bool {
@@ -85,7 +86,7 @@ func longestRateWindow(rates []config.RateSpec) time.Duration {
 	return longest
 }
 
-func (e *Executor) removeLogLocked(trackingID string) {
+func (e *Executor) removeLogLocked(trackingID string, evicted map[*InternalLogEntry]bool) {
 	entry := e.logs[trackingID]
 	delete(e.logs, trackingID)
 
@@ -93,24 +94,36 @@ func (e *Executor) removeLogLocked(trackingID string) {
 		return
 	}
 
-	e.removeLogFromBindingLocked(entry)
+	evicted[entry] = true
 }
 
-func (e *Executor) removeLogFromBindingLocked(entry *InternalLogEntry) {
-	bindingID := entry.Binding.ID
-	bindingLogs := e.LogsByBindingId[bindingID]
+// Each affected binding's list is rebuilt once per eviction, not once per
+// evicted entry, so evicting many entries of one binding stays linear.
+func (e *Executor) removeEvictedFromBindingsLocked(evicted map[*InternalLogEntry]bool) {
+	bindingIDs := make(map[string]bool)
+	for entry := range evicted {
+		bindingIDs[entry.Binding.ID] = true
+	}
 
-	index := slices.Index(bindingLogs, entry)
-	if index < 0 {
-		return
+	for bindingID := range bindingIDs {
+		e.removeEvictedFromBindingLocked(bindingID, evicted)
+	}
+}
+
+func (e *Executor) removeEvictedFromBindingLocked(bindingID string, evicted map[*InternalLogEntry]bool) {
+	// Build a new slice rather than deleting in place, because callers may still
+	// be reading the previous slice after releasing the lock.
+	remaining := make([]*InternalLogEntry, 0, len(e.LogsByBindingId[bindingID]))
+	for _, entry := range e.LogsByBindingId[bindingID] {
+		if !evicted[entry] {
+			remaining = append(remaining, entry)
+		}
 	}
 
-	if len(bindingLogs) == 1 {
+	if len(remaining) == 0 {
 		delete(e.LogsByBindingId, bindingID)
 		return
 	}
 
-	// Build a new slice rather than deleting in place, because callers may still
-	// be reading the previous slice after releasing the lock.
-	e.LogsByBindingId[bindingID] = slices.Concat(bindingLogs[:index], bindingLogs[index+1:])
+	e.LogsByBindingId[bindingID] = remaining
 }

+ 25 - 0
service/internal/executor/log_retention_test.go

@@ -178,3 +178,28 @@ func TestLogHistoryLoadedFromDiskIsBounded(t *testing.T) {
 	e.logmutex.RUnlock()
 	assertLogStoresConsistent(t, e, binding.ID)
 }
+
+func TestRequestLogEntrySurvivesHistoryEviction(t *testing.T) {
+	e, cfg, binding := newRetentionTestExecutor(t, &config.Action{Title: "retention", Shell: "true"})
+
+	req := &ExecutionRequest{
+		Binding:           binding,
+		Cfg:               cfg,
+		AuthenticatedUser: auth.UserFromSystem(cfg, "test"),
+	}
+	wg, trackingID := e.ExecRequest(req)
+	wg.Wait()
+
+	for range cfg.LogHistoryLimit + 1 {
+		addRetentionTestLog(e, newQueueTestLogEntry(binding, true))
+	}
+
+	_, found := e.GetLog(trackingID)
+	require.False(t, found, "the request's entry is evicted from the history")
+
+	entry := req.LogEntry()
+	require.NotNil(t, entry)
+	assert.Equal(t, trackingID, entry.ExecutionTrackingID)
+	assert.True(t, entry.ExecutionFinished)
+	assert.Equal(t, int32(0), entry.ExitCode)
+}

+ 28 - 1
service/internal/filehelper/file_change_notify.go

@@ -354,18 +354,45 @@ func resolveWatchedPath(ctx *watchContext) (changed bool, resolved bool) {
 	target, err := filepath.EvalSymlinks(ctx.watchedPath)
 	if err != nil {
 		log.Debugf("fsnotify could not resolve %v: %v", ctx.watchedPath, err)
+		watchDanglingTargetDir(ctx)
 		return false, false
 	}
 
+	// The target's directory is watched again even when the target has not
+	// changed, because a dangling symlink in between may have moved the extra
+	// watch to the directory it pointed into.
+	watchResolvedDir(ctx, filepath.Dir(target))
+
 	if target == ctx.resolvedPath {
 		return false, true
 	}
 
 	ctx.resolvedPath = target
-	watchResolvedDir(ctx, filepath.Dir(target))
 	return true, true
 }
 
+// watchDanglingTargetDir watches the directory a dangling symlink points into.
+// Directory watches are not recursive, so when that directory is not already
+// watched, creating the missing target there would give no event, and the file
+// would not be reloaded once it can be read.
+func watchDanglingTargetDir(ctx *watchContext) {
+	target, err := os.Readlink(ctx.watchedPath)
+	if err != nil {
+		return
+	}
+
+	if !filepath.IsAbs(target) {
+		target = filepath.Join(filepath.Dir(ctx.watchedPath), target)
+	}
+
+	dir := filepath.Dir(target)
+	if _, err := os.Stat(dir); err != nil {
+		return
+	}
+
+	watchResolvedDir(ctx, dir)
+}
+
 func watchResolvedDir(ctx *watchContext, dir string) {
 	if dir == ctx.resolvedDir {
 		return

+ 45 - 0
service/internal/filehelper/file_watch_symlink_test.go

@@ -192,6 +192,51 @@ func TestWatchFileWriteWaitsForDanglingReplacement(t *testing.T) {
 	recorder.expectOneCall(t)
 }
 
+func TestWatchFileWriteWaitsForDanglingTargetInAnotherDirectory(t *testing.T) {
+	skipWithoutSymlinks(t)
+
+	linkDir, targetDir := t.TempDir(), t.TempDir()
+	path := filepath.Join(linkDir, "entities.yaml")
+	writeFile(t, path, "a: 1\n")
+	recorder := watchFileForTest(t, path)
+
+	missing := filepath.Join(targetDir, "entities.yaml")
+	temporary := filepath.Join(linkDir, "entities.yaml.tmp")
+	require.NoError(t, os.Symlink(missing, temporary))
+	require.NoError(t, os.Rename(temporary, path))
+	recorder.expectNone(t)
+
+	writeFile(t, missing, "a: 2\n")
+	recorder.expectOneCall(t)
+}
+
+func TestWatchFileWriteKeepsWatchingTargetAfterDanglingLinkIsUndone(t *testing.T) {
+	skipWithoutSymlinks(t)
+
+	linkDir, targetDir, otherDir := t.TempDir(), t.TempDir(), t.TempDir()
+	target := filepath.Join(targetDir, "real.yaml")
+	writeFile(t, target, "a: 1\n")
+
+	path := filepath.Join(linkDir, "entities.yaml")
+	require.NoError(t, os.Symlink(target, path))
+	recorder := watchFileForTest(t, path)
+
+	replaceLink := func(destination string) {
+		temporary := filepath.Join(linkDir, "entities.yaml.tmp")
+		require.NoError(t, os.Symlink(destination, temporary))
+		require.NoError(t, os.Rename(temporary, path))
+	}
+
+	replaceLink(filepath.Join(otherDir, "missing.yaml"))
+	recorder.expectNone(t)
+
+	replaceLink(target)
+	recorder.expectOneCall(t)
+
+	writeFile(t, target, "a: 2\n")
+	recorder.expectOneCall(t)
+}
+
 func TestWatchFileWriteReloadsRenameSave(t *testing.T) {
 	path := filepath.Join(t.TempDir(), "entities.yaml")
 	writeFile(t, path, "a: 1\n")

+ 46 - 12
service/internal/logfilter/allowlist.go

@@ -44,15 +44,14 @@ var allowedFunctions = map[string]bool{
 
 var errUnsupportedSyntax = fmt.Errorf("unsupported filter expression; use field comparisons, and/or/not, contains, includes() and hasTag()")
 
-type allowlistVisitor struct {
-	err error
-}
-
-func (v *allowlistVisitor) Visit(node *ast.Node) {
-	if v.err != nil {
-		return
-	}
-	v.err = checkNode(*node)
+var errFilterTooComplex = fmt.Errorf("filter expression is too complex")
+
+// The parser shares the middle operand of a chained comparison between two
+// branches, so nesting them makes the tree grow exponentially while the text
+// stays short. Each node is checked before its children, and the walk stops
+// after maxFilterNodes visits, so the check itself stays cheap.
+type allowlistWalker struct {
+	visited int
 }
 
 func checkAllowedSyntax(expression string) error {
@@ -61,9 +60,44 @@ func checkAllowedSyntax(expression string) error {
 		return err
 	}
 
-	visitor := &allowlistVisitor{}
-	ast.Walk(&tree.Node, visitor)
-	return visitor.err
+	walker := &allowlistWalker{}
+	return walker.check(tree.Node)
+}
+
+func (walker *allowlistWalker) check(node ast.Node) error {
+	walker.visited++
+	if walker.visited > maxFilterNodes {
+		return errFilterTooComplex
+	}
+
+	if err := checkNode(node); err != nil {
+		return err
+	}
+
+	return walker.checkAll(childNodes(node))
+}
+
+func (walker *allowlistWalker) checkAll(nodes []ast.Node) error {
+	for _, child := range nodes {
+		if err := walker.check(child); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+func childNodes(node ast.Node) []ast.Node {
+	switch typed := node.(type) {
+	case *ast.UnaryNode:
+		return []ast.Node{typed.Node}
+	case *ast.BinaryNode:
+		return []ast.Node{typed.Left, typed.Right}
+	case *ast.CallNode:
+		return typed.Arguments
+	case *ast.ArrayNode:
+		return typed.Nodes
+	}
+	return nil
 }
 
 func checkNode(node ast.Node) error {

+ 24 - 0
service/internal/logfilter/filter_test.go

@@ -2,6 +2,7 @@ package logfilter
 
 import (
 	"testing"
+	"time"
 
 	"github.com/expr-lang/expr/vm"
 	"github.com/stretchr/testify/assert"
@@ -153,3 +154,26 @@ func TestCompileAllowsSupportedExpressions(t *testing.T) {
 		assert.Equal(t, expected, matched, expression)
 	}
 }
+
+func nestedChainedComparison(depth int) string {
+	term := "0"
+	for range depth {
+		term = "0<(" + term + ")<0"
+	}
+	return term
+}
+
+func TestCompileRejectsNestedChainedComparisonsQuickly(t *testing.T) {
+	expressions := []string{
+		"unknown(" + nestedChainedComparison(40) + ")",
+		nestedChainedComparison(40),
+	}
+
+	for _, expression := range expressions {
+		start := time.Now()
+		program, err := Compile(expression)
+		require.Error(t, err)
+		assert.Nil(t, program)
+		assert.Less(t, time.Since(start), time.Second)
+	}
+}

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

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

+ 26 - 7
service/internal/webhooks/jsonpath.go

@@ -61,25 +61,44 @@ func (m *JSONMatcher) ExtractValue(pathExpr string) (string, error) {
 	return string(jsonBytes), nil
 }
 
+// HasValue reports whether the path matches at least one value.
+func (m *JSONMatcher) HasValue(pathExpr string) (bool, error) {
+	_, nodes, err := m.selectNodes(pathExpr)
+	if err != nil {
+		return false, err
+	}
+	return len(nodes) > 0, nil
+}
+
 // selectValue returns the single value for a path that can only match one node,
-// and a list for a path that can match several (wildcards, descendants). A path
-// that matches nothing is an error, which callers use to tell that it is absent.
+// and a list for a path that can match several (wildcards, descendants). A
+// singular path that matches nothing is an error, which callers use to tell
+// that it is absent. A path that can match several nodes returns a list even
+// when it is empty, so that "$.commits[*].id" on a push with no commits is "[]".
 func (m *JSONMatcher) selectValue(pathExpr string) (any, error) {
-	path, err := jsonpath.Parse(withRootSelector(pathExpr))
+	path, nodes, err := m.selectNodes(pathExpr)
 	if err != nil {
 		return nil, err
 	}
 
-	nodes := path.Select(m.payload)
+	if path.Query().Singular() == nil {
+		return append([]any{}, nodes...), nil
+	}
+
 	if len(nodes) == 0 {
 		return nil, fmt.Errorf("no value found at JSONPath %q", pathExpr)
 	}
 
-	if path.Query().Singular() != nil {
-		return nodes[0], nil
+	return nodes[0], nil
+}
+
+func (m *JSONMatcher) selectNodes(pathExpr string) (*jsonpath.Path, []any, error) {
+	path, err := jsonpath.Parse(withRootSelector(pathExpr))
+	if err != nil {
+		return nil, nil, err
 	}
 
-	return []any(nodes), nil
+	return path, path.Select(m.payload), nil
 }
 
 // Earlier versions of OliveTin accepted paths without the leading "$", such as

+ 36 - 0
service/internal/webhooks/jsonpath_test.go

@@ -78,3 +78,39 @@ func TestMatchPath(t *testing.T) {
 	_, err = matcher.MatchPath("$.missing", "x")
 	assert.Error(t, err)
 }
+
+func TestEmptyCollectionIsExtractedAndMatchedAsAnEmptyList(t *testing.T) {
+	matcher, err := NewJSONMatcher([]byte(`{"commits": []}`))
+	require.NoError(t, err)
+
+	value, err := matcher.ExtractValue("$.commits[*].id")
+	require.NoError(t, err)
+	assert.Equal(t, "[]", value)
+
+	matched, err := matcher.MatchPath("$.commits[*].id", "[]")
+	require.NoError(t, err)
+	assert.True(t, matched)
+
+	found, err := matcher.HasValue("$.commits[*].id")
+	require.NoError(t, err)
+	assert.False(t, found, "an empty collection has no value for an existence check")
+}
+
+func TestHasValue(t *testing.T) {
+	matcher := newTestJSONMatcher(t)
+
+	cases := map[string]bool{
+		"$.repository.name":   true,
+		"$.repository.topics": true,
+		"$.commits[*].id":     true,
+		"$.missing":           false,
+		"$.commits[5]":        false,
+	}
+	for path, expected := range cases {
+		t.Run(path, func(t *testing.T) {
+			found, err := matcher.HasValue(path)
+			require.NoError(t, err)
+			assert.Equal(t, expected, found)
+		})
+	}
+}

+ 20 - 11
service/internal/webhooks/matcher.go

@@ -12,6 +12,7 @@ import (
 type WebhookMatcher struct {
 	config    config.WebhookConfig
 	req       *http.Request
+	log       *log.Entry
 	bodyBytes []byte
 }
 
@@ -20,9 +21,17 @@ func NewWebhookMatcher(cfg config.WebhookConfig, r *http.Request, bodyBytes []by
 		config:    cfg,
 		req:       r,
 		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 {
 	if !m.matchHeaders() {
 		return false
@@ -47,10 +56,10 @@ func (m *WebhookMatcher) matchHeaders() bool {
 	for key, expectedValue := range m.config.MatchHeaders {
 		actualValue := m.req.Header.Get(key)
 		if !m.compareValues(actualValue, expectedValue) {
-			log.WithFields(log.Fields{
-				"header":   key,
-				"expected": expectedValue,
-				"actual":   actualValue,
+			// Header values can be credentials, such as a token or signature, so
+			// only the header name is logged.
+			m.log.WithFields(log.Fields{
+				"header": key,
 			}).Debugf("Header mismatch")
 			return false
 		}
@@ -67,7 +76,7 @@ func (m *WebhookMatcher) matchQuery() bool {
 	for key, expectedValue := range m.config.MatchQuery {
 		actualValue := query.Get(key)
 		if !m.compareValues(actualValue, expectedValue) {
-			log.WithFields(log.Fields{
+			m.log.WithFields(log.Fields{
 				"query":    key,
 				"expected": expectedValue,
 				"actual":   actualValue,
@@ -86,7 +95,7 @@ func (m *WebhookMatcher) matchPath() bool {
 	jsonPath, expectedValue := m.parseMatchPath()
 	matcher, err := NewJSONMatcher(m.bodyBytes)
 	if err != nil {
-		log.WithFields(log.Fields{
+		m.log.WithFields(log.Fields{
 			"error": err,
 		}).Debugf("Failed to create JSON matcher")
 		return false
@@ -107,13 +116,13 @@ func (m *WebhookMatcher) parseMatchPath() (string, string) {
 
 func (m *WebhookMatcher) matchPathValue(matcher *JSONMatcher, jsonPath, expectedValue string) bool {
 	if expectedValue == "" {
-		_, err := matcher.ExtractValue(jsonPath)
-		return err == nil
+		found, err := matcher.HasValue(jsonPath)
+		return err == nil && found
 	}
 
 	matches, err := matcher.MatchPath(jsonPath, expectedValue)
 	if err != nil {
-		log.WithFields(log.Fields{
+		m.log.WithFields(log.Fields{
 			"jsonPath": jsonPath,
 			"error":    err,
 		}).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 {
 		matched, err := regexp.MatchString(pattern, actual)
 		if err != nil {
-			log.WithFields(log.Fields{
+			m.log.WithFields(log.Fields{
 				"pattern": pattern,
 				"error":   err,
 			}).Warnf("Invalid regex pattern")
@@ -169,7 +178,7 @@ func (m *WebhookMatcher) extractJSONPathValues(matcher *JSONMatcher) map[string]
 	for argName, jsonPath := range m.config.Extract {
 		value, err := matcher.ExtractValue(jsonPath)
 		if err != nil {
-			log.WithFields(log.Fields{
+			m.log.WithFields(log.Fields{
 				"argName":  argName,
 				"jsonPath": jsonPath,
 				"error":    err,