Browse Source

fix(googlereader): reject kept-unread followed by read in edit-tag

The read case checked a KeptUnreadStream key that is never set, so
a=kept-unread&a=read was accepted and marked entries as read. Reject
it like the reverse order.

Add unit tests for the stream, filter, tag, response and auth
middleware helpers.
Fred 6 hours ago
parent
commit
bb0f58a757

+ 2 - 1
internal/googlereader/handler.go

@@ -1250,7 +1250,8 @@ func checkAndSimplifyTags(addTags []Stream, removeTags []Stream) (map[StreamType
 	for _, s := range addTags {
 		switch s.Type {
 		case ReadStream:
-			if _, ok := tags[KeptUnreadStream]; ok {
+			// kept-unread is stored as ReadStream=false.
+			if read, ok := tags[ReadStream]; ok && !read {
 				return nil, errSimultaneously
 			}
 			tags[ReadStream] = true

+ 136 - 0
internal/googlereader/handler_test.go

@@ -0,0 +1,136 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package googlereader // import "miniflux.app/v2/internal/googlereader"
+
+import (
+	"errors"
+	"maps"
+	"net/http"
+	"net/http/httptest"
+	"net/url"
+	"strings"
+	"testing"
+)
+
+func TestCheckAndSimplifyTags(t *testing.T) {
+	read := Stream{Type: ReadStream}
+	keptUnread := Stream{Type: KeptUnreadStream}
+	starred := Stream{Type: StarredStream}
+	like := Stream{Type: LikeStream}
+	broadcast := Stream{Type: BroadcastStream}
+
+	scenarios := []struct {
+		name     string
+		add      []Stream
+		remove   []Stream
+		expected map[StreamType]bool
+	}{
+		{"add read", []Stream{read}, nil, map[StreamType]bool{ReadStream: true}},
+		{"remove read", nil, []Stream{read}, map[StreamType]bool{ReadStream: false}},
+		{"add kept-unread", []Stream{keptUnread}, nil, map[StreamType]bool{ReadStream: false}},
+		{"remove kept-unread", nil, []Stream{keptUnread}, map[StreamType]bool{ReadStream: true}},
+		{"add starred", []Stream{starred}, nil, map[StreamType]bool{StarredStream: true}},
+		{"remove starred", nil, []Stream{starred}, map[StreamType]bool{StarredStream: false}},
+		{"add read twice", []Stream{read, read}, nil, map[StreamType]bool{ReadStream: true}},
+		{"add read and starred", []Stream{read, starred}, nil, map[StreamType]bool{ReadStream: true, StarredStream: true}},
+		{"add read and remove starred", []Stream{read}, []Stream{starred}, map[StreamType]bool{ReadStream: true, StarredStream: false}},
+		{"like and broadcast are ignored", []Stream{like, broadcast}, []Stream{like, broadcast}, map[StreamType]bool{}},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			result, err := checkAndSimplifyTags(scenario.add, scenario.remove)
+			if err != nil {
+				t.Fatalf(`Unexpected error: %v`, err)
+			}
+			if !maps.Equal(result, scenario.expected) {
+				t.Errorf(`Unexpected tags, got %v instead of %v`, result, scenario.expected)
+			}
+		})
+	}
+}
+
+func TestCheckAndSimplifyTagsRejectsConflicts(t *testing.T) {
+	read := Stream{Type: ReadStream}
+	keptUnread := Stream{Type: KeptUnreadStream}
+	starred := Stream{Type: StarredStream}
+
+	scenarios := []struct {
+		name   string
+		add    []Stream
+		remove []Stream
+	}{
+		{"add and remove read", []Stream{read}, []Stream{read}},
+		{"add read then kept-unread", []Stream{read, keptUnread}, nil},
+		{"add kept-unread then read", []Stream{keptUnread, read}, nil},
+		{"add and remove kept-unread", []Stream{keptUnread}, []Stream{keptUnread}},
+		{"add and remove starred", []Stream{starred}, []Stream{starred}},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			if result, err := checkAndSimplifyTags(scenario.add, scenario.remove); err == nil {
+				t.Errorf(`Expected an error, got %v`, result)
+			}
+		})
+	}
+}
+
+func TestCheckAndSimplifyTagsRejectsUnsupportedTags(t *testing.T) {
+	for _, stream := range []Stream{
+		{Type: ReadingListStream},
+		{Type: BroadcastFriendsStream},
+		{Type: LabelStream, ID: "Tech"},
+		{Type: FeedStream, ID: "1"},
+		{Type: NoStream},
+	} {
+		if _, err := checkAndSimplifyTags([]Stream{stream}, nil); err == nil {
+			t.Errorf(`Expected an error when adding %v`, stream)
+		}
+		if _, err := checkAndSimplifyTags(nil, []Stream{stream}); err == nil {
+			t.Errorf(`Expected an error when removing %v`, stream)
+		}
+	}
+}
+
+func TestCheckAndSimplifyTagsReturnsSimultaneousError(t *testing.T) {
+	_, err := checkAndSimplifyTags([]Stream{{Type: ReadStream}, {Type: KeptUnreadStream}}, nil)
+	if !errors.Is(err, errSimultaneously) {
+		t.Errorf(`Expected errSimultaneously, got %v`, err)
+	}
+}
+
+func TestCheckOutputFormat(t *testing.T) {
+	newPostRequest := func(target string, form url.Values) *http.Request {
+		r := httptest.NewRequest(http.MethodPost, target, strings.NewReader(form.Encode()))
+		r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+		return r
+	}
+
+	scenarios := []struct {
+		name    string
+		request *http.Request
+		valid   bool
+	}{
+		{"GET with output=json", httptest.NewRequest(http.MethodGet, "/?output=json", nil), true},
+		{"GET without output", httptest.NewRequest(http.MethodGet, "/", nil), false},
+		{"GET with output=xml", httptest.NewRequest(http.MethodGet, "/?output=xml", nil), false},
+		{"POST with output=json in the body", newPostRequest("/", url.Values{"output": {"json"}}), true},
+		{"POST with output=json in the query string", newPostRequest("/?output=json", url.Values{}), true},
+		{"POST without output", newPostRequest("/", url.Values{"T": {"token"}}), false},
+		{"POST with output=atom", newPostRequest("/", url.Values{"output": {"atom"}}), false},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			err := checkOutputFormat(scenario.request)
+			if scenario.valid && err != nil {
+				t.Errorf(`Unexpected error: %v`, err)
+			}
+			if !scenario.valid && err == nil {
+				t.Error(`Expected an error`)
+			}
+		})
+	}
+}

