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

small: the OAuth discovery documents answer a repeat fetch with 304, like /.well-known/mcp and /openapi.json do #15923

Merged opened this

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

Merged

torque/forge:torque/15922-small-the-oauth-discovery-documents-answ → main 0 commits fork

  • Merged. torque/15922-small-the-oauth-discovery-documents-answ was merged into main as 799e6da.

Review

Sign in to review this change.
2 files changed +40 −10
src/http/oauth.ts +19 −10
@@ -21,9 +21,10 @@ import {
2121 import { jwks, OIDC_SCOPES, userinfo } from "../core/oidc.ts";
2222 import { RateLimiter } from "../core/ratelimit.ts";
2323 import type { Handler } from "./context.ts";
24 import { requestHolds } from "./conditional.ts";
2425 import { clientBucket } from "./peer.ts";
2526 import { readBounded } from "./limits.ts";
26 import { boundedBody, json, retryAfterOf, tryAgain } from "./respond.ts";
27 import { boundedBody, json, retryAfterOf, securityFloor, tryAgain } from "./respond.ts";
2728 import type { Router } from "./router.ts";
2829 import { bearerSecret } from "./token_header.ts";
2930 import { authorizePage, authorizeSubmit } from "../web/pages/oauth.ts";
@@ -78,6 +79,18 @@ export const bearerChallenge = (origin: string, request?: Request): string => {
7879 const open = { "access-control-allow-origin": "*" };
7980 const docHeaders = { ...open, "cache-control": "public, max-age=300" };
8081
82 /**
83 * A discovery document with a strong etag of its own body (the body embeds the
84 * request origin, so the tag is taken from it, never constant). A matching
85 * `If-None-Match` is a 304 with no body and the same headers.
86 */
87 function tagged(request: Request, doc: unknown): Response {
88 const etag = `"${new Bun.CryptoHasher("sha256").update(JSON.stringify(doc)).digest("hex").slice(0, 32)}"`;
89 const headers = { ...docHeaders, etag };
90 if (requestHolds(request, etag)) return securityFloor(new Response(null, { status: 304, headers }));
91 return json(doc, 200, headers);
92 }
93
8194 const noStore = { ...open, "cache-control": "no-store", pragma: "no-cache" };
8295 const grantError = (error: string, status = 400) =>
8396 json({ error }, status, noStore);
@@ -187,8 +200,8 @@ export function oauthRoutes(router: Router<Handler>): void {
187200 router.add("GET", "/oauth/userinfo", userinfoRoute);
188201 router.add("POST", "/oauth/userinfo", userinfoRoute);
189202 router.add("GET", "/.well-known/openid-configuration", (ctx) =>
190 json(
191 {
203 tagged(
204 ctx.request, {
192205 issuer: ctx.url.origin,
193206 authorization_endpoint: `${ctx.url.origin}${OAUTH_ENDPOINTS.authorize}`,
194207 token_endpoint: `${ctx.url.origin}${OAUTH_ENDPOINTS.token}`,
@@ -206,16 +219,14 @@ export function oauthRoutes(router: Router<Handler>): void {
206219 revocation_endpoint_auth_methods_supported: ["none"],
207220 claims_supported: ["sub", "iss", "aud", "exp", "iat", "nonce", "name", "preferred_username", "email", "email_verified"],
208221 },
209 200,
210 docHeaders,
211222 ),
212223 );
213224 router.add("GET", "/.well-known/oauth-protected-resource", (ctx) =>
214 json(protectedResource(ctx.url.origin, OAUTH_SCOPES), 200, docHeaders),
225 tagged(ctx.request, protectedResource(ctx.url.origin, OAUTH_SCOPES)),
215226 );
216227 router.add("GET", "/.well-known/oauth-authorization-server", (ctx) =>
217 json(
218 {
228 tagged(
229 ctx.request, {
219230 issuer: ctx.url.origin,
220231 authorization_endpoint: `${ctx.url.origin}${OAUTH_ENDPOINTS.authorize}`,
221232 token_endpoint: `${ctx.url.origin}${OAUTH_ENDPOINTS.token}`,
@@ -228,8 +239,6 @@ export function oauthRoutes(router: Router<Handler>): void {
228239 token_endpoint_auth_methods_supported: ["none"],
229240 revocation_endpoint_auth_methods_supported: ["none"],
230241 },
231 200,
232 docHeaders,
233242 ),
234243 );
235244 router.add("POST", "/oauth/register", async (ctx) => {
test/oauth-discovery.test.ts +21
@@ -195,4 +195,25 @@ describe("oauth discovery and registration", () => {
195195 expect(doc.keys[0]).toMatchObject({ kty: "EC", crv: "P-256", alg: "ES256", use: "sig" });
196196 expect(doc.keys[0].d).toBeUndefined();
197197 });
198
199 test("the discovery documents carry a strong etag and answer a repeat with 304", async () => {
200 for (const path of ["/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource"]) {
201 const first = await fetch(`${base}${path}`);
202 const etag = first.headers.get("etag") ?? "";
203 expect(etag).toMatch(/^"[0-9a-f]+"$/);
204 expect(first.headers.get("cache-control")).toBe("public, max-age=300");
205 await first.text();
206 const again = await fetch(`${base}${path}`, { headers: { "if-none-match": etag } });
207 expect(again.status).toBe(304);
208 expect(await again.text()).toBe("");
209 expect(again.headers.get("x-content-type-options")).toBe("nosniff");
210 expect(again.headers.get("cache-control")).toBe("public, max-age=300");
211 const stale = await fetch(`${base}${path}`, { headers: { "if-none-match": '"other"' } });
212 expect(stale.status).toBe(200);
213 // The body embeds the origin, so another origin is another tag.
214 const other = await fetch(`${base.replace("localhost", "127.0.0.1")}${path}`);
215 expect(other.status).toBe(200);
216 expect(other.headers.get("etag")).not.toBe(etag);
217 }
218 });
198219 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs