Explorar o código

refactor(urllib): consolidate URL redaction in errors

The fetcher and RSS-Bridge repeated the same block to redact the URL of
a *url.Error, while the HTTP client and Pinboard each had their own
helper. Pinboard errors now keep the scheme and host, like the other
integrations whose URL is a secret.
Frédéric Guillot hai 5 horas
pai
achega
fec92327c0

+ 1 - 20
internal/http/client/client.go

@@ -12,7 +12,6 @@ import (
 	"io"
 	"io"
 	"net"
 	"net"
 	"net/http"
 	"net/http"
-	"net/url"
 	"time"
 	"time"
 
 
 	"miniflux.app/v2/internal/config"
 	"miniflux.app/v2/internal/config"
@@ -177,25 +176,7 @@ func (r *requestBuilder) Do() (*http.Response, error) {
 
 
 func (r *requestBuilder) redactURL(err error) error {
 func (r *requestBuilder) redactURL(err error) error {
 	if r.secretEndpoint {
 	if r.secretEndpoint {
-		return RedactURLInError(err)
-	}
-	return err
-}
-
-// RedactURLInError hides the path and query of the URL carried by a
-// *url.Error in err, for requests whose URL embeds a secret such as a token.
-// Only the scheme and host are kept, which is enough to diagnose network
-// failures. The error is modified in place and returned.
-//
-// Call it before wrapping err: fmt.Errorf formats the message of the
-// wrapping error immediately, so a later change would not be reflected.
-func RedactURLInError(err error) error {
-	if urlErr, ok := errors.AsType[*url.Error](err); ok {
-		redactedURL := "xxxxx"
-		if parsedURL, parseErr := url.Parse(urlErr.URL); parseErr == nil && parsedURL.Host != "" {
-			redactedURL = parsedURL.Scheme + "://" + parsedURL.Host + "/xxxxx"
-		}
-		urlErr.URL = redactedURL
+		return urllib.RedactSecretURLInError(err)
 	}
 	}
 	return err
 	return err
 }
 }

+ 0 - 42
internal/http/client/client_test.go

@@ -9,7 +9,6 @@ import (
 	"net"
 	"net"
 	"net/http"
 	"net/http"
 	"net/http/httptest"
 	"net/http/httptest"
-	"net/url"
 	"strings"
 	"strings"
 	"testing"
 	"testing"
 	"time"
 	"time"
@@ -224,47 +223,6 @@ func TestRequestBuilderWithSecretEndpointRedactsErrors(t *testing.T) {
 	}
 	}
 }
 }
 
 