+ 56 - 0
internal/googlereader/middleware_test.go

@@ -35,3 +35,59 @@ func TestAuthMiddlewareRejectsTokenWithEmptyUsername(t *testing.T) {
 		}
 	}
 }
+
+func TestAuthMiddlewareRejectsMalformedCredentials(t *testing.T) {
+	newGetRequest := func(target, authorization string) *http.Request {
+		r := httptest.NewRequest(http.MethodGet, target, nil)
+		if authorization != "" {
+			r.Header.Set("Authorization", authorization)
+		}
+		return r
+	}
+
+	newPostRequest := func(body, authorization string) *http.Request {
+		r := httptest.NewRequest(http.MethodPost, "/reader/api/0/edit-tag", strings.NewReader(body))
+		r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+		if authorization != "" {
+			r.Header.Set("Authorization", authorization)
+		}
+		return r
+	}
+
+	scenarios := []struct {
+		name    string
+		request *http.Request
+	}{
+		{"GET without Authorization header", newGetRequest("/reader/api/0/user-info", "")},
+		{"GET with the token in the query string", newGetRequest("/reader/api/0/user-info?T=reader/abc", "")},
+		{"GET with a scheme only", newGetRequest("/reader/api/0/user-info", "GoogleLogin")},
+		{"GET with another scheme", newGetRequest("/reader/api/0/user-info", "Bearer auth=reader/abc")},
+		{"GET with a capitalized auth field", newGetRequest("/reader/api/0/user-info", "GoogleLogin Auth=reader/abc")},
+		{"GET without an auth value", newGetRequest("/reader/api/0/user-info", "GoogleLogin auth")},
+		{"GET with several equal signs", newGetRequest("/reader/api/0/user-info", "GoogleLogin auth=reader/abc=")},
+		{"GET with an extra field", newGetRequest("/reader/api/0/user-info", "GoogleLogin auth=reader/abc extra")},
+		{"GET with a token without a slash", newGetRequest("/reader/api/0/user-info", "GoogleLogin auth=readerabc")},
+		{"GET with a token with several slashes", newGetRequest("/reader/api/0/user-info", "GoogleLogin auth=reader/abc/def")},
+		{"GET with a token without a username", newGetRequest("/reader/api/0/user-info", "GoogleLogin auth=/abc")},
+		{"POST without a T field", newPostRequest(url.Values{"i": {"1"}}.Encode(), "")},
+		{"POST with the token in the Authorization header", newPostRequest("", "GoogleLogin auth=reader/abc")},
+		{"POST with an empty T field", newPostRequest("T=", "")},
+		{"POST with a token without a slash", newPostRequest("T=readerabc", "")},
+		{"POST with a token without a username", newPostRequest("T=%2Fabc", "")},
+		{"POST with an invalid form body", newPostRequest("T=%zz", "")},
+	}
+
+	// The store is nil: every request must be rejected before the store is queried.
+	middleware := newAuthMiddleware(nil)
+	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		t.Fatal("next handler should not be called")
+	})
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			recorder := httptest.NewRecorder()
+			middleware.validateApiKey(next).ServeHTTP(recorder, scenario.request)
+			checkUnauthorizedResponse(t, recorder)
+		})
+	}
+}

