Public: anyone can read this; the crew can change it.

/api/v1/user/repos refuses a bad limit or page with 422 instead of quietly using the default #14424

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/14418-api-v1-user-repos-refuses-a-bad-limit-or → main 4 commits fork

  • Merged. torque/14418-api-v1-user-repos-refuses-a-bad-limit-or was merged into main as f1bb0c5.

Review

Sign in to review this change.
4 files changed +45 −13
src/contract/openapi/routes/getApiV1UserRepos.ts +7 −2
@@ -1,4 +1,4 @@
1 import type { Route } from "../shared.ts";
1 import { limitTo, type Route } from "../shared.ts";
22
33 export const route: Route = {
44 method: "get",
@@ -6,5 +6,10 @@ export const route: Route = {
66 summary: "The caller's own repositories, private ones included, as a bare array in the Gitea shape (page, limit; Link rel=next): what a forge connecting to this one as an origin lists",
77 auth: true,
88 role: "member",
9 refusals: { unauthorized: "no valid credentials were sent" },
9 query: { limit: limitTo(100), page: { type: "integer", min: 1, max: 1000 } },
10 refusals: {
11 unauthorized: "no valid credentials were sent",
12 invalid_limit: "limit is not a whole number from 1 to 100 (422)",
13 invalid_page: "page is not a whole number from 1 to 1000 (422)",
14 },
1015 };
src/contract/page_query.ts +13
@@ -45,3 +45,16 @@ export function limitRefusal(max: number, extra: Record<string, unknown> = {}):
4545 export function cursorRefusal(message: string = CURSOR_SAYS): Response {
4646 return json({ error: CURSOR_ERROR, field: "cursor", message }, 422);
4747 }
48
49 export const PAGE_ERROR = "invalid_page";
50 export const pageSays = (max: number): string => `page is a whole number from 1 to ${max}`;
51
52 /** Parse a raw `page`: `fallback` when absent, a whole number 1..max, else undefined. */
53 export function parsePage(raw: string | null, max: number, fallback = 1): number | undefined {
54 return parseLimit(raw, max, fallback);
55 }
56
57 /** The 422 for a bad `page` on a route whose last page number is `max`. */
58 export function pageRefusal(max: number): Response {
59 return json({ error: PAGE_ERROR, field: "page", message: pageSays(max), hint: pageSays(max) }, 422);
60 }
src/http/api/forge_origin.ts +5 −8
@@ -13,6 +13,7 @@
1313
1414 import { listReposByOwner, visibleReposMarker, type Repo } from "../../core/repos.ts";
1515 import type { Ctx, Handler } from "../context.ts";
16 import { limitRefusal, limitSays, pageRefusal, parseLimit, parsePage } from "../../contract/page_query.ts";
1617 import { holds, weakEtag } from "../etag.ts";
1718 import { json, unauthorized } from "../respond.ts";
1819 import type { Router } from "../router.ts";
@@ -44,12 +45,6 @@ export function giteaShape(ctx: Ctx, repo: Repo) {
4445 };
4546 }
4647
47 /** A positive integer from the query, or the fallback. */
48 function whole(raw: string | null, fallback: number, max: number): number {
49 const n = Number(raw);
50 return Number.isInteger(n) && n > 0 ? Math.min(n, max) : fallback;
51 }
52
5348 export function forgeOriginRoutes(router: Router<Handler>): void {
5449 router.add("GET", "/api/v1/version", (ctx) => {
5550 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
@@ -70,8 +65,10 @@ export function forgeOriginRoutes(router: Router<Handler>): void {
7065 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
7166 const me = ctx.auth.user;
7267 if (!me) return unauthorized();
73 const limit = whole(ctx.url.searchParams.get("limit"), 50, PAGE_MAX);
74 const page = whole(ctx.url.searchParams.get("page"), 1, OWNED_MAX);
68 const limit = parseLimit(ctx.url.searchParams.get("limit"), PAGE_MAX, 50);
69 if (limit === undefined) return limitRefusal(PAGE_MAX, { hint: `send ${limitSays(PAGE_MAX)}; page through the rest with page` });
70 const page = parsePage(ctx.url.searchParams.get("page"), OWNED_MAX);
71 if (page === undefined) return pageRefusal(OWNED_MAX);
7572 const owned: Repo[] = [];
7673 let cursor: string | undefined;
7774 // Pushes and open-issue counts are not in the body, so the tag also digests
test/forge-origin-edges.test.ts +20 −3
@@ -115,11 +115,28 @@ describe("the repositories a forge lists to another", () => {
115115 expect(await beyond.json()).toEqual([]);
116116 });
117117
118 test("a limit over 100 is 100, and nonsense is the default", async () => {
119 expect(((await (await get("/api/v1/user/repos?limit=5000", `token ${aliceToken}`)).json()) as unknown[]).length).toBe(100);
120 expect(((await (await get("/api/v1/user/repos?limit=-3&page=abc", `token ${aliceToken}`)).json()) as unknown[]).length).toBe(50);
118 test("a bad limit or page is refused with 422 and names what is allowed", async () => {
119 const auth = `token ${aliceToken}`;
120 expect(((await (await get("/api/v1/user/repos", auth)).json()) as unknown[]).length).toBe(50);
121 expect(((await (await get("/api/v1/user/repos?limit=100&page=1", auth)).json()) as unknown[]).length).toBe(100);
122 for (const q of ["limit=0", "limit=abc", "limit=-3", "limit=101", "limit=9999"]) {
123 const r = await get(`/api/v1/user/repos?${q}`, auth);
124 expect(r.status).toBe(422);
125 const b = (await r.json()) as { error: string; field: string; message: string; hint: string };
126 expect([b.error, b.field]).toEqual(["invalid_limit", "limit"]);
127 expect(b.message).toContain("100");
128 expect(b.hint.length).toBeGreaterThan(0);
129 }
130 for (const q of ["page=0", "page=-1", "page=abc", "page=1001"]) {
131 const r = await get(`/api/v1/user/repos?${q}`, auth);
132 expect(r.status).toBe(422);
133 const b = (await r.json()) as { error: string; field: string; message: string; hint: string };
134 expect([b.error, b.field]).toEqual(["invalid_page", "page"]);
135 expect(b.message).toContain("1000");
136 }
121137 });
122138
139
123140 test("1005 owned repositories are read as 1000, and say so", async () => {
124141 const r = await get("/api/v1/user/repos?limit=1", `token ${aliceToken}`);
125142 expect(r.headers.get("x-total-count")).toBe("1000");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs