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 <noreply@anthropic.com>
This commit is contained in:
parent
5ce8f1c14c
commit
767852ef96
5 changed files with 127 additions and 25 deletions
55
src/app.ts
55
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<FastifyIn
|
|||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
state: OAuthStatePayload,
|
||||
error: "state_not_bound" | "state_already_launched" | "state_already_used"
|
||||
error: "state_not_bound" | "state_already_launched" | "state_already_used" | "consent_text_missing"
|
||||
) => {
|
||||
reply.code(400);
|
||||
const profile = getAppProfile(state.app_slug);
|
||||
|
|
@ -1385,7 +1403,15 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
// the page so that the form's answer can only come from the browser
|
||||
// that was shown it, and carries the text it was shown.
|
||||
const ask = consentAskFor(state);
|
||||
setConsentAskCookie(reply, state, signConsentAsk(config, keys, state, consentText(ask)), state.exp - nowEpochSeconds());
|
||||
const shown = consentText(ask);
|
||||
const askCookie = signConsentAsk(config, keys, state, shown);
|
||||
// An ask the cookies cannot carry is refused, not shown: the person
|
||||
// could press Continue and nothing would bind.
|
||||
if (Buffer.byteLength(shown, "utf8") > 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<FastifyIn
|
|||
await denyBrowserAttempt("state_not_bound");
|
||||
return refuseVerifiedState(request, reply, statePayload, "state_not_bound");
|
||||
}
|
||||
// A custody flow carries the wording its person was shown in the launch
|
||||
// binding. A binding without it did not pass through the ask (a launch
|
||||
// from before it existed): refuse here, before the state is spent and
|
||||
// before any code is exchanged, so nothing is kept and nothing is burned.
|
||||
const shownText = cookieConsentText(config, keys, request.cookies[oauthBindingCookieName(statePayload.jti)], oauthBindingType, statePayload);
|
||||
const callbackProfile = getAppProfile(statePayload.app_slug);
|
||||
const mint = callbackProfile ? callbackMint(callbackProfile, request.params.provider, statePayload.mode, statePayload.connection) : "refused";
|
||||
if (mint === "custody_only" && shownText === null) {
|
||||
await denyBrowserAttempt("consent_text_missing");
|
||||
return refuseVerifiedState(request, reply, statePayload, "consent_text_missing");
|
||||
}
|
||||
setOAuthBindingCookie(reply, statePayload, "", 0);
|
||||
const firstCallback = await store.claimOAuthStateUse({
|
||||
jti: statePayload.jti,
|
||||
|
|
@ -1614,21 +1651,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
const runtime = oauthRuntimes[request.params.provider];
|
||||
|
||||
try {
|
||||
const callbackProfile = getAppProfile(statePayload.app_slug);
|
||||
const mint = callbackProfile ? callbackMint(callbackProfile, request.params.provider, statePayload.mode, statePayload.connection) : "refused";
|
||||
if (mint === "refused") {
|
||||
throw new Error("The signed state names a mode the provider has no role for in this app.");
|
||||
}
|
||||
// The text the person was shown rode in the launch binding. A custody
|
||||
// flow that did not pass through the ask has none: it exchanges no code
|
||||
// and stores no credential.
|
||||
const shownText =
|
||||
mint === "custody_only"
|
||||
? cookieConsentText(config, keys, request.cookies[oauthBindingCookieName(statePayload.jti)], oauthBindingType, statePayload)
|
||||
: null;
|
||||
if (mint === "custody_only" && shownText === null) {
|
||||
throw new Error("A managed connection completed without the consent text the person was shown.");
|
||||
}
|
||||
const callbackDescriptor = providerCatalog[request.params.provider];
|
||||
const oidc = callbackDescriptor.oidc ? deriveOidcSecrets(statePayload.jti, keys.privateKey) : undefined;
|
||||
const tokenSet = await runtime.exchangeAuthorizationCode({
|
||||
|
|
|
|||
|
|
@ -488,6 +488,10 @@ export class InMemoryStore implements HeimdallStore {
|
|||
|
||||
async createConsentReceipt(input: CreateConsentReceiptInput): Promise<{ receipt: StoredConsentReceipt; created: boolean }> {
|
||||
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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) };
|
||||
|
|
|
|||
|
|
@ -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<typeof getHeimdallRuntimeContext>, 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 () => {
|
||||
|
|
|
|||
|
|
@ -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" },
|
||||
])
|
||||
|
|
|
|||
Loading…
Reference in a new issue