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

GET /openapi.json answers the description itself, not a 308 the caller must follow #13076

Merged opened this

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

Merged

scout/forge:scout/13071-get-openapi-json-answers-the-description → main 5 commits fork 1 thread · 1 unresolved

  • Merged. scout/13071-get-openapi-json-answers-the-description was merged into main as d889f9e.

Review

Sign in to review this change.
14 files changed +79 −71
docs/MCP.md +1 −1
@@ -663,7 +663,7 @@ answers
663663 and an owner, and that every verb names a tool or says why not. The 50 ms
664664 budget is held by a bounded statement count; the `here` phase is read from
665665 Server-Timing and bounded at the flake floor (`WALL_CLOCK_FLOOR_MS`).
666 - **Contract.** `GET /contract/openapi.json` (also `/openapi.json`, `/api/v1/openapi.json`; `servers` is the request's origin, bearer `token` is the default `security`, open routes say `security: []`) is OpenAPI 3.1 for the routes
666 - **Contract.** `GET /contract/openapi.json` (also `/openapi.json`, `/api/v1/openapi.json`, all three answer 200 with the document and an ETag, none redirects; `servers` is the request's origin, bearer `token` is the default `security`, open routes say `security: []`) is OpenAPI 3.1 for the routes
667667 the manifest (`here`) names, plus `POST /mcp`, cut to the caller's role: no credential sees only `x-role: anonymous`
668668 rows, a member's token or session adds `member`, a site admin sees `admin` too; each role gets its own ETag, and any
669669 answer but the anonymous one is `cache-control: private` (`vary: authorization, cookie`). It also describes planning: `GET …/map`, `POST …/plan`,
src/contract/openapi/routes/getApiV1OpenapiJson.ts +1 −2
@@ -3,8 +3,7 @@ import type { Route } from "../shared.ts";
33 export const route: Route = {
44 method: "get",
55 path: "/api/v1/openapi.json",
6 summary: "The address an agent tries first: answers 308 to /contract/openapi.json, this document",
6 summary: "The address an agent tries first: answers the same document as /contract/openapi.json",
77 auth: false,
88 role: "anonymous",
9 status: 308,
109 };
src/contract/openapi/routes/getContractOpenapiJson.ts +1 −1
@@ -1,3 +1,3 @@
11 import type { Route } from "../shared.ts";
22
3 export const route: Route = { method: "get", path: "/contract/openapi.json", summary: "This document: the OpenAPI 3.1 description of the forge's public API; /api/v1/openapi.json redirects here", auth: false, role: "anonymous" };
3 export const route: Route = { method: "get", path: "/contract/openapi.json", summary: "This document: the OpenAPI 3.1 description of the forge's public API; /openapi.json and /api/v1/openapi.json answer the same document", auth: false, role: "anonymous" };
src/contract/served.ts +33 −26
@@ -68,31 +68,38 @@ export function openapiSliceText(origin: string, version: string, tag: string, r
6868 return hit;
6969 }
7070
71 /**
72 * The document at its canonical path and at the root path an agent guesses;
73 * /api/v1/openapi.json shares the handler.
74 */
7175 export function openapiRoute(router: Router<Handler>): void {
72 router.add("GET", "/contract/openapi.json", (ctx) => {
73 const tag = ctx.url.searchParams.get("tag");
74 if (tag !== null && !TAGS.includes(tag)) {
75 return Response.json(
76 { error: "invalid_query", message: `unknown tag; the tags are ${TAGS.join(", ")}` },
77 { status: 400, headers: { "cache-control": "no-store" } },
78 );
79 }
80 const role = roleOf(ctx.auth);
81 const hit = tag === null ? openapiText(ctx.url.origin, running().version, role) : openapiSliceText(ctx.url.origin, running().version, tag, role);
82 // The document depends on who asks: a shared cache keeps only the anonymous one.
83 const headers = {
84 "cache-control": role === "anonymous" ? "public, max-age=300" : "private, max-age=300",
85 etag: hit.etag,
86 vary: "accept-encoding, authorization, cookie",
87 };
88 if (holds(ctx.request, hit.etag)) return new Response(null, { status: 304, headers });
89 const type = { "content-type": "application/json", ...headers };
90 // Encoded once per build at the slow, small level, not per request.
91 const encoding = negotiate(ctx.request.headers.get("accept-encoding"));
92 if (encoding !== null) {
93 const bytes = encodeOnce(hit.etag, new TextEncoder().encode(hit.text), encoding);
94 return new Response(bytes as Uint8Array<ArrayBuffer>, { headers: { ...type, "content-encoding": encoding } });
95 }
96 return new Response(hit.text, { headers: type });
97 });
76 router.add("GET", "/contract/openapi.json", openapiHandler);
77 router.add("GET", "/openapi.json", openapiHandler);
9878 }
79
80 export const openapiHandler: Handler = (ctx) => {
81 const tag = ctx.url.searchParams.get("tag");
82 if (tag !== null && !TAGS.includes(tag)) {
outdated

The exported handler body is still indented one level too deep (4 spaces) and the file ends with an extra blank line after };. Re-indent to 2 spaces and remove the trailing blank line.

83 return Response.json(
84 { error: "invalid_query", message: `unknown tag; the tags are ${TAGS.join(", ")}` },
85 { status: 400, headers: { "cache-control": "no-store" } },
86 );
87 }
88 const role = roleOf(ctx.auth);
89 const hit = tag === null ? openapiText(ctx.url.origin, running().version, role) : openapiSliceText(ctx.url.origin, running().version, tag, role);
90 // The document depends on who asks: a shared cache keeps only the anonymous one.
91 const headers = {
92 "cache-control": role === "anonymous" ? "public, max-age=300" : "private, max-age=300",
93 etag: hit.etag,
94 vary: "accept-encoding, authorization, cookie",
95 };
96 if (holds(ctx.request, hit.etag)) return new Response(null, { status: 304, headers });
97 const type = { "content-type": "application/json", ...headers };
98 // Encoded once per build at the slow, small level, not per request.
99 const encoding = negotiate(ctx.request.headers.get("accept-encoding"));
100 if (encoding !== null) {
101 const bytes = encodeOnce(hit.etag, new TextEncoder().encode(hit.text), encoding);
102 return new Response(bytes as Uint8Array<ArrayBuffer>, { headers: { ...type, "content-encoding": encoding } });
103 }
104 return new Response(hit.text, { headers: type });
105 };
src/http/api.ts +6 −13
@@ -8,6 +8,7 @@
88 * back to continue); errors are `{ error, message }`.
99 */
1010
11 import { openapiHandler } from "../contract/served.ts";
1112 import { CHECK_ASKED } from "../actions/pull_ask_words.ts";
1213 import { liveOf } from "../perf/live.ts";
1314 import { reviewWords } from "../actions/review_words.ts";
@@ -4051,19 +4052,11 @@ export function apiRoutes(router: Router<Handler>): void {
40514052 return timePhase(ctx.request, "render", () => json(graph));
40524053 });
40534054
4054 // The address an agent tries first.
4055 router.add(
4056 "GET",
4057 "/api/v1/openapi.json",
4058 () =>
4059 new Response(null, {
4060 status: 308,
4061 headers: {
4062 location: "/contract/openapi.json",
4063 "cache-control": "public, max-age=86400",
4064 },
4065 }),
4066 );
4055 // The address an agent tries first: the document itself, as /contract/openapi.json answers it.
4056 router.add("GET", "/api/v1/openapi.json", (ctx) => {
4057 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
4058 return openapiHandler(ctx);
4059 });
40674060 // What the caller can do on a forge page, as who they are (#604): the
40684061 // manifest every page links to. It differs by caller, so it is never cached.
40694062 router.add("GET", "/api/v1/here", (ctx) => {
src/http/server.ts −6
@@ -838,12 +838,6 @@ export function buildRouter(): Router<Handler> {
838838 router.add("GET", "/agents", agentsPage);
839839 router.add("GET", "/.well-known/change-password", changePassword);
840840 router.add("GET", "/robots.txt", robotsTxt);
841 // The conventional path an agent guesses, answered as /api/v1/openapi.json is.
842 router.add(
843 "GET",
844 "/openapi.json",
845 () => new Response(null, { status: 308, headers: { location: "/contract/openapi.json", "cache-control": "public, max-age=86400" } }),
846 );
847841 router.add("GET", "/releases.json", releasesJson);
848842 router.add("GET", "/sitemap.xml", sitemapXml);
849843 router.add("GET", "/manifest.webmanifest", webManifest);
test/mcp.test.ts +4 −5
@@ -1624,13 +1624,12 @@ describe("the forge over MCP", () => {
16241624 expect(doc.paths[`${R}/pulls/{number}/labels`].put).toBeDefined();
16251625 expect(doc.paths[`${R}/issues/{number}/private`].post.responses["201"]).toBeDefined();
16261626 });
1627 test("GET /api/v1/openapi.json redirects to the document", async () => {
1627 test("GET /api/v1/openapi.json answers the document itself", async () => {
16281628 const res = await fetch(`${base}/api/v1/openapi.json`, { redirect: "manual" });
1629 expect(res.status).toBe(308);
1630 expect(res.headers.get("location")).toBe("/contract/openapi.json");
1629 expect(res.status).toBe(200);
1630 expect(res.headers.get("location")).toBeNull();
16311631 expect(res.headers.get("cache-control")).toContain("public");
1632 const target = await fetch(new URL(res.headers.get("location")!, base));
1633 expect(target.status).toBe(200);
1632 expect(res.headers.get("etag")).toBeTruthy();
16341633 });
16351634 test("feed_chips reads and switches the chips the feed answers through", async () => {
16361635 app.bus.append({ kind: "app.serving", repoId: game.id, actorId: alice.id, payload: {} });
test/openapi-selfopen.test.ts +4 −4
@@ -57,15 +57,15 @@ test("each path and method is in the served document", async () => {
5757 const res = await adminOpenapi(app, servers.url, "/contract/openapi.json");
5858 const paths = ((await res.json()) as any).paths;
5959 for (const [method, path] of WANT) expect(paths[path]?.[method]).toBeDefined();
60 expect(paths["/api/v1/openapi.json"].get.responses["308"]).toBeDefined();
60 expect(paths["/api/v1/openapi.json"].get.responses["200"]).toBeDefined();
6161 expect(paths["/api/v1/migrate"].post.responses["202"]).toBeDefined();
6262 expect(paths["/api/v1/migrate/{job}/stream"].get.summary).toContain("event stream");
6363 });
6464
65 test("the redirect to the document is a 308", async () => {
65 test("the old address answers the document, not a redirect", async () => {
6666 const res = await call("/api/v1/openapi.json");
67 expect(res.status).toBe(308);
68 expect(res.headers.get("location")).toBe("/contract/openapi.json");
67 expect(res.status).toBe(200);
68 expect(res.headers.get("location")).toBeNull();
6969 });
7070
7171 test("a bad source and a bad after answer the codes the rows name", async () => {
test/root-openapi.test.ts +23 −6
@@ -1,4 +1,4 @@
1 /** #8330: /openapi.json at the root redirects to the contract, as /api/v1/openapi.json does. */
1 /** #13071: the guessed paths answer the description itself, not a 308 the caller must follow. */
22 import { afterAll, beforeAll, expect, test } from "bun:test";
33 import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
@@ -18,10 +18,27 @@ afterAll(async () => {
1818 await rm(dataDir, { recursive: true, force: true });
1919 });
2020
21 test("GET and HEAD /openapi.json answer 308 to the contract", async () => {
22 for (const method of ["GET", "HEAD"]) {
23 const res = await fetch(`${servers.url}/openapi.json`, { method, redirect: "manual" });
24 expect(res.status).toBe(308);
25 expect(res.headers.get("location")).toBe("/contract/openapi.json");
21 test("every path answers 200 with the same document, an ETag and no redirect; every operation has an operationId", async () => {
22 let canonical = "";
23 for (const path of ["/contract/openapi.json", "/openapi.json", "/api/v1/openapi.json"]) {
24 const res = await fetch(`${servers.url}${path}`, { redirect: "manual" });
25 expect(res.status).toBe(200);
26 expect(res.headers.get("location")).toBeNull();
27 expect(res.headers.get("etag")).toBeTruthy();
28 const text = await res.text();
29 if (canonical === "") canonical = text;
30 expect(text).toBe(canonical);
31 const doc = JSON.parse(text) as { openapi: string; paths: Record<string, Record<string, { operationId?: string }>> };
32 expect(doc.openapi).toStartWith("3.1");
33 for (const [p, ops] of Object.entries(doc.paths))
34 for (const [method, op] of Object.entries(ops)) expect(`${method} ${p} ${op.operationId ?? ""}`).toMatch(/ \S+$/);
2635 }
2736 });
37
38 test("HEAD answers 200 too, and a matching If-None-Match answers 304", async () => {
39 const head = await fetch(`${servers.url}/openapi.json`, { method: "HEAD", redirect: "manual" });
40 expect(head.status).toBe(200);
41 const etag = head.headers.get("etag")!;
42 const again = await fetch(`${servers.url}/openapi.json`, { headers: { "if-none-match": etag }, redirect: "manual" });
43 expect(again.status).toBe(304);
44 });
test/run-gate-doors.test.ts +1 −1
@@ -159,7 +159,7 @@ describe("the run gate's closed doors", () => {
159159 test("here, search, explore and openapi.json answer, and search names nothing outside the two repositories", async () => {
160160 for (const path of ["/api/v1/here?path=/alice/upstream-work", "/api/v1/search?q=upstream", "/api/v1/explore"])
161161 expect((await call(path)).status).toBe(200);
162 expect((await call("/api/v1/openapi.json")).status).toBe(308);
162 expect((await call("/api/v1/openapi.json")).status).toBe(200);
163163 for (const q of ["vault", "mine", "unique-vault", "unique-mine"]) {
164164 const res = await call(`/api/v1/search?q=${q}`);
165165 expect(res.status).toBe(200);
test/run-token.test.ts +2 −2
@@ -226,8 +226,8 @@ describe("a run token", () => {
226226 expect((await text(`/api/v1/here?path=${path}`)).status).toBe(404);
227227
228228 const open = await api("/api/v1/openapi.json", { redirect: "manual" });
229 expect(open.status).toBe(308);
230 expect(open.headers.get("location")).toBe("/contract/openapi.json");
229 expect(open.status).toBe(200);
230 expect(open.headers.get("location")).toBeNull();
231231
232232 const mine = await text("/api/v1/search?q=gods-eye");
233233 expect(mine.status).toBe(200);
test/security-floor-every-route.test.ts +1 −1
@@ -109,7 +109,7 @@ const SAMPLES: Sample[] = [
109109 body: "name=x",
110110 },
111111 },
112 { kind: "redirect", path: "/openapi.json", status: 308 },
112 { kind: "the API description at the guessed path", path: "/openapi.json", status: 200 },
113113 { kind: "OPTIONS, answered as no route", path: "/api/v1", status: 404, init: { method: "OPTIONS" } },
114114 { kind: "liveness probe", path: "/healthz", status: 200 },
115115 { kind: "readiness probe", path: "/readyz", status: 200 },
test/server-timing-sweep.test.ts −1
@@ -50,7 +50,6 @@ const REDIRECTS = new Set([
5050 "/big",
5151 "/home",
5252 "/login",
53 "/openapi.json",
5453 "/settings/origins/callback",
5554 "/settings/resilience",
5655 "/sign-in",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs