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

One answer for a bad `limit`: /api/v1/explore says `invalid` (1 to 100), /api/v1/repos says `invalid_limit` (1 to 200) #14402

Merged opened this

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

Merged

torque/forge:torque/14390-one-answer-for-a-bad-limit-api-v1-explor → main 10 commits fork 6 threads · 6 unresolved

  • Merged. torque/14390-one-answer-for-a-bad-limit-api-v1-explor was merged into main as 460c945.

Review

Sign in to review this change.
19 files changed +349 −119
docs/features/list-limit.md added +68
@@ -0,0 +1,68 @@
1 ---
2 topic: Your apps
3 row: One refusal for a bad limit
4 docs: Use it | One refusal for a bad limit | every list route answers a bad limit with one 422.
5 ---
6 # One refusal for a bad `limit`
7
8 Every list route under `/api/v1` reads `?limit=` through `src/contract/page_query.ts`. A value that is not a whole number from 1 to the route's own maximum (the `maximum` the route states in `contract/openapi.json`) is a 422:
9
10 ```json
11 { "error": "invalid_limit", "field": "limit", "message": "limit is a whole number from 1 to 100" }
12 ```
13
14 A bad cursor is a 422 `invalid_cursor` with `field: "cursor"`, from the same file (`parseCursor`). Nothing is clamped. `parseLimit` and `parseCursor` in `src/contract/page_query.ts` are the only parsers: a whole number is one to six digits everywhere.
15
16 ## What changed for a caller
17
18 This is breaking where a route used to be lenient:
19
20 - `commits`, `runs`, `gates` and `turns` used to clamp a too-large `limit` to their maximum; they answer 422 now.
21 - `maintenance/runs` used to fall back to 20 on a bad `limit` and accept any size; it is 1 to 100 now.
22 - `explore` answered a bad cursor with a 400; it is a 422 now. `fleet/ops` and `runs` used to ignore a bad cursor; they refuse it.
23 - `user/repos` is the exception: it keeps Gitea's clamping `page` and `limit`, because forges connecting as an origin send those, and the contract states no maximum for it.
24
25 `GET /api/v1/explore` used to answer `error: "invalid"`. That code rides as `legacy_error: "invalid"` for one release, then goes.
26
27 `test/list-limit-shape.test.ts` walks the contract's list routes and fails when one answers its own shape.
28
29 ## The list routes
30
31 Every GET route the contract gives a `limit`, read by `parseLimit` (directly, or through `offsetQuery`, `keyedWindow`, `readLimit`, `eventsLimit`, `decisionsLimit`, `searchRefusal`). The test walks this list from the contract, so a box is ticked only while the walk passes. Not ticked, and why:
32
33 - [x] `/api/v1/admin/accounts` (max 200, cursor)
34 - [x] `/api/v1/admin/invites` (max 200, cursor)
35 - [x] `/api/v1/admin/people` (max 200, cursor)
36 - [x] `/api/v1/conversation/turns` (max 200)
37 - [x] `/api/v1/explore` (max 100, cursor)
38 - [x] `/api/v1/feed` (max 50, cursor)
39 - [x] `/api/v1/fleet/ops` (max 200, cursor)
40 - [x] `/api/v1/maintenance/runs` (max 100)
41 - [x] `/api/v1/orgs/{org}/teams` (max 200, cursor)
42 - [x] `/api/v1/orgs/{org}/teams/{team}/members` (max 200, cursor)
43 - [x] `/api/v1/repos` (max 200, cursor)
44 - [x] `/api/v1/repos/{owner}/{name}/app/pulls` (max 100)
45 - [x] `/api/v1/repos/{owner}/{name}/branches` (max 200, cursor)
46 - [x] `/api/v1/repos/{owner}/{name}/commits` (max 100)
47 - [x] `/api/v1/repos/{owner}/{name}/decisions` (max 100, cursor)
48 - [x] `/api/v1/repos/{owner}/{name}/events` (max 200, cursor)
49 - [x] `/api/v1/repos/{owner}/{name}/family` (max 200)
50 - [x] `/api/v1/repos/{owner}/{name}/forks` (max 200, cursor)
51 - [x] `/api/v1/repos/{owner}/{name}/hooks` (max 200, cursor)
52 - [x] `/api/v1/repos/{owner}/{name}/issues` (max 200, cursor)
53 - [x] `/api/v1/repos/{owner}/{name}/issues/{number}/comments` (max 100, cursor)
54 - [x] `/api/v1/repos/{owner}/{name}/labels` (max 200, cursor)
55 - [x] `/api/v1/repos/{owner}/{name}/milestones` (max 200, cursor)
56 - [x] `/api/v1/repos/{owner}/{name}/pulls` (max 200, cursor)
57 - [x] `/api/v1/repos/{owner}/{name}/queue/gates` (max 100, cursor)
58 - [x] `/api/v1/repos/{owner}/{name}/releases` (max 200)
59 - [x] `/api/v1/repos/{owner}/{name}/runs` (max 200, cursor)
60 - [x] `/api/v1/repos/{owner}/{name}/tags` (max 200, cursor)
61 - [x] `/api/v1/search` (max 100)
62 - [x] `/api/v1/templates` (max 200, cursor)
63 - [x] `/api/v1/user/keys` (max 200, cursor)
64 - [x] `/api/v1/user/orgs` (max 200, cursor)
65 - [x] `/api/v1/user/pins` (max 200, cursor)
66 - [x] `/api/v1/users/{username}/repos` (max 200, cursor)
67 - [ ] `/api/v1/user/repos`: Gitea's `page` and `limit`, clamped, for origins that connect as Gitea clients; the contract states no maximum
68 - [ ] the MCP tools (`src/http/mcp`): they take a JSON number, not a query string, and refuse it in their own `bad(...)` shape; a separate change
src/contract/openapi/routes/getApiV1Explore.ts +1 −1
@@ -1,3 +1,3 @@
11 import { limitTo, type Route } from "../shared.ts";
22
3 export const route: Route = { method: "get", path: "/api/v1/explore", summary: "Explore apps and repositories; `q` takes words and `kind:`/`owner:` filters; answers { query, items, next_cursor } (an app item carries forks, ships, likes and updatedAt, the time of its last ship, not of its last push, null when never shipped) (`limit` 1 to 100 rows a page, default 30; next_cursor null on the last; a bad `limit`, `sort` or `kind` is a 422 naming the field); cursor from next_cursor; a bad cursor is a 400; the answer carries an ETag (cache-control private, no-cache; vary authorization, cookie) that changes when anything listed changes, and a repeat sending it in If-None-Match gets 304 with no body", auth: false, role: "anonymous", alsoStatus: [304, 422], query: { q: "string", cursor: "string", limit: limitTo(100), sort: "string", kind: "string" } };
3 export const route: Route = { method: "get", path: "/api/v1/explore", summary: "Explore apps and repositories; `q` takes words and `kind:`/`owner:` filters; answers { query, items, next_cursor } (an app item carries forks, ships, likes and updatedAt, the time of its last ship, not of its last push, null when never shipped) (`limit` 1 to 100 rows a page, default 30; next_cursor null on the last; a bad `limit`, `sort` or `kind` is a 422 naming the field); cursor from next_cursor; a bad cursor is a 422 `invalid_cursor`; the answer carries an ETag (cache-control private, no-cache; vary authorization, cookie) that changes when anything listed changes, and a repeat sending it in If-None-Match gets 304 with no body", auth: false, role: "anonymous", alsoStatus: [304, 422], query: { q: "string", cursor: "string", limit: limitTo(100), sort: "string", kind: "string" } };
src/contract/openapi/routes/getApiV1MaintenanceRuns.ts +3 −1
@@ -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,6 +6,8 @@ export const route: Route = {
66 summary:
77 "The latest maintenance duty runs, newest first, each with its findings, actions and probes (a forge admin's token; ?limit= up to 100); answers { runs }",
88 auth: true,
9 alsoStatus: [422],
10 query: { limit: limitTo(100) },
911 role: "admin",
1012 refusals: { forbidden: "the token is not a forge admin" },
1113 };
src/contract/page_query.ts added +47
@@ -0,0 +1,47 @@
1 /**
2 * The one parser of `?limit=` and `?cursor=` for a list route (#14390): plain
3 * strings in, plain values out, then the one 422 for each. Two routes cannot disagree on what a
4 * whole number is, because only this file says.
5 */
6
7 import { json } from "../http/respond.ts";
8
9 /** A limit is a whole number written in at most six digits. */
10 const WHOLE = /^\d{1,6}$/;
11
12 /** Parse a raw `limit`: `fallback` when absent, a whole number 1..max, else undefined. */
13 export function parseLimit(raw: string | null, max: number, fallback: number): number | undefined {
14 if (raw === null) return fallback;
15 if (!WHOLE.test(raw)) return undefined;
16 const n = Number(raw);
17 return n >= 1 && n <= max ? n : undefined;
18 }
19
20 /**
21 * Parse a raw `cursor` against the shape the route issues: null when absent,
22 * the string when it matches `shape`, undefined when it does not.
23 */
24 export function parseCursor(raw: string | null, shape: RegExp): string | null | undefined {
25 if (raw === null) return null;
26 return shape.test(raw) ? raw : undefined;
27 }
28
29 /**
30 * The refusal's `error` code; the old `invalid` of /api/v1/explore rides as `legacy_error` for one
31 * release.
32 */
33 export const LIMIT_ERROR = "invalid_limit";
34 export const CURSOR_ERROR = "invalid_cursor";
35
36 export const limitSays = (max: number): string => `limit is a whole number from 1 to ${max}`;
37 export const CURSOR_SAYS = "cursor is the next_cursor of a previous page";
38
39 /** The 422 for a bad `limit` on a route whose maximum is `max`. */
40 export function limitRefusal(max: number, extra: Record<string, unknown> = {}): Response {
41 return json({ error: LIMIT_ERROR, field: "limit", message: limitSays(max), ...extra }, 422);
42 }
43
44 /** The 422 for a bad `cursor`. */
45 export function cursorRefusal(message: string = CURSOR_SAYS): Response {
46 return json({ error: CURSOR_ERROR, field: "cursor", message }, 422);
47 }
src/http/api.ts +55 −52
@@ -8,6 +8,8 @@
88 * back to continue); errors are `{ error, message }`.
99 */
1010
11 import { cursorRefusal, limitRefusal } from "../contract/page_query.ts";

