From 767852ef96ed3d2fc818217fc868b93fe108a275 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:37:13 +0000 Subject: [PATCH] WIP t10: inflate cap, consent_text_missing before claim, scope caps, revocation FK Tests green locally; mutants not yet run; not pushed; PR body not updated. Co-Authored-By: Claude Sonnet 5.5 --- src/app.ts | 55 ++++++++++++++++++++-------- src/store/in-memory.ts | 4 +++ src/store/schema.ts | 10 ++++-- tests/joystick-consent.test.ts | 66 +++++++++++++++++++++++++++++++--- tests/store.test.ts | 17 +++++++-- 5 files changed, 127 insertions(+), 25 deletions(-) diff --git a/src/app.ts b/src/app.ts index bb5c4d9..f4a48e5 100644 --- a/src/app.ts +++ b/src/app.ts @@ -272,6 +272,14 @@ function signOAuthBinding( const consentAskType = "heimdall_consent_ask"; +/** The most wording a cookie may carry, before and after compression. The ask refuses what exceeds it; the readers never inflate past it. */ +const maxConsentTextBytes = 16 * 1024; +/** Browsers drop a cookie above 4096 bytes; the ask refuses one it could not keep. */ +const maxConsentCookieChars = 3800; +/** What an app may request: more is not a scope list a person can read. */ +const maxRequestedScopes = 32; +const maxRequestedScopeChars = 512; + function consentAskCookieName(jti: string): string { return `__Host-heimdall-ask-${jti}`; } @@ -305,7 +313,7 @@ function cookieConsentText( return null; } try { - return inflateRawSync(Buffer.from(ct, "base64url")).toString("utf8"); + return inflateRawSync(Buffer.from(ct, "base64url"), { maxOutputLength: maxConsentTextBytes }).toString("utf8"); } catch { return null; } @@ -746,6 +754,16 @@ export async function startOAuthFlow( return { statusCode: 400, body: { error: "initiator_only_in_link_mode" } }; } + if ( + input.requestedScopes !== undefined && + (input.requestedScopes.length > maxRequestedScopes || input.requestedScopes.some((scope) => scope.length > maxRequestedScopeChars)) + ) { + return { + statusCode: 400, + body: { error: "requested_scopes_too_large", detail: `At most ${maxRequestedScopes} scopes of ${maxRequestedScopeChars} characters each.` }, + }; + } + if (!isAllowedReturnOrigin(profile, input.returnTo)) { return { statusCode: 400, @@ -1221,7 +1239,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { reply.code(400); const profile = getAppProfile(state.app_slug); @@ -1385,7 +1403,15 @@ export async function buildApp(options: BuildAppOptions = {}): Promise maxConsentTextBytes || askCookie.length > maxConsentCookieChars) { + reply.code(400); + return { error: "consent_ask_too_large" }; + } + setConsentAskCookie(reply, state, askCookie, state.exp - nowEpochSeconds()); reply.header("Cache-Control", "no-store"); reply.header("Referrer-Policy", "no-referrer"); reply.header("X-Frame-Options", "DENY"); @@ -1507,6 +1533,17 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { if (input.kind === "revocation") { + // The table's foreign key: a revocation names a receipt of the same account. + if (!this.consentReceipts.some((r) => r.id === input.revokesReceiptId && r.accountId === input.accountId)) { + throw new Error("A revocation must name a receipt of its own account."); + } const existing = this.consentReceipts.find((r) => r.kind === "revocation" && r.revokesReceiptId === input.revokesReceiptId); if (existing) return { receipt: clone(existing), created: false }; } diff --git a/src/store/schema.ts b/src/store/schema.ts index 71a4a43..294ee2d 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -193,10 +193,14 @@ CREATE TABLE IF NOT EXISTS consent_receipts ( scopes_granted TEXT, consent_page_digest TEXT, consent_text TEXT, - revokes_receipt_id TEXT + revokes_receipt_id TEXT, + UNIQUE(id, account_id), + FOREIGN KEY (revokes_receipt_id, account_id) REFERENCES consent_receipts(id, account_id) ); --- A grant is taken back once: the second revocation naming it conflicts. +-- A revocation names a receipt of its own account (the composite foreign key; +-- NULL skips it for grants). A grant is taken back once: the second +-- revocation naming it conflicts. CREATE UNIQUE INDEX IF NOT EXISTS consent_receipts_revokes_unique_idx ON consent_receipts(revokes_receipt_id) WHERE revokes_receipt_id IS NOT NULL; @@ -265,7 +269,7 @@ export const REQUIRED_TABLES = createdTables.map(({ table }) => table); export const REQUIRED_COLUMNS = [ ...createdTables.flatMap(({ table, lines }) => lines - .filter((line) => !/^(?:PRIMARY KEY|UNIQUE)\b/.test(line)) + .filter((line) => !/^(?:PRIMARY KEY|UNIQUE|FOREIGN KEY)\b/.test(line)) .map((line) => { const [, column, type] = /^(\w+) (\w+)/.exec(line)!; return { table, column: column!, type: type!, nullable: !/\b(?:NOT NULL|PRIMARY KEY)\b/.test(line) }; diff --git a/tests/joystick-consent.test.ts b/tests/joystick-consent.test.ts index e227522..5dd9ead 100644 --- a/tests/joystick-consent.test.ts +++ b/tests/joystick-consent.test.ts @@ -1,4 +1,5 @@ -import { createHash } from "node:crypto"; +import { createHash, randomBytes } from "node:crypto"; +import { deflateRawSync } from "node:zlib"; import { afterEach, describe, expect, it, vi } from "vitest"; import { type FastifyInstance } from "fastify"; import { buildApp, getHeimdallRuntimeContext } from "../src/app.js"; @@ -197,17 +198,72 @@ describe("the ask", () => { expect(bindingCookieOf(go)!.length).toBeLessThan(3500); }); - it("a managed connection that never passed through the ask completes nothing and leaves no receipt", async () => { + it("a binding without the shown wording is refused with consent_text_missing before the state is spent", async () => { const { app, store } = await newApp(); const ctx = getHeimdallRuntimeContext(app); const state = await startConnect(app); const { jti, exp } = decodeJwt(state).payload as { jti: string; exp: number }; - // A binding that names this state but carries no wording: what any launch outside the ask would leave. + // A binding that names this state but carries no wording: what a launch from before the ask would leave. const bare = signJwt({ typ: "heimdall_oauth_binding", iss: ctx.config.issuer, jti, iat: exp - 600, exp }, ctx.keys); const done = await callback(app, state, `__Host-heimdall-oauth-${jti}=${bare}`, "code=code-a"); - expect(done.statusCode).not.toBe(201); - expect(done.json()).not.toHaveProperty("consentReceiptId"); + expect(done.statusCode).toBe(400); + expect(done.json()).toEqual({ error: "consent_text_missing" }); expect(await store.findStoredLinkedIdentity("joystick", "joy-a"), "no credential is kept").toBeNull(); + // Neither use of the state was spent by the refusal. + const usedAt = new Date().toISOString(); + const expiresAt = new Date(exp * 1000).toISOString(); + expect(await store.claimOAuthStateUse({ jti, phase: "callback", appSlug: "streampixels", usedAt, expiresAt })).toBe(true); + }); + + describe("the wording a cookie may carry", () => { + const signedAsk = (ctx: ReturnType, jti: string, exp: number, text: Buffer) => + signJwt({ typ: "heimdall_consent_ask", iss: ctx.config.issuer, jti, iat: exp - 600, exp, ct: deflateRawSync(text).toString("base64url") }, ctx.keys); + + it("is read up to 16 KB and no further: one byte over is refused, and a bomb is refused quickly", async () => { + const { app } = await newApp(); + const ctx = getHeimdallRuntimeContext(app); + const state = await startConnect(app); + const { jti, exp } = decodeJwt(state).payload as { jti: string; exp: number }; + const answerWith = (text: Buffer, decision: "decline" | "continue" = "decline") => + answer(app, state, decision, `__Host-heimdall-ask-${jti}=${signedAsk(ctx, jti, exp, text)}`, "application/json"); + expect((await answerWith(Buffer.alloc(16 * 1024 + 1, 97))).json()).toEqual({ error: "state_not_bound" }); + const t0 = Date.now(); + expect((await answerWith(Buffer.alloc(300 * 1024 * 1024))).json()).toEqual({ error: "state_not_bound" }); + expect(Date.now() - t0).toBeLessThan(1500); + // At the cap it is read. + expect((await answerWith(Buffer.alloc(16 * 1024, 97))).json()).toMatchObject({ error: "consent_refused" }); + }); + + it("requested scopes are capped at 32 of 512 characters, at start", async () => { + const { app } = await newApp(); + const startWith = (requestedScopes: string[]) => + app.inject({ + method: "POST", + url: "/v1/oauth/joystick/start", + headers: secret, + payload: { appSlug: "streampixels", mode: "connect", connection: { kind: "creator", targetId: "c" }, returnTo: "https://streampixels.gamecult.org/s", handoff: { kind: "browser_completion" }, requestedScopes }, + }); + const scopes = (n: number, len: number) => Array.from({ length: n }, (_, i) => `${i}`.padEnd(len, "x")); + expect((await startWith(scopes(33, 10))).json()).toMatchObject({ error: "requested_scopes_too_large" }); + expect((await startWith(scopes(1, 513))).json()).toMatchObject({ error: "requested_scopes_too_large" }); + expect((await startWith(scopes(32, 512))).statusCode).toBe(201); + }); + + it("an ask the cookies could not carry is refused, not shown", async () => { + const { app } = await newApp(); + const noise = Array.from({ length: 32 }, () => randomBytes(256).toString("hex")); // 32 x 512 incompressible + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/joystick/start", + headers: secret, + payload: { appSlug: "streampixels", mode: "connect", connection: { kind: "creator", targetId: "c" }, returnTo: "https://streampixels.gamecult.org/s", handoff: { kind: "browser_completion" }, requestedScopes: noise }, + }); + expect(start.statusCode).toBe(201); + const page = await app.inject({ method: "GET", url: launchUrl(stateOf(start.json())), headers: { accept: "text/html" } }); + expect(page.statusCode).toBe(400); + expect(page.json()).toEqual({ error: "consent_ask_too_large" }); + expect(askCookieOf(page)).toBeUndefined(); + }); }); it("the consent route refuses a flow that has no ask", async () => { diff --git a/tests/store.test.ts b/tests/store.test.ts index ddec729..b107197 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -14,7 +14,7 @@ import { samePredicate, STORE_TABLE_PRIVILEGES, } from "../src/store/postgres.js"; -import { REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "../src/store/schema.js"; +import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "../src/store/schema.js"; describe("PostgresStore", () => { it("round-trips core auth records through postgres", async () => { @@ -198,6 +198,18 @@ describe("PostgresStore", () => { }); }); +describe("consent_receipts foreign key", () => { + it("a revocation names a receipt of its own account: the schema says so and the memory store enforces it", async () => { + expect(CREATE_SCHEMA_SQL).toContain("FOREIGN KEY (revokes_receipt_id, account_id) REFERENCES consent_receipts(id, account_id)"); + const store = new InMemoryStore(); + const base = { appSlug: "streampixels" as const, provider: "joystick" as const, createdAt: "2026-11-08T00:00:00.000Z" }; + const { receipt: grant } = await store.createConsentReceipt({ ...base, accountId: "a", kind: "grant", scopesAsked: [], scopesGranted: [], consentPageDigest: "d", consentText: "t" }); + await expect(store.createConsentReceipt({ ...base, accountId: "b", kind: "revocation", revokesReceiptId: grant.id })).rejects.toThrow(/own account/); + await expect(store.createConsentReceipt({ ...base, accountId: "a", kind: "revocation", revokesReceiptId: "no-such" })).rejects.toThrow(/own account/); + expect(await store.listConsentReceipts("a")).toHaveLength(1); + }); +}); + describe("InMemoryStore.createConsentReceipt", () => { it("writes one revocation per grant: the second names the first and is not created", async () => { const store = new InMemoryStore(); @@ -297,13 +309,14 @@ describe("PostgresStore.checkSchema", () => { { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, ]) ); - expect(REQUIRED_KEYS).toHaveLength(16); + expect(REQUIRED_KEYS).toHaveLength(17); expect(REQUIRED_KEYS).toEqual( expect.arrayContaining([ { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, { table: "private_command_receipts", columns: "app_slug,idempotency_key", predicate: "" }, { table: "oauth_state_uses", columns: "jti,phase", predicate: "" }, { table: "consent_receipts", columns: "revokes_receipt_id", predicate: "revokes_receipt_id IS NOT NULL" }, + { table: "consent_receipts", columns: "account_id,id", predicate: "" }, { table: "entitlement_snapshots", columns: "account_id,provider,scope", predicate: "" }, { table: "auth_completions", columns: "app_slug,attempt_id", predicate: "attempt_id IS NOT NULL AND consumed_at IS NULL" }, ])