Răsfoiți Sursa

fix(webhook): keep the webhook URL out of logs and errors

Webhook receivers often embed a secret in the URL path or query, but
the full URL was logged at debug, warn and error level and included in
the status error. Drop it from the logs and the status error, and keep
only the scheme and host in request errors.
Frédéric Guillot 8 ore în urmă
părinte
comite
b249b8e420

+ 0 - 4
internal/integration/integration.go

@@ -432,7 +432,6 @@ func SendEntry(entry *model.Entry, userIntegrations *model.Integration) {
 			slog.Int64("user_id", userIntegrations.UserID),
 			slog.Int64("entry_id", entry.ID),
 			slog.String("entry_url", entry.URL),
-			slog.String("webhook_url", webhookURL),
 		)
 
 		webhookClient := webhook.NewClient(webhookURL, userIntegrations.WebhookSecret)
@@ -441,7 +440,6 @@ func SendEntry(entry *model.Entry, userIntegrations *model.Integration) {
 				slog.Int64("user_id", userIntegrations.UserID),
 				slog.Int64("entry_id", entry.ID),
 				slog.String("entry_url", entry.URL),
-				slog.String("webhook_url", webhookURL),
 				slog.Any("error", err),
 			)
 		}
@@ -546,7 +544,6 @@ func PushEntries(feed *model.Feed, entries model.Entries, userIntegrations *mode
 			slog.Int64("user_id", userIntegrations.UserID),
 			slog.Int("nb_entries", len(entries)),
 			slog.Int64("feed_id", feed.ID),
-			slog.String("webhook_url", webhookURL),
 		)
 
 		webhookClient := webhook.NewClient(webhookURL, userIntegrations.WebhookSecret)
@@ -555,7 +552,6 @@ func PushEntries(feed *model.Feed, entries model.Entries, userIntegrations *mode
 				slog.Int64("user_id", userIntegrations.UserID),
 				slog.Int("nb_entries", len(entries)),
 				slog.Int64("feed_id", feed.ID),
-				slog.String("webhook_url", webhookURL),
 				slog.Any("error", err),
 			)
 		}

+ 88 - 0
internal/integration/integration_test.go

@@ -6,9 +6,12 @@ package integration
 import (
 	"bytes"
 	"log/slog"
+	"net/http"
+	"net/http/httptest"
 	"strings"
 	"testing"
 
+	"miniflux.app/v2/internal/config"
 	"miniflux.app/v2/internal/model"
 )
 
@@ -61,3 +64,88 @@ func TestSendEntryLogsLinkwardenWithoutCollectionID(t *testing.T) {
 		t.Fatalf("did not expect collection_id in logs; got: %s", out)
 	}
 }
+
+func TestSendEntryDoesNotLogWebhookURL(t *testing.T) {
+	configureIntegrationAllowPrivateNetworksOption(t)
+	logs := captureDebugLogs(t)
+	webhookURL := newFailingWebhookURL(t)
+
+	entry := &model.Entry{
+		ID:    52,
+		URL:   "https://example.org/test.html",
+		Title: "Test",
+		Feed:  &model.Feed{ID: 1, Category: &model.Category{ID: 1}},
+	}
+	userIntegrations := &model.Integration{UserID: 1, WebhookEnabled: true, WebhookURL: webhookURL}
+
+	SendEntry(entry, userIntegrations)
+
+	assertLogsDoNotContainWebhookURL(t, logs, "Unable to send entry to Webhook")
+}
+
+func TestPushEntriesDoesNotLogWebhookURL(t *testing.T) {
+	configureIntegrationAllowPrivateNetworksOption(t)
+	logs := captureDebugLogs(t)
+	webhookURL := newFailingWebhookURL(t)
+
+	feed := &model.Feed{ID: 1, Category: &model.Category{ID: 1}, WebhookURL: webhookURL}
+	entries := model.Entries{&model.Entry{ID: 52, URL: "https://example.org/test.html", Title: "Test"}}
+	userIntegrations := &model.Integration{UserID: 1, WebhookEnabled: true}
+
+	PushEntries(feed, entries, userIntegrations)
+
+	assertLogsDoNotContainWebhookURL(t, logs, "Unable to send new entries to Webhook")
+}
+
+// newFailingWebhookURL returns a webhook URL with secrets in its userinfo, path and query, served by a failing server.
+func newFailingWebhookURL(t *testing.T) string {
+	t.Helper()
+
+	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+		writer.WriteHeader(http.StatusInternalServerError)
+	}))
+	t.Cleanup(server.Close)
+
+	return strings.Replace(server.URL, "://", "://user:secret-password@", 1) + "/api/webhook/secret-id?token=secret-token"
+}
+
+func assertLogsDoNotContainWebhookURL(t *testing.T, logs *bytes.Buffer, expectedMessage string) {
+	t.Helper()
+
+	if !strings.Contains(logs.String(), expectedMessage) {
+		t.Fatalf("expected %q in logs; got: %s", expectedMessage, logs.String())
+	}
+
+	for _, secret := range []string{"secret-password", "secret-id", "secret-token"} {
+		if strings.Contains(logs.String(), secret) {
+			t.Errorf("expected logs to not contain %q; got: %s", secret, logs.String())
+		}
+	}
+}
+
+func captureDebugLogs(t *testing.T) *bytes.Buffer {
+	t.Helper()
+
+	var logs bytes.Buffer
+	previousLogger := slog.Default()
+	slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})))
+	t.Cleanup(func() { slog.SetDefault(previousLogger) })
+	return &logs
+}
+
+func configureIntegrationAllowPrivateNetworksOption(t *testing.T) {
+	t.Helper()
+
+	t.Setenv("INTEGRATION_ALLOW_PRIVATE_NETWORKS", "1")
+
+	parsedOptions, err := config.NewConfigParser().ParseEnvironmentVariables()
+	if err != nil {
+		t.Fatalf("Unable to configure test options: %v", err)
+	}
+
+	previousOptions := config.Opts
+	config.Opts = parsedOptions
+	t.Cleanup(func() {
+		config.Opts = previousOptions
+	})
+}

