Prune oauth_state_uses on claim: bounded delete past exp + skew + margin (#12)

Not in the 74004bf release list. The runtime role needs GRANT SELECT, DELETE ON oauth_state_uses before this build starts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-13 05:58:45 +00:00
commit 96256d2839
7 changed files with 282 additions and 47 deletions

View file

@ -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" };
}

View file

@ -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<T>(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<boolean> {
// 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;
}

View file

@ -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<Record<string, readonly ("SELECT" | "INSERT" | "UPDATE")[]>> = {
export const STORE_TABLE_PRIVILEGES: Readonly<Record<string, readonly ("SELECT" | "INSERT" | "UPDATE" | "DELETE")[]>> = {
accounts: ["SELECT", "INSERT", "UPDATE"],
linked_identities: ["SELECT", "INSERT", "UPDATE"],
sessions: ["SELECT", "INSERT", "UPDATE"],
@ -460,7 +463,7 @@ export const STORE_TABLE_PRIVILEGES: Readonly<Record<string, readonly ("SELECT"
private_command_receipts: ["SELECT", "INSERT"],
auth_completions: ["SELECT", "INSERT", "UPDATE"],
pending_links: ["SELECT", "INSERT", "UPDATE"],
oauth_state_uses: ["INSERT"],
oauth_state_uses: ["SELECT", "INSERT", "DELETE"],
capability_grants: ["SELECT", "INSERT"],
entitlement_snapshots: ["SELECT", "INSERT", "UPDATE"],
consent_receipts: ["SELECT", "INSERT"],
@ -598,7 +601,9 @@ export async function checkSchemaRequirements(pool: Pick<Pool, "query">, 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<boolean> {
// 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<void> {

View file

@ -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,

View file

@ -173,6 +173,22 @@ export interface StoredAuthCompletion {
payloadJson: Record<string, unknown>;
}
/** 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";