api_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package api // import "miniflux.app/v2/internal/api"
  4. import (
  5. "database/sql"
  6. "database/sql/driver"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/url"
  13. "reflect"
  14. "runtime"
  15. "slices"
  16. "strconv"
  17. "testing"
  18. "miniflux.app/v2/internal/config"
  19. "miniflux.app/v2/internal/storage"
  20. "miniflux.app/v2/internal/version"
  21. )
  22. func TestNewHandlerHandlesOptionsRequests(t *testing.T) {
  23. handler := NewHandler(nil, nil)
  24. r := httptest.NewRequest(http.MethodOptions, "/v1/users", nil)
  25. w := httptest.NewRecorder()
  26. handler.ServeHTTP(w, r)
  27. if got := w.Code; got != http.StatusNoContent {
  28. t.Fatalf(`Unexpected status code, got %d instead of %d`, got, http.StatusNoContent)
  29. }
  30. if got := w.Header().Get("Access-Control-Allow-Origin"); got != "*" {
  31. t.Fatalf(`Unexpected Access-Control-Allow-Origin header, got %q`, got)
  32. }
  33. if got := w.Header().Get("Access-Control-Allow-Methods"); got != "GET, POST, PUT, DELETE, OPTIONS" {
  34. t.Fatalf(`Unexpected Access-Control-Allow-Methods header, got %q`, got)
  35. }
  36. if got := w.Header().Get("Access-Control-Allow-Headers"); got != "X-Auth-Token, Authorization, Content-Type, Accept" {
  37. t.Fatalf(`Unexpected Access-Control-Allow-Headers header, got %q`, got)
  38. }
  39. if got := w.Header().Get("Access-Control-Max-Age"); got != "3600" {
  40. t.Fatalf(`Unexpected Access-Control-Max-Age header, got %q`, got)
  41. }
  42. }
  43. func TestVersionHandler(t *testing.T) {
  44. h := &handler{}
  45. r := httptest.NewRequest(http.MethodGet, "/v1/version", nil)
  46. w := httptest.NewRecorder()
  47. h.versionHandler(w, r)
  48. if got := w.Code; got != http.StatusOK {
  49. t.Fatalf(`Unexpected status code, got %d instead of %d`, got, http.StatusOK)
  50. }
  51. if got := w.Header().Get("Content-Type"); got != "application/json" {
  52. t.Fatalf(`Unexpected Content-Type header, got %q`, got)
  53. }
  54. var responseBody versionResponse
  55. if err := json.NewDecoder(w.Body).Decode(&responseBody); err != nil {
  56. t.Fatalf("Unexpected JSON decoding error: %v", err)
  57. }
  58. if responseBody.Version != version.Version {
  59. t.Fatalf(`Unexpected version, got %q instead of %q`, responseBody.Version, version.Version)
  60. }
  61. if responseBody.Commit != version.Commit {
  62. t.Fatalf(`Unexpected commit, got %q instead of %q`, responseBody.Commit, version.Commit)
  63. }
  64. if responseBody.BuildDate != version.BuildDate {
  65. t.Fatalf(`Unexpected build date, got %q instead of %q`, responseBody.BuildDate, version.BuildDate)
  66. }
  67. if responseBody.GoVersion != runtime.Version() {
  68. t.Fatalf(`Unexpected Go version, got %q instead of %q`, responseBody.GoVersion, runtime.Version())
  69. }
  70. if responseBody.Compiler != runtime.Compiler {
  71. t.Fatalf(`Unexpected compiler, got %q instead of %q`, responseBody.Compiler, runtime.Compiler)
  72. }
  73. if responseBody.Arch != runtime.GOARCH {
  74. t.Fatalf(`Unexpected architecture, got %q instead of %q`, responseBody.Arch, runtime.GOARCH)
  75. }
  76. if responseBody.OS != runtime.GOOS {
  77. t.Fatalf(`Unexpected OS, got %q instead of %q`, responseBody.OS, runtime.GOOS)
  78. }
  79. }
  80. func TestGetEntryIDsHandlerRequiresAuthentication(t *testing.T) {
  81. handler := NewHandler(nil, nil)
  82. for _, query := range []string{"", "?starred=maybe", "?status=invalid"} {
  83. t.Run(query, func(t *testing.T) {
  84. r := httptest.NewRequest(http.MethodGet, "/v1/entries/ids"+query, nil)
  85. w := httptest.NewRecorder()
  86. handler.ServeHTTP(w, r)
  87. if got := w.Code; got != http.StatusUnauthorized {
  88. t.Fatalf(`Unexpected status code, got %d instead of %d`, got, http.StatusUnauthorized)
  89. }
  90. })
  91. }
  92. }
  93. func TestValidateEntryIDsFilters(t *testing.T) {
  94. for _, query := range []string{
  95. "", "status=read&status=unread&status=read", "tags=one&tags=two",
  96. "starred=false&globally_visible=true&order=category_title&direction=desc",
  97. "feed_id=1&category_id=1&before_entry_id=1&after_entry_id=1",
  98. "before=0&after=0&published_before=0&published_after=0&changed_before=0&changed_after=0",
  99. "before_entry_id=9223372036854775807&after_entry_id=9223372036854775807",
  100. "limit=invalid&offset=-1", // Legacy pagination parsing remains independent.
  101. } {
  102. t.Run("valid/"+query, func(t *testing.T) {
  103. r := httptest.NewRequest(http.MethodGet, "/v1/entries/ids?"+query, nil)
  104. if err := validateEntryIDsFilters(r); err != nil {
  105. t.Fatal(err)
  106. }
  107. if _, err := parseEntryFilters(r, 0, 0); err != nil {
  108. t.Fatal(err)
  109. }
  110. })
  111. }
  112. for _, name := range []string{
  113. "feed_id", "category_id", "before_entry_id", "after_entry_id",
  114. "before", "after", "published_before", "published_after", "changed_before", "changed_after",
  115. } {
  116. for _, value := range []string{"", "invalid", "-1", "1.5", "9223372036854775808"} {
  117. t.Run("invalid/"+name+"/"+value, func(t *testing.T) {
  118. r := httptest.NewRequest(http.MethodGet, "/v1/entries/ids?"+url.Values{name: {value}}.Encode(), nil)
  119. if err := validateEntryIDsFilters(r); err == nil {
  120. t.Fatal("Expected invalid numeric parameter to be rejected")
  121. }
  122. })
  123. }
  124. }
  125. }
  126. func TestValidateEntryIDsFiltersRejectsZeroIDs(t *testing.T) {
  127. for _, name := range []string{"feed_id", "category_id", "before_entry_id", "after_entry_id"} {
  128. t.Run(name, func(t *testing.T) {
  129. r := httptest.NewRequest(http.MethodGet, "/v1/entries/ids?"+name+"=0", nil)
  130. if err := validateEntryIDsFilters(r); err == nil {
  131. t.Fatal("Expected an explicit zero ID to be rejected")
  132. }
  133. })
  134. }
  135. }
  136. func TestValidateEntryIDsFiltersRejectsMalformedQueryStrings(t *testing.T) {
  137. for _, query := range []string{
  138. "feed_id=%zz", "status=unread;status=read",
  139. } {
  140. t.Run(query, func(t *testing.T) {
  141. r := httptest.NewRequest(http.MethodGet, "/v1/entries/ids?"+query, nil)
  142. if err := validateEntryIDsFilters(r); err == nil {
  143. t.Fatal("Expected malformed query parameters to be rejected")
  144. }
  145. })
  146. }
  147. }
  148. func TestParseEntryFiltersRejectsValuesPostgreSQLCannotAccept(t *testing.T) {
  149. queries := []string{"search=%00", "search=%ff", "tags=%00", "tags=%ff", "tags=one&tags=%ff"}
  150. for _, name := range []string{"before", "after", "published_before", "published_after", "changed_before", "changed_after"} {
  151. queries = append(queries, name+"=9223372036854775807", name+"="+strconv.FormatInt(maxEntryFilterTimestamp, 10))
  152. }
  153. for _, query := range queries {
  154. t.Run(query, func(t *testing.T) {
  155. r := httptest.NewRequest(http.MethodGet, "/v1/entries?"+query, nil)
  156. if _, err := parseEntryFilters(r, 0, 0); err == nil {
  157. t.Fatal("Expected the value to be rejected")
  158. }
  159. })
  160. }
  161. r := httptest.NewRequest(http.MethodGet, "/v1/entries?before="+strconv.FormatInt(maxEntryFilterTimestamp-1, 10)+"&search=caf%C3%A9", nil)
  162. if _, err := parseEntryFilters(r, 0, 0); err != nil {
  163. t.Fatalf("Expected the last valid timestamp and UTF-8 search text to be accepted: %v", err)
  164. }
  165. }
  166. func TestParseEntryFiltersPreservesEndpointCompatibility(t *testing.T) {
  167. for _, test := range []struct {
  168. routeFeedID int64
  169. routeCategoryID int64
  170. query string
  171. feedID int64
  172. categoryID int64
  173. starred *bool
  174. globallyVisible bool
  175. }{
  176. {query: "feed_id=12&category_id=20", feedID: 12, categoryID: 20},
  177. {query: "feed_id=invalid&category_id=-1"},
  178. {query: "feed_id=0&category_id=0"},
  179. // Route IDs scope the endpoint: the query string cannot replace or clear them.
  180. {routeFeedID: 11, query: "", feedID: 11},
  181. {routeFeedID: 11, query: "feed_id=12", feedID: 11},
  182. {routeFeedID: 11, query: "feed_id=0", feedID: 11},
  183. {routeFeedID: 11, query: "category_id=20", feedID: 11, categoryID: 20},
  184. {routeCategoryID: 10, query: "category_id=20", categoryID: 10},
  185. {routeCategoryID: 10, query: "category_id=0", categoryID: 10},
  186. {routeCategoryID: 10, query: "feed_id=12", feedID: 12, categoryID: 10},
  187. {routeFeedID: 11, query: "feed_id=&category_id=", feedID: 11},
  188. // The route's own ID always wins, so an invalid query value for it is ignored.
  189. {routeFeedID: 11, query: "feed_id=-1", feedID: 11},
  190. {routeFeedID: 11, query: "feed_id=invalid", feedID: 11},
  191. {routeCategoryID: 10, query: "category_id=-1", categoryID: 10},
  192. {routeCategoryID: 10, query: "category_id=invalid", categoryID: 10},
  193. {query: "starred=1", starred: new(true)},
  194. {query: "starred=0", starred: new(false)},
  195. {query: "starred=invalid"},
  196. {query: "globally_visible=invalid", globallyVisible: true},
  197. {query: "globally_visible=false"},
  198. } {
  199. t.Run(fmt.Sprintf("feed=%d/category=%d/%s", test.routeFeedID, test.routeCategoryID, test.query), func(t *testing.T) {
  200. r := httptest.NewRequest(http.MethodGet, "/v1/entries?"+test.query, nil)
  201. filters, err := parseEntryFilters(r, test.routeFeedID, test.routeCategoryID)
  202. if err != nil {
  203. t.Fatal(err)
  204. }
  205. if filters.feedID != test.feedID || filters.categoryID != test.categoryID || filters.globallyVisible != test.globallyVisible {
  206. t.Fatalf("Unexpected filters: %+v", filters)
  207. }
  208. if !reflect.DeepEqual(filters.starred, test.starred) {
  209. t.Fatalf("Unexpected starred filter: %v", filters.starred)
  210. }
  211. })
  212. }
  213. r := httptest.NewRequest(http.MethodGet, "/v1/entries?status=read&status=unread&status=read&tags=one&tags=two", nil)
  214. filters, err := parseEntryFilters(r, 0, 0)
  215. if err != nil {
  216. t.Fatal(err)
  217. }
  218. if !slices.Equal(filters.statuses, []string{"read", "unread", "read"}) || !slices.Equal(filters.tags, []string{"one", "two"}) {
  219. t.Fatalf("Unexpected list filters: %+v", filters)
  220. }
  221. }
  222. func TestParseEntryFiltersRejectsInvalidRouteScopedQueryIDs(t *testing.T) {
  223. for _, route := range []struct {
  224. name string
  225. feedID, categoryID int64
  226. param string
  227. }{
  228. {"feed", 11, 0, "category_id"},
  229. {"category", 0, 10, "feed_id"},
  230. } {
  231. for _, query := range []string{
  232. route.param + "=-1",
  233. route.param + "=invalid",
  234. route.param + "=9223372036854775808",
  235. route.param + "=%zz",
  236. route.param + "=-1;",
  237. route.param + "=&" + route.param + "=-1",
  238. route.param + "=1&" + route.param + "=invalid",
  239. } {
  240. t.Run(route.name+"/"+query, func(t *testing.T) {
  241. r := httptest.NewRequest(http.MethodGet, "/v1/entries?"+query, nil)
  242. if _, err := parseEntryFilters(r, route.feedID, route.categoryID); err == nil {
  243. t.Fatal("Expected invalid scope query ID to be rejected")
  244. }
  245. })
  246. }
  247. }
  248. }
  249. // failingDriver is a database/sql driver whose connections always fail, so a handler
  250. // that reaches the store returns an error instead of crashing on a nil store.
  251. type failingDriver struct{}
  252. func (failingDriver) Open(string) (driver.Conn, error) {
  253. return nil, errors.New("no database in unit tests")
  254. }
  255. func init() {
  256. sql.Register("api-unit-test-failing", failingDriver{})
  257. }
  258. func newFailingStoreHandler(t *testing.T) *handler {
  259. t.Helper()
  260. db, err := sql.Open("api-unit-test-failing", "")
  261. if err != nil {
  262. t.Fatal(err)
  263. }
  264. t.Cleanup(func() { db.Close() })
  265. return &handler{store: storage.NewStorage(db)}
  266. }
  267. func TestRouteScopedEntryHandlersRejectInvalidScopeQueryIDs(t *testing.T) {
  268. tests := []struct {
  269. name string
  270. path string
  271. pathValues map[string]string
  272. handle func(*handler, http.ResponseWriter, *http.Request)
  273. }{
  274. {
  275. name: "feed route",
  276. path: "/v1/feeds/11/entries?category_id=-1",
  277. pathValues: map[string]string{"feedID": "11"},
  278. handle: (*handler).getFeedEntriesHandler,
  279. },
  280. {
  281. name: "category route",
  282. path: "/v1/categories/10/entries?feed_id=invalid",
  283. pathValues: map[string]string{"categoryID": "10"},
  284. handle: (*handler).getCategoryEntriesHandler,
  285. },
  286. }
  287. for _, test := range tests {
  288. t.Run(test.name, func(t *testing.T) {
  289. r := httptest.NewRequest(http.MethodGet, test.path, nil)
  290. for name, value := range test.pathValues {
  291. r.SetPathValue(name, value)
  292. }
  293. w := httptest.NewRecorder()
  294. test.handle(newFailingStoreHandler(t), w, r)
  295. if w.Code != http.StatusBadRequest {
  296. t.Fatalf("Unexpected status code: got %d, want %d", w.Code, http.StatusBadRequest)
  297. }
  298. })
  299. }
  300. }
  301. func TestParseEntryIDsParamsDefaults(t *testing.T) {
  302. r := httptest.NewRequest(http.MethodGet, "/v1/entries/ids", nil)
  303. limit, offset := parseEntryIDsParams(r)
  304. if limit != 10000 {
  305. t.Fatalf(`Expected default limit 10000, got %d`, limit)
  306. }
  307. if offset != 0 {
  308. t.Fatalf(`Expected default offset 0, got %d`, offset)
  309. }
  310. }
  311. func TestParseEntryIDsParamsCustomValues(t *testing.T) {
  312. r := httptest.NewRequest(http.MethodGet, "/v1/entries/ids?limit=500&offset=100", nil)
  313. limit, offset := parseEntryIDsParams(r)
  314. if limit != 500 {
  315. t.Fatalf(`Expected limit 500, got %d`, limit)
  316. }
  317. if offset != 100 {
  318. t.Fatalf(`Expected offset 100, got %d`, offset)
  319. }
  320. }
  321. func TestParseEntryIDsParamsLimitCappedAtMaximum(t *testing.T) {
  322. r := httptest.NewRequest(http.MethodGet, "/v1/entries/ids?limit=99999", nil)
  323. limit, _ := parseEntryIDsParams(r)
  324. if limit != 10000 {
  325. t.Fatalf(`Expected limit capped at 10000, got %d`, limit)
  326. }
  327. }
  328. func TestParseEntryIDsParamsZeroLimitUsesDefault(t *testing.T) {
  329. r := httptest.NewRequest(http.MethodGet, "/v1/entries/ids?limit=0", nil)
  330. limit, _ := parseEntryIDsParams(r)
  331. if limit != 10000 {
  332. t.Fatalf(`Expected zero limit to use default 10000, got %d`, limit)
  333. }
  334. }
  335. func TestNewHandlerSupportsBasePathStripping(t *testing.T) {
  336. scenarios := []struct {
  337. name string
  338. prefix string
  339. path string
  340. }{
  341. {name: "empty base path", prefix: "", path: "/v1/users"},
  342. {name: "non empty base path", prefix: "/base", path: "/base/v1/users"},
  343. }
  344. for _, scenario := range scenarios {
  345. t.Run(scenario.name, func(t *testing.T) {
  346. handler := http.StripPrefix(scenario.prefix, NewHandler(nil, nil))
  347. r := httptest.NewRequest(http.MethodOptions, scenario.path, nil)
  348. w := httptest.NewRecorder()
  349. handler.ServeHTTP(w, r)
  350. if got := w.Code; got != http.StatusNoContent {
  351. t.Fatalf(`Unexpected status code, got %d instead of %d`, got, http.StatusNoContent)
  352. }
  353. })
  354. }
  355. }
  356. func TestBasicAuthIsRejectedWhenLocalAuthDisabled(t *testing.T) {
  357. t.Setenv("DISABLE_LOCAL_AUTH", "1")
  358. t.Setenv("OAUTH2_PROVIDER", "oidc")
  359. t.Setenv("OAUTH2_CLIENT_ID", "client")
  360. t.Setenv("OAUTH2_CLIENT_SECRET", "secret")
  361. t.Setenv("OAUTH2_REDIRECT_URL", "https://example.org/oauth2/oidc/callback")
  362. t.Setenv("OAUTH2_OIDC_DISCOVERY_ENDPOINT", "https://example.org")
  363. parsedOptions, err := config.NewConfigParser().ParseEnvironmentVariables()
  364. if err != nil {
  365. t.Fatalf("Unable to configure test options: %v", err)
  366. }
  367. previousOptions := config.Opts
  368. config.Opts = parsedOptions
  369. t.Cleanup(func() {
  370. config.Opts = previousOptions
  371. })
  372. handler := NewHandler(nil, nil)
  373. r := httptest.NewRequest(http.MethodGet, "/v1/me", nil)
  374. r.SetBasicAuth("admin", "password")
  375. w := httptest.NewRecorder()
  376. handler.ServeHTTP(w, r)
  377. if got := w.Code; got != http.StatusUnauthorized {
  378. t.Fatalf(`Unexpected status code, got %d instead of %d`, got, http.StatusUnauthorized)
  379. }
  380. }