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

fix(googlereader): reject auth tokens when no password is set

An empty stored password makes the token computable from the username
alone. Also require both fields when enabling the integration.
Frédéric Guillot 2 месяцев назад
Родитель
Сommit
589659ffc5
29 измененных файлов с 140 добавлено и 3 удалено
  1. 1 1
      internal/googlereader/middleware.go
  2. 37 0
      internal/googlereader/middleware_test.go
  3. 1 0
      internal/locale/translations/ar_SA.json
  4. 1 0
      internal/locale/translations/de_DE.json
  5. 1 0
      internal/locale/translations/el_EL.json
  6. 1 0
      internal/locale/translations/en_US.json
  7. 1 0
      internal/locale/translations/es_ES.json
  8. 1 0
      internal/locale/translations/fi_FI.json
  9. 1 0
      internal/locale/translations/fr_FR.json
  10. 1 0
      internal/locale/translations/gl_ES.json
  11. 1 0
      internal/locale/translations/hi_IN.json
  12. 1 0
      internal/locale/translations/id_ID.json
  13. 1 0
      internal/locale/translations/it_IT.json
  14. 1 0
      internal/locale/translations/ja_JP.json
  15. 1 0
      internal/locale/translations/ko_KR.json
  16. 1 0
      internal/locale/translations/nan_Latn_pehoeji.json
  17. 1 0
      internal/locale/translations/nl_NL.json
  18. 1 0
      internal/locale/translations/pl_PL.json
  19. 1 0
      internal/locale/translations/pt_BR.json
  20. 1 0
      internal/locale/translations/ro_RO.json
  21. 1 0
      internal/locale/translations/ru_RU.json
  22. 1 0
      internal/locale/translations/tr_TR.json
  23. 1 0
      internal/locale/translations/uk_UA.json
  24. 1 0
      internal/locale/translations/zh_CN.json
  25. 1 0
      internal/locale/translations/zh_TW.json
  26. 2 2
      internal/storage/integration.go
  27. 12 0
      internal/ui/form/integration.go
  28. 59 0
      internal/ui/form/integration_test.go
  29. 6 0
      internal/ui/integration_update.go

+ 1 - 1
internal/googlereader/middleware.go

@@ -112,7 +112,7 @@ func (m *authMiddleware) serveValidated(w http.ResponseWriter, r *http.Request,
 	}
 
 	parts := strings.Split(token, "/")
-	if len(parts) != 2 {
+	if len(parts) != 2 || parts[0] == "" {
 		slog.Warn("[GoogleReader] Auth token does not have the expected structure username/hash",
 			slog.Bool("authentication_failed", true),
 			slog.String("client_ip", clientIP),

+ 37 - 0
internal/googlereader/middleware_test.go

@@ -0,0 +1,37 @@
+// 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"
+	"net/url"
+	"strings"
+	"testing"
+)
+
+func TestAuthMiddlewareRejectsTokenWithEmptyUsername(t *testing.T) {
+	token := getAuthToken("", "")
+
+	getRequest := httptest.NewRequest(http.MethodGet, "/reader/api/0/user-info", nil)
+	getRequest.Header.Set("Authorization", "GoogleLogin auth="+token)
+
+	postRequest := httptest.NewRequest(http.MethodPost, "/reader/api/0/edit-tag", strings.NewReader(url.Values{"T": {token}}.Encode()))
+	postRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+	// The store is nil: the middleware must reject the token before querying it.
+	middleware := newAuthMiddleware(nil)
+	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		t.Fatal("next handler should not be called")
+	})
+
+	for _, request := range []*http.Request{getRequest, postRequest} {
+		recorder := httptest.NewRecorder()
+		middleware.validateApiKey(next).ServeHTTP(recorder, request)
+
+		if recorder.Code != http.StatusUnauthorized {
+			t.Errorf("%s: expected status %d, got %d", request.Method, http.StatusUnauthorized, recorder.Code)
+		}
+	}
+}

