entry_query_integration_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package api
  4. import (
  5. "cmp"
  6. "database/sql"
  7. "encoding/json"
  8. "net/http"
  9. "net/http/httptest"
  10. "net/url"
  11. "os"
  12. "slices"
  13. "strconv"
  14. "strings"
  15. "testing"
  16. "golang.org/x/crypto/bcrypt"
  17. "miniflux.app/v2/internal/config"
  18. "miniflux.app/v2/internal/storage"
  19. )
  20. func newEntryQueryAPI(t *testing.T) (http.Handler, *sql.DB) {
  21. t.Helper()
  22. databaseURL := os.Getenv("TEST_DATABASE_URL")
  23. if databaseURL == "" {
  24. t.Skip("Set TEST_DATABASE_URL to a migrated PostgreSQL database to run API query integration tests")
  25. }
  26. previousOptions := config.Opts
  27. config.Opts = config.NewConfigOptions()
  28. t.Cleanup(func() { config.Opts = previousOptions })
  29. db, err := sql.Open("postgres", databaseURL)
  30. if err != nil {
  31. t.Fatal(err)
  32. }
  33. t.Cleanup(func() { db.Close() })
  34. // Temporary tables stay on one connection and never modify the shared fixture database.
  35. db.SetMaxOpenConns(1)
  36. _, err = db.Exec(`
  37. SET TIME ZONE 'UTC';
  38. CREATE TEMP TABLE users (LIKE users INCLUDING DEFAULTS);
  39. CREATE TEMP TABLE categories (LIKE categories INCLUDING DEFAULTS);
  40. CREATE TEMP TABLE feeds (LIKE feeds INCLUDING DEFAULTS);
  41. CREATE TEMP TABLE entries (LIKE entries INCLUDING DEFAULTS);
  42. CREATE TEMP TABLE enclosures (LIKE enclosures INCLUDING DEFAULTS);
  43. CREATE TEMP TABLE feed_icons (LIKE feed_icons INCLUDING DEFAULTS);
  44. CREATE TEMP TABLE icons (LIKE icons INCLUDING DEFAULTS);
  45. INSERT INTO users (id, username) VALUES (1, 'entry-query-user'), (2, 'entry-query-other');
  46. INSERT INTO categories (id, user_id, title, hide_globally) VALUES
  47. (10, 1, 'Zulu category', false), (20, 1, 'Alpha category', false),
  48. (30, 1, 'Hidden category', true), (40, 2, 'Other category', false);
  49. INSERT INTO feeds (id, user_id, category_id, title, feed_url, site_url, hide_globally) VALUES
  50. (11, 1, 10, 'Visible feed', 'https://example.org/11', 'https://example.org', false),
  51. (12, 1, 20, 'Other visible feed', 'https://example.org/12', 'https://example.org', false),
  52. (13, 1, 10, 'Hidden feed', 'https://example.org/13', 'https://example.org', true),
  53. (14, 1, 30, 'Visible feed in hidden category', 'https://example.org/14', 'https://example.org', false),
  54. (15, 1, 30, 'Hidden feed in hidden category', 'https://example.org/15', 'https://example.org', true),
  55. (16, 2, 40, 'Other user feed', 'https://example.org/16', 'https://example.org', false);
  56. INSERT INTO entries (id, user_id, feed_id, hash, title, url, author, content, status, starred,
  57. published_at, created_at, changed_at, document_vectors, tags) VALUES
  58. (1, 1, 11, '1', 'Zulu entry', 'https://example.org/1', 'Bravo', 'shared content', 'unread', false,
  59. '2025-01-03', '2025-01-02', '2025-01-04', to_tsvector('shared'), ARRAY['one', 'two']),
  60. (2, 1, 12, '2', 'Alpha entry', 'https://example.org/2', 'Charlie', 'shared content', 'read', true,
  61. '2025-01-01', '2025-01-03', '2025-01-02', to_tsvector('shared'), ARRAY['one']),
  62. (3, 1, 11, '3', 'Alpha entry', 'https://example.org/3', 'Alpha', 'shared content', 'unread', false,
  63. '2025-01-02', '2025-01-01', '2025-01-03', to_tsvector('shared'), ARRAY['one', 'two']),
  64. (4, 1, 13, '4', 'Hidden feed entry', 'https://example.org/4', '', '', 'unread', true,
  65. '2025-01-01', '2025-01-01', '2025-01-01', to_tsvector('hidden'), ARRAY[]::text[]),
  66. (5, 1, 14, '5', 'Hidden category entry', 'https://example.org/5', '', '', 'read', false,
  67. '2025-01-01', '2025-01-01', '2025-01-01', to_tsvector('hidden'), ARRAY[]::text[]),
  68. (6, 1, 15, '6', 'Both hidden entry', 'https://example.org/6', '', '', 'unread', false,
  69. '2025-01-01', '2025-01-01', '2025-01-01', to_tsvector('hidden'), ARRAY[]::text[]),
  70. (7, 2, 16, '7', 'Other user entry', 'https://example.org/7', '', '', 'unread', true,
  71. '2025-01-01', '2025-01-01', '2025-01-01', to_tsvector('shared'), ARRAY['one', 'two']),
  72. (8, 1, 11, '8', 'Alpha entry', 'https://example.org/8', 'Alpha', 'shared content', 'unread', false,
  73. '2025-01-02', '2025-01-01', '2025-01-03', to_tsvector('shared'), ARRAY['one', 'two']);
  74. `)
  75. if err != nil {
  76. t.Fatal(err)
  77. }
  78. password, err := bcrypt.GenerateFromPassword([]byte("entry-query-password"), bcrypt.MinCost)
  79. if err != nil {
  80. t.Fatal(err)
  81. }
  82. if _, err := db.Exec(`UPDATE users SET password=$1`, string(password)); err != nil {
  83. t.Fatal(err)
  84. }
  85. return NewHandler(storage.NewStorage(db), nil), db
  86. }
  87. func entryQueryAPIRequest(api http.Handler, method, path, body string) *httptest.ResponseRecorder {
  88. r := httptest.NewRequest(method, path, strings.NewReader(body))
  89. r.SetBasicAuth("entry-query-user", "entry-query-password")
  90. w := httptest.NewRecorder()
  91. api.ServeHTTP(w, r)
  92. return w
  93. }
  94. func checkEntryQueryAPIs(t *testing.T, api http.Handler, query string, want []int64, total int) {
  95. t.Helper()
  96. values, err := url.ParseQuery(query)
  97. if err != nil {
  98. t.Fatal(err)
  99. }
  100. for name, value := range map[string]string{"order": "id", "direction": "asc", "limit": "100", "offset": "0"} {
  101. if !values.Has(name) {
  102. values.Set(name, value)
  103. }
  104. }
  105. query = values.Encode()
  106. w := entryQueryAPIRequest(api, http.MethodGet, "/v1/entries?"+query, "")
  107. if w.Code != http.StatusOK {
  108. t.Fatalf("GetEntries returned %d: %s", w.Code, w.Body.String())
  109. }
  110. var entries entriesResponse
  111. if err := json.Unmarshal(w.Body.Bytes(), &entries); err != nil {
  112. t.Fatal(err)
  113. }
  114. ids := make([]int64, len(entries.Entries))
  115. for i, entry := range entries.Entries {
  116. ids[i] = entry.ID
  117. }
  118. w = entryQueryAPIRequest(api, http.MethodGet, "/v1/entries/ids?"+query, "")
  119. if w.Code != http.StatusOK {
  120. t.Fatalf("GetEntryIDs returned %d: %s", w.Code, w.Body.String())
  121. }
  122. var entryIDs entryIDsResponse
  123. if err := json.Unmarshal(w.Body.Bytes(), &entryIDs); err != nil {
  124. t.Fatal(err)
  125. }
  126. if entryIDs.EntryIDs == nil {
  127. t.Fatal("Expected entry_ids to be a JSON array, not null")
  128. }
  129. if !slices.Equal(ids, entryIDs.EntryIDs) || entries.Total != entryIDs.Total {
  130. t.Fatalf("Queries differ: entries=%v total=%d, IDs=%v total=%d", ids, entries.Total, entryIDs.EntryIDs, entryIDs.Total)
  131. }
  132. if !slices.Equal(ids, want) || entries.Total != total {
  133. t.Fatalf("Got IDs %v total=%d, want %v total=%d", ids, entries.Total, want, total)
  134. }
  135. }
  136. func TestEntryQueryAPIFilters(t *testing.T) {
  137. api, _ := newEntryQueryAPI(t)
  138. all := []int64{1, 2, 3, 4, 5, 6, 8}
  139. for _, test := range []struct {
  140. name string
  141. query string
  142. ids []int64
  143. }{
  144. {"all including hidden", "", all},
  145. {"feed", "feed_id=11", []int64{1, 3, 8}},
  146. {"category", "category_id=10", []int64{1, 3, 4, 8}},
  147. {"unread", "status=unread", []int64{1, 3, 4, 6, 8}},
  148. {"read", "status=read", []int64{2, 5}},
  149. {"multiple statuses", "status=unread&status=read", all},
  150. {"duplicate statuses", "status=unread&status=unread", []int64{1, 3, 4, 6, 8}},
  151. {"mixed duplicate statuses", "status=read&status=unread&status=read", all},
  152. {"trimmed statuses", "status=%20unread%20", []int64{1, 3, 4, 6, 8}},
  153. {"starred", "starred=true", []int64{2, 4}},
  154. {"not starred", "starred=false", []int64{1, 3, 5, 6, 8}},
  155. {"tag", "tags=one", []int64{1, 2, 3, 8}},
  156. {"multiple tags", "tags=ONE&tags=two", []int64{1, 3, 8}},
  157. {"duplicate tags", "tags=one&tags=one", []int64{1, 2, 3, 8}},
  158. {"trimmed tags", "tags=%20one%20&tags=two&tags=", []int64{1, 3, 8}},
  159. {"globally visible", "globally_visible=true", []int64{1, 2, 3, 8}},
  160. {"include hidden explicitly", "globally_visible=false", all},
  161. {"hidden feed", "feed_id=13", []int64{4}},
  162. {"hidden category", "category_id=30", []int64{5, 6}},
  163. {"both hidden", "feed_id=15&category_id=30", []int64{6}},
  164. {"exclude hidden feed", "feed_id=13&globally_visible=true", nil},
  165. {"exclude hidden category", "category_id=30&globally_visible=true", nil},
  166. {"exclude both hidden", "feed_id=15&category_id=30&globally_visible=true", nil},
  167. {"matching scope", "feed_id=11&category_id=10", []int64{1, 3, 8}},
  168. {"mismatched owned scope", "feed_id=11&category_id=20", nil},
  169. {"before ID is exclusive", "before_entry_id=3", []int64{1, 2}},
  170. {"after ID is exclusive", "after_entry_id=3", []int64{4, 5, 6, 8}},
  171. {"combined ID bounds", "after_entry_id=1&before_entry_id=3", []int64{2}},
  172. {"before alias is exclusive", "before=1735776000", []int64{2, 4, 5, 6}},
  173. {"after alias is exclusive", "after=1735776000", []int64{1}},
  174. {"published before is exclusive", "published_before=1735776000", []int64{2, 4, 5, 6}},
  175. {"published after is exclusive", "published_after=1735776000", []int64{1}},
  176. {"changed before is exclusive", "changed_before=1735862400", []int64{2, 4, 5, 6}},
  177. {"changed after is exclusive", "changed_after=1735862400", []int64{1}},
  178. {"both publication aliases apply", "before=1735862400&published_before=1735776000", []int64{2, 4, 5, 6}},
  179. {"both lower aliases apply", "after=1735689600&published_after=1735776000", []int64{1}},
  180. {"publication interval", "published_after=1735689600&published_before=1735862400", []int64{3, 8}},
  181. {"changed interval", "changed_after=1735776000&changed_before=1735948800", []int64{3, 8}},
  182. {"zero time filters stay inactive", "before=0&after=0&published_before=0&published_after=0&changed_before=0&changed_after=0", all},
  183. {"search", "search=shared", []int64{1, 2, 3, 8}},
  184. {"search hidden", "search=hidden", []int64{4, 5, 6}},
  185. {"empty search", "search=", all},
  186. {"empty result", "search=missingterm", nil},
  187. {"no matching tags", "tags=missing", nil},
  188. {"empty ID interval", "after_entry_id=8", nil},
  189. {"conflicting bounds", "before_entry_id=3&after_entry_id=3", nil},
  190. {"combined filters", "feed_id=11&category_id=10&status=unread&starred=false&tags=one&tags=two&globally_visible=true&search=shared&after_entry_id=1&before_entry_id=8&after=1735689600&before=1735862400&changed_after=1735776000&changed_before=1735948800", []int64{3}},
  191. {"read starred scope", "feed_id=12&category_id=20&status=read&starred=true&search=shared", []int64{2}},
  192. } {
  193. t.Run(test.name, func(t *testing.T) {
  194. checkEntryQueryAPIs(t, api, test.query, test.ids, len(test.ids))
  195. })
  196. }
  197. for _, test := range []struct {
  198. query string
  199. ids []int64
  200. total int
  201. }{
  202. {"limit=2", []int64{1, 2}, 7},
  203. {"offset=2", []int64{3, 4, 5, 6, 8}, 7},
  204. {"limit=2&offset=1", []int64{2, 3}, 7},
  205. {"offset=999", nil, 7},
  206. {"after_entry_id=1&before_entry_id=8&limit=2&offset=1", []int64{3, 4}, 5},
  207. {"after_entry_id=1&before_entry_id=3&offset=999", nil, 1},
  208. {"published_after=1735689600&published_before=1735862400&limit=1", []int64{3}, 2},
  209. {"changed_after=1735776000&changed_before=1735948800&offset=999", nil, 2},
  210. } {
  211. t.Run(test.query, func(t *testing.T) {
  212. checkEntryQueryAPIs(t, api, test.query, test.ids, test.total)
  213. })
  214. }
  215. }
  216. func TestEntryQueryAPISorting(t *testing.T) {
  217. api, _ := newEntryQueryAPI(t)
  218. visible := []int64{1, 2, 3, 8}
  219. // Ordinal values describe the fixed fixture, independently of either SQL query.
  220. keys := map[string][]int{
  221. "id": {1, 2, 3, 8},
  222. "status": {0, 1, 0, 0},
  223. "changed_at": {4, 2, 3, 3},
  224. "published_at": {3, 1, 2, 2},
  225. "created_at": {2, 3, 1, 1},
  226. "category_title": {2, 1, 2, 2},
  227. "category_id": {10, 20, 10, 10},
  228. "title": {2, 1, 1, 1},
  229. "author": {2, 3, 1, 1},
  230. }
  231. for order, key := range keys {
  232. for _, direction := range []string{"asc", "desc"} {
  233. for _, search := range []string{"", "shared"} {
  234. t.Run(order+"/"+direction+"/search="+search, func(t *testing.T) {
  235. want := slices.Clone(visible)
  236. slices.SortFunc(want, func(a, b int64) int {
  237. i, j := slices.Index(visible, a), slices.Index(visible, b)
  238. result := cmp.Compare(key[i], key[j])
  239. if result == 0 && search != "" {
  240. // Equal vectors leave the search expression's publication recency first.
  241. if rank := cmp.Compare(keys["published_at"][j], keys["published_at"][i]); rank != 0 {
  242. return rank
  243. }
  244. }
  245. if result == 0 {
  246. result = cmp.Compare(a, b)
  247. }
  248. if direction == "desc" {
  249. result = -result
  250. }
  251. return result
  252. })
  253. query := url.Values{"order": {order}, "direction": {direction}, "search": {search}, "globally_visible": {"true"}}.Encode()
  254. checkEntryQueryAPIs(t, api, query, want, len(want))
  255. })
  256. }
  257. }
  258. }
  259. }
  260. func TestEntryQueryAPISearchRankPrecedesIDTiebreak(t *testing.T) {
  261. api, db := newEntryQueryAPI(t)
  262. if _, err := db.Exec(`DELETE FROM entries WHERE id NOT IN (1, 8);
  263. UPDATE entries SET title='Shared title', published_at='2025-01-02', status='unread';`); err != nil {
  264. t.Fatal(err)
  265. }
  266. for _, direction := range []string{"asc", "desc"} {
  267. highRankID, lowRankID := int64(8), int64(1)
  268. if direction == "desc" {
  269. highRankID, lowRankID = lowRankID, highRankID
  270. }
  271. if _, err := db.Exec(`UPDATE entries SET document_vectors = CASE WHEN id=$1
  272. THEN setweight(to_tsvector('shared'), 'A') ELSE setweight(to_tsvector('shared'), 'D') END`, highRankID); err != nil {
  273. t.Fatal(err)
  274. }
  275. for _, order := range []string{"published_at", "title", "status"} {
  276. t.Run(order+"/"+direction, func(t *testing.T) {
  277. query := "search=shared&order=" + order + "&direction=" + direction
  278. checkEntryQueryAPIs(t, api, query, []int64{highRankID, lowRankID}, 2)
  279. checkEntryQueryAPIs(t, api, query+"&limit=1", []int64{highRankID}, 2)
  280. checkEntryQueryAPIs(t, api, query+"&limit=1&offset=1", []int64{lowRankID}, 2)
  281. })
  282. }
  283. }
  284. }
  285. func TestEntryQueryAPIStablePagination(t *testing.T) {
  286. api, db := newEntryQueryAPI(t)
  287. const count, pageSize = 120, 25
  288. if _, err := db.Exec(`DELETE FROM entries;
  289. INSERT INTO entries (id, user_id, feed_id, hash, title, url, author, content, status, published_at, created_at, changed_at, document_vectors)
  290. SELECT id, 1, 11, id::text, 'Shared pagination title', 'https://example.org/' || id, '', '',
  291. 'unread', '2025-01-02'::timestamptz, '2025-01-02'::timestamptz, '2025-01-02'::timestamptz,
  292. to_tsvector('pagination') FROM generate_series(1, 120) id;`); err != nil {
  293. t.Fatal(err)
  294. }
  295. w := entryQueryAPIRequest(api, http.MethodGet, "/v1/entries", "")
  296. var entries entriesResponse
  297. if err := json.Unmarshal(w.Body.Bytes(), &entries); err != nil {
  298. t.Fatal(err)
  299. }
  300. if w.Code != http.StatusOK || len(entries.Entries) != 100 || entries.Total != count {
  301. t.Fatalf("GetEntries lost its default page size: status=%d length=%d total=%d", w.Code, len(entries.Entries), entries.Total)
  302. }
  303. w = entryQueryAPIRequest(api, http.MethodGet, "/v1/entries/ids", "")
  304. var ids entryIDsResponse
  305. if err := json.Unmarshal(w.Body.Bytes(), &ids); err != nil {
  306. t.Fatal(err)
  307. }
  308. if w.Code != http.StatusOK || len(ids.EntryIDs) != count || ids.Total != count {
  309. t.Fatalf("GetEntryIDs unexpectedly inherited the entries page size: status=%d length=%d total=%d", w.Code, len(ids.EntryIDs), ids.Total)
  310. }
  311. for _, order := range []string{"published_at", "title", "status"} {
  312. for _, direction := range []string{"asc", "desc"} {
  313. for _, search := range []string{"", "pagination"} {
  314. t.Run(order+"/"+direction+"/search="+search, func(t *testing.T) {
  315. want := make([]int64, count)
  316. for i := range count {
  317. want[i] = int64(i + 1)
  318. }
  319. if direction == "desc" {
  320. slices.Reverse(want)
  321. }
  322. for offset := 0; offset <= count; offset += pageSize {
  323. query := url.Values{
  324. "order": {order}, "direction": {direction}, "search": {search},
  325. "offset": {strconv.Itoa(offset)}, "limit": {strconv.Itoa(pageSize)},
  326. }.Encode()
  327. checkEntryQueryAPIs(t, api, query, want[offset:min(offset+pageSize, count)], count)
  328. }
  329. })
  330. }
  331. }
  332. }
  333. }
  334. func TestEntryQueryAPIRejectsInvalidParametersAfterAuthentication(t *testing.T) {
  335. api, _ := newEntryQueryAPI(t)
  336. // Prove these credentials reach the handler before testing its validation errors.
  337. if w := entryQueryAPIRequest(api, http.MethodGet, "/v1/me", ""); w.Code != http.StatusOK {
  338. t.Fatalf("Authentication failed: %d %s", w.Code, w.Body.String())
  339. }
  340. queries := []string{
  341. "status=unread&feed_id=0", "status=unread&category_id=0",
  342. "status=unread&before_entry_id=0", "status=unread&after_entry_id=0",
  343. "feed_id=%zz", "status=unread;status=read", "search=%00", "tags=%00", "search=%ff", "tags=%ff",
  344. "starred=", "starred=maybe", "starred=1", "starred=TRUE",
  345. "globally_visible=", "globally_visible=maybe", "globally_visible=1", "globally_visible=TRUE",
  346. "status=", "status=%20", "status=removed", "status=unread&status=invalid",
  347. "status=invalid&status=unread", "status=unread&status=",
  348. "order=", "order=unknown", "order=id%3BDROP%20TABLE%20entries",
  349. "direction=", "direction=up", "direction=ASC",
  350. }
  351. for _, name := range []string{
  352. "feed_id", "category_id", "before_entry_id", "after_entry_id",
  353. "before", "after", "published_before", "published_after", "changed_before", "changed_after",
  354. } {
  355. for _, value := range []string{"", "invalid", "-1", "1.5", "9223372036854775808"} {
  356. queries = append(queries, url.Values{name: {value}}.Encode())
  357. }
  358. queries = append(queries, url.Values{name: {"1", "2"}}.Encode())
  359. }
  360. for _, name := range []string{"before", "after", "published_before", "published_after", "changed_before", "changed_after"} {
  361. queries = append(queries, name+"=9223372036854775807")
  362. }
  363. for _, name := range []string{"order", "direction", "starred", "globally_visible", "search"} {
  364. queries = append(queries, url.Values{name: {"first", "second"}}.Encode())
  365. }
  366. for _, query := range queries {
  367. t.Run(query, func(t *testing.T) {
  368. w := entryQueryAPIRequest(api, http.MethodGet, "/v1/entries/ids?"+query, "")
  369. if w.Code != http.StatusBadRequest {
  370. t.Fatalf("Got status %d, want 400: %s", w.Code, w.Body.String())
  371. }
  372. })
  373. }
  374. for _, query := range []string{"status=invalid", "status=unread&status=invalid", "order=invalid", "direction=invalid", "limit=1001"} {
  375. t.Run("entries/"+query, func(t *testing.T) {
  376. w := entryQueryAPIRequest(api, http.MethodGet, "/v1/entries?"+query, "")
  377. if w.Code != http.StatusBadRequest {
  378. t.Fatalf("Got status %d, want 400: %s", w.Code, w.Body.String())
  379. }
  380. })
  381. }
  382. // PostgreSQL rejects these values, so every entry endpoint must reject them before querying.
  383. queries = []string{"search=%00", "search=%ff", "tags=%00", "tags=%ff"}
  384. for _, name := range []string{"before", "after", "published_before", "published_after", "changed_before", "changed_after"} {
  385. queries = append(queries, name+"=9223372036854775807", name+"="+strconv.FormatInt(maxEntryFilterTimestamp, 10))
  386. }
  387. for _, path := range []string{"/v1/entries", "/v1/feeds/11/entries", "/v1/categories/10/entries"} {
  388. for _, query := range queries {
  389. t.Run(path+"?"+query, func(t *testing.T) {
  390. w := entryQueryAPIRequest(api, http.MethodGet, path+"?"+query, "")
  391. if w.Code != http.StatusBadRequest {
  392. t.Fatalf("Got status %d, want 400: %s", w.Code, w.Body.String())
  393. }
  394. })
  395. }
  396. }
  397. }
  398. func TestEntryQueryAPIRejectsForeignScopes(t *testing.T) {
  399. api, _ := newEntryQueryAPI(t)
  400. for _, endpoint := range []string{"/v1/entries", "/v1/entries/ids"} {
  401. for _, query := range []string{
  402. "feed_id=16", "category_id=40", "feed_id=16&category_id=40",
  403. "feed_id=16&category_id=10", "feed_id=11&category_id=40",
  404. "feed_id=999", "category_id=999",
  405. } {
  406. t.Run(endpoint+"/"+query, func(t *testing.T) {
  407. w := entryQueryAPIRequest(api, http.MethodGet, endpoint+"?"+query, "")
  408. if w.Code != http.StatusBadRequest {
  409. t.Fatalf("Got status %d, want 400: %s", w.Code, w.Body.String())
  410. }
  411. })
  412. }
  413. }
  414. for _, path := range []string{
  415. "/v1/feeds/16/entries", "/v1/categories/40/entries",
  416. // The query string cannot replace or clear a foreign route scope.
  417. "/v1/feeds/16/entries?feed_id=11", "/v1/feeds/16/entries?feed_id=0",
  418. "/v1/categories/40/entries?category_id=10", "/v1/categories/40/entries?category_id=0",
  419. } {
  420. w := entryQueryAPIRequest(api, http.MethodGet, path, "")
  421. if w.Code != http.StatusBadRequest {
  422. t.Fatalf("%s: got status %d, want 400: %s", path, w.Code, w.Body.String())
  423. }
  424. }
  425. }
  426. func TestEntryQueryAPICompatibility(t *testing.T) {
  427. api, _ := newEntryQueryAPI(t)
  428. for _, test := range []struct {
  429. path string
  430. ids []int64
  431. }{
  432. {"/v1/entries/ids", []int64{8, 6, 5, 4, 3, 2, 1}},
  433. {"/v1/entries/ids?status=read", []int64{5, 2}},
  434. {"/v1/entries/ids?starred=true", []int64{4, 2}},
  435. {"/v1/entries/ids?starred=false&status=unread", []int64{8, 6, 3, 1}},
  436. {"/v1/entries/ids?limit=0", []int64{8, 6, 5, 4, 3, 2, 1}},
  437. {"/v1/entries/ids?limit=99999", []int64{8, 6, 5, 4, 3, 2, 1}},
  438. {"/v1/entries/ids?limit=invalid&offset=-1", []int64{8, 6, 5, 4, 3, 2, 1}},
  439. } {
  440. t.Run(test.path, func(t *testing.T) {
  441. w := entryQueryAPIRequest(api, http.MethodGet, test.path, "")
  442. if w.Code != http.StatusOK {
  443. t.Fatalf("Got status %d: %s", w.Code, w.Body.String())
  444. }
  445. var result entryIDsResponse
  446. if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
  447. t.Fatal(err)
  448. }
  449. if !slices.Equal(result.EntryIDs, test.ids) || result.Total != len(test.ids) {
  450. t.Fatalf("Got IDs %v total=%d, want %v total=%d", result.EntryIDs, result.Total, test.ids, len(test.ids))
  451. }
  452. })
  453. }
  454. for _, test := range []struct {
  455. path string
  456. ids []int64
  457. }{
  458. {"/v1/entries", []int64{2, 4, 5, 6, 3, 8, 1}},
  459. {"/v1/feeds/11/entries", []int64{3, 8, 1}},
  460. {"/v1/categories/10/entries", []int64{4, 3, 8, 1}},
  461. {"/v1/feeds/12/entries?feed_id=11", []int64{2}},
  462. {"/v1/feeds/11/entries?feed_id=0", []int64{3, 8, 1}},
  463. {"/v1/feeds/11/entries?category_id=10", []int64{3, 8, 1}},
  464. {"/v1/categories/20/entries?category_id=10", []int64{2}},
  465. {"/v1/categories/10/entries?category_id=0", []int64{4, 3, 8, 1}},
  466. {"/v1/categories/10/entries?feed_id=13", []int64{4}},
  467. {"/v1/entries?starred=1", []int64{2, 4}},
  468. {"/v1/entries?starred=invalid", []int64{2, 4, 5, 6, 3, 8, 1}},
  469. {"/v1/entries?feed_id=invalid&before_entry_id=-1", []int64{2, 4, 5, 6, 3, 8, 1}},
  470. {"/v1/entries?feed_id=0&category_id=0&before_entry_id=0&after_entry_id=0", []int64{2, 4, 5, 6, 3, 8, 1}},
  471. {"/v1/entries?globally_visible=invalid", []int64{2, 3, 8, 1}},
  472. {"/v1/entries?before=" + strconv.FormatInt(maxEntryFilterTimestamp-1, 10), []int64{2, 4, 5, 6, 3, 8, 1}},
  473. {"/v1/entries?search=caf%C3%A9", nil},
  474. } {
  475. t.Run(test.path, func(t *testing.T) {
  476. w := entryQueryAPIRequest(api, http.MethodGet, test.path, "")
  477. if w.Code != http.StatusOK {
  478. t.Fatalf("Got status %d: %s", w.Code, w.Body.String())
  479. }
  480. var result entriesResponse
  481. if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
  482. t.Fatal(err)
  483. }
  484. ids := make([]int64, len(result.Entries))
  485. for i, entry := range result.Entries {
  486. ids[i] = entry.ID
  487. }
  488. if !slices.Equal(ids, test.ids) || result.Total != len(test.ids) {
  489. t.Fatalf("Got IDs %v total=%d, want %v total=%d", ids, result.Total, test.ids, len(test.ids))
  490. }
  491. })
  492. }
  493. }
  494. func TestEntryQueryAPIUnreadIDBatchesSurviveStatusUpdates(t *testing.T) {
  495. api, _ := newEntryQueryAPI(t)
  496. const query = "/v1/entries/ids?status=unread&order=id&direction=desc"
  497. readPage := func(path string) entryIDsResponse {
  498. t.Helper()
  499. w := entryQueryAPIRequest(api, http.MethodGet, path, "")
  500. if w.Code != http.StatusOK {
  501. t.Fatalf("Got status %d: %s", w.Code, w.Body.String())
  502. }
  503. var page entryIDsResponse
  504. if err := json.Unmarshal(w.Body.Bytes(), &page); err != nil {
  505. t.Fatal(err)
  506. }
  507. return page
  508. }
  509. original := readPage(query)
  510. if !slices.Equal(original.EntryIDs, []int64{8, 6, 4, 3, 1}) {
  511. t.Fatalf("Unexpected target set: %v", original.EntryIDs)
  512. }
  513. var got []int64
  514. var before int64
  515. for {
  516. path := query + "&limit=2"
  517. if before > 0 {
  518. path += "&before_entry_id=" + strconv.FormatInt(before, 10)
  519. }
  520. page := readPage(path)
  521. if remaining := len(original.EntryIDs) - len(got); page.Total != remaining {
  522. t.Fatalf("Got remaining total %d, want %d", page.Total, remaining)
  523. }
  524. if len(page.EntryIDs) == 0 {
  525. break
  526. }
  527. got = append(got, page.EntryIDs...)
  528. if len(got) > len(original.EntryIDs) {
  529. t.Fatal("Pagination repeated entries instead of making progress")
  530. }
  531. body, err := json.Marshal(map[string]any{"entry_ids": page.EntryIDs, "status": "read"})
  532. if err != nil {
  533. t.Fatal(err)
  534. }
  535. w := entryQueryAPIRequest(api, http.MethodPut, "/v1/entries", string(body))
  536. if w.Code != http.StatusNoContent {
  537. t.Fatalf("Unable to mark batch read: %d %s", w.Code, w.Body.String())
  538. }
  539. before = page.EntryIDs[len(page.EntryIDs)-1]
  540. }
  541. if !slices.Equal(got, original.EntryIDs) {
  542. t.Fatalf("Missed or repeated entries after status updates: got %v, want %v", got, original.EntryIDs)
  543. }
  544. if unread := readPage(query); unread.Total != 0 || len(unread.EntryIDs) != 0 {
  545. t.Fatalf("Unread entries remain after consuming all batches: %+v", unread)
  546. }
  547. }