Explorar el Código

fix: reject webhooks that have no authType

A webhook in execOnWebhook with no authType accepted every matching
request, although its match rules are not secrets and the action runs
as the system usergroup. A webhook without an authType is now rejected,
and Diagnostics reports a webhook_auth_type_unset error for it. Open
webhooks must set authType: none explicitly. Webhooks that use a GitHub
template keep the authType the template sets.

The example config's two demo webhooks now set authType: none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread hace 1 día
padre
commit
3ed3bf6f96

+ 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.

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

@@ -92,9 +92,13 @@ 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"
+
 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")

+ 33 - 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,35 @@ 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
+}
+
+// Webhook templates choose their own authType, so only webhooks without a
+// template need one in the config.
+func webhookAuthIssuesForAction(action *config.Action) []configissues.Issue {
+	out := make([]configissues.Issue, 0)
+
+	for index, webhook := range action.ExecOnWebhook {
+		if webhook.AuthType != "" || webhook.Template != "" {
+			continue
+		}
+
+		out = append(out, 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",
+			fmt.Sprintf("execOnWebhook[%d]", index), ""))
+	}
+
+	return out
+}

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

@@ -0,0 +1,49 @@
+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)
+}

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

@@ -25,6 +25,7 @@ const (
 	CodeDeprecatedAPICall      = "deprecated_api_call"
 	CodeOnClickUnknown         = "onclick_unknown"
 	CodeDashboardTypeUnknown   = "dashboard_type_unknown"
+	CodeWebhookAuthTypeUnset   = "webhook_auth_type_unset"
 )
 
 // 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,

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

@@ -0,0 +1,76 @@
+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))
+}