+ 2 - 1
internal/integration/webhook/webhook.go

@@ -121,6 +121,7 @@ func (c *Client) makeRequest(eventType string, payload any) error {
 
 	response, err := client.NewRequestBuilder(c.webhookURL).
 		WithMethod(http.MethodPost).
+		WithSecretEndpoint().
 		WithJSONBody(requestBody).
 		WithHeader("X-Miniflux-Signature", crypto.GenerateSHA256Hmac(c.webhookSecret, requestBody)).
 		WithHeader("X-Miniflux-Event-Type", eventType).
@@ -131,7 +132,7 @@ func (c *Client) makeRequest(eventType string, payload any) error {
 	defer response.Body.Close()
 
 	if response.StatusCode >= 400 {
-		return fmt.Errorf("webhook: incorrect response status code %d for url %s", response.StatusCode, c.webhookURL)
+		return fmt.Errorf("webhook: incorrect response status code %d", response.StatusCode)
 	}
 
 	return nil

+ 99 - 0
internal/integration/webhook/webhook_test.go

@@ -0,0 +1,99 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package webhook
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+
+	"miniflux.app/v2/internal/config"
+	"miniflux.app/v2/internal/model"
+)
+
+var webhookURLSecrets = []string{"secret-password", "secret-id", "secret-token"}
+
+func secretWebhookURL(serverURL string) string {
+	return strings.Replace(serverURL, "://", "://user:secret-password@", 1) + "/api/webhook/secret-id?token=secret-token"
+}
+
+func TestSendNewEntriesWebhookEventErrorsDoNotContainWebhookURL(t *testing.T) {
+	configureIntegrationAllowPrivateNetworksOption(t)
+
+	closeConnection := func(t *testing.T, writer http.ResponseWriter) {
+		connection, _, err := writer.(http.Hijacker).Hijack()
+		if err != nil {
+			t.Errorf("unable to hijack connection: %v", err)
+			return
+		}
+		connection.Close()
+	}
+
+	scenarios := []struct {
+		name            string
+		handler         func(t *testing.T, writer http.ResponseWriter)
+		wantErrContains string
+	}{
+		{
+			name: "connection fails",
+			handler: func(t *testing.T, writer http.ResponseWriter) {
+				closeConnection(t, writer)
+			},
+			wantErrContains: "webhook: unable to send request",
+		},
+		{
+			name: "error status",
+			handler: func(t *testing.T, writer http.ResponseWriter) {
+				writer.WriteHeader(http.StatusInternalServerError)
+			},
+			wantErrContains: "webhook: incorrect response status code 500",
+		},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+				scenario.handler(t, writer)
+			}))
+			defer server.Close()
+
+			feed := &model.Feed{ID: 1, Title: "Feed", Category: &model.Category{ID: 1, Title: "Category"}}
+			entries := model.Entries{&model.Entry{ID: 1, Title: "Entry", URL: "https://example.org/entry"}}
+
+			err := NewClient(secretWebhookURL(server.URL), "signing-secret").SendNewEntriesWebhookEvent(feed, entries)
+			if err == nil {
+				t.Fatal("expected an error, got nil")
+			}
+
+			for _, secret := range webhookURLSecrets {
+				if strings.Contains(err.Error(), secret) {
+					t.Errorf("expected the error to not contain %q, got %q", secret, err)
+				}
+			}
+
+			if !strings.Contains(err.Error(), scenario.wantErrContains) {
+				t.Errorf("expected the error to contain %q, got %q", scenario.wantErrContains, err)
+			}
+		})
+	}
+}
+
+func configureIntegrationAllowPrivateNetworksOption(t *testing.T) {
+	t.Helper()
+
+	t.Setenv("INTEGRATION_ALLOW_PRIVATE_NETWORKS", "1")
+
+	configParser := config.NewConfigParser()
+	parsedOptions, err := configParser.ParseEnvironmentVariables()
+	if err != nil {
+		t.Fatalf("Unable to configure test options: %v", err)
+	}
+
+	previousOptions := config.Opts
+	config.Opts = parsedOptions
+	t.Cleanup(func() {
+		config.Opts = previousOptions
+	})
+}