Просмотр исходного кода

test(googlereader): add integration tests for authentication

Run the Google Reader API tests against the in-process server. The test
users get their Google Reader credentials from the store, because no API
can set them.
Frédéric Guillot 10 часов назад
Родитель
Сommit
45a6055932

+ 1 - 0
Makefile

@@ -121,6 +121,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/api
+	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/googlereader
 
 clean-integration-test:
 	@ psql -U postgres -c 'drop database if exists miniflux_test;'

+ 216 - 0
internal/googlereader/auth_integration_test.go

@@ -0,0 +1,216 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package googlereader_test
+
+import (
+	"fmt"
+	"net/http"
+	"net/url"
+	"strconv"
+	"strings"
+	"testing"
+)
+
+func TestClientLogin(t *testing.T) {
+	t.Parallel()
+
+	user := newTestUser(t)
+	anonymous := &googleReaderClient{baseURL: requireTestServer(t).URL}
+	credentials := url.Values{"Email": {user.username}, "Passwd": {testGoogleReaderPassword}}
+
+	if !strings.HasPrefix(user.reader.token, user.username+"/") {
+		t.Errorf(`Expected the token to start with the username, got %q`, user.reader.token)
+	}
+
+	t.Run("json output", func(t *testing.T) {
+		var result loginResult
+		anonymous.postJSON(t, "/accounts/ClientLogin", credentials, &result)
+
+		expected := loginResult{SID: user.reader.token, LSID: user.reader.token, Auth: user.reader.token}
+		if result != expected {
+			t.Errorf(`Unexpected response, got %+v instead of %+v`, result, expected)
+		}
+	})
+
+	t.Run("text output", func(t *testing.T) {
+		status, body := anonymous.post(t, "/accounts/ClientLogin", credentials)
+		requireStatus(t, status, body, http.StatusOK)
+
+		expected := fmt.Sprintf("SID=%[1]s\nLSID=%[1]s\nAuth=%[1]s\n", user.reader.token)
+		if string(body) != expected {
+			t.Errorf(`Unexpected response, got %q instead of %q`, body, expected)
+		}
+	})
+}
+
+func TestClientLoginRejectsInvalidCredentials(t *testing.T) {
+	t.Parallel()
+
+	user := newTestUser(t)
+	disabledUser := newTestUser(t)
+	setGoogleReaderIntegration(t, disabledUser.id, false, testGoogleReaderPassword)
+
+	anonymous := &googleReaderClient{baseURL: requireTestServer(t).URL}
+
+	scenarios := []struct {
+		name     string
+		username string
+		password string
+	}{
+		{"wrong password", user.username, "wrong password"},
+		{"Miniflux password", user.username, testUserPassword},
+		{"unknown username", "unknown_googlereader_user", testGoogleReaderPassword},
+		{"empty username", "", testGoogleReaderPassword},
+		{"empty password", user.username, ""},
+		{"Google Reader disabled", disabledUser.username, testGoogleReaderPassword},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			status, body := anonymous.post(t, "/accounts/ClientLogin", url.Values{
+				"Email":  {scenario.username},
+				"Passwd": {scenario.password},
+				"output": {"json"},
+			})
+			requireStatus(t, status, body, http.StatusUnauthorized)
+		})
+	}
+}
+
+func TestAuthenticationRejectsInvalidTokens(t *testing.T) {
+	t.Parallel()
+
+	user := newTestUser(t)
+	otherUser := newTestUser(t)
+	baseURL := requireTestServer(t).URL
+
+	_, hash, _ := strings.Cut(user.reader.token, "/")
+	_, otherHash, _ := strings.Cut(otherUser.reader.token, "/")
+	tamperedToken := user.username + "/" + strings.Repeat("0", len(hash))
+
+	// Malformed credentials are covered by the middleware unit tests: these tokens are well-formed.
+	getScenarios := []struct {
+		name  string
+		token string
+	}{
+		{"tampered hash", tamperedToken},
+		{"hash of another user", user.username + "/" + otherHash},
+		{"unknown username", "unknown_googlereader_user/" + hash},
+	}
+
+	for _, scenario := range getScenarios {
+		t.Run("GET with "+scenario.name, func(t *testing.T) {
+			client := &googleReaderClient{baseURL: baseURL, token: scenario.token}
+			status, body := client.get(t, "/reader/api/0/user-info", url.Values{"output": {"json"}})
+			requireStatus(t, status, body, http.StatusUnauthorized)
+		})
+	}
+
+	// POST requests are authenticated by the T field only, the Authorization header is ignored.
+	postScenarios := []struct {
+		name          string
+		token         string
+		authorization string
+	}{
+		{"no T field but a valid Authorization header", "", "GoogleLogin auth=" + user.reader.token},
+		{"tampered T field", tamperedToken, ""},
+		{"T field of another user", user.username + "/" + otherHash, ""},
+	}
+
+	for _, scenario := range postScenarios {
+		t.Run("POST with "+scenario.name, func(t *testing.T) {
+			form := url.Values{"output": {"json"}}
+			if scenario.token != "" {
+				form.Set("T", scenario.token)
+			}
+
+			request, err := http.NewRequest(http.MethodPost, baseURL+"/reader/api/0/stream/items/contents", strings.NewReader(form.Encode()))
+			if err != nil {
+				t.Fatal(err)
+			}
+			request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+			if scenario.authorization != "" {
+				request.Header.Set("Authorization", scenario.authorization)
+			}
+
+			status, body := send(t, request)
+			requireStatus(t, status, body, http.StatusUnauthorized)
+		})
+	}
+}
+
+func TestTokenIsRevokedWhenGoogleReaderSettingsChange(t *testing.T) {
+	t.Parallel()
+
+	scenarios := []struct {
+		name     string
+		enabled  bool
+		password string
+	}{
+		{"password changed", true, "new_googlereader_password"},
+		{"integration disabled", false, testGoogleReaderPassword},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			t.Parallel()
+
+			user := newTestUser(t)
+			setGoogleReaderIntegration(t, user.id, scenario.enabled, scenario.password)
+
+			status, body := user.reader.get(t, "/reader/api/0/user-info", url.Values{"output": {"json"}})
+			requireStatus(t, status, body, http.StatusUnauthorized)
+		})
+	}
+}
+
+func TestTokenEndpoint(t *testing.T) {
+	t.Parallel()
+
+	user := newTestUser(t)
+
+	status, body := user.reader.get(t, "/reader/api/0/token", nil)
+	requireStatus(t, status, body, http.StatusOK)
+
+	if string(body) != user.reader.token {
+		t.Errorf(`Unexpected token, got %q instead of %q`, body, user.reader.token)
+	}
+}
+
+func TestUserInfoEndpoint(t *testing.T) {
+	t.Parallel()
+
+	user := newTestUser(t)
+
+	var result userInfoResult
+	user.reader.getJSON(t, "/reader/api/0/user-info", nil, &result)
+
+	userID := strconv.FormatInt(user.id, 10)
+	expected := userInfoResult{UserID: userID, UserName: user.username, UserProfileID: userID, UserEmail: user.username}
+	if result != expected {
+		t.Errorf(`Unexpected user info, got %+v instead of %+v`, result, expected)
+	}
+}
+
+func TestUnimplementedEndpointsReturnEmptyList(t *testing.T) {
+	t.Parallel()
+
+	user := newTestUser(t)
+	anonymous := &googleReaderClient{baseURL: requireTestServer(t).URL}
+
+	status, body := user.reader.get(t, "/reader/api/0/unread-count", nil)
+	requireStatus(t, status, body, http.StatusOK)
+	if strings.TrimSpace(string(body)) != "[]" {
+		t.Errorf(`Expected an empty list for GET, got %s`, body)
+	}
+
+	status, body = user.reader.post(t, "/reader/api/0/subscription/export", nil)
+	requireStatus(t, status, body, http.StatusOK)
+	if strings.TrimSpace(string(body)) != "[]" {
+		t.Errorf(`Expected an empty list for POST, got %s`, body)
+	}
+
+	status, body = anonymous.get(t, "/reader/api/0/unread-count", nil)
+	requireStatus(t, status, body, http.StatusUnauthorized)
+}