+ 116 - 0
internal/googlereader/request_modifier_test.go

@@ -0,0 +1,116 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package googlereader // import "miniflux.app/v2/internal/googlereader"
+
+import (
+	"context"
+	"net/http"
+	"net/http/httptest"
+	"reflect"
+	"testing"
+
+	"miniflux.app/v2/internal/http/request"
+)
+
+func newStreamFilterRequest(query string) *http.Request {
+	r := httptest.NewRequest(http.MethodGet, "/reader/api/0/stream/items/ids?"+query, nil)
+	return r.WithContext(context.WithValue(r.Context(), request.UserIDContextKey, int64(42)))
+}
+
+func TestParseStreamFilterFromRequest(t *testing.T) {
+	scenarios := []struct {
+		name     string
+		query    string
+		expected requestModifiers
+	}{
+		{
+			name:     "defaults",
+			query:    "",
+			expected: requestModifiers{UserID: 42, SortDirection: "desc", Streams: []Stream{}, ExcludeTargets: []Stream{}, FilterTargets: []Stream{}},
+		},
+		{
+			name:     "oldest first",
+			query:    "r=o",
+			expected: requestModifiers{UserID: 42, SortDirection: "asc", Streams: []Stream{}, ExcludeTargets: []Stream{}, FilterTargets: []Stream{}},
+		},
+		{
+			name:     "unknown sort order falls back to newest first",
+			query:    "r=x",
+			expected: requestModifiers{UserID: 42, SortDirection: "desc", Streams: []Stream{}, ExcludeTargets: []Stream{}, FilterTargets: []Stream{}},
+		},
+		{
+			name:  "streams and targets",
+			query: "s=user/-/state/com.google/reading-list&xt=user/-/state/com.google/read&xt=user/42/state/com.google/starred&it=user/-/label/Tech",
+			expected: requestModifiers{
+				UserID:         42,
+				SortDirection:  "desc",
+				Streams:        []Stream{{ReadingListStream, ""}},
+				ExcludeTargets: []Stream{{ReadStream, ""}, {StarredStream, ""}},
+				FilterTargets:  []Stream{{LabelStream, "Tech"}},
+			},
+		},
+		{
+			name:  "blank stream values are ignored",
+			query: "s=+&s=feed/12&xt=",
+			expected: requestModifiers{
+				UserID:         42,
+				SortDirection:  "desc",
+				Streams:        []Stream{{FeedStream, "12"}},
+				ExcludeTargets: []Stream{},
+				FilterTargets:  []Stream{},
+			},
+		},
+		{
+			name:  "numeric parameters",
+			query: "n=50&c=100&ot=1700000000&nt=1800000000",
+			expected: requestModifiers{
+				UserID:         42,
+				SortDirection:  "desc",
+				Count:          50,
+				Offset:         100,
+				StartTime:      1700000000,
+				StopTime:       1800000000,
+				Streams:        []Stream{},
+				ExcludeTargets: []Stream{},
+				FilterTargets:  []Stream{},
+			},
+		},
+		{
+			// The 10000 cap is applied by the entry query builder, not here.
+			name:     "count above the maximum is kept as is",
+			query:    "n=20000",
+			expected: requestModifiers{UserID: 42, SortDirection: "desc", Count: 20000, Streams: []Stream{}, ExcludeTargets: []Stream{}, FilterTargets: []Stream{}},
+		},
+		{
+			name:     "invalid and negative numbers fall back to zero",
+			query:    "n=abc&c=-1&ot=yesterday&nt=-5",
+			expected: requestModifiers{UserID: 42, SortDirection: "desc", Streams: []Stream{}, ExcludeTargets: []Stream{}, FilterTargets: []Stream{}},
+		},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			result, err := parseStreamFilterFromRequest(newStreamFilterRequest(scenario.query))
+			if err != nil {
+				t.Fatalf(`Unexpected error: %v`, err)
+			}
+			if !reflect.DeepEqual(result, scenario.expected) {
+				t.Errorf("Unexpected modifiers\ngot:  %#v\nwant: %#v", result, scenario.expected)
+			}
+		})
+	}
+}
+
+func TestParseStreamFilterFromRequestRejectsInvalidStreams(t *testing.T) {
+	for _, query := range []string{
+		"s=invalid",
+		"xt=invalid",
+		"it=invalid",
+		"s=user/-/state/com.google/unknown",
+	} {
+		if result, err := parseStreamFilterFromRequest(newStreamFilterRequest(query)); err == nil {
+			t.Errorf(`Expected an error for query %q, got %v`, query, result)
+		}
+	}
+}