+ 1 - 0
internal/locale/translations/ar_SA.json

@@ -103,6 +103,7 @@
     "error.duplicate_fever_username": "يوجد بالفعل شخص آخر بنفس اسم مستخدم Fever!",
     "error.duplicate_googlereader_username": "يوجد بالفعل شخص آخر بنفس اسم مستخدم Google Reader!",
     "error.linktaco_missing_required_fields": "مطلوب رمز LinkTaco API و Organization Slug",
+    "error.googlereader_missing_required_fields": "مطلوب اسم مستخدم وكلمة مرور Google Reader",
     "error.duplicate_linked_account": "يوجد بالفعل شخص مرتبط بهذا الموفر!",
     "error.duplicated_feed": "هذا المصدر موجود بالفعل.",
     "error.empty_file": "هذا الملف فارغ.",

+ 1 - 0
internal/locale/translations/de_DE.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "Dieser Benutzer existiert bereits.",
     "error.user_mandatory_fields": "Der Benutzername ist obligatorisch.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token und Organization Slug sind erforderlich.",
+    "error.googlereader_missing_required_fields": "Google Reader Benutzername und Passwort sind erforderlich.",
     "form.api_key.label.description": "API-Schlüsselbezeichnung",
     "form.category.hide_globally": "Artikel in der globalen Ungelesen-Liste ausblenden",
     "form.category.label.title": "Titel",

+ 1 - 0
internal/locale/translations/el_EL.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "Αυτός ο χρήστης υπάρχει ήδη.",
     "error.user_mandatory_fields": "Το όνομα χρήστη είναι υποχρεωτικό.",
     "error.linktaco_missing_required_fields": "Το LinkTaco API Token και το Organization Slug είναι απαραίτητα",
+    "error.googlereader_missing_required_fields": "Το όνομα χρήστη και ο κωδικός πρόσβασης του Google Reader είναι απαραίτητα",
     "form.api_key.label.description": "Ετικέτα κλειδιού API",
     "form.category.hide_globally": "Απόκρυψη καταχωρήσεων σε γενική λίστα μη αναγνωσμένων",
     "form.category.label.title": "Τίτλος",

+ 1 - 0
internal/locale/translations/en_US.json

@@ -91,6 +91,7 @@
     "error.duplicate_fever_username": "There is already someone else with the same Fever username!",
     "error.duplicate_googlereader_username": "There is already someone else with the same Google Reader username!",
     "error.linktaco_missing_required_fields": "LinkTaco API Token and Organization Slug are required",
+    "error.googlereader_missing_required_fields": "Google Reader username and password are required",
     "error.duplicate_linked_account": "There is already someone associated with this provider!",
     "error.duplicated_feed": "This feed already exists.",
     "error.empty_file": "This file is empty.",

+ 1 - 0
internal/locale/translations/es_ES.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "Este usuario ya existe.",
     "error.user_mandatory_fields": "El nombre de usuario es obligatorio.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token y Organization Slug son obligatorios.",
+    "error.googlereader_missing_required_fields": "El nombre de usuario y la contraseña de Google Reader son obligatorios.",
     "form.api_key.label.description": "Etiqueta de clave API",
     "form.category.hide_globally": "Ocultar artículos en la lista global de no leídos",
     "form.category.label.title": "Título",

+ 1 - 0
internal/locale/translations/fi_FI.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "Käyttäjä on jo olemassa.",
     "error.user_mandatory_fields": "Käyttäjätunnus on pakollinen.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token ja Organization Slug vaaditaan",
+    "error.googlereader_missing_required_fields": "Google Reader -käyttäjätunnus ja -salasana vaaditaan",
     "form.api_key.label.description": "API-avaimen nimi",
     "form.category.hide_globally": "Piilota artikkelit lukemattomien listassa",
     "form.category.label.title": "Otsikko",

