Explorar o código

test(fever): add integration tests for authentication

Run the Fever API tests against the in-process server. The test users
get their Fever API key from the store, because no API can set it.
Fred hai 9 horas
pai
achega
4bf59aada3

+ 1 - 0
Makefile

@@ -122,6 +122,7 @@ integration-test: miniflux
 	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/storage
 	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/storage
 	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/api
 	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/api
 	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/googlereader
 	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/googlereader
+	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/fever
 
 
 clean-integration-test:
 clean-integration-test:
 	@ psql -U postgres -c 'drop database if exists miniflux_test;'
 	@ psql -U postgres -c 'drop database if exists miniflux_test;'

+ 122 - 0
internal/fever/auth_integration_test.go

@@ -0,0 +1,122 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package fever_test
+
+import (
+	"encoding/json"
+	"net/url"
+	"strconv"
+	"strings"
+	"testing"
+	"time"
+
+	miniflux "miniflux.app/v2/client"
+)
+
+func TestAuthentication(t *testing.T) {
+	t.Parallel()
+
+	user := newTestUser(t)
+
+	t.Run("API key in the query string", func(t *testing.T) {
+		before := time.Now().Unix()
+		var result baseResult
+		user.fever.getJSON(t, nil, &result)
+		after := time.Now().Unix()
+
+		// Miniflux reports the time of the response, not the time of the last feed refresh.
+		if result.LastRefreshedOnTime < before || result.LastRefreshedOnTime > after {
+			t.Errorf(`Expected last_refreshed_on_time between %d and %d, got %d`, before, after, result.LastRefreshedOnTime)
+		}
+	})
+
+	t.Run("API key in the form body", func(t *testing.T) {
+		var result baseResult
+		user.fever.postJSON(t, nil, &result)
+	})
+
+	t.Run("API key in uppercase", func(t *testing.T) {
+		client := &feverClient{baseURL: requireTestServer(t).URL, apiKey: strings.ToUpper(user.fever.apiKey)}
+
+		var result baseResult
+		client.getJSON(t, nil, &result)
+	})
+
+	t.Run("selector without a value", func(t *testing.T) {
+		status, body := user.fever.getRawQuery(t, "groups&api_key="+user.fever.apiKey)
+
+		var result map[string]json.RawMessage
+		decodeAuthenticatedJSON(t, status, body, &result)
+		if _, found := result["groups"]; !found {
+			t.Errorf(`Expected the groups member, got %s`, body)
+		}
+	})
+}
+
+func TestAuthenticationRejectsInvalidAPIKeys(t *testing.T) {
+	t.Parallel()
+
+	user := newTestUser(t)
+	disabledUser := newTestUser(t)
+	disabledAPIKey := setFeverIntegration(t, disabledUser.id, false, testFeverPassword)
+
+	// The anonymous client sends the API key of each scenario as is.
+	anonymous := &feverClient{baseURL: requireTestServer(t).URL}
+
+	scenarios := []struct {
+		name   string
+		params url.Values
+	}{
+		{"no API key", nil},
+		{"an empty API key", url.Values{"api_key": {""}}},
+		{"the key of a wrong password", url.Values{"api_key": {feverAPIKey(user.username, "wrong password")}}},
+		{"the key of the Miniflux password", url.Values{"api_key": {feverAPIKey(user.username, testUserPassword)}}},
+		{"the key of an unknown username", url.Values{"api_key": {feverAPIKey("unknown_fever_user", testFeverPassword)}}},
+		{"the key of a user with Fever disabled", url.Values{"api_key": {disabledAPIKey}}},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run("GET with "+scenario.name, func(t *testing.T) {
+			status, body := anonymous.get(t, scenario.params)
+			requireAuthFailure(t, status, body)
+		})
+
+		t.Run("POST with "+scenario.name, func(t *testing.T) {
+			status, body := anonymous.post(t, scenario.params)
+			requireAuthFailure(t, status, body)
+		})
+	}
+}
+
+func TestRejectedRequestsDoNotChangeEntries(t *testing.T) {
+	t.Parallel()
+
+	user := newTestUser(t)
+	_, entries := subscribeToFixture(t, user)
+	entryID := entries[0].ID
+	markAsRead := url.Values{"mark": {"item"}, "as": {"read"}, "id": {strconv.FormatInt(entryID, 10)}}
+
+	intruder := &feverClient{baseURL: requireTestServer(t).URL, apiKey: feverAPIKey(user.username, "wrong password")}
+	status, body := intruder.post(t, markAsRead)
+	requireAuthFailure(t, status, body)
+	requireEntryStatus(t, user, entryID, miniflux.EntryStatusUnread)
+
+	// The same request with the right API key changes the entry, so the rejection above is what kept it unread.
+	var result baseResult
+	user.fever.postJSON(t, markAsRead, &result)
+	requireEntryStatus(t, user, entryID, miniflux.EntryStatusRead)
+}
+
+// requireEntryStatus fails the test unless the REST API reports the expected status for the entry.
+func requireEntryStatus(t *testing.T, user *testUser, entryID int64, expected string) {
+	t.Helper()
+
+	entry, err := user.rest.Entry(entryID)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if entry.Status != expected {
+		t.Fatalf(`Expected entry %d to be %q, got %q`, entryID, expected, entry.Status)
+	}
+}