+ 43 - 0
internal/googlereader/response_test.go

@@ -0,0 +1,43 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package googlereader // import "miniflux.app/v2/internal/googlereader"
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"testing"
+)
+
+func TestLoginResponseString(t *testing.T) {
+	result := loginResponse{SID: "user/sid", LSID: "user/lsid", Auth: "user/auth"}.String()
+	expected := "SID=user/sid\nLSID=user/lsid\nAuth=user/auth\n"
+
+	if result != expected {
+		t.Errorf(`Unexpected login response, got %q instead of %q`, result, expected)
+	}
+}
+
+func TestSendUnauthorizedResponse(t *testing.T) {
+	recorder := httptest.NewRecorder()
+	sendUnauthorizedResponse(recorder, httptest.NewRequest(http.MethodGet, "/reader/api/0/user-info", nil))
+
+	checkUnauthorizedResponse(t, recorder)
+}
+
+func checkUnauthorizedResponse(t *testing.T, recorder *httptest.ResponseRecorder) {
+	t.Helper()
+
+	if recorder.Code != http.StatusUnauthorized {
+		t.Errorf(`Unexpected status code, got %d instead of %d`, recorder.Code, http.StatusUnauthorized)
+	}
+	if value := recorder.Header().Get("X-Reader-Google-Bad-Token"); value != "true" {
+		t.Errorf(`Unexpected X-Reader-Google-Bad-Token header, got %q`, value)
+	}
+	if value := recorder.Header().Get("Content-Type"); value != "text/plain; charset=utf-8" {
+		t.Errorf(`Unexpected Content-Type header, got %q`, value)
+	}
+	if body := recorder.Body.String(); body != "Unauthorized" {
+		t.Errorf(`Unexpected body, got %q`, body)
+	}
+}