+ 1 - 0
internal/locale/translations/fr_FR.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "Cet utilisateur existe déjà.",
     "error.user_mandatory_fields": "Le nom d'utilisateur est obligatoire.",
     "error.linktaco_missing_required_fields": "Le token API LinkTaco et le slug de l'organisation sont requis.",
+    "error.googlereader_missing_required_fields": "Le nom d'utilisateur et le mot de passe Google Reader sont requis.",
     "form.api_key.label.description": "Libellé de la clé d'API",
     "form.category.hide_globally": "Masquer les entrées dans la liste globale non lue",
     "form.category.label.title": "Titre",

+ 1 - 0
internal/locale/translations/gl_ES.json

@@ -91,6 +91,7 @@
     "error.duplicate_fever_username": "Xa hai alguén con ese identificador en Fever!",
     "error.duplicate_googlereader_username": "Xa hai alguén con ese identificador en Google Reader!",
     "error.linktaco_missing_required_fields": "Requírese LinkTaco API Token e Organization Slug",
+    "error.googlereader_missing_required_fields": "Requírense o nome de usuario e o contrasinal de Google Reader",
     "error.duplicate_linked_account": "Xa hai alguén asociado con este provedor!",
     "error.duplicated_feed": "Xa existe a canle.",
     "error.empty_file": "O ficheiro está baleiro.",

+ 1 - 0
internal/locale/translations/hi_IN.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "यह उपयोगकर्ता पहले से ही मौजूद है।",
     "error.user_mandatory_fields": "उपयोगकर्ता नाम अनिवार्य है।",
     "error.linktaco_missing_required_fields": "LinkTaco API Token और Organization Slug आवश्यक हैं",
+    "error.googlereader_missing_required_fields": "Google Reader उपयोगकर्ता नाम और पासवर्ड आवश्यक हैं",
     "form.api_key.label.description": "एपीआई कुंजी लेबल",
     "form.category.hide_globally": "वैश्विक अपठित सूची में प्रविष्टियां छिपाएं",
     "form.category.label.title": "शीर्षक",

+ 1 - 0
internal/locale/translations/id_ID.json

@@ -160,6 +160,7 @@
     "error.user_already_exists": "Pengguna ini sudah ada.",
     "error.user_mandatory_fields": "Harus ada nama pengguna.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token dan Organization Slug diperlukan",
+    "error.googlereader_missing_required_fields": "Nama pengguna dan kata sandi Google Reader diperlukan",
     "form.api_key.label.description": "Label Kunci API",
     "form.category.hide_globally": "Sembunyikan entri di daftar belum dibaca global",
     "form.category.label.title": "Judul",

+ 1 - 0
internal/locale/translations/it_IT.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "Questo utente esiste già.",
     "error.user_mandatory_fields": "Il nome utente è obbligatorio.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token e Organization Slug sono richiesti",
+    "error.googlereader_missing_required_fields": "Nome utente e password di Google Reader sono richiesti",
     "form.api_key.label.description": "Etichetta chiave API",
     "form.category.hide_globally": "Nascondere le voci nella lista globale dei non letti",
     "form.category.label.title": "Titolo",

+ 1 - 0
internal/locale/translations/ja_JP.json

@@ -160,6 +160,7 @@
     "error.user_already_exists": "このユーザーは既に存在します。",
     "error.user_mandatory_fields": "ユーザー名が必要です。",
     "error.linktaco_missing_required_fields": "LinkTaco API TokenとOrganization Slugが必要です",
+    "error.googlereader_missing_required_fields": "Google Readerのユーザー名とパスワードが必要です",
     "form.api_key.label.description": "API キーラベル",
     "form.category.hide_globally": "未読一覧に記事を表示しない",
     "form.category.label.title": "タイトル",

+ 1 - 0
internal/locale/translations/ko_KR.json

