Browse Source

fix(processor): don't follow redirects from the YouTube API

The HTTP client forwards custom headers to the redirect target, which
would send the X-Goog-Api-Key header to another host.
Frédéric Guillot 9 hours ago
parent
commit
a76fdcf588
2 changed files with 27 additions and 1 deletions
  1. 8 1
      internal/reader/processor/youtube.go
  2. 19 0
      internal/reader/processor/youtube_test.go

+ 8 - 1
internal/reader/processor/youtube.go

@@ -5,6 +5,7 @@ package processor // import "miniflux.app/v2/internal/reader/processor"
 
 import (
 	"encoding/json"
+	"errors"
 	"fmt"
 	"log/slog"
 	"net/url"
@@ -86,9 +87,11 @@ func fetchYouTubeWatchTimeFromApiInBulk(apiURL string, videoIDs []string) (map[s
 	apiQuery.Set("id", strings.Join(videoIDs, ","))
 	apiQuery.Set("part", "contentDetails")
 
-	// The key goes in a header rather than the query string to keep it out of logged URLs.
+	// The key goes in a header to keep it out of logged URLs, and redirects are not
+	// followed because the HTTP client forwards custom headers to the redirect target.
 	requestBuilder := fetcher.NewRequestBuilder().
 		WithHeader("X-Goog-Api-Key", config.Opts.YouTubeAPIKey()).
+		WithoutRedirects().
 		WithTimeout(config.Opts.HTTPClientTimeout()).
 		WithProxyRotator(proxyrotator.ProxyRotatorInstance)
 
@@ -100,6 +103,10 @@ func fetchYouTubeWatchTimeFromApiInBulk(apiURL string, videoIDs []string) (map[s
 		return nil, localizedError.Error()
 	}
 
+	if responseHandler.IsRedirect() {
+		return nil, errors.New("youtube: unexpected redirect from the API")
+	}
+
 	videos := struct {
 		Items []struct {
 			ID             string `json:"id"`

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

@@ -142,3 +142,22 @@ func TestFetchYouTubeWatchTimeFromAPIInBulkKeepsKeyOutOfErrors(t *testing.T) {
 		t.Errorf("Logs contain the API key:\n%s", logs.String())
 	}
 }
+
+func TestFetchYouTubeWatchTimeFromAPIInBulkDoesNotFollowRedirects(t *testing.T) {
+	const apiKey = "AIzaSyTestKey"
+	configureYouTubeAPIOptions(t, apiKey)
+
+	redirectTarget := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+		t.Errorf("Expected the redirect not to be followed, got a request with X-Goog-Api-Key %q", request.Header.Get("X-Goog-Api-Key"))
+	}))
+	defer redirectTarget.Close()
+
+	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+		http.Redirect(writer, request, redirectTarget.URL, http.StatusFound)
+	}))
+	defer server.Close()
+
+	if _, err := fetchYouTubeWatchTimeFromApiInBulk(server.URL, []string{"video1"}); err == nil {
+		t.Fatal("Expected an error when the API responds with a redirect")
+	}
+}