+ 85 - 1
internal/googlereader/stream_test.go

@@ -3,7 +3,10 @@
 
 package googlereader // import "miniflux.app/v2/internal/googlereader"
 
-import "testing"
+import (
+	"slices"
+	"testing"
+)
 
 func TestStreamTypeString(t *testing.T) {
 	scenarios := map[StreamType]string{
@@ -20,3 +23,84 @@ func TestStreamTypeString(t *testing.T) {
 		}
 	}
 }
+
+func TestGetStream(t *testing.T) {
+	const userID = int64(42)
+
+	scenarios := []struct {
+		streamID string
+		expected Stream
+	}{
+		{"", Stream{NoStream, ""}},
+		{"feed/123", Stream{FeedStream, "123"}},
+		{"feed/https://example.org/feed.xml", Stream{FeedStream, "https://example.org/feed.xml"}},
+		{"user/-/state/com.google/read", Stream{ReadStream, ""}},
+		{"user/-/state/com.google/starred", Stream{StarredStream, ""}},
+		{"user/-/state/com.google/reading-list", Stream{ReadingListStream, ""}},
+		{"user/-/state/com.google/kept-unread", Stream{KeptUnreadStream, ""}},
+		{"user/-/state/com.google/broadcast", Stream{BroadcastStream, ""}},
+		{"user/-/state/com.google/broadcast-friends", Stream{BroadcastFriendsStream, ""}},
+		{"user/-/state/com.google/like", Stream{LikeStream, ""}},
+		{"user/42/state/com.google/read", Stream{ReadStream, ""}},
+		{"user/42/state/com.google/reading-list", Stream{ReadingListStream, ""}},
+		{"user/-/label/Tech", Stream{LabelStream, "Tech"}},
+		{"user/42/label/Tech News", Stream{LabelStream, "Tech News"}},
+		{"user/-/label/", Stream{LabelStream, ""}},
+	}
+
+	for _, scenario := range scenarios {
+		result, err := getStream(scenario.streamID, userID)
+		if err != nil {
+			t.Errorf(`Unexpected error for stream %q: %v`, scenario.streamID, err)
+			continue
+		}
+		if result != scenario.expected {
+			t.Errorf(`Unexpected stream for %q, got %v instead of %v`, scenario.streamID, result, scenario.expected)
+		}
+	}
+}
+
+func TestGetStreamRejectsInvalidStreams(t *testing.T) {
+	const userID = int64(42)
+
+	for _, streamID := range []string{
+		"invalid",
+		"user/-/state/com.google/unknown",
+		"user/42/state/com.google/unknown",
+		// Another user's ID is not interchangeable with "-".
+		"user/7/state/com.google/read",
+		"user/7/label/Tech",
+	} {
+		if result, err := getStream(streamID, userID); err == nil {
+			t.Errorf(`Expected an error for stream %q, got %v`, streamID, result)
+		}
+	}
+}
+
+func TestGetStreams(t *testing.T) {
+	result, err := getStreams([]string{"feed/1", "user/-/label/Tech", "user/-/state/com.google/starred"}, 42)
+	if err != nil {
+		t.Fatalf(`Unexpected error: %v`, err)
+	}
+
+	expected := []Stream{{FeedStream, "1"}, {LabelStream, "Tech"}, {StarredStream, ""}}
+	if !slices.Equal(result, expected) {
+		t.Errorf(`Unexpected streams, got %v instead of %v`, result, expected)
+	}
+
+	result, err = getStreams(nil, 42)
+	if err != nil {
+		t.Fatalf(`Unexpected error: %v`, err)
+	}
+	if result == nil || len(result) != 0 {
+		t.Errorf(`Expected an empty non-nil slice, got %#v`, result)
+	}
+
+	result, err = getStreams([]string{"feed/1", "invalid"}, 42)
+	if err == nil {
+		t.Fatal(`Expected an error when one of the streams is invalid`)
+	}
+	if len(result) != 0 {
+		t.Errorf(`Expected no streams on error, got %v`, result)
+	}
+}