-func TestRedactURLInError(t *testing.T) {
-	tests := []struct {
-		name string
-		err  error
-		want string
-	}{
-		{
-			name: "network error",
-			err:  &url.Error{Op: "Post", URL: "https://example.org/bot123:secret-token/sendMessage?key=secret-token", Err: io.ErrUnexpectedEOF},
-			want: `Post "https://example.org/xxxxx": unexpected EOF`,
-		},
-		{
-			name: "network error with userinfo and port",
-			err:  &url.Error{Op: "Get", URL: "https://user:password@example.org:8443/secret-token", Err: io.ErrUnexpectedEOF},
-			want: `Get "https://example.org:8443/xxxxx": unexpected EOF`,
-		},
-		{
-			name: "unparsable URL",
-			err:  &url.Error{Op: "parse", URL: "https://example.org/secret-token\n", Err: errors.New("net/url: invalid control character in URL")},
-			want: `parse "xxxxx": net/url: invalid control character in URL`,
-		},
-		{
-			name: "error without URL",
-			err:  io.ErrUnexpectedEOF,
-			want: "unexpected EOF",
-		},
-	}
-
-	for _, tt := range tests {
-		t.Run(tt.name, func(t *testing.T) {
-			if got := RedactURLInError(tt.err).Error(); got != tt.want {
-				t.Fatalf("expected %q, got %q", tt.want, got)
-			}
-		})
-	}
-
-	if err := RedactURLInError(nil); err != nil {
-		t.Fatalf("expected nil, got %v", err)
-	}
-}
-
 func configureIntegrationAllowPrivateNetworksOption(t *testing.T) {
 func configureIntegrationAllowPrivateNetworksOption(t *testing.T) {
 	t.Helper()
 	t.Helper()
 
 

+ 3 - 10
internal/integration/pinboard/pinboard.go

@@ -12,6 +12,7 @@ import (
 	"time"
 	"time"
 
 
 	"miniflux.app/v2/internal/http/client"
 	"miniflux.app/v2/internal/http/client"
+	"miniflux.app/v2/internal/urllib"
 	"miniflux.app/v2/internal/version"
 	"miniflux.app/v2/internal/version"
 )
 )
 
 
@@ -67,7 +68,7 @@ func (c *Client) CreateBookmark(entryURL, entryTitle, pinboardTags string, markA
 	httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
 	httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
 	response, err := httpClient.Do(request)
 	response, err := httpClient.Do(request)
 	if err != nil {
 	if err != nil {
-		return fmt.Errorf("pinboard: unable to send request: %w", withoutURL(err))
+		return fmt.Errorf("pinboard: unable to send request: %w", urllib.RedactSecretURLInError(err))
 	}
 	}
 	defer response.Body.Close()
 	defer response.Body.Close()
 
 
@@ -99,7 +100,7 @@ func (c *Client) getBookmark(entryURL string) (*Post, error) {
 	httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
 	httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
 	response, err := httpClient.Do(request)
 	response, err := httpClient.Do(request)
 	if err != nil {
 	if err != nil {
-		return nil, fmt.Errorf("pinboard: unable fetch bookmark: %w", withoutURL(err))
+		return nil, fmt.Errorf("pinboard: unable fetch bookmark: %w", urllib.RedactSecretURLInError(err))
 	}
 	}
 	defer response.Body.Close()
 	defer response.Body.Close()
 
 
@@ -119,11 +120,3 @@ func (c *Client) getBookmark(entryURL string) (*Post, error) {
 
 
 	return &results.Posts[0], nil
 	return &results.Posts[0], nil
 }
 }
-
-// withoutURL drops the request URL, which contains the auth token, from HTTP client errors.
-func withoutURL(err error) error {
-	if urlErr, ok := errors.AsType[*url.Error](err); ok {
-		return urlErr.Err
-	}
-	return err
-}

+ 1 - 5
internal/integration/rssbridge/rssbridge.go

@@ -5,7 +5,6 @@ package rssbridge // import "miniflux.app/v2/internal/integration/rssbridge"
 
 
 import (
 import (
 	"encoding/json"
 	"encoding/json"
-	"errors"
 	"fmt"
 	"fmt"
 	"log/slog"
 	"log/slog"
 	"net/http"
 	"net/http"
@@ -58,10 +57,7 @@ func DetectBridges(rssBridgeURL, rssBridgeToken, websiteURL string) ([]*Bridge,
 
 
 	response, err := httpClient.Do(request)
 	response, err := httpClient.Do(request)
 	if err != nil {
 	if err != nil {
-		if urlErr, ok := errors.AsType[*url.Error](err); ok {
-			urlErr.URL = urllib.RedactedURL(urlErr.URL)
-		}
-		return nil, fmt.Errorf("rssbridge: unable to execute request: %w", err)
+		return nil, fmt.Errorf("rssbridge: unable to execute request: %w", urllib.RedactURLInError(err))
 	}
 	}
 	defer response.Body.Close()
 	defer response.Body.Close()
 
 

+ 3 - 2
internal/integration/telegrambot/client.go

@@ -12,6 +12,7 @@ import (
 	"time"
 	"time"
 
 
 	"miniflux.app/v2/internal/http/client"
 	"miniflux.app/v2/internal/http/client"
+	"miniflux.app/v2/internal/urllib"
 	"miniflux.app/v2/internal/version"
 	"miniflux.app/v2/internal/version"
 )
 )
 
 
@@ -56,7 +57,7 @@ func (c *Client) GetMe() (*User, error) {
 	httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
 	httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
 	response, err := httpClient.Do(request)
 	response, err := httpClient.Do(request)
 	if err != nil {
 	if err != nil {
-		return nil, fmt.Errorf("telegram: unable to send request: %v", client.RedactURLInError(err))
+		return nil, fmt.Errorf("telegram: unable to send request: %v", urllib.RedactSecretURLInError(err))
 	}
 	}
 	defer response.Body.Close()
 	defer response.Body.Close()
 
 
@@ -96,7 +97,7 @@ func (c *Client) SendMessage(message *MessageRequest) (*Message, error) {
 	httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
 	httpClient := client.NewClientWithOptions(client.Options{Timeout: defaultClientTimeout})
 	response, err := httpClient.Do(request)
 	response, err := httpClient.Do(request)
 	if err != nil {
 	if err != nil {
-		return nil, fmt.Errorf("telegram: unable to send request: %v", client.RedactURLInError(err))
+		return nil, fmt.Errorf("telegram: unable to send request: %v", urllib.RedactSecretURLInError(err))
 	}
 	}
 	defer response.Body.Close()
 	defer response.Body.Close()
 
 

+ 1 - 4
internal/reader/fetcher/request_builder.go

@@ -337,10 +337,7 @@ func (r *RequestBuilder) ExecuteRequest(requestURL string) (*http.Response, erro
 	))
 	))
 
 
 	response, err := client.Do(req)
 	response, err := client.Do(req)
-	if urlErr, ok := errors.AsType[*url.Error](err); ok {
-		urlErr.URL = urllib.RedactedURL(urlErr.URL)
-	}
-	return response, err
+	return response, urllib.RedactURLInError(err)
 }
 }
 
 
 // redactedHeaders returns a copy of headers with the credential values replaced, for logging.
 // redactedHeaders returns a copy of headers with the credential values replaced, for logging.

+ 27 - 2
internal/urllib/url.go

@@ -212,21 +212,46 @@ func JoinBaseURLAndPath(baseURL, path string) (string, error) {
 	return finalURL, nil
 	return finalURL, nil
 }
 }
 
 