@@ -160,6 +160,7 @@
     "error.user_already_exists": "이 사용자는 이미 존재합니다.",
     "error.user_mandatory_fields": "사용자명이 필요합니다.",
     "error.linktaco_missing_required_fields": "LinkTaco API 토큰과 조직 슬러그가 필요합니다",
+    "error.googlereader_missing_required_fields": "Google Reader 사용자 이름과 비밀번호가 필요합니다",
     "form.api_key.label.description": "API키 설명",
     "form.category.hide_globally": "읽지 않음 목록에 게시물을 표시하지 않음",
     "form.category.label.title": "제목",

+ 1 - 0
internal/locale/translations/nan_Latn_pehoeji.json

@@ -160,6 +160,7 @@
     "error.user_already_exists": "Chit ê sú-iōng-lâng í-keng chûn-chāi.",
     "error.user_mandatory_fields": "Tio̍h-ài su-li̍p kháu-chō miâ",
     "error.linktaco_missing_required_fields": "LinkTaco API Token kâh Organization Slug sio̍kêi",
+    "error.googlereader_missing_required_fields": "Google Reader ê sú-iōng-chiá miâ kah bi̍t-bé sī pit-iàu ê",
     "form.api_key.label.description": "API só-sîkhan-á",
     "form.category.hide_globally": "Mài hián-sī siau-sit tī choân-he̍k ah-bōe tha̍k lia̍t-pió lāi",
     "form.category.label.title": "Piau-tôe",

+ 1 - 0
internal/locale/translations/nl_NL.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "Deze gebruiker bestaat al.",
     "error.user_mandatory_fields": "Gebruikersnaam is verplicht",
     "error.linktaco_missing_required_fields": "LinkTaco API Token en Organization Slug zijn verplicht",
+    "error.googlereader_missing_required_fields": "Google Reader gebruikersnaam en wachtwoord zijn verplicht",
     "form.api_key.label.description": "API-sleutel omschrijving",
     "form.category.hide_globally": "Verberg artikelen in de globale ongelezen lijst",
     "form.category.label.title": "Titel",

+ 1 - 0
internal/locale/translations/pl_PL.json

@@ -166,6 +166,7 @@
     "error.user_already_exists": "Ten użytkownik już istnieje.",
     "error.user_mandatory_fields": "Nazwa użytkownika jest obowiązkowa.",
     "error.linktaco_missing_required_fields": "Token API LinkTaco i ślimak organizacji są wymagane",
+    "error.googlereader_missing_required_fields": "Nazwa użytkownika i hasło Google Reader są wymagane",
     "form.api_key.label.description": "Etykieta klucza API",
     "form.category.hide_globally": "Ukryj wpisy na globalnej liście nieprzeczytanych",
     "form.category.label.title": "Tytuł",

+ 1 - 0
internal/locale/translations/pt_BR.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "Esse usuário já existe.",
     "error.user_mandatory_fields": "O nome de usuário é obrigatório.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token e Organization Slug são obrigatórios",
+    "error.googlereader_missing_required_fields": "Nome de usuário e senha do Google Reader são obrigatórios",
     "form.api_key.label.description": "Etiqueta da chave de API",
     "form.category.hide_globally": "Ocultar entradas na lista global não lida",
     "form.category.label.title": "Título",

+ 1 - 0
internal/locale/translations/ro_RO.json

@@ -166,6 +166,7 @@
     "error.user_already_exists": "Acest utilizator există deja.",
     "error.user_mandatory_fields": "Numele utilizatorului este obligatoriu.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token și Organization Slug sunt necesare",
+    "error.googlereader_missing_required_fields": "Numele de utilizator și parola Google Reader sunt necesare",
     "form.api_key.label.description": "Etichetă Cheie API",
     "form.category.hide_globally": "Ascunde intrările în lista globală de articole necitite",
     "form.category.label.title": "Titlu",

+ 1 - 0
internal/locale/translations/ru_RU.json

