4
0
Эх сурвалжийг харах

fix(processor): send the YouTube API key in a header

The key was sent as a query parameter, so it appeared in the fetcher
debug log and in the request error logged at warn level when the API
call failed. Send it in the X-Goog-Api-Key header instead, and redact
that header in the debug log.
Frédéric Guillot 9 цаг өмнө
parent
commit
8c1dd9dd3b

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

@@ -342,7 +342,7 @@ func (r *RequestBuilder) ExecuteRequest(requestURL string) (*http.Response, erro
 // redactedHeaders returns a copy of headers with the credential values replaced, for logging.
 func redactedHeaders(headers http.Header) http.Header {
 	redacted := headers.Clone()
-	for _, headerName := range []string{"Authorization", "Cookie", "Proxy-Authorization"} {
+	for _, headerName := range []string{"Authorization", "Cookie", "Proxy-Authorization", "X-Goog-Api-Key"} {
 		if redacted.Get(headerName) != "" {
 			redacted.Set(headerName, "<redacted>")
 		}

+ 2 - 0
internal/reader/fetcher/request_builder_test.go

@@ -345,6 +345,7 @@ func TestRequestBuilder_CredentialsNotLogged(t *testing.T) {
 		"Authorization":       "Basic dGVzdDpwYXNzd29yZA==", // base64 of "test:password"
 		"Cookie":              "session=abc123",
 		"Proxy-Authorization": "Basic cHJveHk6c2VjcmV0", // base64 of "proxy:secret"
+		"X-Goog-Api-Key":      "AIzaSyTestKey",
 	}
 
 	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
@@ -366,6 +367,7 @@ func TestRequestBuilder_CredentialsNotLogged(t *testing.T) {
 		WithUsernameAndPassword("test", "password").
 		WithCookie(credentialHeaders["Cookie"], server.URL).
 		WithHeader("Proxy-Authorization", credentialHeaders["Proxy-Authorization"]).
+		WithHeader("X-Goog-Api-Key", credentialHeaders["X-Goog-Api-Key"]).
 		ExecuteRequest(server.URL)
 	if err != nil {
 		t.Fatalf("Expected no error, got %v", err)

+ 7 - 11
internal/reader/processor/youtube.go

@@ -17,6 +17,8 @@ import (
 	"miniflux.app/v2/internal/reader/fetcher"
 )
 
+const youTubeVideosAPIURL = "https://www.googleapis.com/youtube/v3/videos"
+
 func isYouTubeVideoURL(websiteURL string) bool {
 	return strings.Contains(websiteURL, "youtube.com/watch?v=")
 }
@@ -64,7 +66,7 @@ func fetchYouTubeWatchTimeInBulk(entries []*model.Entry) {
 		return
 	}
 
-	watchTimeMap, err := fetchYouTubeWatchTimeFromApiInBulk(videoIDs)
+	watchTimeMap, err := fetchYouTubeWatchTimeFromApiInBulk(youTubeVideosAPIURL, videoIDs)
 	if err != nil {
 		slog.Warn("Unable to fetch YouTube watch time in bulk", slog.Any("error", err))
 		return
@@ -77,26 +79,20 @@ func fetchYouTubeWatchTimeInBulk(entries []*model.Entry) {
 	}
 }
 
-func fetchYouTubeWatchTimeFromApiInBulk(videoIDs []string) (map[string]time.Duration, error) {
+func fetchYouTubeWatchTimeFromApiInBulk(apiURL string, videoIDs []string) (map[string]time.Duration, error) {
 	slog.Debug("Fetching YouTube watch time in bulk", slog.Any("video_ids", videoIDs))
 
 	apiQuery := url.Values{}
 	apiQuery.Set("id", strings.Join(videoIDs, ","))
-	apiQuery.Set("key", config.Opts.YouTubeAPIKey())
 	apiQuery.Set("part", "contentDetails")
 
-	apiURL := url.URL{
-		Scheme:   "https",
-		Host:     "www.googleapis.com",
-		Path:     "youtube/v3/videos",
-		RawQuery: apiQuery.Encode(),
-	}
-
+	// The key goes in a header rather than the query string to keep it out of logged URLs.
 	requestBuilder := fetcher.NewRequestBuilder().
+		WithHeader("X-Goog-Api-Key", config.Opts.YouTubeAPIKey()).
 		WithTimeout(config.Opts.HTTPClientTimeout()).
 		WithProxyRotator(proxyrotator.ProxyRotatorInstance)
 
-	responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(apiURL.String()))
+	responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(apiURL + "?" + apiQuery.Encode()))
 	defer responseHandler.Close()
 
 	if localizedError := responseHandler.LocalizedError(); localizedError != nil {

+ 102 - 0
internal/reader/processor/youtube_test.go

@@ -4,7 +4,15 @@
 package processor // import "miniflux.app/v2/internal/reader/processor"
 
 import (
+	"bytes"
+	"log/slog"
+	"net/http"
+	"net/http/httptest"
+	"strings"
 	"testing"
+	"time"
+
+	"miniflux.app/v2/internal/config"
 )
 
 func TestGetYouTubeVideoIDFromURL(t *testing.T) {
@@ -40,3 +48,97 @@ func TestIsYouTubeVideoURL(t *testing.T) {
 		}
 	}
 }
+
+func configureYouTubeAPIOptions(t *testing.T, apiKey string) {
+	t.Helper()
+
+	t.Setenv("YOUTUBE_API_KEY", apiKey)
+	t.Setenv("FETCHER_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
+	})
+}
+
+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 TestFetchYouTubeWatchTimeFromAPIInBulkSendsKeyInHeader(t *testing.T) {
+	const apiKey = "AIzaSyTestKey"
+	configureYouTubeAPIOptions(t, apiKey)
+	logs := captureDebugLogs(t)
+
+	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+		if got := request.Header.Get("X-Goog-Api-Key"); got != apiKey {
+			t.Errorf("Expected the X-Goog-Api-Key header to be %q, got %q", apiKey, got)
+		}
+		if request.URL.Query().Has("key") {
+			t.Errorf("Expected no key query parameter, got %q", request.URL.RawQuery)
+		}
+		if got := request.URL.Query().Get("id"); got != "video1,video2" {
+			t.Errorf("Expected the id query parameter to be %q, got %q", "video1,video2", got)
+		}
+		if got := request.URL.Query().Get("part"); got != "contentDetails" {
+			t.Errorf("Expected the part query parameter to be %q, got %q", "contentDetails", got)
+		}
+
+		writer.Header().Set("Content-Type", "application/json")
+		writer.Write([]byte(`{"items":[{"id":"video1","contentDetails":{"duration":"PT1M30S"}},{"id":"video2","contentDetails":{"duration":"PT1H"}}]}`))
+	}))
+	defer server.Close()
+
+	watchTimeMap, err := fetchYouTubeWatchTimeFromApiInBulk(server.URL, []string{"video1", "video2"})
+	if err != nil {
+		t.Fatalf("Expected no error, got %v", err)
+	}
+
+	expectedWatchTimes := map[string]time.Duration{
+		"video1": 90 * time.Second,
+		"video2": time.Hour,
+	}
+	for videoID, expectedWatchTime := range expectedWatchTimes {
+		if watchTimeMap[videoID] != expectedWatchTime {
+			t.Errorf("Expected watch time %v for %q, got %v", expectedWatchTime, videoID, watchTimeMap[videoID])
+		}
+	}
+
+	if strings.Contains(logs.String(), apiKey) {
+		t.Errorf("Logs contain the API key:\n%s", logs.String())
+	}
+}
+
+func TestFetchYouTubeWatchTimeFromAPIInBulkKeepsKeyOutOfErrors(t *testing.T) {
+	const apiKey = "AIzaSyTestKey"
+	configureYouTubeAPIOptions(t, apiKey)
+	logs := captureDebugLogs(t)
+
+	server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+	serverURL := server.URL
+	server.Close()
+
+	_, err := fetchYouTubeWatchTimeFromApiInBulk(serverURL, []string{"video1"})
+	if err == nil {
+		t.Fatal("Expected an error when the API is unreachable")
+	}
+
+	if strings.Contains(err.Error(), apiKey) {
+		t.Errorf("Error contains the API key: %v", err)
+	}
+	if strings.Contains(logs.String(), apiKey) {
+		t.Errorf("Logs contain the API key:\n%s", logs.String())
+	}
+}