+// redactedPlaceholder replaces secrets in URLs, like url.URL.Redacted does for passwords.
+const redactedPlaceholder = "xxxxx"
+
 // RedactedURL returns rawURL with the userinfo password and the token query
 // RedactedURL returns rawURL with the userinfo password and the token query
 // parameter replaced by "xxxxx", for logs and errors. It returns "xxxxx" when
 // parameter replaced by "xxxxx", for logs and errors. It returns "xxxxx" when
 // rawURL cannot be parsed, since the raw string could hold a password.
 // rawURL cannot be parsed, since the raw string could hold a password.
 func RedactedURL(rawURL string) string {
 func RedactedURL(rawURL string) string {
 	parsedURL, err := url.Parse(rawURL)
 	parsedURL, err := url.Parse(rawURL)
 	if err != nil {
 	if err != nil {
-		return "xxxxx"
+		return redactedPlaceholder
 	}
 	}
 	if values := parsedURL.Query(); values.Has("token") {
 	if values := parsedURL.Query(); values.Has("token") {
-		values.Set("token", "xxxxx")
+		values.Set("token", redactedPlaceholder)
 		parsedURL.RawQuery = values.Encode()
 		parsedURL.RawQuery = values.Encode()
 	}
 	}
 	return parsedURL.Redacted()
 	return parsedURL.Redacted()
 }
 }
 
 
