diff --git a/src/app.ts b/src/app.ts index e3c4931..2977f08 100644 --- a/src/app.ts +++ b/src/app.ts @@ -43,6 +43,7 @@ import { authorizationScopes, buildAuthorizationUrl, providerCatalog, providerEx import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js"; import { createStore, type HeimdallStore } from "./store/index.js"; import { + OAUTH_STATE_SKEW_MS, type CreateAccountInput, type StoredCapabilityGrant, type StoredLinkedIdentity, @@ -218,8 +219,8 @@ type OAuthStateVerdict = /** * The one place a signed OAuth state becomes trusted: signature, shape, issuer, - * audience and provider, and the time window with the same 30 s skew refresh - * tokens use. Every route that turns a state into navigation or a completion + * audience and provider, and the time window with OAUTH_STATE_SKEW_MS of skew + * (30 s, as refresh tokens use). Every route that turns a state into navigation or a completion * runs this first; the refusals are fixed codes and never echo the token. */ function verifyOAuthState( @@ -242,7 +243,7 @@ function verifyOAuthState( } const now = nowEpochSeconds(); - if (payload.nbf > now + 30 || payload.exp <= now - 30) { + if (payload.nbf > now + OAUTH_STATE_SKEW_MS / 1000 || payload.exp <= now - OAUTH_STATE_SKEW_MS / 1000) { return { ok: false, error: "state_expired" }; } diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index e86490d..5df37ea 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -4,6 +4,8 @@ import { type CreateAccountInput, type CreateAuthAttemptInput, type ClaimOAuthStateUseInput, + OAUTH_STATE_PRUNE_BATCH, + oauthStatePruneCutoffMs, type CreateAuthCompletionInput, type CreateConsentReceiptInput, type CreatePendingLinkInput, @@ -26,9 +28,6 @@ import { type UpsertLinkedIdentityInput, } from "./types.js"; -/** The skew a signed OAuth state is still accepted for past its exp (verifyOAuthState). */ -const OAUTH_STATE_SKEW_MS = 30_000; - function clone(value: T): T { return JSON.parse(JSON.stringify(value)) as T; } @@ -464,18 +463,23 @@ export class InMemoryStore implements HeimdallStore { } async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise { - // A state is still accepted until its exp + 30 s skew, so a use record must outlive that. - const usedAtMs = Date.parse(input.usedAt); - for (const [key, expiresAt] of this.oauthStateUses) { - if (Date.parse(expiresAt) + OAUTH_STATE_SKEW_MS <= usedAtMs) { - this.oauthStateUses.delete(key); - } - } const key = `${input.jti}:${input.phase}`; if (this.oauthStateUses.has(key)) { return false; } this.oauthStateUses.set(key, input.expiresAt); + // A state is still accepted until its exp + skew; a record is kept a margin longer, and each + // successful claim removes at most a batch of what is past that (oauthStatePruneCutoffMs), as + // the Postgres store does. + const cutoff = oauthStatePruneCutoffMs(Date.parse(input.usedAt)); + let pruned = 0; + for (const [oldKey, expiresAt] of this.oauthStateUses) { + if (pruned >= OAUTH_STATE_PRUNE_BATCH) break; + if (Date.parse(expiresAt) <= cutoff) { + this.oauthStateUses.delete(oldKey); + pruned += 1; + } + } return true; } diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 6d96598..247260c 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -18,6 +18,8 @@ import { type CreateSessionInput, type CreatePrivateCommandReceiptInput, type HeimdallStore, + OAUTH_STATE_PRUNE_BATCH, + oauthStatePruneCutoffMs, type StoredAccount, type StoredAuthAttempt, type StoredAuthCompletion, @@ -449,10 +451,11 @@ export function samePredicate(declared: string, actual: string, keyColumns: stri /** * What the store's statements do to each table, and so the privileges its * database role needs: it reads what it returns or looks up, inserts what it - * creates, updates what it changes or upserts, and deletes nothing. + * creates, updates what it changes or upserts, and deletes only expired + * oauth_state_uses rows (which needs SELECT for its WHERE). * audit_events is written and never read back. */ -export const STORE_TABLE_PRIVILEGES: Readonly> = { +export const STORE_TABLE_PRIVILEGES: Readonly> = { accounts: ["SELECT", "INSERT", "UPDATE"], linked_identities: ["SELECT", "INSERT", "UPDATE"], sessions: ["SELECT", "INSERT", "UPDATE"], @@ -460,7 +463,7 @@ export const STORE_TABLE_PRIVILEGES: Readonly, require SELECT 1 FROM unnest($2::text[], $3::text[]) AS used(table_name, column_name) JOIN pg_attribute a ON a.attrelid = to_regclass(used.table_name) AND a.attname = used.column_name AND NOT a.attisdropped WHERE used.table_name = required.table_name - AND NOT has_column_privilege(a.attrelid, a.attnum, required.privilege) + AND NOT CASE WHEN required.privilege = 'DELETE' + THEN has_table_privilege(a.attrelid, 'DELETE') -- DELETE is a row privilege, never held per column + ELSE has_column_privilege(a.attrelid, a.attnum, required.privilege) END ) `, [ @@ -1221,7 +1226,7 @@ export class PostgresStore implements HeimdallStore { } async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise { - // No conflict target and no RETURNING: both need SELECT, and the role has INSERT only. + // No conflict target and no RETURNING: ON CONFLICT DO NOTHING alone says whether the row was new. const result = await this.pool.query( ` INSERT INTO oauth_state_uses (jti, phase, app_slug, used_at, expires_at) @@ -1230,7 +1235,24 @@ export class PostgresStore implements HeimdallStore { `, [input.jti, input.phase, input.appSlug, input.usedAt, input.expiresAt] ); - return result.rowCount === 1; + if (result.rowCount !== 1) return false; + // Retention: one bounded delete of records past the shared cutoff, inline as the memory store does. + // The claim row is already written, so a prune failure must not fail the claim: a throw would make + // the user's retry look like a replay. Unpruned rows are harmless and the next claim prunes them. + try { + await this.pool.query( + ` + DELETE FROM oauth_state_uses + WHERE (jti, phase) IN ( + SELECT jti, phase FROM oauth_state_uses WHERE expires_at <= $1 LIMIT $2 + ) + `, + [new Date(oauthStatePruneCutoffMs(Date.parse(input.usedAt))), OAUTH_STATE_PRUNE_BATCH] + ); + } catch { + // deliberately swallowed, see above + } + return true; } async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise { diff --git a/src/store/schema.ts b/src/store/schema.ts index 7aa6823..3678122 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -143,9 +143,10 @@ CREATE UNIQUE INDEX IF NOT EXISTS auth_completions_attempt_unconsumed_unique_idx -- One use per (state jti, phase): a signed OAuth state launches once and -- completes once. The first INSERT for a pair wins; ON CONFLICT DO NOTHING --- reports every later claim as no row. The Postgres store deletes nothing, so rows --- stay like consumed auth_completions; a state is accepted until expires_at + 30 s --- of skew, so a row may be pruned only after that and is never consulted again. +-- reports every later claim as no row. A state is accepted until expires_at + 30 s +-- of skew, so a row may be pruned only after that and is never consulted again; +-- each successful claim deletes a bounded batch of rows past expires_at + skew +-- + margin (OAUTH_STATE_* in types.ts), found through the expires_at index. CREATE TABLE IF NOT EXISTS oauth_state_uses ( jti TEXT NOT NULL, phase TEXT NOT NULL, @@ -155,6 +156,8 @@ CREATE TABLE IF NOT EXISTS oauth_state_uses ( PRIMARY KEY (jti, phase) ); +CREATE INDEX IF NOT EXISTS oauth_state_uses_expires_at_idx ON oauth_state_uses(expires_at); + CREATE TABLE IF NOT EXISTS capability_grants ( id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, diff --git a/src/store/types.ts b/src/store/types.ts index 9eb805b..a2a792d 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -173,6 +173,22 @@ export interface StoredAuthCompletion { payloadJson: Record; } +/** The skew a signed OAuth state is still accepted for past its exp: verifyOAuthState in app.ts reads this, so the two cannot drift. */ +export const OAUTH_STATE_SKEW_MS = 30_000; +/** Extra time a use record is kept past exp + skew before it may be pruned. */ +export const OAUTH_STATE_PRUNE_MARGIN_MS = 10 * 60_000; +/** The most use records one claim deletes. */ +export const OAUTH_STATE_PRUNE_BATCH = 50; + +/** + * The one retention rule for oauth_state_uses, shared by both stores: a record + * is prunable when expires_at + skew + margin <= now, that is when its + * expires_at is at or before this cutoff. + */ +export function oauthStatePruneCutoffMs(nowMs: number): number { + return nowMs - OAUTH_STATE_SKEW_MS - OAUTH_STATE_PRUNE_MARGIN_MS; +} + export interface ClaimOAuthStateUseInput { jti: string; phase: "launch" | "callback"; diff --git a/tests/oauth-state-binding.test.ts b/tests/oauth-state-binding.test.ts index 01abba0..c82bd94 100644 --- a/tests/oauth-state-binding.test.ts +++ b/tests/oauth-state-binding.test.ts @@ -4,6 +4,7 @@ import { type FastifyInstance } from "fastify"; import { buildApp, getHeimdallRuntimeContext, startOAuthFlow } from "../src/app.js"; import { resolveAppCaller } from "../src/app-caller.js"; import { decodeJwt, signJwt } from "../src/signing.js"; +import { OAUTH_STATE_PRUNE_BATCH, OAUTH_STATE_PRUNE_MARGIN_MS, OAUTH_STATE_SKEW_MS } from "../src/store/types.js"; import { createMockDiscordRuntime, createTestConfig, launchFlow, setCookieOf, stateOf } from "./oauth-flow.js"; // Heimdall's OAuth states complete once, only in the browser that launched @@ -280,23 +281,69 @@ describe("OAuth state binding", () => { }); }); - it("the memory store keeps a use record until the state's exp + 30 s skew", async () => { - const app = await newApp(); - const ctx = getHeimdallRuntimeContext(app); - const claim = (jti: string, usedAt: number) => - ctx.store.claimOAuthStateUse({ - jti, - phase: "launch", - appSlug: "bifrost", - usedAt: new Date(usedAt).toISOString(), - expiresAt: new Date(1_000_000).toISOString(), - }); - expect(await claim("a", 900_000)).toBe(true); - // Past exp but inside the skew a state still verifies, so its record must still refuse a replay. - expect(await claim("b", 1_000_000 + 29_999)).toBe(true); - expect(await claim("a", 1_000_000 + 29_999)).toBe(false); - expect(await claim("c", 1_000_000 + 30_000)).toBe(true); - expect(await claim("a", 1_000_000 + 30_000)).toBe(true); + describe("use-record retention", () => { + // Only Date is faked: the routes stamp each claim with the clock, and the rest of the event loop stays real. + const clockAt = (ms: number) => vi.useFakeTimers({ toFake: ["Date"], now: ms }); + const seedStale = async (app: FastifyInstance, count: number, beforeMs: number) => { + const ctx = getHeimdallRuntimeContext(app); + for (let i = 0; i < count; i += 1) { + const expiresAt = new Date(beforeMs - i).toISOString(); + await ctx.store.claimOAuthStateUse({ jti: `stale-${i}`, phase: "launch", appSlug: "bifrost", usedAt: expiresAt, expiresAt }); + } + }; + + it("later claims never prune a live state: its launch and callback replays stay refused", async () => { + const app = await newApp(); + const start = await bifrostStart(app); + const victim = await launchFlow(app, start); + const exp = decodeJwt(victim.state).payload.exp as number; + + // More stale records than one batch, then another user's flow, whose claims do the pruning. + const staleBefore = Date.now() - OAUTH_STATE_SKEW_MS - OAUTH_STATE_PRUNE_MARGIN_MS; + await seedStale(app, OAUTH_STATE_PRUNE_BATCH + 10, staleBefore); + await launchFlow(app, await bifrostStart(app)); + + const launchReplay = await app.inject({ method: "GET", url: launchUrl(start) }); + expect(launchReplay.json()).toEqual({ error: "state_already_launched" }); + + // The callback is not pruned either: it completes once, and its replay is refused. + expect((await callback(app, victim.state, victim.cookie, "code=victim-code")).statusCode).toBe(201); + expect((await callback(app, victim.state, victim.cookie, "code=victim-code")).json()).toEqual({ error: "state_already_used" }); + + // Inside exp + skew the state still verifies, and the record still refuses it. + clockAt((exp + OAUTH_STATE_SKEW_MS / 1000 - 1) * 1000); + await launchFlow(app, await bifrostStart(app)); + const lateReplay = await app.inject({ method: "GET", url: launchUrl(start) }); + expect(lateReplay.json()).toEqual({ error: "state_already_launched" }); + + }); + + it("once its records are pruned, an expired state is refused as state_expired, by the state and not the record", async () => { + const app = await newApp(); + const ctx = getHeimdallRuntimeContext(app); + const start = await bifrostStart(app); + const victim = await launchFlow(app, start); + const exp = decodeJwt(victim.state).payload.exp as number; + + // Past exp + skew + margin the victim's launch record is prunable; a new claim removes it. + const pruneAt = (exp + (OAUTH_STATE_SKEW_MS + OAUTH_STATE_PRUNE_MARGIN_MS) / 1000 + 1) * 1000; + clockAt(pruneAt); + await launchFlow(app, await bifrostStart(app)); + const record = { + jti: decodeJwt(victim.state).payload.jti as string, + phase: "launch" as const, + appSlug: "bifrost" as const, + usedAt: new Date(pruneAt).toISOString(), + expiresAt: new Date(exp * 1000).toISOString(), + }; + // The record is gone, as the store (not the route) would now let the claim through ... + expect(await ctx.store.claimOAuthStateUse(record)).toBe(true); + // ... yet the routes refuse the state itself. + const launchReplay = await app.inject({ method: "GET", url: launchUrl(start) }); + expect(launchReplay.statusCode).toBe(400); + expect(launchReplay.json()).toEqual({ error: "state_expired" }); + expect((await callback(app, victim.state, victim.cookie)).json()).toEqual({ error: "state_expired" }); + }); }); it("a provider refusal from the launching browser still denies the attempt, once", async () => { diff --git a/tests/store.test.ts b/tests/store.test.ts index 75ee256..dc0fbe2 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -14,6 +14,11 @@ import { samePredicate, STORE_TABLE_PRIVILEGES, } from "../src/store/postgres.js"; +import { + OAUTH_STATE_PRUNE_BATCH, + OAUTH_STATE_PRUNE_MARGIN_MS, + OAUTH_STATE_SKEW_MS, +} from "../src/store/types.js"; import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "../src/store/schema.js"; describe("PostgresStore", () => { @@ -276,19 +281,82 @@ describe("InMemoryStore.claimOAuthStateUse", () => { expect(await store.claimOAuthStateUse({ ...use, jti: "state-2" })).toBe(true); }); - it("drops a record once its state's exp + 30 s skew has passed, and keeps it until then", async () => { + it("drops a record only once its state's exp + skew + margin has passed", async () => { const store = new InMemoryStore(); await store.claimOAuthStateUse(use); - // Before expiry a later claim of another state leaves the record in force. - await store.claimOAuthStateUse({ ...use, jti: "state-2", usedAt: "2026-04-26T12:09:59.000Z" }); + const expMs = Date.parse(use.expiresAt); + const at = (ms: number) => new Date(ms).toISOString(); + // Inside the skew past expiry the state still verifies, and the margin keeps the record beyond that. + await store.claimOAuthStateUse({ ...use, jti: "state-2", usedAt: at(expMs + OAUTH_STATE_SKEW_MS) }); expect(await store.claimOAuthStateUse(use)).toBe(false); - // Inside the 30 s skew past expiry the state still verifies, so the record still refuses a replay. - await store.claimOAuthStateUse({ ...use, jti: "state-3", usedAt: "2026-04-26T12:10:29.999Z" }); + const boundary = expMs + OAUTH_STATE_SKEW_MS + OAUTH_STATE_PRUNE_MARGIN_MS; + await store.claimOAuthStateUse({ ...use, jti: "state-3", usedAt: at(boundary - 1) }); expect(await store.claimOAuthStateUse(use)).toBe(false); - // At exp + 30 s the state is refused before any claim and the record is dead weight. - await store.claimOAuthStateUse({ ...use, jti: "state-4", usedAt: "2026-04-26T12:10:30.000Z" }); + // At exactly exp + skew + margin the record is prunable (the rule is <=). + await store.claimOAuthStateUse({ ...use, jti: "state-4", usedAt: at(boundary) }); expect(await store.claimOAuthStateUse(use)).toBe(true); }); + + it("removes at most one batch of prunable records per successful claim", async () => { + const store = new InMemoryStore(); + const expMs = Date.parse(use.expiresAt); + const total = OAUTH_STATE_PRUNE_BATCH * 2 + 7; + for (let i = 0; i < total; i += 1) await store.claimOAuthStateUse({ ...use, jti: `old-${i}` }); + const size = () => (store as unknown as { oauthStateUses: Map }).oauthStateUses.size; + expect(size()).toBe(total); + const later = new Date(expMs + OAUTH_STATE_SKEW_MS + OAUTH_STATE_PRUNE_MARGIN_MS).toISOString(); + await store.claimOAuthStateUse({ ...use, jti: "fresh-1", usedAt: later, expiresAt: later }); + expect(size()).toBe(total + 1 - OAUTH_STATE_PRUNE_BATCH); + // A refused (replayed) claim prunes nothing, as on Postgres where the delete follows a new row. + await store.claimOAuthStateUse({ ...use, jti: "fresh-1", usedAt: later, expiresAt: later }); + expect(size()).toBe(total + 1 - OAUTH_STATE_PRUNE_BATCH); + }); +}); + +describe("PostgresStore.claimOAuthStateUse retention", () => { + const use = { + jti: "state-1", + phase: "launch" as const, + appSlug: "repixelizer" as const, + usedAt: "2026-04-26T12:00:00.000Z", + expiresAt: "2026-04-26T12:10:00.000Z", + }; + + function doublePool(prune: "ok" | "throws", inserted = 1) { + const calls: Array<{ sql: string; params: unknown[] }> = []; + const pool = { + query: async (sql: string, params: unknown[]) => { + calls.push({ sql, params }); + if (calls.length === 1) return { rowCount: inserted, rows: [] }; + if (prune === "throws") throw Object.assign(new Error("permission denied for table oauth_state_uses"), { code: "42501" }); + return { rowCount: 0, rows: [] }; + }, + }; + return { calls, store: new PostgresStore(pool as unknown as Pool) }; + } + + it("runs one bounded delete after a new row, at the shared cutoff and batch", async () => { + const { calls, store } = doublePool("ok"); + expect(await store.claimOAuthStateUse(use)).toBe(true); + expect(calls).toHaveLength(2); + expect(calls[1]!.sql).toMatch(/DELETE FROM oauth_state_uses/); + expect(calls[1]!.params).toEqual([ + new Date(Date.parse(use.usedAt) - OAUTH_STATE_SKEW_MS - OAUTH_STATE_PRUNE_MARGIN_MS), + OAUTH_STATE_PRUNE_BATCH, + ]); + }); + + it("prunes nothing when the claim is a replay", async () => { + const { calls, store } = doublePool("ok", 0); + expect(await store.claimOAuthStateUse(use)).toBe(false); + expect(calls).toHaveLength(1); + }); + + it("a failing prune does not change the claim's result", async () => { + const { calls, store } = doublePool("throws"); + expect(await store.claimOAuthStateUse(use)).toBe(true); + expect(calls).toHaveLength(2); + }); }); describe("createPostgresStore", () => { @@ -481,6 +549,15 @@ async function exerciseStore(store: PostgresStore): Promise> { expect(await s.claimOAuthStateUse(stateUse)).toBe(true); expect(await s.claimOAuthStateUse(stateUse)).toBe(false); expect(await s.claimOAuthStateUse({ ...stateUse, phase: "callback" })).toBe(true); + // The prune is swallowed when the role may not run it, so the exercise proves it ran: a long-expired + // record is gone after the next new claim. A missing prune stands for the privilege refusal behind it. + const stale = { ...stateUse, jti: randomUUID(), usedAt: "2000-01-01T00:00:00.000Z", expiresAt: "2000-01-01T00:10:00.000Z" }; + expect(await s.claimOAuthStateUse(stale)).toBe(true); + expect(await s.claimOAuthStateUse({ ...stateUse, jti: randomUUID() })).toBe(true); + const retained = await s.claimOAuthStateUse(stale); + if (!retained) { + throw Object.assign(new Error("oauth_state_uses was not pruned"), { code: "42501" }); + } const { receipt: grant } = await s.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: now, scopesAsked: ["a", "b"], scopesGranted: ["a"], consentPageDigest: "d", consentText: "t" }); const revocation = { kind: "revocation" as const, accountId: account.id, appSlug: "streampixels" as const, provider: "joystick" as const, createdAt: later, revokesReceiptId: grant.id }; const first = await s.createConsentReceipt(revocation); @@ -639,6 +716,68 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD } }); + describe("oauth_state_uses retention", () => { + const expMs = Date.parse("2026-04-26T12:10:00.000Z"); + const boundary = expMs + OAUTH_STATE_SKEW_MS + OAUTH_STATE_PRUNE_MARGIN_MS; + const use = (jti: string, usedAtMs: number, expiresAtMs = expMs) => ({ + jti, + phase: "launch" as const, + appSlug: "repixelizer" as const, + usedAt: new Date(usedAtMs).toISOString(), + expiresAt: new Date(expiresAtMs).toISOString(), + }); + const count = async (owner: Pool) => Number((await owner.query("SELECT count(*) AS n FROM oauth_state_uses")).rows[0].n); + const seed = async (owner: Pool, jti: string) => { + await owner.query( + "INSERT INTO oauth_state_uses (jti, phase, app_slug, used_at, expires_at) VALUES ($1, 'launch', 'repixelizer', $2, $2)", + [jti, new Date(expMs)] + ); + }; + + it.each([ + [boundary - 1, true], + [boundary, false], + [boundary + 1, false], + ])("a claim at exp + skew + margin %i ms keeps the record: %s", async (usedAtMs, kept) => { + const { owner } = await appliedDatabase(); + const store = new PostgresStore(owner); + expect(await store.claimOAuthStateUse(use("old", expMs - 1000))).toBe(true); + expect(await store.claimOAuthStateUse(use("other", usedAtMs, usedAtMs + 600_000))).toBe(true); + expect(await store.claimOAuthStateUse(use("old", usedAtMs))).toBe(!kept); + }); + + it("removes at most one batch per claim and never the live record", async () => { + const { owner } = await appliedDatabase(); + const store = new PostgresStore(owner); + const total = OAUTH_STATE_PRUNE_BATCH * 2 + 7; + for (let i = 0; i < total; i += 1) await seed(owner, `old-${i}`); + const fresh = use("fresh", boundary + 5, boundary + 600_000); + expect(await store.claimOAuthStateUse(fresh)).toBe(true); + expect(await count(owner)).toBe(total + 1 - OAUTH_STATE_PRUNE_BATCH); + expect(await store.claimOAuthStateUse(fresh)).toBe(false); + expect(await count(owner)).toBe(total + 1 - OAUTH_STATE_PRUNE_BATCH); + }); + + it("keeps its expires_at index", async () => { + const { owner } = await appliedDatabase(); + const found = await owner.query("SELECT 1 FROM pg_indexes WHERE indexname = 'oauth_state_uses_expires_at_idx'"); + expect(found.rowCount).toBe(1); + }); + + it("a role without DELETE still claims, and leaves the old records", async () => { + const { name, owner } = await appliedDatabase(); + await grant(owner, { ...STORE_TABLE_PRIVILEGES, oauth_state_uses: ["SELECT", "INSERT"] }); + await seed(owner, "old"); + const pool = fixturePool(urlFor(name, role, rolePassword)); + cleanup.push(async () => { + await pool.end(); + }); + const store = new PostgresStore(pool); + expect(await store.claimOAuthStateUse(use("fresh", boundary + 5, boundary + 600_000))).toBe(true); + expect(await count(owner)).toBe(2); + }); + }); + it("refuses to apply the schema as a role that may not, and closes the store", async () => { const { name, owner } = await appliedDatabase(); await grant(owner, STORE_TABLE_PRIVILEGES); @@ -686,7 +825,10 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD await owner.query(`GRANT USAGE ON SCHEMA public TO ${role}`); for (const [table, wanted] of Object.entries(STORE_TABLE_PRIVILEGES)) { const columns = REQUIRED_COLUMNS.filter((column) => column.table === table).map((column) => column.column).join(", "); - for (const privilege of wanted) await owner.query(`GRANT ${privilege} (${columns}) ON ${table} TO ${role}`); + for (const privilege of wanted) { + // DELETE removes rows and cannot be granted per column. + await owner.query(privilege === "DELETE" ? `GRANT DELETE ON ${table} TO ${role}` : `GRANT ${privilege} (${columns}) ON ${table} TO ${role}`); + } } expect(await start(urlFor(name, role, rolePassword), false)).toBe("started");