+ 152 - 0
internal/fever/integration_client_test.go

@@ -0,0 +1,152 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package fever_test
+
+import (
+	"encoding/json"
+	"io"
+	"net/http"
+	"net/url"
+	"strings"
+	"testing"
+)
+
+// feverAPIVersion is the API version that every Fever response reports.
+const feverAPIVersion = 3
+
+// feverClient calls the Fever API. It sends no API key when apiKey is empty.
+//
+// Like Fever clients, it always calls the endpoint with the api parameter, which has no value.
+type feverClient struct {
+	baseURL string
+	apiKey  string
+}
+
+// get sends a GET request with the API key and the parameters in the query string.
+func (client *feverClient) get(t *testing.T, query url.Values) (int, []byte) {
+	t.Helper()
+
+	return client.getRawQuery(t, client.withAPIKey(query).Encode())
+}
+
+// getRawQuery sends a GET request with the given query string, without adding the API key.
+// It sends selectors without a value, such as "groups" rather than "groups=", as Fever clients do.
+func (client *feverClient) getRawQuery(t *testing.T, rawQuery string) (int, []byte) {
+	t.Helper()
+
+	request, err := http.NewRequest(http.MethodGet, client.endpoint(rawQuery), nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return send(t, request)
+}
+
+// post sends a form with the API key and the parameters in the request body.
+func (client *feverClient) post(t *testing.T, form url.Values) (int, []byte) {
+	t.Helper()
+
+	body := strings.NewReader(client.withAPIKey(form).Encode())
+	request, err := http.NewRequest(http.MethodPost, client.endpoint(""), body)
+	if err != nil {
+		t.Fatal(err)
+	}
+	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+	return send(t, request)
+}
+
+// getJSON sends a GET request and decodes the authenticated response into result.
+func (client *feverClient) getJSON(t *testing.T, query url.Values, result any) {
+	t.Helper()
+
+	status, body := client.get(t, query)
+	decodeAuthenticatedJSON(t, status, body, result)
+}
+
+// postJSON sends a form and decodes the authenticated response into result.
+func (client *feverClient) postJSON(t *testing.T, form url.Values, result any) {
+	t.Helper()
+
+	status, body := client.post(t, form)
+	decodeAuthenticatedJSON(t, status, body, result)
+}
+
+func (client *feverClient) endpoint(rawQuery string) string {
+	if rawQuery == "" {
+		return client.baseURL + "/fever/?api"
+	}
+	return client.baseURL + "/fever/?api&" + rawQuery
+}
+
+// withAPIKey returns a copy of the parameters with the API key of the client, when it has one.
+func (client *feverClient) withAPIKey(params url.Values) url.Values {
+	values := url.Values{}
+	for key, list := range params {
+		values[key] = list
+	}
+	if client.apiKey != "" {
+		values.Set("api_key", client.apiKey)
+	}
+	return values
+}
+
+func send(t *testing.T, request *http.Request) (int, []byte) {
+	t.Helper()
+
+	response, err := http.DefaultClient.Do(request)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer response.Body.Close()
+
+	body, err := io.ReadAll(response.Body)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return response.StatusCode, body
+}
+
+func decodeJSON(t *testing.T, status int, body []byte, result any) {
+	t.Helper()
+
+	if status != http.StatusOK {
+		t.Fatalf(`Expected status 200, got %d: %s`, status, body)
+	}
+	if err := json.Unmarshal(body, result); err != nil {
+		t.Fatalf(`Unable to decode %s: %v`, body, err)
+	}
+}
+
+// decodeAuthenticatedJSON decodes a successful response into result, and fails the test
+// unless the response reports the Fever API version and a successful authentication.
+func decodeAuthenticatedJSON(t *testing.T, status int, body []byte, result any) {
+	t.Helper()
+
+	var base baseResult
+	decodeJSON(t, status, body, &base)
+	if base.APIVersion != feverAPIVersion || base.Auth != 1 {
+		t.Fatalf(`Expected an authenticated response for API version %d, got %s`, feverAPIVersion, body)
+	}
+	decodeJSON(t, status, body, result)
+}
+
+// requireAuthFailure fails the test unless the response is the Fever authentication failure:
+// HTTP 200, because Fever clients only look at the auth member, with auth set to 0.
+func requireAuthFailure(t *testing.T, status int, body []byte) {
+	t.Helper()
+
+	var result baseResult
+	decodeJSON(t, status, body, &result)
+	if result.APIVersion != feverAPIVersion || result.Auth != 0 {
+		t.Fatalf(`Expected an authentication failure for API version %d, got %s`, feverAPIVersion, body)
+	}
+}
+
+// The response types below mirror the JSON documents sent to clients. They are not the
+// package's own types, so renaming a JSON field fails the tests as it would break clients.
+
+type baseResult struct {
+	APIVersion          int   `json:"api_version"`
+	Auth                int   `json:"auth"`
+	LastRefreshedOnTime int64 `json:"last_refreshed_on_time"`
+}

+ 156 - 0
internal/fever/integration_server_test.go

@@ -0,0 +1,156 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package fever_test
+
+import (
+	"crypto/md5"
+	"encoding/hex"
+	"fmt"
+	"math/rand/v2"
+	"os"
+	"testing"
+
+	miniflux "miniflux.app/v2/client"
+	"miniflux.app/v2/internal/http/server/servertest"
+	"miniflux.app/v2/internal/model"
+)
+
+const (
+	skipIntegrationTestsMessage = `Set TEST_DATABASE_URL to a PostgreSQL database to run the Fever API integration tests`
+
+	// testUserPassword is the Miniflux password of the test users, used by the REST API.
+	testUserPassword = "miniflux_test_password"
+
+	// testFeverPassword is the Fever password of the test users, hashed into their API key.
+	testFeverPassword = "fever_test_password"
+)
+
+// testServer is the Miniflux server started by TestMain, or nil when TEST_DATABASE_URL is not set.
+var testServer *servertest.Server
+
+func TestMain(m *testing.M) {
+	os.Exit(runTests(m))
+}
+
+func runTests(m *testing.M) int {
+	databaseURL := os.Getenv("TEST_DATABASE_URL")
+	if databaseURL == "" {
+		return m.Run()
+	}
+
+	server, err := servertest.NewServer(databaseURL)
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Unable to start the integration test server: %v\n", err)
+		return 1
+	}
+	defer server.Close()
+
+	testServer = server
+	return m.Run()
+}
+
+// requireTestServer returns the integration test server, or skips the test when TEST_DATABASE_URL is not set.
+func requireTestServer(t *testing.T) *servertest.Server {
+	t.Helper()
+
+	if testServer == nil {
+		t.Skip(skipIntegrationTestsMessage)
+	}
+	return testServer
+}
+
+// testUser is a Miniflux user with the Fever API enabled.
+type testUser struct {
+	id       int64
+	username string
+
+	// fever calls the Fever API with the API key of the user.
+	fever *feverClient
+
+	// rest calls the REST API, to set up data and to check changes independently.
+	rest *miniflux.Client
+}
+
+// newTestUser creates a user with the Fever API enabled that is removed when the test ends.
+func newTestUser(t *testing.T) *testUser {
+	t.Helper()
+
+	server := requireTestServer(t)
+	user, err := server.Store.CreateUser(&model.UserCreationRequest{
+		Username: fmt.Sprintf("fever_test_user_%d", rand.Int()),
+		Password: testUserPassword,
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() {
+		if err := server.Store.RemoveUser(user.ID); err != nil {
+			t.Errorf(`Unable to remove user %d: %v`, user.ID, err)
+		}
+	})
+
+	apiKey := setFeverIntegration(t, user.ID, true, testFeverPassword)
+
+	return &testUser{
+		id:       user.ID,
+		username: user.Username,
+		fever:    &feverClient{baseURL: server.URL, apiKey: apiKey},
+		rest:     miniflux.NewClient(server.URL, user.Username, testUserPassword),
+	}
+}
+
+// setFeverIntegration changes the Fever settings of the user, using the Miniflux username,
+// and returns the API key. No API can change these settings, so they are written to the store.
+func setFeverIntegration(t *testing.T, userID int64, enabled bool, password string) string {
+	t.Helper()
+
+	server := requireTestServer(t)
+	integration, err := server.Store.Integration(userID)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	user, err := server.Store.UserByID(userID)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	apiKey := feverAPIKey(user.Username, password)
+	integration.FeverEnabled = enabled
+	integration.FeverUsername = user.Username
+	integration.FeverToken = apiKey
+	if err := server.Store.UpdateIntegration(integration); err != nil {
+		t.Fatal(err)
+	}
+	return apiKey
+}
+
+// feverAPIKey returns the API key that Fever clients send: the MD5 hash of "username:password",
+// which is also the token that the integrations page stores.
+func feverAPIKey(username, password string) string {
+	sum := md5.Sum([]byte(username + ":" + password))
+	return hex.EncodeToString(sum[:])
+}
+
+// subscribeToFixture subscribes the user to a new fixture feed and returns the feed ID with its entries.
+func subscribeToFixture(t *testing.T, user *testUser) (int64, miniflux.Entries) {
+	t.Helper()
+
+	feedID := servertest.NewFeedFixture(t).Subscribe(t, user.rest)
+	return feedID, feedEntries(t, user, feedID)
+}
+
+// feedEntries returns the entries of the feed oldest first: entry 1 is published on 2025-01-01, entry 3 on 2025-01-03.
+func feedEntries(t *testing.T, user *testUser, feedID int64) miniflux.Entries {
+	t.Helper()
+
+	result, err := user.rest.FeedEntries(feedID, &miniflux.Filter{Order: "published_at", Direction: "asc"})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(result.Entries) != servertest.EntryCount {
+		t.Fatalf(`Expected %d entries, got %d`, servertest.EntryCount, len(result.Entries))
+	}
+	return result.Entries
+}

+ 55 - 0
internal/fever/middleware_test.go

@@ -0,0 +1,55 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package fever // import "miniflux.app/v2/internal/fever"
+
+import (
+	"encoding/json"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+)
+
+func TestMiddlewareRejectsMissingAPIKey(t *testing.T) {
+	newPostRequest := func(body string) *http.Request {
+		r := httptest.NewRequest(http.MethodPost, "/fever/?api", strings.NewReader(body))
+		r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+		return r
+	}
+
+	scenarios := []struct {
+		name    string
+		request *http.Request
+	}{
+		{"GET without api_key", httptest.NewRequest(http.MethodGet, "/fever/?api&groups", nil)},
+		{"GET with an empty api_key", httptest.NewRequest(http.MethodGet, "/fever/?api&groups&api_key=", nil)},
+		{"POST without api_key", newPostRequest("mark=item&as=read&id=1")},
+		{"POST with an empty api_key", newPostRequest("api_key=&mark=item&as=read&id=1")},
+	}
+
+	// The store is nil: every request must be rejected before the store is queried.
+	middleware := Middleware(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(next).ServeHTTP(recorder, scenario.request)
+
+			if recorder.Code != http.StatusOK {
+				t.Fatalf(`Expected status %d, got %d`, http.StatusOK, recorder.Code)
+			}
+
+			var result baseResponse
+			if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
+				t.Fatalf(`Unable to decode %s: %v`, recorder.Body.Bytes(), err)
+			}
+			if result.Version != 3 || result.Authenticated != 0 {
+				t.Errorf(`Expected an authentication failure for API version 3, got %s`, recorder.Body.Bytes())
+			}
+		})
+	}
+}