+// RedactURLInError applies RedactedURL to the URL of the *url.Error in err, in
+// place, and returns err; call it before fmt.Errorf wraps err.
+func RedactURLInError(err error) error {
+	if urlErr, ok := errors.AsType[*url.Error](err); ok {
+		urlErr.URL = RedactedURL(urlErr.URL)
+	}
+	return err
+}
+
+// RedactSecretURLInError keeps only the scheme and host of the URL of the
+// *url.Error in err, in place, and returns err; call it before fmt.Errorf wraps err.
+func RedactSecretURLInError(err error) error {
+	if urlErr, ok := errors.AsType[*url.Error](err); ok {
+		redactedURL := redactedPlaceholder
+		if parsedURL, parseErr := url.Parse(urlErr.URL); parseErr == nil && parsedURL.Host != "" {
+			redactedURL = parsedURL.Scheme + "://" + parsedURL.Host + "/" + redactedPlaceholder
+		}
+		urlErr.URL = redactedURL
+	}
+	return err
+}
+
 // IsNonPublicIP returns true if the given IP is not safe to access from the network.
 // IsNonPublicIP returns true if the given IP is not safe to access from the network.
 func IsNonPublicIP(ip net.IP) bool {
 func IsNonPublicIP(ip net.IP) bool {
 	addr, ok := netip.AddrFromSlice(ip)
 	addr, ok := netip.AddrFromSlice(ip)

+ 79 - 0
internal/urllib/url_test.go

@@ -4,6 +4,8 @@
 package urllib // import "miniflux.app/v2/internal/urllib"
 package urllib // import "miniflux.app/v2/internal/urllib"
 
 
 import (
 import (
+	"errors"
+	"io"
 	"net"
 	"net"
 	"net/url"
 	"net/url"
 	"testing"
 	"testing"
@@ -288,6 +290,83 @@ func TestRedactedURL(t *testing.T) {
 	}
 	}
 }
 }
 
 
+func TestRedactURLInError(t *testing.T) {
+	tests := []struct {
+		name string
+		err  error
+		want string
+	}{
+		{
+			name: "password and token",
+			err:  &url.Error{Op: "Get", URL: "https://user:secret@bridge.example.org/?action=display&token=secret", Err: io.ErrUnexpectedEOF},
+			want: `Get "https://user:xxxxx@bridge.example.org/?action=display&token=xxxxx": unexpected EOF`,
+		},
+		{
+			name: "unparsable URL",
+			err:  &url.Error{Op: "parse", URL: "https://user:secret@example.org/\n", Err: errors.New("net/url: invalid control character in URL")},
+			want: `parse "xxxxx": net/url: invalid control character in URL`,
+		},
+		{
+			name: "error without URL",
+			err:  io.ErrUnexpectedEOF,
+			want: "unexpected EOF",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := RedactURLInError(tt.err).Error(); got != tt.want {
+				t.Fatalf("expected %q, got %q", tt.want, got)
+			}
+		})
+	}
+
+	if err := RedactURLInError(nil); err != nil {
+		t.Fatalf("expected nil, got %v", err)
+	}
+}
+
+func TestRedactSecretURLInError(t *testing.T) {
+	tests := []struct {
+		name string
+		err  error
+		want string
+	}{
+		{
+			name: "network error",
+			err:  &url.Error{Op: "Post", URL: "https://example.org/bot123:secret-token/sendMessage?key=secret-token", Err: io.ErrUnexpectedEOF},
+			want: `Post "https://example.org/xxxxx": unexpected EOF`,
+		},
+		{
+			name: "network error with userinfo and port",
+			err:  &url.Error{Op: "Get", URL: "https://user:password@example.org:8443/secret-token", Err: io.ErrUnexpectedEOF},
+			want: `Get "https://example.org:8443/xxxxx": unexpected EOF`,
+		},
+		{
+			name: "unparsable URL",
+			err:  &url.Error{Op: "parse", URL: "https://example.org/secret-token\n", Err: errors.New("net/url: invalid control character in URL")},
+			want: `parse "xxxxx": net/url: invalid control character in URL`,
+		},
+		{
+			name: "error without URL",
+			err:  io.ErrUnexpectedEOF,
+			want: "unexpected EOF",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := RedactSecretURLInError(tt.err).Error(); got != tt.want {
+				t.Fatalf("expected %q, got %q", tt.want, got)
+			}
+		})
+	}
+
+	if err := RedactSecretURLInError(nil); err != nil {
+		t.Fatalf("expected nil, got %v", err)
+	}
+}
+
 func TestIsNonPublicIP(t *testing.T) {
 func TestIsNonPublicIP(t *testing.T) {
 	testCases := []struct {
 	testCases := []struct {
 		name     string
 		name     string