+ 129 - 0
internal/googlereader/integration_client_test.go

@@ -0,0 +1,129 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package googlereader_test
+
+import (
+	"encoding/json"
+	"io"
+	"net/http"
+	"net/url"
+	"strings"
+	"testing"
+)
+
+// googleReaderClient calls the Google Reader API. It sends no credentials when token is empty.
+type googleReaderClient struct {
+	baseURL string
+	token   string
+}
+
+// get sends a GET request with the token in the Authorization header.
+func (client *googleReaderClient) get(t *testing.T, path string, query url.Values) (int, []byte) {
+	t.Helper()
+
+	request, err := http.NewRequest(http.MethodGet, client.baseURL+path+"?"+query.Encode(), nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if client.token != "" {
+		request.Header.Set("Authorization", "GoogleLogin auth="+client.token)
+	}
+	return send(t, request)
+}
+
+// post sends a form with the token in the T field.
+func (client *googleReaderClient) post(t *testing.T, path string, form url.Values) (int, []byte) {
+	t.Helper()
+
+	values := url.Values{}
+	for key, list := range form {
+		values[key] = list
+	}
+	if client.token != "" {
+		values.Set("T", client.token)
+	}
+
+	request, err := http.NewRequest(http.MethodPost, client.baseURL+path, strings.NewReader(values.Encode()))
+	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 with output=json and decodes the successful response into result.
+func (client *googleReaderClient) getJSON(t *testing.T, path string, query url.Values, result any) {
+	t.Helper()
+
+	values := url.Values{"output": {"json"}}
+	for key, list := range query {
+		values[key] = list
+	}
+	status, body := client.get(t, path, values)
+	decodeJSON(t, status, body, result)
+}
+
+// postJSON sends a form with output=json and decodes the successful response into result.
+func (client *googleReaderClient) postJSON(t *testing.T, path string, form url.Values, result any) {
+	t.Helper()
+
+	values := url.Values{"output": {"json"}}
+	for key, list := range form {
+		values[key] = list
+	}
+	status, body := client.post(t, path, values)
+	decodeJSON(t, status, body, result)
+}
+
+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)
+	}
+}
+
+// requireStatus fails the test when the response status is not the expected one.
+func requireStatus(t *testing.T, status int, body []byte, expected int) {
+	t.Helper()
+
+	if status != expected {
+		t.Fatalf(`Expected status %d, got %d: %s`, expected, status, 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 loginResult struct {
+	SID  string `json:"SID"`
+	LSID string `json:"LSID"`
+	Auth string `json:"Auth"`
+}
+
+type userInfoResult struct {
+	UserID        string `json:"userId"`
+	UserName      string `json:"userName"`
+	UserProfileID string `json:"userProfileId"`
+	UserEmail     string `json:"userEmail"`
+}

+ 141 - 0
internal/googlereader/integration_server_test.go

@@ -0,0 +1,141 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package googlereader_test
+
+import (
+	"fmt"
+	"math/rand/v2"
+	"net/url"
+	"os"
+	"testing"
+
+	"miniflux.app/v2/internal/crypto"
+	"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 Google Reader API integration tests`
+
+	// testUserPassword is the Miniflux password of the test users.
+	testUserPassword = "miniflux_test_password"
+
+	// testGoogleReaderPassword is the Google Reader password of the test users, used by ClientLogin.
+	testGoogleReaderPassword = "googlereader_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 Google Reader API enabled.
+type testUser struct {
+	id       int64
+	username string
+
+	// reader calls the Google Reader API with the token returned by ClientLogin.
+	reader *googleReaderClient
+}
+
+// newTestUser creates a user with the Google Reader 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("googlereader_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)
+		}
+	})
+
+	setGoogleReaderIntegration(t, user.ID, true, testGoogleReaderPassword)
+
+	return &testUser{
+		id:       user.ID,
+		username: user.Username,
+		reader:   &googleReaderClient{baseURL: server.URL, token: clientLogin(t, user.Username, testGoogleReaderPassword)},
+	}
+}
+
+// setGoogleReaderIntegration changes the Google Reader settings of the user, using the Miniflux username.
+func setGoogleReaderIntegration(t *testing.T, userID int64, enabled bool, password 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)
+	}
+
+	passwordHash, err := crypto.HashPassword(password)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	integration.GoogleReaderEnabled = enabled
+	integration.GoogleReaderUsername = user.Username
+	integration.GoogleReaderPassword = passwordHash
+	if err := server.Store.UpdateIntegration(integration); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// clientLogin authenticates with ClientLogin and returns the auth token.
+func clientLogin(t *testing.T, username, password string) string {
+	t.Helper()
+
+	var result loginResult
+	anonymous := &googleReaderClient{baseURL: requireTestServer(t).URL}
+	anonymous.postJSON(t, "/accounts/ClientLogin", url.Values{
+		"Email":  {username},
+		"Passwd": {password},
+	}, &result)
+
+	if result.Auth == "" {
+		t.Fatalf(`ClientLogin returned an empty token: %+v`, result)
+	}
+	return result.Auth
+}