@@ -166,6 +166,7 @@
     "error.user_already_exists": "Этот пользователь уже существует.",
     "error.user_mandatory_fields": "Имя пользователя обязательно.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token и Organization Slug обязательны",
+    "error.googlereader_missing_required_fields": "Имя пользователя и пароль Google Reader обязательны",
     "form.api_key.label.description": "Описание API-ключа",
     "form.category.hide_globally": "Скрыть записи в глобальном списке непрочитанных",
     "form.category.label.title": "Название",

+ 1 - 0
internal/locale/translations/tr_TR.json

@@ -163,6 +163,7 @@
     "error.user_already_exists": "Bu kullanıcı zaten mevcut.",
     "error.user_mandatory_fields": "Kullanıcı adı zorunlu.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token ve Organization Slug gereklidir",
+    "error.googlereader_missing_required_fields": "Google Reader kullanıcı adı ve parolası gereklidir",
     "form.api_key.label.description": "API Anahtar Etiketi",
     "form.category.hide_globally": "Genel okunmamış listesindeki girişleri gizle",
     "form.category.label.title": "Başlık",

+ 1 - 0
internal/locale/translations/uk_UA.json

@@ -166,6 +166,7 @@
     "error.user_already_exists": "Такий користувач вже існує.",
     "error.user_mandatory_fields": "Ім'я користувача є обов'язковим.",
     "error.linktaco_missing_required_fields": "LinkTaco API Token і Organization Slug є обов'язковими",
+    "error.googlereader_missing_required_fields": "Ім'я користувача та пароль Google Reader є обов'язковими",
     "form.api_key.label.description": "Назва ключа API",
     "form.category.hide_globally": "Приховати записи в глобальному списку непрочитаного",
     "form.category.label.title": "Назва",

+ 1 - 0
internal/locale/translations/zh_CN.json

@@ -160,6 +160,7 @@
     "error.user_already_exists": "此用户已存在。",
     "error.user_mandatory_fields": "必须填写用户名。",
     "error.linktaco_missing_required_fields": "LinkTaco API Token 和 Organization Slug 是必需的",
+    "error.googlereader_missing_required_fields": "Google Reader 用户名和密码是必需的",
     "form.api_key.label.description": "API 密钥标签",
     "form.category.hide_globally": "在全局未读列表中隐藏条目",
     "form.category.label.title": "标题",

+ 1 - 0
internal/locale/translations/zh_TW.json

@@ -160,6 +160,7 @@
     "error.user_already_exists": "使用者已存在",
     "error.user_mandatory_fields": "必須填寫使用者名稱",
     "error.linktaco_missing_required_fields": "LinkTaco API 權杖和 Organization Slug 是必需的",
+    "error.googlereader_missing_required_fields": "Google Reader 使用者名稱和密碼是必需的",
     "form.api_key.label.description": "API 金鑰標籤",
     "form.category.hide_globally": "在全域未讀清單中隱藏文章",
     "form.category.label.title": "標題",

+ 2 - 2
internal/storage/integration.go

@@ -63,7 +63,7 @@ func (s *Storage) GoogleReaderUserCheckPassword(username, password string) error
 		FROM
 			integrations
 		WHERE
-			integrations.googlereader_enabled='t' AND integrations.googlereader_username=$1
+			integrations.googlereader_enabled='t' AND integrations.googlereader_username=$1 AND integrations.googlereader_password <> ''
 	`
 
 	err := s.db.QueryRow(query, username).Scan(&hash)
@@ -93,7 +93,7 @@ func (s *Storage) GoogleReaderUserGetIntegration(username string) (*model.Integr
 		FROM
 			integrations
 		WHERE
-			integrations.googlereader_enabled='t' AND integrations.googlereader_username=$1
+			integrations.googlereader_enabled='t' AND integrations.googlereader_username=$1 AND integrations.googlereader_password <> ''
 	`
 
 	err := s.db.QueryRow(query, username).Scan(&integration.UserID, &integration.GoogleReaderEnabled, &integration.GoogleReaderUsername, &integration.GoogleReaderPassword)

