auth_integration_test.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package googlereader_test
  4. import (
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "testing"
  11. "time"
  12. "miniflux.app/v2/internal/http/server/servertest"
  13. )
  14. func TestClientLogin(t *testing.T) {
  15. t.Parallel()
  16. user := newTestUser(t)
  17. anonymous := &googleReaderClient{baseURL: servertest.Require(t).URL}
  18. credentials := url.Values{"Email": {user.username}, "Passwd": {testGoogleReaderPassword}}
  19. if !strings.HasPrefix(user.reader.token, user.username+"/") {
  20. t.Errorf(`Expected the token to start with the username, got %q`, user.reader.token)
  21. }
  22. t.Run("json output", func(t *testing.T) {
  23. var result loginResult
  24. anonymous.postJSON(t, "/accounts/ClientLogin", credentials, &result)
  25. expected := loginResult{SID: user.reader.token, LSID: user.reader.token, Auth: user.reader.token}
  26. if result != expected {
  27. t.Errorf(`Unexpected response, got %+v instead of %+v`, result, expected)
  28. }
  29. })
  30. t.Run("text output", func(t *testing.T) {
  31. status, body := anonymous.post(t, "/accounts/ClientLogin", credentials)
  32. requireStatus(t, status, body, http.StatusOK)
  33. expected := fmt.Sprintf("SID=%[1]s\nLSID=%[1]s\nAuth=%[1]s\n", user.reader.token)
  34. if string(body) != expected {
  35. t.Errorf(`Unexpected response, got %q instead of %q`, body, expected)
  36. }
  37. })
  38. }
  39. func TestClientLoginRejectsInvalidCredentials(t *testing.T) {
  40. t.Parallel()
  41. user := newTestUser(t)
  42. disabledUser := newTestUser(t)
  43. setGoogleReaderIntegration(t, disabledUser.id, false, testGoogleReaderPassword)
  44. anonymous := &googleReaderClient{baseURL: servertest.Require(t).URL}
  45. scenarios := []struct {
  46. name string
  47. username string
  48. password string
  49. }{
  50. {"wrong password", user.username, "wrong password"},
  51. {"Miniflux password", user.username, testUserPassword},
  52. {"unknown username", "unknown_googlereader_user", testGoogleReaderPassword},
  53. {"empty username", "", testGoogleReaderPassword},
  54. {"empty password", user.username, ""},
  55. {"Google Reader disabled", disabledUser.username, testGoogleReaderPassword},
  56. }
  57. for _, scenario := range scenarios {
  58. t.Run(scenario.name, func(t *testing.T) {
  59. status, body := anonymous.post(t, "/accounts/ClientLogin", url.Values{
  60. "Email": {scenario.username},
  61. "Passwd": {scenario.password},
  62. "output": {"json"},
  63. })
  64. requireStatus(t, status, body, http.StatusUnauthorized)
  65. })
  66. }
  67. }
  68. // ClientLogin must take as long for usernames that cannot log in as for a wrong password, or the response time reveals which usernames exist.
  69. func TestClientLoginTakesAsLongForUnknownUsernames(t *testing.T) {
  70. // Not parallel: Go runs sequential tests while the parallel ones are paused, so no other ClientLogin skews the measurements.
  71. user := newTestUser(t)
  72. disabledUser := newTestUser(t)
  73. setGoogleReaderIntegration(t, disabledUser.id, false, testGoogleReaderPassword)
  74. anonymous := &googleReaderClient{baseURL: servertest.Require(t).URL}
  75. // The first scenario is the baseline: the username exists, so the password is compared with its bcrypt hash.
  76. scenarios := []struct {
  77. name string
  78. username string
  79. }{
  80. {"wrong password", user.username},
  81. {"unknown username", "unknown_googlereader_user"},
  82. {"Google Reader disabled", disabledUser.username},
  83. }
  84. // Interleave the scenarios so that load on the machine affects them all alike, and keep the fastest attempt because noise only adds time.
  85. fastest := make([]time.Duration, len(scenarios))
  86. for attempt := range 5 {
  87. for index, scenario := range scenarios {
  88. start := time.Now()
  89. status, body := anonymous.post(t, "/accounts/ClientLogin", url.Values{
  90. "Email": {scenario.username},
  91. "Passwd": {"wrong password"},
  92. "output": {"json"},
  93. })
  94. elapsed := time.Since(start)
  95. requireStatus(t, status, body, http.StatusUnauthorized)
  96. if attempt == 0 || elapsed < fastest[index] {
  97. fastest[index] = elapsed
  98. }
  99. }
  100. }
  101. baseline := fastest[0]
  102. for index, scenario := range scenarios[1:] {
  103. if elapsed := fastest[index+1]; elapsed < baseline/2 {
  104. t.Errorf(`ClientLogin with %s took %v, much less than the %v it took with a wrong password: the response time reveals whether the username exists`,
  105. scenario.name, elapsed, baseline)
  106. }
  107. }
  108. }
  109. func TestAuthenticationRejectsInvalidTokens(t *testing.T) {
  110. t.Parallel()
  111. user := newTestUser(t)
  112. otherUser := newTestUser(t)
  113. baseURL := servertest.Require(t).URL
  114. _, hash, _ := strings.Cut(user.reader.token, "/")
  115. _, otherHash, _ := strings.Cut(otherUser.reader.token, "/")
  116. tamperedToken := user.username + "/" + strings.Repeat("0", len(hash))
  117. // Malformed credentials are covered by the middleware unit tests: these tokens are well-formed.
  118. getScenarios := []struct {
  119. name string
  120. token string
  121. }{
  122. {"tampered hash", tamperedToken},
  123. {"hash of another user", user.username + "/" + otherHash},
  124. {"unknown username", "unknown_googlereader_user/" + hash},
  125. }
  126. for _, scenario := range getScenarios {
  127. t.Run("GET with "+scenario.name, func(t *testing.T) {
  128. client := &googleReaderClient{baseURL: baseURL, token: scenario.token}
  129. status, body := client.get(t, "/reader/api/0/user-info", url.Values{"output": {"json"}})
  130. requireStatus(t, status, body, http.StatusUnauthorized)
  131. })
  132. }
  133. // POST requests are authenticated by the T field only, the Authorization header is ignored.
  134. postScenarios := []struct {
  135. name string
  136. token string
  137. authorization string
  138. }{
  139. {"no T field but a valid Authorization header", "", "GoogleLogin auth=" + user.reader.token},
  140. {"tampered T field", tamperedToken, ""},
  141. {"T field of another user", user.username + "/" + otherHash, ""},
  142. }
  143. for _, scenario := range postScenarios {
  144. t.Run("POST with "+scenario.name, func(t *testing.T) {
  145. form := url.Values{"output": {"json"}}
  146. if scenario.token != "" {
  147. form.Set("T", scenario.token)
  148. }
  149. request, err := http.NewRequest(http.MethodPost, baseURL+"/reader/api/0/stream/items/contents", strings.NewReader(form.Encode()))
  150. if err != nil {
  151. t.Fatal(err)
  152. }
  153. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  154. if scenario.authorization != "" {
  155. request.Header.Set("Authorization", scenario.authorization)
  156. }
  157. status, body := servertest.Send(t, request)
  158. requireStatus(t, status, body, http.StatusUnauthorized)
  159. })
  160. }
  161. }
  162. func TestTokenIsRevokedWhenGoogleReaderSettingsChange(t *testing.T) {
  163. t.Parallel()
  164. scenarios := []struct {
  165. name string
  166. enabled bool
  167. password string
  168. }{
  169. {"password changed", true, "new_googlereader_password"},
  170. {"integration disabled", false, testGoogleReaderPassword},
  171. }
  172. for _, scenario := range scenarios {
  173. t.Run(scenario.name, func(t *testing.T) {
  174. t.Parallel()
  175. user := newTestUser(t)
  176. setGoogleReaderIntegration(t, user.id, scenario.enabled, scenario.password)
  177. status, body := user.reader.get(t, "/reader/api/0/user-info", url.Values{"output": {"json"}})
  178. requireStatus(t, status, body, http.StatusUnauthorized)
  179. })
  180. }
  181. }
  182. func TestTokenEndpoint(t *testing.T) {
  183. t.Parallel()
  184. user := newTestUser(t)
  185. status, body := user.reader.get(t, "/reader/api/0/token", nil)
  186. requireStatus(t, status, body, http.StatusOK)
  187. if string(body) != user.reader.token {
  188. t.Errorf(`Unexpected token, got %q instead of %q`, body, user.reader.token)
  189. }
  190. }
  191. func TestUserInfoEndpoint(t *testing.T) {
  192. t.Parallel()
  193. user := newTestUser(t)
  194. var result userInfoResult
  195. user.reader.getJSON(t, "/reader/api/0/user-info", nil, &result)
  196. userID := strconv.FormatInt(user.id, 10)
  197. expected := userInfoResult{UserID: userID, UserName: user.username, UserProfileID: userID, UserEmail: user.username}
  198. if result != expected {
  199. t.Errorf(`Unexpected user info, got %+v instead of %+v`, result, expected)
  200. }
  201. }
  202. func TestUnimplementedEndpointsReturnEmptyList(t *testing.T) {
  203. t.Parallel()
  204. user := newTestUser(t)
  205. anonymous := &googleReaderClient{baseURL: servertest.Require(t).URL}
  206. status, body := user.reader.get(t, "/reader/api/0/unread-count", nil)
  207. requireStatus(t, status, body, http.StatusOK)
  208. if strings.TrimSpace(string(body)) != "[]" {
  209. t.Errorf(`Expected an empty list for GET, got %s`, body)
  210. }
  211. status, body = user.reader.post(t, "/reader/api/0/subscription/export", nil)
  212. requireStatus(t, status, body, http.StatusOK)
  213. if strings.TrimSpace(string(body)) != "[]" {
  214. t.Errorf(`Expected an empty list for POST, got %s`, body)
  215. }
  216. status, body = anonymous.get(t, "/reader/api/0/unread-count", nil)
  217. requireStatus(t, status, body, http.StatusUnauthorized)
  218. }