Store: claimOAuthStateUse claims one use of a signed OAuth state per (jti, phase), on both stores and an INSERT-only table
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
607c2b0a20
commit
14e0cde26c
5 changed files with 99 additions and 15 deletions
|
|
@ -3,6 +3,7 @@ import { type AppSlug, type LinkedIdentityInput, type Provider } from "../contra
|
|||
import {
|
||||
type CreateAccountInput,
|
||||
type CreateAuthAttemptInput,
|
||||
type ClaimOAuthStateUseInput,
|
||||
type CreateAuthCompletionInput,
|
||||
type CreateAuditEventInput,
|
||||
type CreateCapabilityGrantInput,
|
||||
|
|
@ -48,6 +49,8 @@ export class InMemoryStore implements HeimdallStore {
|
|||
private readonly privateCommandReceipts = new Map<string, StoredPrivateCommandReceipt>();
|
||||
private readonly authCompletions = new Map<string, StoredAuthCompletion>();
|
||||
private readonly authCompletionsByAttempt = new Map<string, string>();
|
||||
/** `${jti}:${phase}` -> the state's expiresAt. */
|
||||
private readonly oauthStateUses = new Map<string, string>();
|
||||
private readonly entitlementSnapshots = new Map<string, CreateEntitlementSnapshotInput>();
|
||||
private readonly auditEvents = new Map<string, CreateAuditEventInput>();
|
||||
|
||||
|
|
@ -424,6 +427,20 @@ export class InMemoryStore implements HeimdallStore {
|
|||
return this.consumeAuthCompletion(appSlug, code, at);
|
||||
}
|
||||
|
||||
async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise<boolean> {
|
||||
for (const [key, expiresAt] of this.oauthStateUses) {
|
||||
if (expiresAt <= input.usedAt) {
|
||||
this.oauthStateUses.delete(key);
|
||||
}
|
||||
}
|
||||
const key = `${input.jti}:${input.phase}`;
|
||||
if (this.oauthStateUses.has(key)) {
|
||||
return false;
|
||||
}
|
||||
this.oauthStateUses.set(key, input.expiresAt);
|
||||
return true;
|
||||
}
|
||||
|
||||
async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void> {
|
||||
const key = `${input.accountId}:${input.provider}:${input.scope}`;
|
||||
this.entitlementSnapshots.set(key, clone(input));
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } f
|
|||
import {
|
||||
type CreateAccountInput,
|
||||
type CreateAuthAttemptInput,
|
||||
type ClaimOAuthStateUseInput,
|
||||
type CreateAuthCompletionInput,
|
||||
type CreateAuditEventInput,
|
||||
type CreateCapabilityGrantInput,
|
||||
|
|
@ -378,6 +379,7 @@ export const STORE_TABLE_PRIVILEGES: Readonly<Record<string, readonly ("SELECT"
|
|||
auth_attempts: ["SELECT", "INSERT", "UPDATE"],
|
||||
private_command_receipts: ["SELECT", "INSERT"],
|
||||
auth_completions: ["SELECT", "INSERT", "UPDATE"],
|
||||
oauth_state_uses: ["INSERT"],
|
||||
capability_grants: ["SELECT", "INSERT"],
|
||||
entitlement_snapshots: ["SELECT", "INSERT", "UPDATE"],
|
||||
audit_events: ["INSERT"],
|
||||
|
|
@ -1061,6 +1063,19 @@ export class PostgresStore implements HeimdallStore {
|
|||
return result.rowCount ? mapAuthCompletionRow(expectRow(result.rows[0], "consumeAuthCompletionByAttempt")) : null;
|
||||
}
|
||||
|
||||
async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise<boolean> {
|
||||
// No conflict target and no RETURNING: both need SELECT, and the role has INSERT only.
|
||||
const result = await this.pool.query(
|
||||
`
|
||||
INSERT INTO oauth_state_uses (jti, phase, app_slug, used_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT DO NOTHING
|
||||
`,
|
||||
[input.jti, input.phase, input.appSlug, input.usedAt, input.expiresAt]
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void> {
|
||||
await this.pool.query(
|
||||
`
|
||||
|
|
|
|||
|
|
@ -119,6 +119,20 @@ CREATE UNIQUE INDEX IF NOT EXISTS auth_completions_attempt_unconsumed_unique_idx
|
|||
ON auth_completions(app_slug, attempt_id)
|
||||
WHERE attempt_id IS NOT NULL AND consumed_at IS NULL;
|
||||
|
||||
-- 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 store deletes nothing, so rows stay
|
||||
-- like consumed auth_completions; after expires_at a state is refused before
|
||||
-- any claim, so a row is never consulted again.
|
||||
CREATE TABLE IF NOT EXISTS oauth_state_uses (
|
||||
jti TEXT NOT NULL,
|
||||
phase TEXT NOT NULL,
|
||||
app_slug TEXT NOT NULL,
|
||||
used_at TIMESTAMPTZ NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (jti, phase)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS capability_grants (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
|
|
|
|||
|
|
@ -165,6 +165,14 @@ export interface StoredAuthCompletion {
|
|||
payloadJson: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ClaimOAuthStateUseInput {
|
||||
jti: string;
|
||||
phase: "launch" | "callback";
|
||||
appSlug: AppSlug;
|
||||
usedAt: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export interface CreateAuthCompletionInput {
|
||||
/**
|
||||
* Correlation handle only (see StoredAuthCompletion.attemptId). The store
|
||||
|
|
@ -272,5 +280,15 @@ export interface HeimdallStore {
|
|||
*/
|
||||
consumeAuthCompletionByAttempt(appSlug: AppSlug, attemptId: string, at: string): Promise<StoredAuthCompletion | null>;
|
||||
upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void>;
|
||||
/**
|
||||
* Claim one use of a signed OAuth state: true only for the first claim of
|
||||
* (jti, phase), false for every later one. Without it a state is a bearer
|
||||
* token any number of browsers can complete, so an attacker who learns a
|
||||
* victim's state completes it as themselves and hands the victim a code
|
||||
* for the attacker's account. `expiresAt` is the state's own expiry; the
|
||||
* state is refused at that time before any claim, so the record is dead
|
||||
* after it and a store may drop it.
|
||||
*/
|
||||
claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise<boolean>;
|
||||
createAuditEvent(input: CreateAuditEventInput): Promise<void>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { Pool } from "pg";
|
|||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { newDb } from "pg-mem";
|
||||
import { type HeimdallConfig } from "../src/config.js";
|
||||
import { createStore } from "../src/store/index.js";
|
||||
import { createStore, InMemoryStore } from "../src/store/index.js";
|
||||
import {
|
||||
createPostgresStore,
|
||||
PostgresStore,
|
||||
|
|
@ -159,18 +159,6 @@ describe("PostgresStore", () => {
|
|||
const consumedAgain = await store.consumeAuthCompletion("repixelizer", completion.code, "2026-04-26T12:02:00.000Z");
|
||||
expect(consumedAgain).toBeNull();
|
||||
|
||||
const stateUse = {
|
||||
jti: "state-1",
|
||||
phase: "launch" as const,
|
||||
appSlug: "repixelizer" as const,
|
||||
usedAt: now,
|
||||
expiresAt: "2026-04-26T12:10:00.000Z",
|
||||
};
|
||||
expect(await store.claimOAuthStateUse(stateUse)).toBe(true);
|
||||
expect(await store.claimOAuthStateUse(stateUse)).toBe(false);
|
||||
expect(await store.claimOAuthStateUse({ ...stateUse, phase: "callback" })).toBe(true);
|
||||
expect(await store.claimOAuthStateUse({ ...stateUse, jti: "state-2" })).toBe(true);
|
||||
|
||||
const attempt = await store.createAuthAttempt({
|
||||
handle: "attempt-123",
|
||||
appSlug: "ghostlight",
|
||||
|
|
@ -210,6 +198,36 @@ describe("PostgresStore", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("InMemoryStore.claimOAuthStateUse", () => {
|
||||
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",
|
||||
};
|
||||
|
||||
it("is true once per (jti, phase)", async () => {
|
||||
const store = new InMemoryStore();
|
||||
expect(await store.claimOAuthStateUse(use)).toBe(true);
|
||||
expect(await store.claimOAuthStateUse(use)).toBe(false);
|
||||
expect(await store.claimOAuthStateUse({ ...use, phase: "callback" })).toBe(true);
|
||||
expect(await store.claimOAuthStateUse({ ...use, phase: "callback" })).toBe(false);
|
||||
expect(await store.claimOAuthStateUse({ ...use, jti: "state-2" })).toBe(true);
|
||||
});
|
||||
|
||||
it("drops a record once its state has expired, and keeps it until then", 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" });
|
||||
expect(await store.claimOAuthStateUse(use)).toBe(false);
|
||||
// At and after expiry the record is dead weight: the state is refused before any claim.
|
||||
await store.claimOAuthStateUse({ ...use, jti: "state-3", usedAt: "2026-04-26T12:10:00.000Z" });
|
||||
expect(await store.claimOAuthStateUse(use)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createPostgresStore", () => {
|
||||
// pg emits an idle client's connection loss on the pool. With no listener
|
||||
// that event kills the process, and Node prints the pg Client with its
|
||||
|
|
@ -245,11 +263,12 @@ describe("PostgresStore.checkSchema", () => {
|
|||
"auth_attempts",
|
||||
"private_command_receipts",
|
||||
"auth_completions",
|
||||
"oauth_state_uses",
|
||||
"capability_grants",
|
||||
"entitlement_snapshots",
|
||||
"audit_events",
|
||||
]);
|
||||
expect(REQUIRED_COLUMNS).toHaveLength(85);
|
||||
expect(REQUIRED_COLUMNS).toHaveLength(90);
|
||||
expect(REQUIRED_COLUMNS).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ table: "auth_completions", column: "code", type: "TEXT", nullable: false },
|
||||
|
|
@ -260,11 +279,12 @@ describe("PostgresStore.checkSchema", () => {
|
|||
{ table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true },
|
||||
])
|
||||
);
|
||||
expect(REQUIRED_KEYS).toHaveLength(12);
|
||||
expect(REQUIRED_KEYS).toHaveLength(13);
|
||||
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: "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