+ 12 - 0
internal/ui/form/integration.go

@@ -7,6 +7,7 @@ import (
 	"net/http"
 	"strconv"
 
+	"miniflux.app/v2/internal/locale"
 	"miniflux.app/v2/internal/model"
 )
 
@@ -257,6 +258,17 @@ func (i IntegrationForm) Merge(integration *model.Integration) {
 	integration.ArchiveorgEnabled = i.ArchiveorgEnabled
 }
 
+// ValidateGoogleReader ensures the Google Reader integration is not enabled without credentials.
+func (i IntegrationForm) ValidateGoogleReader(storedPasswordHash string) *locale.LocalizedError {
+	if !i.GoogleReaderEnabled {
+		return nil
+	}
+	if i.GoogleReaderUsername == "" || (i.GoogleReaderPassword == "" && storedPasswordHash == "") {
+		return locale.NewLocalizedError("error.googlereader_missing_required_fields")
+	}
+	return nil
+}
+
 // NewIntegrationForm returns a new IntegrationForm.
 func NewIntegrationForm(r *http.Request) *IntegrationForm {
 	return &IntegrationForm{

+ 59 - 0
internal/ui/form/integration_test.go

@@ -0,0 +1,59 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package form // import "miniflux.app/v2/internal/ui/form"
+
+import (
+	"testing"
+)
+
+func TestValidateGoogleReader(t *testing.T) {
+	scenarios := []struct {
+		name               string
+		form               IntegrationForm
+		storedPasswordHash string
+		expectError        bool
+	}{
+		{
+			name: "disabled without credentials",
+			form: IntegrationForm{},
+		},
+		{
+			name: "enabled with username and new password",
+			form: IntegrationForm{GoogleReaderEnabled: true, GoogleReaderUsername: "user", GoogleReaderPassword: "secret"},
+		},
+		{
+			name:               "enabled with username and stored password",
+			form:               IntegrationForm{GoogleReaderEnabled: true, GoogleReaderUsername: "user"},
+			storedPasswordHash: "$2a$10$hash",
+		},
+		{
+			name:        "enabled without password",
+			form:        IntegrationForm{GoogleReaderEnabled: true, GoogleReaderUsername: "user"},
+			expectError: true,
+		},
+		{
+			name:               "enabled without username",
+			form:               IntegrationForm{GoogleReaderEnabled: true, GoogleReaderPassword: "secret"},
+			storedPasswordHash: "$2a$10$hash",
+			expectError:        true,
+		},
+		{
+			name:        "enabled without username and password",
+			form:        IntegrationForm{GoogleReaderEnabled: true},
+			expectError: true,
+		},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			validationErr := scenario.form.ValidateGoogleReader(scenario.storedPasswordHash)
+			if scenario.expectError && validationErr == nil {
+				t.Fatal("expected a validation error")
+			}
+			if !scenario.expectError && validationErr != nil {
+				t.Fatalf("unexpected validation error: %v", validationErr)
+			}
+		})
+	}
+}

+ 6 - 0
internal/ui/integration_update.go

@@ -43,6 +43,12 @@ func (h *handler) updateIntegration(w http.ResponseWriter, r *http.Request) {
 		integration.FeverToken = ""
 	}
 
+	if validationErr := integrationForm.ValidateGoogleReader(integration.GoogleReaderPassword); validationErr != nil {
+		sess.SetErrorMessage(validationErr.Translate(sess.Language()))
+		response.HTMLRedirect(w, r, h.routePath("/integrations"))
+		return
+	}
+
 	if integration.GoogleReaderUsername != "" && h.store.HasDuplicateGoogleReaderUsername(userID, integration.GoogleReaderUsername) {
 		sess.SetErrorMessage(printer.Print("error.duplicate_googlereader_username"))
 		response.HTMLRedirect(w, r, h.routePath("/integrations"))