Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(control-api): serialize reactive OAuth refresh under a per-grant row lock (R2-M1)

Diego Zacarias0a9ad9a8b2ad
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 15465495b..6e248e919 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.653",
+ "version": "0.1.654",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.653",
+ "version": "0.1.654",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index 99dedcfef..182cc1cf8 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.653",
+ "version": "0.1.654",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index 96b542789..ea547c73c 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -6610,6 +6610,18 @@ export const HOST_MODEL_WRITE_CARRIER_IDLE_TIMEOUT_MS = boundedEnvInteger(
MAX_CARRIER_IDLE_TIMEOUT_MS
)
+// Idle-in-transaction bound for the REACTIVE OAuth-refresh carrier transaction —
+// the one that holds a per-grant `FOR UPDATE` row lock across the refresh POST.
+// Default 20s > the 15s HTTP AbortSignal so the client aborts a hung AS first;
+// the GUC is only the backstop for a wedged abort. Same [1s, 60s] bounds as the
+// host↔model carrier.
+export const OAUTH_REFRESH_LOCK_CARRIER_IDLE_TIMEOUT_MS = boundedEnvInteger(
+ 'CONTROL_API_OAUTH_REFRESH_LOCK_IDLE_TIMEOUT_MS',
+ 20_000,
+ MIN_CARRIER_IDLE_TIMEOUT_MS,
+ MAX_CARRIER_IDLE_TIMEOUT_MS
+)
+
/**
* Take the transaction-scoped advisory lock for one model NAME. Auto-released on
* COMMIT/ROLLBACK and on backend death, so it never orphans. Must be a statement
@@ -6653,3 +6665,16 @@ export async function boundCarrierTransactionIdleTimeout(
): Promise<void> {
await db.query(`SELECT set_config('idle_in_transaction_session_timeout', $1, true)`, [String(ms)])
}
+
+/**
+ * Bound the idle-in-transaction tenancy of the reactive OAuth-refresh carrier
+ * transaction — the one that HOLDS the per-grant `FOR UPDATE` row lock across the
+ * refresh POST (mini-spec 16, R2-M1). While that POST is awaited no statement
+ * runs, so this GUC is the only timeout that can release the row lock + pool
+ * connection if the AS hangs. Thin wrapper over
+ * {@link boundCarrierTransactionIdleTimeout} pinned to the OAuth carrier's own
+ * env-bounded value.
+ */
+export async function boundOAuthRefreshLockIdleTimeout(db: DbTransactionClient): Promise<void> {
+ await boundCarrierTransactionIdleTimeout(db, OAUTH_REFRESH_LOCK_CARRIER_IDLE_TIMEOUT_MS)
+}
diff --git a/control-api/src/oauth/reactiveTokenHelper.ts b/control-api/src/oauth/reactiveTokenHelper.ts
new file mode 100644
index 000000000..0a94cc6da
--- /dev/null
+++ b/control-api/src/oauth/reactiveTokenHelper.ts
@@ -0,0 +1,73 @@
+import { boundOAuthRefreshLockIdleTimeout, withTransaction } from '../db.js'
+import type { DbTransactionClient } from '../db.js'
+import { getOAuthGrant, lockOAuthGrantForRefresh } from './store.js'
+import {
+ type GetAccessTokenDeps,
+ type GetAccessTokenInput,
+ type GetAccessTokenResult,
+ REACTIVE_REFRESH_BUFFER_MS,
+ getAccessToken,
+ isAccessTokenStale,
+} from './tokenHelper.js'
+
+// Lives OUTSIDE tokenHelper.ts on purpose. `config.ts` imports tokenHelper.ts
+// (for REACTIVE_REFRESH_BUFFER_MS), so a value import of db.ts INTO tokenHelper
+// would close a config → tokenHelper → db → …/llmProviderAttemptStore → config
+// initialization cycle and leave `config` in the TDZ at boot. The reactive
+// wrapper needs db.ts (withTransaction + the carrier idle timeout), so it sits in
+// its own module that nothing on the config init path imports.
+
+export interface GetAccessTokenReactiveDeps extends GetAccessTokenDeps {
+ /**
+ * Runs `work` inside a short transaction. Default: `withTransaction` from db.ts
+ * (module pool). Injectable for tests. The provided client is transaction-scoped
+ * so it can take the row lock and bound the carrier's idle timeout.
+ */
+ runInTransaction?: <T>(work: (txDb: DbTransactionClient) => Promise<T>) => Promise<T>
+}
+
+/**
+ * Reactive entry point to the refresh engine — the one the four on-demand token
+ * routes call. Serializes the `read → refresh → persist` critical section per grant
+ * so a rotating refresh token is POSTed exactly once even under P↔R / R↔R
+ * concurrency (mini-spec 16, R2-M1).
+ *
+ * Two paths:
+ * - FAST-PATH: a loose-pool read; a valid (non-stale) token, or a stale token
+ * with no refresh token, returns WITHOUT opening a transaction or taking a lock
+ * (~99% of calls pay nothing). A stale-but-no-refresh-token grant degrades to
+ * `no_grant` (re-consent) with nothing to serialize.
+ * - SLOW-PATH (stale + has refresh token): open a tx, take a BLOCKING `FOR UPDATE`
+ * on the grant row, bound the carrier's idle timeout, then run the engine on the
+ * SAME tx client. The engine re-reads under the lock (its first line is
+ * `getOAuthGrant`), so if a proactive or concurrent reactive refresh already
+ * rotated the token while we waited, we return the fresh token and issue NO POST.
+ *
+ * Return type is identical to {@link getAccessToken}, so callers' `switch` is
+ * unchanged.
+ */
+export async function getAccessTokenReactive(
+ input: GetAccessTokenInput,
+ deps: GetAccessTokenReactiveDeps
+): Promise<GetAccessTokenResult> {
+ // FAST-PATH: loose read, no tx, no lock.
+ const grant = await getOAuthGrant(deps.db, deps.encryptionKey, input)
+ if (!grant) return { kind: 'no_grant' }
+ const refreshBufferMs = deps.refreshBufferMs ?? REACTIVE_REFRESH_BUFFER_MS
+ if (!isAccessTokenStale(grant, refreshBufferMs)) {
+ return { kind: 'ok', accessToken: grant.accessToken, expiresAt: grant.accessTokenExpiresAt }
+ }
+ // Stale with no refresh token → re-consent; nothing to serialize.
+ if (!grant.refreshToken) return { kind: 'no_grant' }
+
+ // SLOW-PATH: serialize the refresh under a per-grant row lock.
+ const runInTransaction = deps.runInTransaction ?? withTransaction
+ return runInTransaction(async txDb => {
+ await lockOAuthGrantForRefresh(txDb, input)
+ await boundOAuthRefreshLockIdleTimeout(txDb)
+ // The engine re-reads the grant under the lock (double-check): if it is no
+ // longer stale, it returns `ok` without POSTing. `requireBackground` flows
+ // through `input` untouched.
+ return getAccessToken(input, { ...deps, db: txDb })
+ })
+}
diff --git a/control-api/src/oauth/store.ts b/control-api/src/oauth/store.ts
index b00e44608..ab8f45283 100644
--- a/control-api/src/oauth/store.ts
+++ b/control-api/src/oauth/store.ts
@@ -906,3 +906,66 @@ export async function claimRemoteGrantForRefresh(
)
return (result.rowCount ?? 0) > 0
}
+
+/**
+ * Take the per-grant row lock for the REACTIVE refresh path (mini-spec 16,
+ * R2-M1). `SELECT 1 … FOR UPDATE` keyed by the exact grant coordinate — BLOCKING
+ * (no `SKIP LOCKED`) and with NO window predicate, unlike the proactive claim
+ * ({@link claimRemoteGrantForRefresh}): a reactive caller must WAIT for whoever
+ * holds the row (proactive or another reactive) and then re-read the fresh token,
+ * rather than skip and double-spend the rotating refresh token. Sharing the same
+ * row is what makes the reactive lock mutually exclusive with the proactive
+ * `FOR UPDATE SKIP LOCKED`.
+ *
+ * Returns `rowCount > 0`: `false` means the row is absent (deleted, or never
+ * existed). The engine's re-read under the lock already surfaces that as
+ * `no_grant`, so the boolean is an informational signal, not a required branch.
+ *
+ * `txClient` MUST be inside an open transaction (BEGIN issued); the lock only
+ * survives until COMMIT/ROLLBACK.
+ *
+ * F2 Class-check: the per-flavor WHERE (owner_kind + coordinate + grant_kind) is
+ * repeated verbatim across `getOAuthGrant`, `oauthGrantExists`, `deleteOAuthGrant`,
+ * `refreshOAuthGrantTokens`, `claimRemoteGrantForRefresh` — this is the 6th site.
+ * Deliberately NOT extracted to a shared helper: that would touch the proactive
+ * claim (hot path, green). If the key semantics change, grep `grant_kind = 'user'`
+ * / `'shared'` / `'service'` and change all six together.
+ */
+export async function lockOAuthGrantForRefresh(
+ txClient: DbClient,
+ key: OAuthGrantKey
+): Promise<boolean> {
+ const ownerKind = resolveOwnerKind(key)
+
+ if (key.grantKind === 'user') {
+ const result = await txClient.query(
+ `SELECT 1 FROM oauth_grants
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id = $4 AND oauth_client_id = $5 AND grant_kind = 'user'
+ FOR UPDATE`,
+ [ownerKind, key.recipeNamespace, key.recipeName, key.userId, key.oauthClientId]
+ )
+ return (result.rowCount ?? 0) > 0
+ }
+
+ if (key.grantKind === 'shared') {
+ const result = await txClient.query(
+ `SELECT 1 FROM oauth_grants
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id IS NULL AND context_id = $4 AND oauth_client_id = $5
+ AND grant_kind = 'shared'
+ FOR UPDATE`,
+ [ownerKind, key.recipeNamespace, key.recipeName, key.contextId, key.oauthClientId]
+ )
+ return (result.rowCount ?? 0) > 0
+ }
+
+ const result = await txClient.query(
+ `SELECT 1 FROM oauth_grants
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id IS NULL AND oauth_client_id = $4 AND grant_kind = 'service'
+ FOR UPDATE`,
+ [ownerKind, key.recipeNamespace, key.recipeName, key.oauthClientId]
+ )
+ return (result.rowCount ?? 0) > 0
+}
diff --git a/control-api/src/oauth/tokenHelper.ts b/control-api/src/oauth/tokenHelper.ts
index 5a6f09442..7908bf87f 100644
--- a/control-api/src/oauth/tokenHelper.ts
+++ b/control-api/src/oauth/tokenHelper.ts
@@ -29,6 +29,14 @@ import { type OAuthGrantKey, getOAuthGrant, refreshOAuthGrantTokens } from './st
* Callers: the cookie-authed `POST /sandbox-ui/oauth/token` endpoint for `user`
* grants (spec §9.9), and the broker route `POST /api/v1/recipe-oauth/token`
* for `service` grants (Path B, spec §10).
+ *
+ * CONCURRENCY GUARD-RAIL: this is the UNLOCKED refresh engine. It must only be
+ * called (a) with a `deps.db` that already holds this grant's row lock inside an
+ * open transaction — the proactive cron and {@link getAccessTokenReactive} do
+ * exactly this — or (b) via {@link getAccessTokenReactive}, which takes the row
+ * lock for you. A direct reactive call on a loose pool client re-opens the
+ * double-spend hole (two POSTs with the same rotating refresh token → the AS kills
+ * the grant). Reactive callers use {@link getAccessTokenReactive}, never this.
*/
/**
@@ -40,6 +48,22 @@ import { type OAuthGrantKey, getOAuthGrant, refreshOAuthGrantTokens } from './st
*/
export const REACTIVE_REFRESH_BUFFER_MS = 60_000
+/**
+ * A stored access token is "stale" — due for refresh — once it sits within
+ * `refreshBufferMs` of expiry. A grant with no known expiry (`accessTokenExpiresAt`
+ * absent) is never stale: there is nothing to refresh against. Single source of
+ * truth for the staleness rule (regla D4): both the reactive fast-path
+ * ({@link getAccessTokenReactive}) and the engine ({@link getAccessToken}) call
+ * this, so they can never disagree on what "stale" means.
+ */
+export function isAccessTokenStale(
+ grant: { accessTokenExpiresAt?: Date },
+ refreshBufferMs: number
+): boolean {
+ if (!grant.accessTokenExpiresAt) return false
+ return grant.accessTokenExpiresAt.getTime() - refreshBufferMs <= Date.now()
+}
+
export type GetAccessTokenInput = OAuthGrantKey & {
/**
* Require a background-consented grant (per-user broker, SEC-5). Parametrized,
@@ -86,10 +110,7 @@ export async function getAccessToken(
if (!grant) return { kind: 'no_grant' }
const refreshBufferMs = deps.refreshBufferMs ?? REACTIVE_REFRESH_BUFFER_MS
- const stillValid =
- !grant.accessTokenExpiresAt ||
- grant.accessTokenExpiresAt.getTime() - refreshBufferMs > Date.now()
- if (stillValid) {
+ if (!isAccessTokenStale(grant, refreshBufferMs)) {
return { kind: 'ok', accessToken: grant.accessToken, expiresAt: grant.accessTokenExpiresAt }
}
diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.ts
index 89e68384d..c47816682 100644
--- a/control-api/src/routes/internal/oauth.ts
+++ b/control-api/src/routes/internal/oauth.ts
@@ -23,8 +23,8 @@ import {
resolveServerOAuth,
resolveServerOAuthSubject,
} from '../../oauth/mcpServerOAuthSpec.js'
+import { getAccessTokenReactive } from '../../oauth/reactiveTokenHelper.js'
import { deleteOAuthGrant } from '../../oauth/store.js'
-import { getAccessToken } from '../../oauth/tokenHelper.js'
import { getUserContexts } from '../../services/directory/index.js'
import { K8sNotFoundError } from '../../services/resourceService.js'
import { buildPublicCallbackUrl } from '../external/oauthCallback.js'
@@ -529,7 +529,7 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
return res.status(400).json({ error: 'invalid_recipe_namespace' })
}
- const result = await getAccessToken(
+ const result = await getAccessTokenReactive(
{
grantKind: 'user',
recipeNamespace: recipeNs,
diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.ts
index 22ade3f2a..8cf367bb3 100644
--- a/control-api/src/routes/mcpOauth.ts
+++ b/control-api/src/routes/mcpOauth.ts
@@ -19,8 +19,8 @@ import {
resolveServerOAuth,
resolveServerOAuthSubject,
} from '../oauth/mcpServerOAuthSpec.js'
+import { getAccessTokenReactive } from '../oauth/reactiveTokenHelper.js'
import { type OAuthGrantKey, oauthGrantExists } from '../oauth/store.js'
-import { getAccessToken } from '../oauth/tokenHelper.js'
import { type Logger, rootLogger } from '../observability/logger.js'
import { K8sNotFoundError } from '../services/resourceService.js'
import {
@@ -496,7 +496,7 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {
// Interactive live-session path — a human session is present, so
// background consent is NOT required here (requireBackground: false).
- const result = await getAccessToken(
+ const result = await getAccessTokenReactive(
{ ...key, requireBackground: false },
{
db: { query: (text, values) => pool.query(text, values) },
diff --git a/control-api/src/routes/recipeOauth.ts b/control-api/src/routes/recipeOauth.ts
index dae4f1baa..d35203e23 100644
--- a/control-api/src/routes/recipeOauth.ts
+++ b/control-api/src/routes/recipeOauth.ts
@@ -13,8 +13,8 @@ import {
} from '../oauth/callback.js'
import { deriveOAuthEncryptionKey } from '../oauth/encryption.js'
import { integrationNotConfigured, isSecretNotFound } from '../oauth/integrationNotConfigured.js'
+import { getAccessTokenReactive } from '../oauth/reactiveTokenHelper.js'
import { listBackgroundUserGrants } from '../oauth/store.js'
-import { getAccessToken } from '../oauth/tokenHelper.js'
import { K8sNotFoundError } from '../services/resourceService.js'
/**
@@ -111,7 +111,7 @@ export function createRecipeOauthRouter(gateway: K8sGateway): Router {
return res.status(400).json({ error: 'unknown_oauth_client' })
}
- const result = await getAccessToken(
+ const result = await getAccessTokenReactive(
{
grantKind: 'service',
recipeNamespace,
@@ -223,7 +223,7 @@ export function createRecipeOauthRouter(gateway: K8sGateway): Router {
return res.status(400).json({ error: 'unknown_oauth_client' })
}
- const result = await getAccessToken(
+ const result = await getAccessTokenReactive(
{
grantKind: 'user',
recipeNamespace,
diff --git a/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts b/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts
new file mode 100644
index 000000000..4570e7680
--- /dev/null
+++ b/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts
@@ -0,0 +1,290 @@
+/**
+ * Reactive refresh row-lock serialization (mini-spec 16, R2-M1), on a REAL
+ * Postgres so the BLOCKING `FOR UPDATE` and its mutual exclusion with the
+ * proactive `FOR UPDATE SKIP LOCKED` are exercised against the actual schema —
+ * a mock `DbClient` cannot model row locking.
+ *
+ * Fixtures come from the REAL producers (`bootstrapSharedOAuthGrant`, T1). The
+ * fake token endpoint (a `PinnedTransport`, like the proactive test) models a
+ * ROTATING refresh token: the first POST rotates it and returns fresh tokens; any
+ * later POST that presents an already-used refresh token gets `400 invalid_grant`.
+ * Counting POSTs is the observable (T4): the bug is two POSTs (double-spend) that
+ * kill the grant; the fix is exactly one.
+ *
+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \
+ * test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts
+ */
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { config } from '../src/config.js'
+import type { DbClient, DbTransactionClient } from '../src/db.js'
+import { initDb } from '../src/db.js'
+import type {
+ PinnedRawResponse,
+ PinnedTransport,
+ PinnedTransportInput,
+} from '../src/http/pinnedFetch.js'
+import type { RecipeWithOAuthClients } from '../src/oauth/callback.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'
+import { getAccessTokenReactive } from '../src/oauth/reactiveTokenHelper.js'
+import {
+ type OAuthGrantKey,
+ bootstrapSharedOAuthGrant,
+ claimRemoteGrantForRefresh,
+ getOAuthGrant,
+} from '../src/oauth/store.js'
+import { getAccessToken } from '../src/oauth/tokenHelper.js'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+const NS = config.mcpServersNamespace
+// Bp/Br as the proactive sweep uses them; a token in the proactive window is
+// treated as stale by BOTH sides here (refreshBufferMs = Bp), which is what lets
+// the proactive claim (window predicate) and the reactive refresh contend on the
+// SAME row — the crux of the P↔R case.
+const WINDOW = { proactiveBufferMs: 300_000, reactiveBufferMs: 60_000 }
+const IN_WINDOW_SEC = 200 // 60s < 200s ≤ 300s → proactive window AND stale under Bp
+const REMOTE_OAUTH_ID = 'https://control.example.com/.well-known/evenfire-mcp-client'
+const REMOTE_TOKEN_ENDPOINT = 'https://as.example.com/token'
+const REMOTE_VALIDATED_IP = '93.184.216.34'
+
+describeRealPostgres('oauth reactive refresh — row-lock serialization (real Postgres)', () => {
+ const database = `control_api_reactive_lock_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+
+ beforeAll(async () => {
+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })
+ await initDb({ connect: () => dbPool.connect() })
+ db = { query: (text, values) => dbPool.query(text, values) }
+ })
+
+ afterAll(async () => {
+ await dbPool?.end()
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ const sharedKey = (server: string, ctx: string): OAuthGrantKey => ({
+ grantKind: 'shared',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: server,
+ contextId: ctx,
+ oauthClientId: REMOTE_OAUTH_ID,
+ })
+
+ async function seedShared(server: string, ctx: string, expiresInSec: number): Promise<void> {
+ await bootstrapSharedOAuthGrant(db, KEY, {
+ ...sharedKey(server, ctx),
+ bootstrappedByUserId: 'user-1',
+ provider: 'remote',
+ accessToken: 'AT-0',
+ refreshToken: 'RT-0',
+ accessTokenExpiresInSec: expiresInSec,
+ })
+ }
+
+ function remoteOwnerDecl(): RecipeWithOAuthClients {
+ const resolved = resolveServerOAuthSubject({
+ spec: {
+ contextRef: 'ctx-1',
+ oauth: {
+ source: 'remote',
+ id: REMOTE_OAUTH_ID,
+ clientMode: 'public',
+ authorizationEndpoint: 'https://as.example.com/authorize',
+ tokenEndpoint: REMOTE_TOKEN_ENDPOINT,
+ issuer: 'https://as.example.com',
+ resource: 'https://as.example.com',
+ grantScope: 'user',
+ scopes: ['read'],
+ bearerInBody: false,
+ supportsRefresh: true,
+ },
+ },
+ })
+ if (!resolved) throw new Error('fixture: remote resolve returned null')
+ return { spec: { oauthClients: [resolved.decl] } }
+ }
+
+ /**
+ * Rotating-refresh-token AS. Each accepted POST invalidates the presented
+ * refresh token and mints a new pair; reusing a spent refresh token → 400
+ * invalid_grant (what a real AS does on rotation reuse, killing the grant).
+ */
+ function rotatingAs() {
+ const validRefreshTokens = new Set<string>(['RT-0'])
+ let generation = 0
+ let postCount = 0
+ const transport: PinnedTransport = async (
+ input: PinnedTransportInput
+ ): Promise<PinnedRawResponse> => {
+ postCount += 1
+ const presented = new URLSearchParams(input.body ?? '').get('refresh_token') ?? ''
+ if (!validRefreshTokens.has(presented)) {
+ return {
+ status: 400,
+ headers: { 'content-type': 'application/json' },
+ bodyText: JSON.stringify({ error: 'invalid_grant' }),
+ }
+ }
+ validRefreshTokens.delete(presented)
+ generation += 1
+ const next = `RT-${generation}`
+ validRefreshTokens.add(next)
+ return {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ bodyText: JSON.stringify({
+ access_token: `AT-${generation}`,
+ refresh_token: next,
+ expires_in: 3600,
+ }),
+ }
+ }
+ return {
+ transport,
+ get postCount() {
+ return postCount
+ },
+ }
+ }
+
+ const reactiveDeps = (transport: PinnedTransport) => ({
+ db,
+ recipeReader: { read: async () => remoteOwnerDecl() },
+ secretReader: { read: async () => ({}) },
+ fetchFn: (async () => {
+ throw new Error('remote refresh must not use fetchFn')
+ }) as unknown as typeof fetch,
+ encryptionKey: KEY,
+ resolveDns: async () => [REMOTE_VALIDATED_IP],
+ pinnedTransport: transport,
+ // Bp so an in-proactive-window token is treated as stale by the reactive path
+ // too — exactly the overlap that produced the double-spend.
+ refreshBufferMs: WINDOW.proactiveBufferMs,
+ // Reactive slow-path tx bound to the TEST pool (the module `pool` points at the
+ // real configured DB, not this ephemeral one), so the row lock lands here.
+ runInTransaction: async <T>(work: (txDb: DbTransactionClient) => Promise<T>): Promise<T> => {
+ const client = await dbPool.connect()
+ try {
+ await client.query('BEGIN')
+ const txDb = {
+ query: (t: string, v?: unknown[]) => client.query(t, v),
+ } as unknown as DbTransactionClient
+ const result = await work(txDb)
+ await client.query('COMMIT')
+ return result
+ } catch (err) {
+ await client.query('ROLLBACK').catch(() => {})
+ throw err
+ } finally {
+ client.release()
+ }
+ },
+ })
+
+ async function waitForLockWaiter(): Promise<void> {
+ for (let i = 0; i < 200; i += 1) {
+ const r = await adminPool.query(
+ `SELECT count(*)::int AS n FROM pg_stat_activity
+ WHERE datname = $1 AND wait_event_type = 'Lock'`,
+ [database]
+ )
+ if (((r.rows[0] as { n: number }).n ?? 0) > 0) return
+ await new Promise(res => setTimeout(res, 25))
+ }
+ throw new Error('the reactive refresh never blocked on the row lock')
+ }
+
+ it('P↔R: a reactive refresh blocks on the proactive row lock, then re-reads fresh (1 POST)', async () => {
+ await seedShared('pr', 'ctx-1', IN_WINDOW_SEC)
+ const key = sharedKey('pr', 'ctx-1')
+ const as = rotatingAs()
+
+ // Proactive side: claim (FOR UPDATE SKIP LOCKED) + refresh on the SAME tx,
+ // held OPEN (uncommitted) so it owns the row lock while the reactive contends.
+ const c1 = await dbPool.connect()
+ try {
+ await c1.query('BEGIN')
+ const c1Tx = { query: (t: string, v?: unknown[]) => c1.query(t, v) }
+ const claimed = await claimRemoteGrantForRefresh(c1Tx, key, WINDOW)
+ expect(claimed).toBe(true)
+ const proactive = await getAccessToken(
+ { ...key, requireBackground: false },
+ {
+ db: c1Tx,
+ recipeReader: { read: async () => remoteOwnerDecl() },
+ secretReader: { read: async () => ({}) },
+ fetchFn: (async () => {
+ throw new Error('remote refresh must not use fetchFn')
+ }) as unknown as typeof fetch,
+ encryptionKey: KEY,
+ resolveDns: async () => [REMOTE_VALIDATED_IP],
+ pinnedTransport: as.transport,
+ refreshBufferMs: WINDOW.proactiveBufferMs,
+ }
+ )
+ expect(proactive.kind).toBe('ok')
+ expect(as.postCount).toBe(1) // proactive did the single POST
+
+ // Reactive side: still sees the OLD (uncommitted) token → wants to refresh →
+ // blocks on the row lock. It must NOT double-spend.
+ const reactivePromise = getAccessTokenReactive(key, reactiveDeps(as.transport))
+ await waitForLockWaiter()
+
+ await c1.query('COMMIT') // releases the lock; row now carries the fresh token
+ const reactive = await reactivePromise
+ expect(reactive.kind).toBe('ok')
+ } finally {
+ c1.release()
+ }
+
+ // The observable: exactly ONE POST total; the grant survives with the rotated
+ // token; no invalid_grant was ever provoked.
+ expect(as.postCount).toBe(1)
+ const after = await getOAuthGrant(db, KEY, key)
+ expect(after?.accessToken).toBe('AT-1')
+ expect(after?.refreshToken).toBe('RT-1')
+ })
+
+ it('R↔R: two concurrent reactive refreshes over one grant issue exactly 1 POST', async () => {
+ await seedShared('rr', 'ctx-1', IN_WINDOW_SEC)
+ const key = sharedKey('rr', 'ctx-1')
+ const as = rotatingAs()
+
+ const [a, b] = await Promise.all([
+ getAccessTokenReactive(key, reactiveDeps(as.transport)),
+ getAccessTokenReactive(key, reactiveDeps(as.transport)),
+ ])
+
+ expect(a.kind).toBe('ok')
+ expect(b.kind).toBe('ok')
+ expect(as.postCount).toBe(1) // one refreshed, the other re-read fresh under the lock
+ const after = await getOAuthGrant(db, KEY, key)
+ expect(after?.accessToken).toBe('AT-1')
+ expect(after?.refreshToken).toBe('RT-1')
+ })
+})