diff --git a/src/app-profiles.ts b/src/app-profiles.ts index 34400cc..8b6a86c 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -286,14 +286,11 @@ export function isAllowedReturnOrigin(profile: AppProfile, returnTo: string): bo } /** - * A connection target names something: at least one letter or number that is - * not a default-ignorable code point (the Hangul and Khmer fillers are letters - * that render as nothing). An allowlist, so marks, private-use, unassigned and - * surrogate code points and symbols cannot stand in for a name. The one - * definition the start gate and the callback mint both use. + * A connection target names something: non-empty after trimming whitespace. + * The one definition the start gate and the callback mint both use. */ export function isUsableConnectionTarget(targetId: string): boolean { - return /(?![\p{Default_Ignorable_Code_Point}])[\p{L}\p{N}]/u.test(targetId); + return targetId.trim().length > 0; } /** diff --git a/src/app.ts b/src/app.ts index f43dc73..9492f74 100644 --- a/src/app.ts +++ b/src/app.ts @@ -25,7 +25,6 @@ import { type Provider, } from "./contracts.js"; import { issueAccessClaim, proofCovers, proofTier, signAssertedStepUpClaim, STEP_UP_PROOF_TTL_SECONDS, type IssueAccessClaimInput } from "./claims.js"; -import { FixedWindowBudget, type FixedWindowLimit } from "./fixed-window.js"; import { builtInAppProfiles, getAppProfile, isAllowedReturnOrigin, serializeAppProfile, admitsProviderForMode, callbackMint, isUsableConnectionTarget } from "./app-profiles.js"; import { renderBrowserHandoffPage } from "./browser-handoff.js"; import { consentText, digestOfText, grantViews, GRANTS_PATH, renderConsentPage, renderGrantsPage, type ConsentAsk } from "./consent.js"; @@ -974,43 +973,16 @@ async function resolveAccessAccount( return (await resolveBearer(ctx, authorization))?.accountId ?? null; } -/** What an app may spend asserting step-up proofs: per member account, and per calling app. */ -export const STEP_UP_ASSERT_LIMITS: { account: FixedWindowLimit; app: FixedWindowLimit; notPermitted: FixedWindowLimit } = { - account: { max: 10, windowMs: 600_000 }, - app: { max: 120, windowMs: 60_000 }, - // An app whose profile has no grant, holding its own secret: a handful of refusals per window, no more. - notPermitted: { max: 5, windowMs: 60_000 }, -}; - -export interface StepUpAssertBudgets { - account: FixedWindowBudget; - app: FixedWindowBudget; - notPermitted: FixedWindowBudget; -} - -export function createStepUpAssertBudgets(now: () => number = () => Date.now()): StepUpAssertBudgets { - return { - account: new FixedWindowBudget(STEP_UP_ASSERT_LIMITS.account, now), - app: new FixedWindowBudget(STEP_UP_ASSERT_LIMITS.app, now), - notPermitted: new FixedWindowBudget(STEP_UP_ASSERT_LIMITS.notPermitted, now), - }; -} - /** * POST /v1/apps/{app}/step-up. The app says its member just passed a factor * the app checked; Heimdall cannot see the factor, so the word is bounded by * what the route demands: the app's secret AND the member's live bearer for - * that same app, the profile's explicit grant and method allowlist, a nonce - * spent once per session, and a rate per account and per app. Every - * refusal after the secret verified is recorded, except that a flood is not: - * a rate-limited refusal is recorded once per window per budget (its first), - * and an app without the grant is recorded once per window; a request without - * the secret writes nothing, since anyone can send one. The audit rows carry a digest of - * the nonce, never the nonce, the bearer or the secret. + * that same app, the profile's explicit grant and method allowlist, and a nonce + * spent once per session. Every refusal after the secret verifies is audited + * with a digest of the nonce, never the nonce, the bearer or the secret. */ export async function assertStepUp( ctx: Pick, - budgets: StepUpAssertBudgets, appSlug: AppSlug, headers: Record, input: { method: string; nonce: string } @@ -1022,31 +994,25 @@ export async function assertStepUp( const permitted = getAppProfile(appSlug)?.stepUpAssertion; let known: { accountId: string; sessionId: string } | undefined; let nonceDigest: string | undefined; - let tripped: string | undefined; - const refuse = async (statusCode: number, error: string, extra: Record = {}, record = true): Promise => { - if (!record) return { statusCode, body: { error, ...extra } }; + const refuse = async (statusCode: number, error: string, extra: Record = {}): Promise => { await store.createAuditEvent({ ...(known ? { accountId: known.accountId, sessionId: known.sessionId } : {}), appSlug, eventType: "step_up_assertion_refused", - eventPayloadJson: { outcome: "refused", code: error, budget: tripped ?? null, method: permitted?.methods.includes(input.method) ? input.method : null, nonceDigest: nonceDigest ?? null }, + eventPayloadJson: { + outcome: "refused", + code: error, + method: permitted?.methods.includes(input.method) ? input.method : null, + nonceDigest: nonceDigest ?? null, + }, createdAt: new Date().toISOString(), }); return { statusCode, body: { error, ...extra } }; }; - // Audit only the first denial of a window: the rows record that a budget tripped, not every request behind it. - const limited = (budget: string, spent: { n: number; retryAfterSeconds: number }, max: number) => { - tripped = budget; - return refuse(429, "step_up_rate_limited", { retryAfterSeconds: spent.retryAfterSeconds }, spent.n === max + 1); - }; if (!permitted) { - const spent = budgets.notPermitted.spend(appSlug); - if (spent.retryAfterSeconds) return limited("notPermitted", spent, STEP_UP_ASSERT_LIMITS.notPermitted.max); - return refuse(403, "step_up_assertion_not_permitted", { detail: `${appSlug} may not assert step-up proofs.` }, spent.n === 1); + return refuse(403, "step_up_assertion_not_permitted", { detail: `${appSlug} may not assert step-up proofs.` }); } - const appSpent = budgets.app.spend(appSlug); - if (appSpent.retryAfterSeconds) return limited("app", appSpent, STEP_UP_ASSERT_LIMITS.app.max); const bearer = await resolveBearer(ctx, headers.authorization as string | undefined); if (!bearer) { @@ -1057,8 +1023,6 @@ export async function assertStepUp( if (bearer.claims.aud !== appSlug) { return refuse(403, "bearer_app_mismatch", { detail: `The access token was not issued to ${appSlug}.` }); } - const accountSpent = budgets.account.spend(bearer.accountId); - if (accountSpent.retryAfterSeconds) return limited("account", accountSpent, STEP_UP_ASSERT_LIMITS.account.max); nonceDigest = createHash("sha256").update(`heimdall-step-up-nonce\0${sessionId}\0${input.nonce}`).digest("hex"); if (!permitted.methods.includes(input.method)) { @@ -2773,7 +2737,6 @@ export async function buildApp(options: BuildAppOptions = {}): Promise( "/v1/apps/:appSlug/step-up", { @@ -2797,7 +2760,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { - const result = await assertStepUp({ config, keys, store }, stepUpBudgets, request.params.appSlug, request.headers, request.body); + const result = await assertStepUp({ config, keys, store }, request.params.appSlug, request.headers, request.body); reply.code(result.statusCode).header("cache-control", "no-store"); return result.body; } diff --git a/src/fixed-window.ts b/src/fixed-window.ts deleted file mode 100644 index cfb7f00..0000000 --- a/src/fixed-window.ts +++ /dev/null @@ -1,49 +0,0 @@ -// A fixed-window attempt budget per key, held in memory by the process that -// serves the route. It bounds a credentialed caller's rate; it is not a -// security boundary on its own and resets on restart. The clock is injected -// so tests can move it. - -export interface FixedWindowLimit { - max: number; - windowMs: number; -} - -export class FixedWindowBudget { - private readonly windows = new Map(); - - constructor( - private readonly limit: FixedWindowLimit, - private readonly now: () => number = Date.now, - private readonly maxKeys = 4096, - ) {} - - /** - * Spend one attempt for `key`. `n` counts attempts in the window, denied ones - * included, so a caller can act on the first denial (`n === max + 1`) and not - * on the flood behind it. `retryAfterSeconds` is 0 when allowed. - */ - spend(key: string): { n: number; retryAfterSeconds: number } { - const at = this.now(); - let current = this.windows.get(key); - if (!current || at - current.startedAt >= this.limit.windowMs) { - this.sweep(at); - current = { startedAt: at, used: 0 }; - this.windows.set(key, current); - } - current.used += 1; - if (current.used <= this.limit.max) return { n: current.used, retryAfterSeconds: 0 }; - return { n: current.used, retryAfterSeconds: Math.max(1, Math.ceil((current.startedAt + this.limit.windowMs - at) / 1000)) }; - } - - /** Drop turned-over windows once the table is full; if it is still full, the oldest key goes. */ - private sweep(at: number): void { - if (this.windows.size < this.maxKeys) return; - for (const [key, window] of this.windows) { - if (at - window.startedAt >= this.limit.windowMs) this.windows.delete(key); - } - if (this.windows.size >= this.maxKeys) { - const oldest = this.windows.keys().next().value; - if (oldest !== undefined) this.windows.delete(oldest); - } - } -} diff --git a/tests/app.test.ts b/tests/app.test.ts index eac76f9..7dd94d9 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -1440,15 +1440,8 @@ describe("Heimdall service", () => { expect(urls).toEqual([]); }); - // Targets made only of whitespace, format characters, controls and the invisible fillers that render as nothing. - const BLANK_TARGETS = [ - " ", "\t", "\n ", "\u200B", "\u00A0\uFEFF", - "\u2800", "\u3164", "\u115F", "\u1160", "\uFFA0", "\u034F", "\u0000", "\u0007", " \u2800\u3164 ", - // Marks, private-use, unassigned and lone-surrogate code points, and the symbols that read as nothing: none is a letter or a number. - "\u0300", "\uE000", "\u0378", "\uD800", "\u{16FE4}", "\u{1D159}", "\u{F0000}", "\u0300\uE000 ", - ]; - // A target is usable when it holds a letter or a number that is not an invisible filler. - const NAMING_TARGETS = ["creator-1", " creator-1 ", "Framgång", "42", "\u2800a\u3164", "\u3164\u0300x"]; + const BLANK_TARGETS = ["", " ", "\t", "\n ", "\u00A0\uFEFF"]; + const NAMING_TARGETS = ["creator-1", " creator-1 ", "Framgång", "42"]; describe("a connect start that names a connection target is the app backend's", () => { // The target is app-backend authority: the StreamPixels backend proves the creator-manage session and states the @@ -1519,7 +1512,7 @@ describe("Heimdall service", () => { apps.push(app); for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }]) { - for (const targetId of [" ", "\u2800"]) { + for (const targetId of [" ", "\t\n"]) { const refused = await startFor(app, provider, { kind: "creator", targetId }, headers); expect([refused.statusCode, refused.json()], JSON.stringify(targetId)).toEqual([401, { error: "app_auth_required" }]); } @@ -1531,8 +1524,6 @@ describe("Heimdall service", () => { for (const targetId of BLANK_TARGETS) { expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId }), JSON.stringify(targetId)).toBe("refused"); } - // A visible character among the blanks names a target. - expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId: "\u2800a\u3164" })).toBe("custody_only"); for (const targetId of NAMING_TARGETS) { expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId }), JSON.stringify(targetId)).toBe("custody_only"); } diff --git a/tests/step-up-assertion.test.ts b/tests/step-up-assertion.test.ts index f064e00..7ed66e2 100644 --- a/tests/step-up-assertion.test.ts +++ b/tests/step-up-assertion.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; -import { buildApp, STEP_UP_ASSERT_LIMITS } from "../src/app.js"; +import { buildApp } from "../src/app.js"; import { builtInAppProfiles } from "../src/app-profiles.js"; import { issueAccessClaim } from "../src/claims.js"; import { type Provider } from "../src/contracts.js"; @@ -312,85 +312,6 @@ describe("the method and the nonce", () => { }); }); -describe("rate limits", () => { - it("trips per account, leaves other accounts alone, and turns over with the window", async () => { - const r = await rig(); - const m = await member(r); - const other = await member(r); - vi.useFakeTimers({ toFake: ["Date"] }); - for (let i = 0; i < STEP_UP_ASSERT_LIMITS.account.max; i += 1) { - expect((await assertStepUp(r, { token: m.token, nonce: nonce(`r${i}`) })).statusCode, `attempt ${i}`).toBe(201); - } - const tripped = await assertStepUp(r, { token: m.token, nonce: nonce("over") }); - expect(refused(tripped)).toEqual([429, "step_up_rate_limited"]); - expect(tripped.json().retryAfterSeconds).toBeGreaterThan(0); - expect(tripped.json()).not.toHaveProperty("accessToken"); - expect((await assertStepUp(r, { token: other.token })).statusCode).toBe(201); - vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.account.windowMs + 1000); - expect((await assertStepUp(r, { token: m.token, nonce: nonce("after") })).statusCode).toBe(201); - // The tripped attempt did not spend its nonce. - expect((await assertStepUp(r, { token: m.token, nonce: nonce("over") })).statusCode).toBe(201); - }); - - it("trips per app across accounts, counting attempts that failed their bearer", async () => { - const r = await rig(); - const m = await member(r); - vi.useFakeTimers({ toFake: ["Date"] }); - for (let i = 0; i < STEP_UP_ASSERT_LIMITS.app.max; i += 1) { - expect((await assertStepUp(r, { token: "garbage", nonce: nonce(`g${i}`) })).statusCode).toBe(401); - } - expect(refused(await assertStepUp(r, { token: m.token }))).toEqual([429, "step_up_rate_limited"]); - vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.app.windowMs + 1000); - expect((await assertStepUp(r, { token: m.token })).statusCode).toBe(201); - }); -}); - -describe("flood handling", () => { - it("the not-permitted budget is per app: one app's flood neither blocks bifrost's own call nor another ungranted app's first refusal", async () => { - const r = await rig(); - const sp = await member(r, "streampixels"); - const rp = await member(r, "repixelizer"); - const b = await member(r); - const as = (app: string, appSecret: string, token: string, i: number) => assertStepUp(r, { app, headers: { "x-heimdall-app-secret": appSecret }, token, nonce: nonce(`i${i}`) }); - for (let i = 0; i < 50; i += 1) await as("streampixels", "streampixels-secret", sp.token, i); - expect((await as("streampixels", "streampixels-secret", sp.token, 99)).statusCode).toBe(429); - expect(refused(await as("repixelizer", "repixelizer-secret", rp.token, 1))).toEqual([403, "step_up_assertion_not_permitted"]); - expect((await assertStepUp(r, { token: b.token })).statusCode).toBe(201); - }); - - it("a flood is not an audit flood: an app without the grant is audited once per window, a tripped budget once per window", async () => { - const r = await rig(); - const sp = await member(r, "streampixels"); - vi.useFakeTimers({ toFake: ["Date"] }); - const codes: Record = {}; - for (let i = 0; i < 500; i += 1) { - const res = await assertStepUp(r, { app: "streampixels", headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: sp.token, nonce: nonce(`f${i}`) }); - codes[res.statusCode] = (codes[res.statusCode] ?? 0) + 1; - } - expect(codes).toEqual({ 403: STEP_UP_ASSERT_LIMITS.notPermitted.max, 429: 500 - STEP_UP_ASSERT_LIMITS.notPermitted.max }); - const rows = (code: string) => auditOf(r, "step_up_assertion_refused").filter((e) => e.eventPayloadJson.code === code); - expect(rows("step_up_assertion_not_permitted")).toHaveLength(1); - expect(rows("step_up_rate_limited")).toHaveLength(1); - expect(rows("step_up_rate_limited")[0]!.eventPayloadJson.budget).toBe("notPermitted"); - vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.notPermitted.windowMs + 1000); - await assertStepUp(r, { app: "streampixels", headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: sp.token }); - expect(rows("step_up_assertion_not_permitted")).toHaveLength(2); - - // The same for the granted app's per-app and per-account budgets. - const m = await member(r); - const before = r.audit.length; - for (let i = 0; i < 300; i += 1) await assertStepUp(r, { token: "garbage", nonce: nonce(`g${i}`) }); - expect(r.audit.length - before, "garbage-bearer refusals up to the budget, then one row for the trip").toBe(STEP_UP_ASSERT_LIMITS.app.max + 1); - vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.app.windowMs + 1000); - const mark = r.audit.length; - for (let i = 0; i < 30; i += 1) await assertStepUp(r, { token: m.token, nonce: nonce(`a${i}`) }); - const accountRows = r.audit.slice(mark); - expect(accountRows.filter((e) => e.eventType === "step_up_asserted")).toHaveLength(STEP_UP_ASSERT_LIMITS.account.max); - const trips = accountRows.filter((e) => e.eventPayloadJson.code === "step_up_rate_limited"); - expect(trips.map((e) => e.eventPayloadJson.budget)).toEqual(["account"]); - }); -}); - describe("receipts", () => { it("records every assertion and every post-secret refusal with account, app, session, method, outcome and time, and nothing secret", async () => { const r = await rig();