Procházet zdrojové kódy

fix: reject webhooks that have no authType (#1184)

James Read před 1 dnem
rodič
revize
e3c4512032

+ 8 - 2
config.yaml

@@ -31,7 +31,8 @@ actions:
     onclick: execution-dialog
     # Second webhook example: POST /webhooks?demo=disk-space
     execOnWebhook:
-      - matchQuery:
+      - authType: none
+        matchQuery:
           demo: disk-space
 
   # This uses `onclick: execution-dialog` to show a dialog with more
@@ -120,6 +121,10 @@ actions:
   # webhook request can only start it, not change what it runs. Replace the
   # command with your own script.
   #
+  # Every webhook needs an `authType`. These demo webhooks use `authType: none`,
+  # so anyone who can reach /webhooks can start them. For your own scripts, use
+  # `authType: bearer` (or hmac-sha256) with a `secret`.
+  #
   # Docs: https://docs.olivetin.app/action_execution/onwebhook.html
   # POST to /webhooks with the header X-OliveTin-Demo: run-script
   - title: Run script on webhook
@@ -128,7 +133,8 @@ actions:
     exec: ["echo", "Webhook received. Replace this with your own script."]
     onclick: execution-dialog
     execOnWebhook:
-      - matchHeaders:
+      - authType: none
+        matchHeaders:
           X-OliveTin-Demo: run-script
 
   # OliveTin can control containers - docker is just a command line app.

+ 44 - 14
docs/modules/ROOT/pages/action_execution/onwebhook.adoc

@@ -18,11 +18,13 @@ actions:
     exec:
       - /opt/scripts/deploy.sh
     execOnWebhook:
-      - matchHeaders:
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchHeaders:
           X-Event-Type: deploy
 ----
 
-This action will be triggered when a POST request is sent to `/webhooks` with the header `X-Event-Type: deploy`.
+This action will be triggered when a POST request is sent to `/webhooks` with the header `X-Event-Type: deploy` and the header `Authorization: Bearer <token>`, where the token is the value of the `WEBHOOK_TOKEN` environment variable. Every webhook needs an `authType`; see <<every-webhook-needs-an-authtype,Webhook Authentication>>.
 
 == Webhook Endpoint
 
@@ -56,7 +58,9 @@ actions:
       - echo
       - "Processing event"
     execOnWebhook:
-      - matchHeaders:
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchHeaders:
           X-Event-Type: my-event
           X-Source: my-service
 ----
@@ -78,7 +82,9 @@ actions:
       - name: service
         type: ascii
     execOnWebhook:
-      - matchQuery:
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchQuery:
           action: deploy
           env: production
         extract:
@@ -102,7 +108,9 @@ actions:
       - name: branch
         type: ascii
     execOnWebhook:
-      - matchPath: "$.event_type=push"
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchPath: "$.event_type=push"
         extract:
           branch: "$.branch"
 ----
@@ -112,7 +120,9 @@ The `matchPath` format is `jsonpath=value`. You can also just specify a JSONPath
 [source,yaml]
 ----
 execOnWebhook:
-  - matchPath: "$.repository.name"  # Matches if this path exists in the JSON
+  - authType: bearer
+    secret: "${{ WEBHOOK_TOKEN }}"
+    matchPath: "$.repository.name"  # Matches if this path exists in the JSON
 ----
 
 === Using Regex for Matching
@@ -127,7 +137,9 @@ actions:
       - echo
       - "Handling event"
     execOnWebhook:
-      - matchHeaders:
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchHeaders:
           X-Event-Type: "regex:^(push|pull_request|release)$"
 ----
 
@@ -143,7 +155,9 @@ actions:
       - /opt/scripts/deploy.sh
       - production
     execOnWebhook:
-      - matchHeaders:
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchHeaders:
           X-Event-Type: deploy
         matchQuery:
           environment: production
@@ -168,7 +182,9 @@ actions:
       - name: environment
         type: ascii
     execOnWebhook:
-      - matchHeaders:
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchHeaders:
           X-Event-Type: deploy
         extract:
           version: "$.release.tag_name"
@@ -199,7 +215,9 @@ actions:
       - name: webhook_header_x-request-id
         type: ascii
     execOnWebhook:
-      - matchHeaders:
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchHeaders:
           X-Event-Type: log
 ----
 
@@ -209,9 +227,16 @@ Header names that contain hyphens become argument keys with the same hyphens (fo
 
 OliveTin supports several authentication methods to verify webhook requests:
 
+[#every-webhook-needs-an-authtype]
+=== Every webhook needs an `authType`
+
+Every webhook must set an `authType`. A webhook without one is rejected, and the xref:advanced_configuration/diagnostics.adoc[Diagnostics] page shows an error for it (code `webhook_auth_type_unset`). Webhooks that use one of the xref:action_execution/onwebhook_github.adoc[GitHub templates] choose their own `authType`. A `template` name that OliveTin does not know is ignored, and Diagnostics shows an error for it (code `webhook_template_unknown`). See xref:upgrade/upgrade_notes.adoc#webhook-auth-type-required[Upgrade Notes].
+
+`matchHeaders`, `matchQuery` and `matchPath` only decide which action a request is for. They are not secrets, so use one of the authentication methods below unless anyone who can reach `/webhooks` may run the action. Webhook-triggered actions run as the `system` usergroup, not as the caller (see xref:security/acl.adoc#acls-for-triggers[ACLs for triggers]).
+
 === No Authentication
 
-By default, webhooks have no authentication. Any request matching the criteria will trigger the action:
+To accept webhook requests without any authentication, set `authType: none` explicitly. Any request that matches will then trigger the action, so only do this for actions that are safe for anyone to run:
 
 [source,yaml]
 ----
@@ -301,9 +326,13 @@ actions:
     exec:
       - /opt/scripts/deploy.sh
     execOnWebhook:
-      - matchHeaders:
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchHeaders:
           X-Event-Type: deploy-manual
-      - matchHeaders:
+      - authType: bearer
+        secret: "${{ WEBHOOK_TOKEN }}"
+        matchHeaders:
           X-Event-Type: deploy-auto
         matchPath: "$.status=success"
 ----
@@ -314,9 +343,10 @@ You can test your webhook configuration using `curl`:
 
 [source,bash]
 ----
-# Simple webhook with headers
+# Simple webhook with headers and a bearer token
 curl -X POST \
   -H "Content-Type: application/json" \
+  -H "Authorization: Bearer $WEBHOOK_TOKEN" \
   -H "X-Event-Type: deploy" \
   -d '{"version": "1.2.3"}' \
   http://localhost:1337/webhooks

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

@@ -5,6 +5,13 @@ OliveTin releases are published to GitHub, and the release notes are contained t
 
 == Next release (unreleased)
 
+[#webhook-auth-type-required]
+=== Webhooks need an `authType`, and `authType: none` must be set for open webhooks
+
+A webhook in `execOnWebhook` without an `authType` used to accept every request that matched. It is now rejected, and the Diagnostics page shows an error for it (code `webhook_auth_type_unset`). Webhooks that use a GitHub `template` are not affected, because the template sets its own `authType`.
+
+If you have webhooks without an `authType`, add one. Use `authType: bearer`, `hmac-sha256`, `hmac-sha1` or `basic` with a `secret`, or set `authType: none` if the webhook should accept requests from anyone who can reach `/webhooks`. See xref:action_execution/onwebhook.adoc#every-webhook-needs-an-authtype[Webhook Authentication].
+
 [#whoami-session-fingerprint]
 === `WhoAmI` no longer returns the session ID
 

+ 21 - 1
service/internal/config/config.go

@@ -2,6 +2,7 @@ package config
 
 import (
 	"fmt"
+	"slices"
 )
 
 // ReservedArgumentNamePrefix is reserved for OliveTin-injected system arguments.
@@ -92,9 +93,28 @@ type RateSpec struct {
 }
 
 // WebhookConfig defines configuration for generic webhook triggers.
+// WebhookAuthTypeNone must be set explicitly for a webhook that accepts
+// unauthenticated requests.
+const WebhookAuthTypeNone = "none"
+
+// WebhookTemplateNames are the webhook templates OliveTin knows. Each one sets
+// its own authType, so a webhook that uses one does not need an authType in
+// the config.
+var WebhookTemplateNames = []string{
+	"github-push",
+	"github-pr",
+	"github-pull-request",
+	"github-release",
+	"github-workflow",
+}
+
+func IsKnownWebhookTemplate(name string) bool {
+	return slices.Contains(WebhookTemplateNames, name)
+}
+
 type WebhookConfig struct {
 	Secret        string            `koanf:"secret"`        // Optional: secret for signature verification
-	AuthType      string            `koanf:"authType"`      // Optional: "hmac-sha256", "hmac-sha1", "bearer", "basic", "none"
+	AuthType      string            `koanf:"authType"`      // Required unless set by a template: "hmac-sha256", "hmac-sha1", "bearer", "basic", "none"
 	AuthHeader    string            `koanf:"authHeader"`    // Optional: custom header name for auth (default: "X-Webhook-Signature")
 	MatchHeaders  map[string]string `koanf:"matchHeaders"`  // Match HTTP headers
 	MatchPath     string            `koanf:"matchPath"`     // JSONPath expression to match in request body (format: "jsonpath=value" or just "jsonpath")

+ 50 - 0
service/internal/configcheck/rebuild.go

@@ -40,6 +40,7 @@ func Rebuild(cfg *config.Config, extra ...configissues.Issue) {
 	collected = append(collected, collectCronIssues(cfg)...)
 	collected = append(collected, collectWatcherPathIssues(cfg)...)
 	collected = append(collected, collectDashboardTypeIssues(cfg)...)
+	collected = append(collected, collectWebhookAuthIssues(cfg)...)
 	collected = append(collected, extra...)
 	configissues.Replace(collected)
 }
@@ -574,3 +575,52 @@ func missingWatchDirIssue(displayPath, dirToStat, configFile, actionID, actionTi
 		ConfigFile:  configFile,
 	}}
 }
+
+func collectWebhookAuthIssues(cfg *config.Config) []configissues.Issue {
+	out := make([]configissues.Issue, 0)
+
+	for _, action := range cfg.Actions {
+		if action == nil {
+			continue
+		}
+
+		out = append(out, webhookAuthIssuesForAction(action)...)
+	}
+
+	return out
+}
+
+// Known webhook templates choose their own authType, so only webhooks without
+// one need an authType in the config. An unknown template name sets nothing,
+// so it is reported, and does not excuse a missing authType.
+func webhookAuthIssuesForAction(action *config.Action) []configissues.Issue {
+	out := make([]configissues.Issue, 0)
+
+	for index, webhook := range action.ExecOnWebhook {
+		source := fmt.Sprintf("execOnWebhook[%d]", index)
+		out = append(out, webhookTemplateIssues(action, webhook, source)...)
+		out = append(out, webhookAuthTypeIssues(action, webhook, source)...)
+	}
+
+	return out
+}
+
+func webhookTemplateIssues(action *config.Action, webhook config.WebhookConfig, source string) []configissues.Issue {
+	if webhook.Template == "" || config.IsKnownWebhookTemplate(webhook.Template) {
+		return nil
+	}
+
+	return []configissues.Issue{actionIssue(action, configissues.SeverityError, configissues.CodeWebhookTemplateUnknown,
+		fmt.Sprintf("Webhook template %q is not known, so it is ignored. Known templates are: %s", webhook.Template, strings.Join(config.WebhookTemplateNames, ", ")),
+		source, "")}
+}
+
+func webhookAuthTypeIssues(action *config.Action, webhook config.WebhookConfig, source string) []configissues.Issue {
+	if webhook.AuthType != "" || config.IsKnownWebhookTemplate(webhook.Template) {
+		return nil
+	}
+
+	return []configissues.Issue{actionIssue(action, configissues.SeverityError, configissues.CodeWebhookAuthTypeUnset,
+		"Webhook has no authType, so its requests are rejected. Set an authType such as hmac-sha256 or bearer, or authType: none to allow unauthenticated requests",
+		source, "")}
+}

+ 75 - 0
service/internal/configcheck/webhook_auth_test.go

@@ -0,0 +1,75 @@
+package configcheck_test
+
+import (
+	"testing"
+
+	"github.com/OliveTin/OliveTin/internal/config"
+	"github.com/OliveTin/OliveTin/internal/configcheck"
+	"github.com/OliveTin/OliveTin/internal/configissues"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+)
+
+func webhookAuthIssues(webhooks ...config.WebhookConfig) []configissues.Issue {
+	configissues.BeginConfigLoad()
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{{ID: "deploy", Title: "Deploy", Exec: []string{"true"}, ExecOnWebhook: webhooks}}
+
+	configcheck.Rebuild(cfg)
+
+	return issuesWithCode(configissues.List(), configissues.CodeWebhookAuthTypeUnset)
+}
+
+func TestRebuildReportsWebhookWithoutAuthType(t *testing.T) {
+	issues := webhookAuthIssues(config.WebhookConfig{MatchQuery: map[string]string{"demo": "x"}})
+
+	require.Len(t, issues, 1)
+	assert.Equal(t, configissues.SeverityError, issues[0].Severity)
+	assert.Equal(t, "Deploy", issues[0].ActionTitle)
+	assert.Contains(t, issues[0].Message, "authType: none")
+}
+
+func TestRebuildAcceptsWebhookWithExplicitAuthType(t *testing.T) {
+	assert.Empty(t, webhookAuthIssues(
+		config.WebhookConfig{AuthType: config.WebhookAuthTypeNone},
+		config.WebhookConfig{AuthType: "bearer", Secret: "token"},
+	))
+}
+
+func TestRebuildAcceptsWebhookTemplateWithoutAuthType(t *testing.T) {
+	assert.Empty(t, webhookAuthIssues(config.WebhookConfig{Template: "github-push", Secret: "s3cret"}))
+}
+
+func TestRebuildReportsEachWebhookWithoutAuthType(t *testing.T) {
+	issues := webhookAuthIssues(config.WebhookConfig{}, config.WebhookConfig{AuthType: "bearer"}, config.WebhookConfig{})
+
+	require.Len(t, issues, 2)
+	assert.Equal(t, "execOnWebhook[0]", issues[0].Source)
+	assert.Equal(t, "execOnWebhook[2]", issues[1].Source)
+}
+
+func TestRebuildReportsUnknownWebhookTemplateWithoutAuthType(t *testing.T) {
+	webhook := config.WebhookConfig{Template: "github-pus", Secret: "s3cret"}
+
+	assert.Len(t, webhookAuthIssues(webhook), 1, "a misspelt template must not excuse a missing authType")
+
+	templateIssues := issuesWithCode(configissues.List(), configissues.CodeWebhookTemplateUnknown)
+	require.Len(t, templateIssues, 1)
+	assert.Contains(t, templateIssues[0].Message, "github-pus")
+	assert.Contains(t, templateIssues[0].Message, "github-push")
+	assert.Equal(t, "execOnWebhook[0]", templateIssues[0].Source)
+}
+
+func TestRebuildReportsUnknownWebhookTemplateEvenWithAuthType(t *testing.T) {
+	webhook := config.WebhookConfig{Template: "gitlab-push", AuthType: "bearer", Secret: "token"}
+
+	assert.Empty(t, webhookAuthIssues(webhook))
+	assert.Len(t, issuesWithCode(configissues.List(), configissues.CodeWebhookTemplateUnknown), 1)
+}
+
+func TestRebuildAcceptsEveryKnownWebhookTemplate(t *testing.T) {
+	for _, name := range config.WebhookTemplateNames {
+		assert.Empty(t, webhookAuthIssues(config.WebhookConfig{Template: name, Secret: "s3cret"}), name)
+		assert.Empty(t, issuesWithCode(configissues.List(), configissues.CodeWebhookTemplateUnknown), name)
+	}
+}

+ 2 - 0
service/internal/configissues/issue.go

@@ -25,6 +25,8 @@ const (
 	CodeDeprecatedAPICall      = "deprecated_api_call"
 	CodeOnClickUnknown         = "onclick_unknown"
 	CodeDashboardTypeUnknown   = "dashboard_type_unknown"
+	CodeWebhookAuthTypeUnset   = "webhook_auth_type_unset"
+	CodeWebhookTemplateUnknown = "webhook_template_unknown"
 )
 
 // Issue is a configuration warning or error surfaced on Diagnostics.

+ 13 - 1
service/internal/webhooks/auth.go

@@ -31,8 +31,15 @@ func (v *AuthVerifier) Verify(r *http.Request, payload []byte) bool {
 
 type authVerifierFunc func(*http.Request, []byte) bool
 
+// Webhooks match on headers, query parameters and the body, which are not
+// secrets, so a webhook with no authType is rejected. Operators who want an
+// open webhook must say so with authType: none.
 func (v *AuthVerifier) getVerifier() authVerifierFunc {
-	if v.config.AuthType == "" || v.config.AuthType == "none" {
+	if v.config.AuthType == "" {
+		return rejectMissingAuthType
+	}
+
+	if v.config.AuthType == config.WebhookAuthTypeNone {
 		return func(_ *http.Request, _ []byte) bool {
 			return true
 		}
@@ -58,6 +65,11 @@ func (v *AuthVerifier) buildVerifierMap() map[string]authVerifierFunc {
 	}
 }
 
+func rejectMissingAuthType(_ *http.Request, _ []byte) bool {
+	log.Warnf("Webhook has no authType, rejecting. Set an authType, or authType: none to allow unauthenticated requests")
+	return false
+}
+
 func (v *AuthVerifier) handleUnknownAuthType() bool {
 	log.WithFields(log.Fields{
 		"authType": v.config.AuthType,

+ 89 - 0
service/internal/webhooks/auth_type_required_test.go

@@ -0,0 +1,89 @@
+package webhooks
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	"github.com/OliveTin/OliveTin/internal/config"
+	"github.com/OliveTin/OliveTin/internal/executor"
+)
+
+func unauthenticatedWebhookRequest(t *testing.T) *http.Request {
+	t.Helper()
+
+	return httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks?demo=open", strings.NewReader(`{}`))
+}
+
+func TestWebhookWithoutAuthTypeIsRejected(t *testing.T) {
+	verifier := NewAuthVerifier(config.WebhookConfig{})
+
+	assert.False(t, verifier.Verify(unauthenticatedWebhookRequest(t), []byte(`{}`)))
+}
+
+func TestWebhookWithAuthTypeNoneAcceptsUnauthenticatedRequests(t *testing.T) {
+	verifier := NewAuthVerifier(config.WebhookConfig{AuthType: config.WebhookAuthTypeNone})
+
+	assert.True(t, verifier.Verify(unauthenticatedWebhookRequest(t), []byte(`{}`)))
+}
+
+func TestGitHubTemplateWithoutAuthTypeStillRequiresSignature(t *testing.T) {
+	webhook := config.WebhookConfig{Template: "github-push", Secret: "s3cret"}
+	ApplyGitHubTemplate(&webhook, webhook.Template)
+
+	assert.Equal(t, "hmac-sha256", webhook.AuthType)
+	assert.False(t, NewAuthVerifier(webhook).Verify(unauthenticatedWebhookRequest(t), []byte(`{}`)))
+}
+
+func webhookExecutionCount(t *testing.T, authType string) int {
+	t.Helper()
+
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{{
+		ID:    "open-webhook",
+		Title: "Open webhook",
+		Exec:  []string{"echo", "ran"},
+		ExecOnWebhook: []config.WebhookConfig{{
+			AuthType:   authType,
+			MatchQuery: map[string]string{"demo": "open"},
+		}},
+	}}
+
+	ex := executor.DefaultExecutor(cfg)
+	ex.RebuildActionMap()
+
+	rec := httptest.NewRecorder()
+	NewWebhookHandler(cfg, ex).HandleWebhook(rec, unauthenticatedWebhookRequest(t))
+	require.Equal(t, http.StatusOK, rec.Code)
+
+	time.Sleep(100 * time.Millisecond)
+	logs, _ := ex.GetLogTrackingIds(0, 100)
+
+	return len(logs)
+}
+
+func TestWebhookHandlerDoesNotRunActionWithoutAuthType(t *testing.T) {
+	assert.Equal(t, 0, webhookExecutionCount(t, ""), "a webhook with no authType must not start its action")
+}
+
+func TestWebhookHandlerRunsActionWithAuthTypeNone(t *testing.T) {
+	assert.Equal(t, 1, webhookExecutionCount(t, config.WebhookAuthTypeNone))
+}
+
+func TestKnownWebhookTemplateNamesMatchTemplateAppliers(t *testing.T) {
+	for _, name := range config.WebhookTemplateNames {
+		webhook := config.WebhookConfig{Template: name}
+		ApplyGitHubTemplate(&webhook, name)
+
+		assert.NotEmpty(t, webhook.AuthType, "known template %q must set an authType", name)
+	}
+
+	for name := range templateAppliers() {
+		assert.True(t, config.IsKnownWebhookTemplate(name), "template %q must be listed in config.WebhookTemplateNames", name)
+	}
+}

+ 8 - 3
service/internal/webhooks/github.go

@@ -15,15 +15,20 @@ func ApplyGitHubTemplate(cfg *config.WebhookConfig, template string) {
 
 type templateApplier func(*config.WebhookConfig)
 
-func getTemplateApplier(template string) templateApplier {
-	templateMap := map[string]templateApplier{
+// The names here must match config.WebhookTemplateNames, which the config
+// check uses to decide whether a webhook needs its own authType.
+func templateAppliers() map[string]templateApplier {
+	return map[string]templateApplier{
 		"github-push":         applyGitHubPushTemplate,
 		"github-pr":           applyGitHubPRTemplate,
 		"github-pull-request": applyGitHubPRTemplate,
 		"github-release":      applyGitHubReleaseTemplate,
 		"github-workflow":     applyGitHubWorkflowTemplate,
 	}
-	return templateMap[template]
+}
+
+func getTemplateApplier(template string) templateApplier {
+	return templateAppliers()[template]
 }
 
 func setDefaultAuth(cfg *config.WebhookConfig) {