Non-blocking: two import lines from the same module; merge into one.

12 import { parseCursor, parseLimit } from "../contract/page_query.ts";
1113 import { noneMatch } from "./conditional.ts";
1214 import { queryTooLong, QUERY_TOO_LONG } from "../core/query_limit.ts";
1315 import { offeredRepoIds } from "../core/offered.ts";
@@ -124,7 +126,7 @@ import { holdPull, releasePull } from "../actions/holds.ts";
124126 import { getHold, type Hold } from "../core/holds.ts";
125127 import { watchMilestone } from "../actions/watches.ts";
126128 import { THOUGHT_MAX, keepThought } from "../actions/thought.ts";
127 import { search, searchRefusal, searchWithin, type SearchPhase } from "../actions/search.ts";
129 import { SEARCH_LIMIT_MAX, search, searchRefusal, searchWithin, type SearchPhase } from "../actions/search.ts";
128130 import { runRepos } from "./run_gate.ts";
129131 import { writeStamp } from "../core/write_clock.ts";
130132 import { listChildren } from "../actions/spawn.ts";
@@ -977,12 +979,9 @@ export function contributeFailure(error: unknown): Response {
977979 export function readLimit(ctx: Ctx, fallback: number): number | Response;
978980 export function readLimit(ctx: Ctx, fallback: undefined): number | undefined | Response;
outdated

readLimit still parses with its own \d{1,4} regex and a 200 literal; use parseLimit(raw, 200, fallback).

979981 export function readLimit(ctx: Ctx, fallback: number | undefined): number | undefined | Response {
980 const rawLimit = ctx.url.searchParams.get("limit");
981 if (rawLimit === null) return fallback;
982 const limit = /^\d{1,4}$/.test(rawLimit) ? Number(rawLimit) : 0;
983 if (limit < 1 || limit > 200)
984 return apiError("invalid_limit", 422, "limit is a whole number from 1 to 200");
985 return limit;
982 const raw = ctx.url.searchParams.get("limit");
983 if (raw === null) return fallback;
984 return parseLimit(raw, 200, 200) ?? limitRefusal(200);
986985 }
987986
988987 /** `?state=&label=&author=&limit=&cursor=` for issue and pull lists. */
@@ -994,9 +993,8 @@ export function listQuery(ctx: Ctx) {
994993 if (stateParam !== null && stateParam !== "open" && stateParam !== "closed" && stateParam !== "all")
995994 return apiError("invalid_state", 422, "state is open, closed or all");
996995 const state: IssueState | "all" = stateParam ?? "open";
997 const rawCursor = q.get("cursor");
998 if (rawCursor !== null && !/^[1-9]\d{0,15}$/.test(rawCursor))
999 return apiError("invalid_cursor", 422, "cursor is the next_cursor of a previous page");
996 const rawCursor = parseCursor(q.get("cursor"), /^[1-9]\d{0,15}$/);
997 if (rawCursor === undefined) return cursorRefusal();
1000998 const label = q.get("label");
1001999 const author = q.get("author");
10021000 return {
@@ -1009,12 +1007,14 @@ export function listQuery(ctx: Ctx) {
10091007 }
10101008
10111009 /** Room for the longest key: a pin's `owner/name` (up to ~40 + 1 + 100 characters). */

Non-blocking: this comment described KEYED_CURSOR_MAX and now sits above the wrong constant; move it onto KEYED_CURSOR.

1012 const KEYED_CURSOR_MAX = 160;
1010 /** A cursor that is the id of the last row of the page before. */
1011 const ID_CURSOR = /^[A-Za-z0-9_-]{1,64}$/;
1012 const KEYED_CURSOR = /^[\s\S]{1,160}$/;
10131013
10141014 export function offsetRefused(error: "invalid_limit" | "invalid_cursor"): Response {
10151015 return error === "invalid_limit"
1016 ? apiError(error, 422, `limit is a whole number from 1 to ${OFFSET_LIMIT_MAX}`)
1017 : apiError(error, 422, "cursor is the next_cursor of a page before");
1016 ? limitRefusal(OFFSET_LIMIT_MAX)
1017 : cursorRefusal("cursor is the next_cursor of a page before");
10181018 }
10191019
10201020 /**
@@ -1023,13 +1023,10 @@ export function offsetRefused(error: "invalid_limit" | "invalid_cursor"): Respon
10231023 */
10241024 export function keyedWindow(ctx: Ctx): { limit: number; cursor: string | null } | Response {
10251025 const q = ctx.url.searchParams;
outdated

keyedWindow parses its own limit; use parseLimit(raw, LIST_LIMIT_MAX, LIST_LIMIT).

1026 const rawLimit = q.get("limit");
1027 const limit = rawLimit === null ? LIST_LIMIT : /^\d{1,4}$/.test(rawLimit) ? Number(rawLimit) : 0;
1028 if (limit < 1 || limit > LIST_LIMIT_MAX)
1029 return apiError("invalid_limit", 422, `limit is a whole number from 1 to ${LIST_LIMIT_MAX}`);
1030 const cursor = q.get("cursor");
1031 if (cursor !== null && (cursor.length < 1 || cursor.length > KEYED_CURSOR_MAX))
1032 return apiError("invalid_cursor", 422, "cursor is the next_cursor of a previous page");
1026 const limit = parseLimit(q.get("limit"), LIST_LIMIT_MAX, LIST_LIMIT);
1027 if (limit === undefined) return limitRefusal(LIST_LIMIT_MAX);
1028 const cursor = parseCursor(q.get("cursor"), KEYED_CURSOR);
1029 if (cursor === undefined) return cursorRefusal();
10331030 return { limit, cursor };
10341031 }
10351032
@@ -1046,7 +1043,7 @@ export function pageParams(
10461043 if (limit instanceof Response) return limit;
10471044 const cursor = q.get("cursor");
10481045 if (cursor !== null && !/^[A-Za-z0-9_-]{1,64}$/.test(cursor))
1049 return apiError("invalid_cursor", 422, "cursor is the next_cursor of a previous page");
1046 return cursorRefusal();
10501047 return { limit, cursor };
10511048 }
10521049
@@ -1098,7 +1095,7 @@ function repoQuery(ctx: Ctx) {
10981095 const q = ctx.url.searchParams;
10991096 const cursor = q.get("cursor");
11001097 if (cursor !== null && !/^[A-Za-z0-9_-]{1,64}$/.test(cursor))
1101 return apiError("invalid_cursor", 422, "cursor is the next_cursor of a previous page");
1098 return cursorRefusal();
11021099 const limit = readLimit(ctx, undefined);
11031100 if (limit instanceof Response) return limit;
11041101 return {
@@ -1611,7 +1608,10 @@ export function apiRoutes(router: Router<Handler>): void {
16111608 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
16121609 const q = ctx.url.searchParams;
16131610 const refusal = searchRefusal(q.get("kind"), q.get("limit"));
1614 if (refusal) return apiError(refusal.code, 422, refusal.message);
1611 if (refusal) {
1612 if (refusal.code === "invalid_limit") return limitRefusal(SEARCH_LIMIT_MAX);
1613 return apiError(refusal.code, 422, refusal.message);
1614 }
16151615 if (queryTooLong(q.get("q"))) return json({ error: "invalid", field: "q", message: QUERY_TOO_LONG }, 422);
16161616 const kind = searchKind(q.get("kind"));
16171617 const query = q.get("q") ?? "";
@@ -1871,10 +1871,10 @@ export function apiRoutes(router: Router<Handler>): void {
18711871 const q = ctx.url.searchParams;
18721872 const limit = eventsLimit(q.get("limit"));
18731873 if (limit === undefined)
1874 return apiError("invalid_limit", 422, `limit is a whole number from 1 to ${EVENTS_LIMIT_MAX}`);
1874 return limitRefusal(EVENTS_LIMIT_MAX);
18751875 const cursor = q.get("cursor");
18761876 if (cursor !== null && !validEventsCursor(cursor))
1877 return apiError("invalid_cursor", 422, "cursor is the next_cursor of a page before");
1877 return cursorRefusal("cursor is the next_cursor of a page before");
18781878 const kind = q.get("kind");
18791879 if (kind !== null && !validEventsKind(kind))
18801880 return apiError("invalid_kind", 422, "kind is an event kind, like repo.settings_updated");
@@ -1894,8 +1894,8 @@ export function apiRoutes(router: Router<Handler>): void {
18941894 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
18951895 const repo = loadRepo(ctx);
18961896 if (!repo) return notFound();
1897 const limit = Number(ctx.url.searchParams.get("limit") ?? 50);
1898 if (!Number.isInteger(limit) || limit < 1 || limit > 200) return apiError("invalid_limit", 422, "limit is a whole number from 1 to 200");
1897 const limit = parseLimit(ctx.url.searchParams.get("limit"), 200, 50);
1898 if (limit === undefined) return limitRefusal(200);
18991899 const before = ctx.url.searchParams.get("before") ?? undefined;
19001900 return json({ items: listAppReleases(ctx.app.db, repo.id, limit, before === undefined || before.length > 80 ? undefined : before) });
19011901 });
@@ -1909,10 +1909,10 @@ export function apiRoutes(router: Router<Handler>): void {
19091909 const q = ctx.url.searchParams;
19101910 const limit = eventsLimit(q.get("limit") ?? undefined);
19111911 if (limit === undefined)
1912 return apiError("invalid_limit", 422, "limit is a whole number from 1 to 200");
1912 return limitRefusal(200);
19131913 const cursor = q.get("cursor");
19141914 if (cursor !== null && (cursor === "" || cursor.length > 255))
1915 return apiError("invalid_cursor", 422, "cursor is the next_cursor of a page before");
1915 return cursorRefusal("cursor is the next_cursor of a page before");
19161916 // List the refs (cheap), take the page, and compare only its rows.
19171917 const dir = dirOf(ctx, repo);
19181918 const page = await timePhaseAsync(ctx.request, "git", async () => {
@@ -1931,7 +1931,7 @@ export function apiRoutes(router: Router<Handler>): void {
19311931 return { slice, total: all.length, more: start + limit < all.length, headers };
19321932 });
19331933 if (page === undefined)
1934 return apiError("invalid_cursor", 422, "cursor is the next_cursor of a page before");
1934 return cursorRefusal("cursor is the next_cursor of a page before");
19351935 if ("notModified" in page) return page.notModified;
19361936 const compared = await timePhaseAsync(ctx.request, "compare", () =>
19371937 compareBranches(dir, repo.defaultBranch, page.slice, page.total),
@@ -1994,10 +1994,10 @@ export function apiRoutes(router: Router<Handler>): void {
19941994 const q = ctx.url.searchParams;
19951995 const limit = eventsLimit(q.get("limit"));
19961996 if (limit === undefined)
1997 return apiError("invalid_limit", 422, `limit is a whole number from 1 to ${EVENTS_LIMIT_MAX}`);
1997 return limitRefusal(EVENTS_LIMIT_MAX);
19981998 const cursor = q.get("cursor");
19991999 if (cursor !== null && (cursor.length > 200 || !isSafeRef(cursor)))
2000 return apiError("invalid_cursor", 422, "cursor is the next_cursor of a page before");
2000 return cursorRefusal("cursor is the next_cursor of a page before");
20012001 const refs = await timePhaseAsync(ctx.request, "git", () =>
20022002 listRefs(dirOf(ctx, repo), "refs/tags/", true),
20032003 );
@@ -2033,10 +2033,8 @@ export function apiRoutes(router: Router<Handler>): void {
20332033 if (!repo) return notFound();
20342034 const ref = ctx.url.searchParams.get("ref") || repo.defaultBranch;
20352035 if (!isSafeRef(ref)) return json({ error: "bad_ref" }, 422);
2036 const limit = Math.min(
2037 Math.max(Number(ctx.url.searchParams.get("limit")) || 30, 1),
2038 100,
2039 );
2036 const limit = parseLimit(ctx.url.searchParams.get("limit"), 100, 30);
2037 if (limit === undefined) return limitRefusal(100);
20402038 const log = await timePhaseAsync(ctx.request, "git", () =>
20412039 commitLog(dirOf(ctx, repo), ref, { limit }),
20422040 );
@@ -2639,10 +2637,10 @@ export function apiRoutes(router: Router<Handler>): void {
26392637 const kind = q.get("kind");
26402638 const limit = decisionsLimit(q.get("limit"));
26412639 if (limit === undefined)
2642 return apiError("invalid_limit", 422, `limit is a whole number from 1 to ${DECISIONS_LIMIT_MAX}`);
2640 return limitRefusal(DECISIONS_LIMIT_MAX);
26432641 const cursor = q.get("cursor");
26442642 if (cursor !== null && !decisionCursorValid(ctx.app.db, repo.id, cursor))
2645 return apiError("invalid_cursor", 422, "cursor is the next_cursor of a page before");
2643 return cursorRefusal("cursor is the next_cursor of a page before");
26462644 const week = new Date(Date.now() - 7 * 24 * 60 * 60_000).toISOString();
26472645 const read = timePhase(ctx.request, "decisions", () => {
26482646 const page = decisionsPage(ctx.app.db, repo.id, {
@@ -3586,8 +3584,10 @@ export function apiRoutes(router: Router<Handler>): void {
35863584 const asked = readLimit(ctx, undefined);
35873585 if (asked instanceof Response) return asked;
35883586 const limit = pageLimit(asked);
3587 const cursor = parseCursor(q.get("cursor"), ID_CURSOR);
3588 if (cursor === undefined) return cursorRefusal();
35893589 const ops = timePhase(ctx.request, "ops", () =>
3590 listFleetOps(ctx.app, ctx.auth.user!, limit, q.get("cursor") ?? undefined),
3590 listFleetOps(ctx.app, ctx.auth.user!, limit, cursor ?? undefined),
35913591 );
35923592 if (!ops.ok) return respondFleet(ops.error);
35933593 return timePhase(ctx.request, "render", () => json(paged(ops.value, limit, (op) => op.id)));
@@ -3663,11 +3663,10 @@ export function apiRoutes(router: Router<Handler>): void {
36633663 router.add("GET", "/api/v1/explore", async (ctx) => {
36643664 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
36653665 // One rule: whatever the explorer does not take is 422, naming the field and the allowed
3666 // values: `limit`, a separate filter parameter, or a word typed in `q` (`unknown_filter`).
3667 const limitRaw = ctx.url.searchParams.get("limit");
3668 if (limitRaw !== null && !(/^\d{1,3}$/.test(limitRaw) && Number(limitRaw) >= 1 && Number(limitRaw) <= 100))
3669 return json({ error: "invalid", field: "limit", message: "limit is an integer from 1 to 100" }, 422);
3670 const limit = limitRaw === null ? 30 : Number(limitRaw);
3666 // values: `limit` (one refusal on every list route), a separate filter parameter, or a word
3667 // typed in `q` (`unknown_filter`).
3668 const limit = parseLimit(ctx.url.searchParams.get("limit"), 100, 30);
3669 if (limit === undefined) return limitRefusal(100, { legacy_error: "invalid" });
36713670 if (queryTooLong(ctx.url.searchParams.get("q")))
36723671 return json({ error: "invalid", field: "q", message: QUERY_TOO_LONG }, 422);
36733672 const refused = badExploreParam((name) => ctx.url.searchParams.get(name));
@@ -3701,7 +3700,7 @@ export function apiRoutes(router: Router<Handler>): void {
37013700 let headers: Record<string, string> = {};
37023701 const cursor = ctx.url.searchParams.get("cursor");
37033702 if (cursor !== null && !cursorFits(cursor, query))
3704 return apiError("invalid_cursor", 400, "cursor is the next_cursor of a page before");
3703 return cursorRefusal("cursor is the next_cursor of a page before");
37053704 if (stamp !== undefined) {
37063705 const viewer = ctx.auth.user === undefined ? "anonymous" : `${ctx.auth.user.id}${ctx.auth.user.isAdmin ? ":admin" : ""}`;
37073706 const confined = mine === undefined ? "" : mine.map((r) => r.id).join(",");
@@ -3716,7 +3715,7 @@ export function apiRoutes(router: Router<Handler>): void {
37163715 explorePage(ctx.app, ctx.auth.user, query, cursor, visible, undefined, limit),
37173716 );
37183717 if (page === null)
3719 return apiError("invalid_cursor", 400, "cursor is the next_cursor of a page before");
3718 return cursorRefusal("cursor is the next_cursor of a page before");
37203719 const items = rowsWithWhy(ctx.app, query, page.items);
37213720 return timePhase(ctx.request, "render", () => json({ query: exploreLine(query), ...(unknown.length === 0 ? {} : { note: exploreNote(unknown) }), ...(suggest === undefined ? {} : { suggest: suggest.line }), items, next_cursor: page.nextCursor }, 200, headers));
37223721 });
@@ -4213,12 +4212,15 @@ export function apiRoutes(router: Router<Handler>): void {
42134212 const state = RUN_STATES.find((s) => s === wanted);
42144213 if (wanted !== null && state === undefined)
42154214 return apiError("invalid_state", 422, `state is one of ${RUN_STATES.join(", ")}`);
4216 const limit = Math.min(Math.max(Number(q.get("limit")) || 50, 1), 200);
4215 const limit = parseLimit(q.get("limit"), 200, 50);
4216 if (limit === undefined) return limitRefusal(200);
4217 const cursor = parseCursor(q.get("cursor"), ID_CURSOR);
4218 if (cursor === undefined) return cursorRefusal();
42174219 const options: ListRunsOptions = {
42184220 ...(kind === "deploy" || kind === "agent" ? { kind } : {}),
42194221 ...(env !== null && isEnvName(env) ? { env } : {}),
42204222 ...(state === undefined ? {} : { state }),
4221 ...(q.get("cursor") ? { cursor: q.get("cursor")! } : {}),
4223 ...(cursor === null || cursor === "" ? {} : { cursor }),
42224224 limit,
42234225 };
42244226 // The tag: repository, viewer, what shapes the page, and a marker over
@@ -4274,10 +4276,11 @@ export function apiRoutes(router: Router<Handler>): void {
42744276 const repo = loadRepo(ctx);
42754277 if (!repo) return notFound();
42764278 const q = ctx.url.searchParams;
4277 const limit = Math.min(Math.max(Number(q.get("limit")) || 20, 1), 100);
4278 const cursor = q.get("cursor") ?? undefined;
4279 if (cursor !== undefined && !/^[0-9A-Za-z]{1,40}$/.test(cursor))
4280 return json({ error: "invalid", message: "`cursor` is a gate id from `next_cursor`" }, 422);
4279 const limit = parseLimit(q.get("limit"), 100, 20);
4280 if (limit === undefined) return limitRefusal(100);
4281 const parsed = parseCursor(q.get("cursor"), /^[0-9A-Za-z]{1,40}$/);
4282 if (parsed === undefined) return cursorRefusal("cursor is a gate id from next_cursor");
4283 const cursor = parsed ?? undefined;
42814284 const items = timePhase(ctx.request, "gates", () => recentGates(ctx.app.db, repo.id, limit, cursor));
42824285 return timePhase(ctx.request, "render", () => json(paged(items, limit, (g) => g.id), 200, { "cache-control": "no-store" }));
42834286 });
src/http/api/app_pulls.ts +4 −7
@@ -5,23 +5,20 @@
55 * read through `pullRunLines` in `apps/pull.ts`.
66 */
77
8 import { limitRefusal } from "../../contract/page_query.ts";
9 import { parseLimit } from "../../contract/page_query.ts";
810 import { requireReader } from "../../actions/access.ts";
911 import { PULL_RUNS_DEFAULT, PULL_RUNS_MAX, pullRunLines } from "../../apps/pull.ts";
1012 import { getAppByRepo } from "../../core/apps.ts";
1113 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1214 import { loadRepo } from "../api.ts";
1315 import type { Ctx, Handler } from "../context.ts";
14 import { apiError, json, notFound } from "../respond.ts";
16 import { json, notFound } from "../respond.ts";
1517 import type { Router } from "../router.ts";
1618
1719 /** `?limit=`: absent is the default, a whole number from 1 to 100 is itself, anything else is a 422. */
1820 function pullsLimit(ctx: Ctx): number | Response {
outdated

The null check is redundant with parseLimit's fallback; drop one.

19 const raw = ctx.url.searchParams.get("limit");
20 if (raw === null) return PULL_RUNS_DEFAULT;
21 const limit = /^\d{1,3}$/.test(raw) ? Number(raw) : 0;
22 if (limit < 1 || limit > PULL_RUNS_MAX)
23 return apiError("invalid_limit", 422, `limit is a whole number from 1 to ${PULL_RUNS_MAX}`);
24 return limit;
21 return parseLimit(ctx.url.searchParams.get("limit"), PULL_RUNS_MAX, PULL_RUNS_DEFAULT) ?? limitRefusal(PULL_RUNS_MAX);
2522 }
2623
2724 export function appPullsRoutes(router: Router<Handler>): void {
src/http/api/conversation_talk.ts +5 −9
@@ -7,6 +7,8 @@
77 * request is same-origin, and sending is throttled per person (`actions/talk.ts`).
88 */
99
10 import { limitRefusal } from "../../contract/page_query.ts";
11 import { parseLimit } from "../../contract/page_query.ts";
1012 import { noTalkAccountBlocked } from "../../actions/blocked_words.ts";
1113 import { blockedFields } from "../../kernel/blocked.ts";
1214 import type { App } from "../../app.ts";
@@ -56,14 +58,6 @@ const talkWait = (error: string): number => TALK_WAIT[error] ?? WINDOW.minute;
5658 /** Room for the words at their cap even when every character is escaped. */
5759 const BODY_MAX = 128_000;
5860
59 /** `?limit=`: whole turns from 1 to `MAX_PAGE`; absent, empty or not a number is `DEFAULT_PAGE`. */
60 export function turnsLimit(raw: string | null): number {
61 if (raw === null || raw.trim() === "") return DEFAULT_PAGE;
62 const n = Number(raw);
63 if (!Number.isFinite(n)) return DEFAULT_PAGE;
64 return Math.min(MAX_PAGE, Math.max(1, Math.floor(n)));
65 }
66
6761 /**
6862 * Files a person may upload in a minute; a refused file still costs a read, so this is checked
6963 * first.
@@ -188,8 +182,10 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
188182 const named = ctx.url.searchParams.get("conversation");
189183 const conversation = named === null ? openConversation(ctx.app.db, user.id) : getConversation(ctx.app.db, user.id, named);
190184 if (conversation === undefined) return apiError("not_found", 404, "no such conversation");
185 const limit = parseLimit(ctx.url.searchParams.get("limit"), MAX_PAGE, DEFAULT_PAGE);
186 if (limit === undefined) return limitRefusal(MAX_PAGE);
191187 const turns = listTurns(ctx.app.db, user.id, conversation.id, {
192 limit: turnsLimit(ctx.url.searchParams.get("limit")),
188 limit,
193189 ...(ctx.url.searchParams.get("before") ? { before: ctx.url.searchParams.get("before")! } : {}),
194190 });
195191 // An agent turn carries the steps line and links of the calls before it (`core/talk_work.ts`).
src/http/api/family.ts +7 −6
@@ -6,6 +6,8 @@
66 * (1-200 nodes) narrow it; `truncated` says when more exists than is shown.
77 */
88
9 import { limitRefusal } from "../../contract/page_query.ts";
10 import { parseLimit } from "../../contract/page_query.ts";
911 import { forkTree } from "../../actions/fork_tree.ts";
1012 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1113 import { loadRepo } from "../api.ts";
@@ -13,12 +15,10 @@ import type { Handler } from "../context.ts";
1315 import { apiError, json, notFound } from "../respond.ts";
1416 import type { Router } from "../router.ts";
1517
16 /** A query value as a whole number in range; undefined when absent, null when not one. */
18 /** `depth`: undefined when absent, null when not a whole number from 1 to `max`. */
1719 function whole(raw: string | null, max: number): number | undefined | null {
1820 if (raw === null) return undefined;
19 if (!/^\d{1,4}$/.test(raw)) return null;
20 const n = Number(raw);
21 return n >= 1 && n <= max ? n : null;
21 return parseLimit(raw, max, max) ?? null;
2222 }
2323
2424 export function familyRoutes(router: Router<Handler>): void {
@@ -28,9 +28,10 @@ export function familyRoutes(router: Router<Handler>): void {
2828 if (!repo) return notFound();
2929 const q = new URL(ctx.request.url).searchParams;
3030 const depth = whole(q.get("depth"), 8);
31 const limit = whole(q.get("limit"), 200);
31 const rawLimit = q.get("limit");
32 const limit = rawLimit === null ? undefined : parseLimit(rawLimit, 200, 200) ?? null;
3233 if (depth === null) return apiError("invalid_depth", 422, "depth is a whole number from 1 to 8");
33 if (limit === null) return apiError("invalid_limit", 422, "limit is a whole number from 1 to 200");
34 if (limit === null) return limitRefusal(200);
3435 const opts: { depth?: number; limit?: number } = {};
3536 if (depth !== undefined) opts.depth = depth;
3637 if (limit !== undefined) opts.limit = limit;
src/http/api/issues.ts +6 −6
@@ -5,6 +5,8 @@
55 * (#7450); the rules live in `actions/issues.ts` and its neighbours.
66 */
77
8 import { cursorRefusal, limitRefusal } from "../../contract/page_query.ts";
9 import { parseLimit } from "../../contract/page_query.ts";
810 import { markQuestion } from "../../actions/issues.ts";
911 import { parseQuestion } from "../../core/issues.ts";
1012 import { mayReadRuns } from "../../actions/runs.ts";
@@ -281,10 +283,8 @@ export function issueRoutes(router: Router<Handler>): void {
281283 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
282284 const found = loadConversation(ctx);
283285 if ("error" in found) return found.error;
284 const rawLimit = ctx.url.searchParams.get("limit");
285 const limit = rawLimit === null ? 50 : /^\d{1,4}$/.test(rawLimit) ? Number(rawLimit) : 0;
286 if (limit < 1 || limit > 100)
287 return apiError("invalid_limit", 422, "limit is a whole number from 1 to 100");
286 const limit = parseLimit(ctx.url.searchParams.get("limit"), 100, 50);
287 if (limit === undefined) return limitRefusal(100);
288288 const after = ctx.url.searchParams.get("after");
289289 if (after !== null && !/^[A-Za-z0-9_-]{1,64}$/.test(after))
290290 return apiError("invalid_after", 422, "after is a comment id");
@@ -293,9 +293,9 @@ export function issueRoutes(router: Router<Handler>): void {
293293 // the page older again (null at the first comment) (#6198).
294294 const cursor = ctx.url.searchParams.get("cursor");
295295 if (cursor !== null && !/^[A-Za-z0-9_-]{1,64}$/.test(cursor))
296 return apiError("invalid_cursor", 422, "cursor is a comment id from commentsNext");
296 return cursorRefusal("cursor is a comment id from commentsNext");
297297 if (cursor !== null && after !== null)
298 return apiError("invalid_cursor", 422, "cursor and after are two ways to page: send one");
298 return cursorRefusal("cursor and after are two ways to page: send one");
299299 if (cursor !== null) {
300300 const older = timePhase(ctx.request, "comments", () =>
301301 listComments(ctx.app.db, found.issue.id, { before: cursor, newest: true, limit: limit + 1 }),
src/http/api/maintenance_runs.ts +4 −2
@@ -1,5 +1,7 @@
11 /** `GET /api/v1/maintenance/runs`: the latest maintenance duty runs, for a forge admin. */
22
3 import { limitRefusal } from "../../contract/page_query.ts";
4 import { parseLimit } from "../../contract/page_query.ts";
35 import { switchDuty, dutyStates } from "../../maintain/pause.ts";
46 import { latest } from "../../maintain/runs.ts";
57 import type { Handler } from "../context.ts";
@@ -15,8 +17,8 @@ export function maintenanceRunsRoutes(router: Router<Handler>): void {
1517 if (!ctx.auth.user.isAdmin) return forbidden();
1618 const denied = requireScope(ctx, "ro");
1719 if (denied) return denied;
18 const asked = Number(ctx.url.searchParams.get("limit") ?? 20);
19 const limit = Number.isInteger(asked) && asked > 0 ? asked : 20;
20 const limit = parseLimit(ctx.url.searchParams.get("limit"), 100, 20);
21 if (limit === undefined) return limitRefusal(100);
2022 return json({ runs: latest(ctx.app.db, limit) });
2123 });
2224 router.add("GET", "/api/v1/maintenance/duties", (ctx) => {
src/http/feed.ts +6 −8
@@ -3,6 +3,8 @@
33 * are the signed-in viewer's own — there is no way to ask for another's.
44 */
55
6 import { cursorRefusal, limitRefusal } from "../contract/page_query.ts";
7 import { parseLimit } from "../contract/page_query.ts";
68 import {
79 parseVariants,
810 toldWords,
@@ -74,21 +76,17 @@ export function feedRoutes(router: Router<Handler>): void {
7476 if (!viewer) return unauthorized();
7577 const q = ctx.url.searchParams;
7678 const rawLimit = q.get("limit");
77 const limit = rawLimit === null ? undefined : Number(rawLimit);
78 if (
79 limit !== undefined &&
80 (!Number.isInteger(limit) || limit < 1 || limit > FEED_LIMIT_MAX)
81 )
82 return apiError("invalid_limit", 422, `limit is 1 to ${FEED_LIMIT_MAX}`);
79 const limit = rawLimit === null ? undefined : parseLimit(rawLimit, FEED_LIMIT_MAX, FEED_LIMIT_MAX);
80 if (rawLimit !== null && limit === undefined) return limitRefusal(FEED_LIMIT_MAX);
8381 const rawCursor = q.get("cursor");
8482 const cursor = rawCursor === null ? undefined : parseCursor(rawCursor);
8583 if (rawCursor !== null && cursor === undefined)
86 return apiError("invalid_cursor", 422, CURSOR_NOT_ISSUED);
84 return cursorRefusal(CURSOR_NOT_ISSUED);
8785 // `before=` is the timeline: newest first, paged by an event id (`feed/timeline.ts`).
8886 const rawBefore = q.get("before");
8987 const before = rawBefore === null ? undefined : parseBefore(rawBefore);
9088 if (rawBefore !== null && (before === undefined || rawCursor !== null))
91 return apiError("invalid_cursor", 422, CURSOR_NOT_ISSUED);
89 return cursorRefusal(CURSOR_NOT_ISSUED);
9290 // A 304 only when nothing the viewer would read has changed (`feedTag`).
9391 // The queue drains first, as `readFeed` would; shares still waiting
9492 // depend on the clock, so they always get a page.
src/http/offset_page.ts +7 −7
@@ -1,5 +1,7 @@
11 /** A list held whole in memory, served a page at a time: `limit` (1-200, 50 by default) and an opaque `cursor`. */
22
3 import { parseCursor, parseLimit } from "../contract/page_query.ts";
4
35 export const OFFSET_LIMIT_DEFAULT = 50;
46 export const OFFSET_LIMIT_MAX = 200;
57
@@ -7,13 +9,11 @@ export type OffsetQuery = { limit: number; offset: number } | { error: "invalid_
79
810 /** Read `?limit=&cursor=`; a bad value is named, never clamped. */
911 export function offsetQuery(q: URLSearchParams): OffsetQuery {
10 const rawLimit = q.get("limit");
11 const limit = rawLimit === null ? OFFSET_LIMIT_DEFAULT : /^\d{1,4}$/.test(rawLimit) ? Number(rawLimit) : 0;
12 if (limit < 1 || limit > OFFSET_LIMIT_MAX) return { error: "invalid_limit" };
13 const rawCursor = q.get("cursor");
14 if (rawCursor === null) return { limit, offset: 0 };
15 if (!/^[1-9]\d{0,8}$/.test(rawCursor)) return { error: "invalid_cursor" };
16 return { limit, offset: Number(rawCursor) };
12 const limit = parseLimit(q.get("limit"), OFFSET_LIMIT_MAX, OFFSET_LIMIT_DEFAULT);
13 if (limit === undefined) return { error: "invalid_limit" };
14 const cursor = parseCursor(q.get("cursor"), /^[1-9]\d{0,8}$/);
15 if (cursor === undefined) return { error: "invalid_cursor" };
16 return { limit, offset: cursor === null ? 0 : Number(cursor) };
1717 }
1818
1919 export function offsetPage<T>(all: readonly T[], limit: number, offset: number): { items: T[]; next_cursor: string | null } {
test/conversation-talk.test.ts +6 −11
@@ -18,7 +18,6 @@ import { createToken } from "../src/core/tokens.ts";
1818 import { createUser } from "../src/core/users.ts";
1919 import { mintViaToken } from "../src/core/via_token.ts";
2020 import { TALK_PER_MINUTE, talk, talkAgain } from "../src/actions/talk.ts";
21 import { turnsLimit } from "../src/http/api/conversation_talk.ts";
2221 import { serve, type Servers } from "../src/http/server.ts";
2322 import { appendTurn, newConversation, openConversation } from "../src/core/conversations.ts";
2423 import { forgeSshSession } from "../src/tui/ssh.ts";
@@ -233,18 +232,14 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t
233232 }
234233 });
235234
236 test("the turns page size is clamped, and junk is the default", async () => {
237 expect(turnsLimit(null)).toBe(50);
238 expect(turnsLimit("")).toBe(50);
239 expect(turnsLimit("ten")).toBe(50);
240 expect(turnsLimit("0")).toBe(1);
241 expect(turnsLimit("-3")).toBe(1);
242 expect(turnsLimit("2.7")).toBe(2);
243 expect(turnsLimit("100000")).toBe(200);
235 test("the turns page size is a whole number from 1 to 200, and anything else is the one 422 (#14390)", async () => {
244236 const one = await fetch(`${servers.url}/api/v1/conversation/turns?limit=1`, { headers: headers(token) });
245237 expect(((await one.json()) as { turns: { text: string }[] }).turns.map((t) => t.text)).toEqual(["Heard."]);
246 const junk = await fetch(`${servers.url}/api/v1/conversation/turns?limit=`, { headers: headers(token) });
247 expect(((await junk.json()) as { turns: unknown[] }).turns).toHaveLength(2);
238 for (const bad of ["", "ten", "0", "201"]) {
239 const junk = await fetch(`${servers.url}/api/v1/conversation/turns?limit=${bad}`, { headers: headers(token) });
240 expect(junk.status).toBe(422);
241 expect(((await junk.json()) as { error: string }).error).toBe("invalid_limit");
242 }
248243 });
249244
250245 test("a token that may only read cannot start a turn that acts with rw (#8230)", async () => {
test/explore-api-paging.test.ts +2 −2
@@ -105,7 +105,7 @@ describe("refusals", () => {
105105 expect(res.status).toBe(422);
106106 expect(((await res.json()) as { field: string }).field).toBe("kind");
107107 });
108 test("a cursor that is not one is still 400", async () => {
109 expect((await get("cursor=%25%25")).status).toBe(400);
108 test("a cursor that is not one is 422 invalid_cursor", async () => {
109 expect((await get("cursor=%25%25")).status).toBe(422);
110110 });
111111 });
test/explore-etag.test.ts +2 −2
@@ -107,9 +107,9 @@ describe("the explore ETag", () => {
107107 expect(await tagOf("alice", "/api/v1/explore?q=kind:person")).not.toBe(a);
108108 });
109109
110 test("a bad cursor is a 400 even with If-None-Match: *", async () => {
110 test("a bad cursor is a 422 even with If-None-Match: *", async () => {
111111 const res = await get(null, "*", "/api/v1/explore?q=kind:app&cursor=nonsense");
112 expect(res.status).toBe(400);
112 expect(res.status).toBe(422);
113113 await res.arrayBuffer();
114114 const ok = await get(null, "*");
115115 expect(ok.status).toBe(304);
test/explore.test.ts +3 −3
@@ -576,11 +576,11 @@ describe("explore past the first page", () => {
576576 test("a malformed cursor, or one from another sort, is refused", async () => {
577577 for (const bad of ["!!", "x".repeat(500), Buffer.from("[1,2]").toString("base64url")]) {
578578 const res = await get("kind:app", bad);
579 expect(res.status).toBe(400);
579 expect(res.status).toBe(422);
580580 expect(((await res.json()) as any).error).toBe("invalid_cursor");
581581 }
582582 const first = (await (await get("kind:app")).json()) as any;
583 expect((await get("kind:app sort:name", first.next_cursor)).status).toBe(400);
583 expect((await get("kind:app sort:name", first.next_cursor)).status).toBe(422);
584584 });
585585
586586 test("MCP explore takes the cursor and answers next_cursor", async () => {
@@ -611,7 +611,7 @@ describe("explore past the first page", () => {
611611 const first = (await (await get(`kind:app sort:${made}`)).json()) as any;
612612 for (const used of sorts) {
613613 const res = await get(`kind:app sort:${used}`, first.next_cursor);
614 expect(res.status).toBe(made === used ? 200 : 400);
614 expect(res.status).toBe(made === used ? 200 : 422);
615615 }
616616 }
617617 });
test/list-limit-shape.test.ts added +114
@@ -0,0 +1,114 @@
1 /**
2 * One answer for a bad `limit` (#14390): every list route the contract gives a
3 * `limit` answers `?limit=abc` and `?limit=<max+1>` with the same 422
4 * `{ error: "invalid_limit", field: "limit", message }`, the message naming the
5 * maximum the contract states for that route, and a route that states none is a
6 * failure. The routes are read from contract/openapi, so a new list route is
7 * walked without being named here.
8 */
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { createRepo } from "../src/actions/repos.ts";
15 import { createIssue } from "../src/core/issues.ts";
16 import { ROUTES } from "../src/contract/openapi.ts";
17 import { limitSays } from "../src/contract/page_query.ts";
18 import { parseCursor, parseLimit } from "../src/contract/page_query.ts";
19 import { createOrg, createTeam } from "../src/core/orgs.ts";
20 import { setSsh } from "../src/settings/ssh.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { seedAdmin } from "./helpers/admin.ts";
outdated

Empty OWN_SHAPE is dead scaffolding; remove it. NEEDS_FIXTURE leaves three list routes unwalked: seed the fixtures instead.

23
24 const FILL: Record<string, string> = {
25 owner: "alice", username: "alice", name: "notes", number: "1", org: "guild",
26 slug: "main", id: "1", team: "core", scope: "alice", job: "1", oid: "0", env: "prod",
27 };
28
29 let dataDir = "";
30 let app: App, servers: Servers, bearer = "";
31
32 beforeAll(async () => {
33 dataDir = await mkdtemp(join(tmpdir(), "forge-limitshape-"));
34 app = createApp({ dataDir, port: 0 });
35 servers = await serve(app);
36 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
37 if (!admin.ok) throw new Error(admin.error);
38 const made = await createRepo(app, admin.value, { name: "notes", visibility: "public", description: "" });
39 if (!made.ok) throw new Error(String(made.error));
40 createIssue(app.db, { repoId: made.value.id, title: "one", body: "b", authorId: admin.value.id });
41 const org = createOrg(app.db, "guild", admin.value.id);
42 if (!org.ok) throw new Error(String(org.error));
43 const team = createTeam(app.db, org.value.id, "core", "read");
44 if (!team.ok) throw new Error(String(team.error));
45 setSsh(app.db, true, admin.value.id);
46 const minted = await fetch(`${servers.url}/api/v1/tokens`, {
47 method: "POST",
48 headers: { "content-type": "application/json" },
49 body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "cli", scope: "admin" }),
50 });
51 bearer = ((await minted.json()) as { token: string }).token;
52 });
53
54 afterAll(async () => {
55 servers.stop();
56 app.close();
57 await rm(dataDir, { recursive: true, force: true });
58 });
59
60 const listRoutes = ROUTES.filter(
61 (r) => r.method === "get" && typeof r.query?.limit === "object" && !r.path.includes("/mcp"),
62 );
63
64 test("the walk finds the list routes", () => {
65 expect(listRoutes.length).toBeGreaterThan(10);
66 });
67
68 test("parseLimit: absent is the default, a whole number in range is itself, the rest is undefined", () => {
69 expect(parseLimit(null, 100, 30)).toBe(30);
70 expect(parseLimit("100", 100, 30)).toBe(100);
71 expect(parseLimit("101", 100, 30)).toBeUndefined();
72 for (const bad of ["0", "-1", "abc", "1.5", "", "1e2", " 5"]) expect(parseLimit(bad, 100, 30)).toBeUndefined();
73 });
74
75 test("every list route states a maximum and refuses a bad limit in one shape", async () => {
76 const failures: string[] = [];
77 for (const r of listRoutes) {
78 const spec = r.query!.limit as { max?: number };
79 if (spec.max === undefined) { failures.push(`${r.path}: the contract states no maximum`); continue; }
80 const path = r.path.replace(/\{(\w+)\}/g, (_, k: string) => FILL[k] ?? "x");
81 for (const bad of ["abc", "-1", "0", String(spec.max + 1)]) {
82 const res = await fetch(`${servers.url}${path}?limit=${bad}`, { headers: { authorization: `Bearer ${bearer}` } });
83 const body = (await res.json().catch(() => null)) as { error?: string; field?: string; message?: string } | null;
84 const ok = res.status === 422 && body?.error === "invalid_limit" && body.field === "limit" && body.message === limitSays(spec.max);
85 if (!ok) failures.push(`${r.path}?limit=${bad}: ${res.status} ${JSON.stringify(body)}`);
86 }
87 }
88 expect(failures).toEqual([]);
89 }, 60_000);
90
91 test("parseCursor: absent is null, a cursor of the route's shape is itself, the rest is undefined", () => {
92 expect(parseCursor(null, /^\d+$/)).toBeNull();
93 expect(parseCursor("12", /^\d+$/)).toBe("12");
94 expect(parseCursor("1x", /^\d+$/)).toBeUndefined();
95 });
96
97 test("every list route with a cursor refuses a bad one as invalid_cursor, field cursor", async () => {
98 const failures: string[] = [];
99 const withCursor = listRoutes.filter((r) => r.query?.cursor !== undefined);
100 expect(withCursor.length).toBeGreaterThan(5);
101 for (const r of withCursor) {
102 const path = r.path.replace(/\{(\w+)\}/g, (_, k: string) => FILL[k] ?? "x");
103 const res = await fetch(`${servers.url}${path}?cursor=${"x".repeat(300)}`, { headers: { authorization: `Bearer ${bearer}` } });
104 const body = (await res.json().catch(() => null)) as { error?: string; field?: string } | null;
105 if (!(res.status === 422 && body?.error === "invalid_cursor" && body.field === "cursor")) failures.push(`${r.path}: ${res.status} ${JSON.stringify(body)}`);
106 }
107 expect(failures).toEqual([]);
108 }, 60_000);
109
110 test("explore keeps its old code as legacy_error for one release", async () => {
111 const res = await fetch(`${servers.url}/api/v1/explore?limit=-1`);
112 expect(res.status).toBe(422);
113 expect(await res.json()).toMatchObject({ error: "invalid_limit", field: "limit", message: limitSays(100), legacy_error: "invalid" });
114 });
test/maintain.test.ts +2 −1
@@ -137,7 +137,8 @@ test("GET /api/v1/maintenance/runs lists the latest rows for an admin only", asy
137137 expect(res.status).toBe(200);
138138 const body = (await res.json()) as { runs: { duty: string; outcome: string }[] };
139139 expect(body.runs[0]).toMatchObject({ duty: "t-list", outcome: "ok" });
140 expect((await get(admin, "?limit=abc")).status).toBe(200);
140 expect((await get(admin, "?limit=abc")).status).toBe(422);
141 expect((await get(admin, "?limit=101")).status).toBe(422);
141142 });
142143
143144 test("a hung duty is recorded as timed out and the next duty still runs, without overlapping itself", async () => {
test/security-floor-errors.test.ts +7 −1
@@ -70,7 +70,13 @@ const tooBig = () => new Uint8Array(BODY_MAX + 1024);
7070 const PROVOKED = (): Provoke[] => [
7171 // 400
7272 { status: 400, side: "page", path: "/talk/stream?after=not-a-turn", signedIn: true, init: { headers: HTML } },
73 { status: 400, side: "api", path: "/api/v1/explore?cursor=not-a-cursor" },
73 {
74 status: 400,
75 side: "api",
76 path: "/api/v1/repos/ada/notes/issues",
77 signedIn: true,
78 init: { method: "POST", headers: { ...own(), "content-type": "application/json" }, body: "{not json" },
79 },
7480 // 401
7581 { status: 401, side: "page", path: "/talk/stream?after=x", init: { headers: HTML } },
7682 { status: 401, side: "api", path: "/api/v1/user" },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs