Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): persist encrypted Codex subscription connection
Alfredo Lopez70343b9a247f
diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex 4d37efad1..9f434cc49 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -5,6 +5,8 @@ import {createBoundedPgPoolForConnection,} from './boundedPgPool.js'import { config } from './config.js'+import { applyCodexSubscriptionConnectionSchema } from './services/codexSubscriptionConnection.js'+import { applyCodexSubscriptionOAuthStateSchema } from './services/codexSubscriptionOAuthState.js'import {applyGfsUploadCleanupSchema,applyGfsUploadFinalizingSchema,@@ -5914,6 +5916,14 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [version: '0099_gfs_upload_finalizing_recovery',apply: applyGfsUploadFinalizingSchema,},+ {+ version: '00a0_codex_subscription_connections',+ apply: applyCodexSubscriptionConnectionSchema,+ },+ {+ version: '00a1_codex_subscription_oauth_states',+ apply: applyCodexSubscriptionOAuthStateSchema,+ },{version: '0100_seed_minimax_allowed_model',apply: async db => {diff --git a/control-api/src/services/codexSubscriptionConnection.ts b/control-api/src/services/codexSubscriptionConnection.tsnew file mode 100644index 000000000..c36e14035--- /dev/null+++ b/control-api/src/services/codexSubscriptionConnection.ts@@ -0,0 +1,335 @@+import type { DbClient } from '../db.js'+import { decryptOAuthSecret, encryptOAuthSecret } from '../oauth/encryption.js'++export const CODEX_SUBSCRIPTION_CONNECTION_KEY = 'deployment-default' as const++export type CodexSubscriptionConnectionStatus =+ | 'disconnected'+ | 'connecting'+ | 'connected'+ | 'reauth_required'+ | 'revoked'++export type CodexSubscriptionCatalogStatus =+ | 'never_synced'+ | 'ready'+ | 'auth-rejected'+ | 'unavailable'++export type CodexSubscriptionSafeConnection = {+ connectionKey: typeof CODEX_SUBSCRIPTION_CONNECTION_KEY+ status: CodexSubscriptionConnectionStatus+ credentialRevision: number+ catalogRevision: number+ accountFingerprint: string | null+ catalogStatus: CodexSubscriptionCatalogStatus+ catalogSyncedAt: Date | null+ lastRefreshAt: Date | null+ lastAuthAt: Date | null+ refreshLockHeld: boolean+ revokedAt: Date | null+ createdAt: Date+ updatedAt: Date+}++export type CodexSubscriptionCredentialWrite = {+ refreshToken: string+ accessToken?: string | null+ accessTokenExpiresAt?: Date | null+ accountFingerprint: string+ status?: Extract<CodexSubscriptionConnectionStatus, 'connected' | 'reauth_required'>+}++export type CodexSubscriptionSecrets = {+ refreshToken: string+ accessToken: string | null+ accessTokenExpiresAt: Date | null+ credentialRevision: number+}++type SafeConnectionRow = {+ connection_key: string+ status: CodexSubscriptionConnectionStatus+ credential_revision: string | number+ catalog_revision: string | number+ account_fingerprint: string | null+ catalog_status: CodexSubscriptionCatalogStatus+ catalog_synced_at: Date | string | null+ last_refresh_at: Date | string | null+ last_auth_at: Date | string | null+ refresh_lock_token: string | null+ refresh_lock_expires_at: Date | string | null+ revoked_at: Date | string | null+ created_at: Date | string+ updated_at: Date | string+}++const SAFE_CONNECTION_COLUMNS = `+ connection_key,+ status,+ credential_revision,+ catalog_revision,+ account_fingerprint,+ catalog_status,+ catalog_synced_at,+ last_refresh_at,+ last_auth_at,+ refresh_lock_token,+ refresh_lock_expires_at,+ revoked_at,+ created_at,+ updated_at+`++export class CodexSubscriptionStaleRevisionError extends Error {+ readonly code = 'codex_subscription_stale_revision'++ constructor() {+ super('Codex subscription credential revision is stale')+ this.name = 'CodexSubscriptionStaleRevisionError'+ }+}++export async function applyCodexSubscriptionConnectionSchema(db: DbClient): Promise<void> {+ await db.query(`+ CREATE TABLE IF NOT EXISTS codex_subscription_connections (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ connection_key TEXT NOT NULL,+ status TEXT NOT NULL CHECK (status IN (+ 'disconnected', 'connecting', 'connected', 'reauth_required', 'revoked'+ )),+ refresh_token_encrypted TEXT,+ access_token_encrypted TEXT,+ access_token_expires_at TIMESTAMPTZ,+ credential_revision BIGINT NOT NULL DEFAULT 1+ CHECK (credential_revision >= 1),+ catalog_revision BIGINT NOT NULL DEFAULT 0+ CHECK (catalog_revision >= 0),+ account_fingerprint TEXT,+ catalog_status TEXT NOT NULL DEFAULT 'never_synced'+ CHECK (catalog_status IN ('never_synced', 'ready', 'auth-rejected', 'unavailable')),+ catalog_synced_at TIMESTAMPTZ,+ last_refresh_at TIMESTAMPTZ,+ last_auth_at TIMESTAMPTZ,+ refresh_lock_token TEXT,+ refresh_lock_expires_at TIMESTAMPTZ,+ revoked_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT codex_subscription_connections_key_check+ CHECK (connection_key = 'deployment-default'),+ CONSTRAINT codex_subscription_connections_connection_key_unique+ UNIQUE (connection_key),+ CONSTRAINT codex_subscription_connections_ciphertext_when_connected+ CHECK (+ status NOT IN ('connected', 'reauth_required')+ OR (+ refresh_token_encrypted IS NOT NULL+ AND account_fingerprint IS NOT NULL+ )+ )+ );++ CREATE UNIQUE INDEX IF NOT EXISTS codex_subscription_connections_active_key+ ON codex_subscription_connections (connection_key)+ WHERE revoked_at IS NULL;++ REVOKE ALL PRIVILEGES ON TABLE codex_subscription_connections FROM PUBLIC;+ REVOKE ALL PRIVILEGES ON TABLE codex_subscription_connections+ FROM trace_maintenance_runtime, workflow_recipes_runtime;+ GRANT SELECT, INSERT, UPDATE ON TABLE codex_subscription_connections TO control_api_runtime;+ REVOKE DELETE, TRUNCATE, REFERENCES, TRIGGER ON TABLE codex_subscription_connections FROM control_api_runtime;+ `)+}++export async function getSafeCodexSubscriptionConnection(+ db: DbClient+): Promise<CodexSubscriptionSafeConnection | null> {+ const result = await db.query(+ `SELECT ${SAFE_CONNECTION_COLUMNS}+ FROM codex_subscription_connections+ WHERE connection_key = $1`,+ [CODEX_SUBSCRIPTION_CONNECTION_KEY]+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ return row ? toSafeConnection(row) : null+}++export async function insertInitialCodexSubscriptionConnection(+ db: DbClient,+ encryptionKey: Buffer,+ input: CodexSubscriptionCredentialWrite+): Promise<CodexSubscriptionSafeConnection> {+ const refreshTokenEncrypted = encryptOAuthSecret(encryptionKey, input.refreshToken)+ const accessTokenEncrypted =+ input.accessToken == null || input.accessToken === ''+ ? null+ : encryptOAuthSecret(encryptionKey, input.accessToken)+ const result = await db.query(+ `INSERT INTO codex_subscription_connections (+ connection_key,+ status,+ refresh_token_encrypted,+ access_token_encrypted,+ access_token_expires_at,+ credential_revision,+ catalog_revision,+ account_fingerprint,+ catalog_status,+ last_auth_at+ ) VALUES ($1, $2, $3, $4, $5, 1, 0, $6, 'never_synced', now())+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ [+ CODEX_SUBSCRIPTION_CONNECTION_KEY,+ input.status ?? 'connected',+ refreshTokenEncrypted,+ accessTokenEncrypted,+ input.accessTokenExpiresAt ?? null,+ input.accountFingerprint,+ ]+ )+ return toSafeConnection(result.rows[0] as SafeConnectionRow)+}++export async function rotateCodexSubscriptionCredentials(+ db: DbClient,+ encryptionKey: Buffer,+ expectedRevision: number,+ input: CodexSubscriptionCredentialWrite+): Promise<CodexSubscriptionSafeConnection> {+ const refreshTokenEncrypted = encryptOAuthSecret(encryptionKey, input.refreshToken)+ const accessTokenEncrypted =+ input.accessToken == null || input.accessToken === ''+ ? null+ : encryptOAuthSecret(encryptionKey, input.accessToken)+ const result = await db.query(+ `UPDATE codex_subscription_connections+ SET refresh_token_encrypted = $1,+ access_token_encrypted = $2,+ access_token_expires_at = $3,+ account_fingerprint = $4,+ status = $5,+ credential_revision = credential_revision + 1,+ last_refresh_at = now(),+ last_auth_at = now(),+ revoked_at = NULL,+ updated_at = now()+ WHERE connection_key = $6+ AND credential_revision = $7+ AND revoked_at IS NULL+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ [+ refreshTokenEncrypted,+ accessTokenEncrypted,+ input.accessTokenExpiresAt ?? null,+ input.accountFingerprint,+ input.status ?? 'connected',+ CODEX_SUBSCRIPTION_CONNECTION_KEY,+ expectedRevision,+ ]+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ if (!row) throw new CodexSubscriptionStaleRevisionError()+ return toSafeConnection(row)+}++export async function acquireCodexSubscriptionRefreshLock(+ db: DbClient,+ lockToken: string,+ ttlMs: number+): Promise<boolean> {+ const result = await db.query(+ `UPDATE codex_subscription_connections+ SET refresh_lock_token = $1,+ refresh_lock_expires_at = now() + ($2 * interval '1 millisecond'),+ updated_at = now()+ WHERE connection_key = $3+ AND revoked_at IS NULL+ AND (+ refresh_lock_token IS NULL+ OR refresh_lock_expires_at IS NULL+ OR refresh_lock_expires_at <= now()+ )+ RETURNING refresh_lock_token`,+ [lockToken, ttlMs, CODEX_SUBSCRIPTION_CONNECTION_KEY]+ )+ return (result.rowCount ?? 0) > 0+}++export async function releaseCodexSubscriptionRefreshLock(+ db: DbClient,+ lockToken: string+): Promise<boolean> {+ const result = await db.query(+ `UPDATE codex_subscription_connections+ SET refresh_lock_token = NULL,+ refresh_lock_expires_at = NULL,+ updated_at = now()+ WHERE connection_key = $1+ AND refresh_lock_token = $2`,+ [CODEX_SUBSCRIPTION_CONNECTION_KEY, lockToken]+ )+ return (result.rowCount ?? 0) > 0+}++export async function loadCodexSubscriptionSecrets(+ db: DbClient,+ encryptionKey: Buffer+): Promise<CodexSubscriptionSecrets | null> {+ const result = await db.query(+ `SELECT refresh_token_encrypted,+ access_token_encrypted,+ access_token_expires_at,+ credential_revision+ FROM codex_subscription_connections+ WHERE connection_key = $1+ AND revoked_at IS NULL`,+ [CODEX_SUBSCRIPTION_CONNECTION_KEY]+ )+ const row = result.rows[0] as+ | {+ refresh_token_encrypted: string | null+ access_token_encrypted: string | null+ access_token_expires_at: Date | string | null+ credential_revision: string | number+ }+ | undefined+ if (!row?.refresh_token_encrypted) return null+ return {+ refreshToken: decryptOAuthSecret(encryptionKey, row.refresh_token_encrypted),+ accessToken: row.access_token_encrypted+ ? decryptOAuthSecret(encryptionKey, row.access_token_encrypted)+ : null,+ accessTokenExpiresAt: asDate(row.access_token_expires_at),+ credentialRevision: Number(row.credential_revision),+ }+}++function toSafeConnection(row: SafeConnectionRow): CodexSubscriptionSafeConnection {+ return {+ connectionKey: CODEX_SUBSCRIPTION_CONNECTION_KEY,+ status: row.status,+ credentialRevision: Number(row.credential_revision),+ catalogRevision: Number(row.catalog_revision),+ accountFingerprint: row.account_fingerprint,+ catalogStatus: row.catalog_status,+ catalogSyncedAt: asDate(row.catalog_synced_at),+ lastRefreshAt: asDate(row.last_refresh_at),+ lastAuthAt: asDate(row.last_auth_at),+ refreshLockHeld: isLockHeld(row.refresh_lock_token, row.refresh_lock_expires_at),+ revokedAt: asDate(row.revoked_at),+ createdAt: asDate(row.created_at) ?? new Date(0),+ updatedAt: asDate(row.updated_at) ?? new Date(0),+ }+}++function isLockHeld(token: string | null, expiresAt: Date | string | null): boolean {+ if (!token) return false+ const expires = asDate(expiresAt)+ return expires !== null && expires.getTime() > Date.now()+}++function asDate(value: Date | string | null | undefined): Date | null {+ if (value == null) return null+ return value instanceof Date ? value : new Date(value)+}diff --git a/control-api/src/services/codexSubscriptionOAuthState.ts b/control-api/src/services/codexSubscriptionOAuthState.tsnew file mode 100644index 000000000..6ecbd4595--- /dev/null+++ b/control-api/src/services/codexSubscriptionOAuthState.ts@@ -0,0 +1,195 @@+import type { DbClient } from '../db.js'+import { decryptOAuthSecret, encryptOAuthSecret } from '../oauth/encryption.js'++export type CodexSubscriptionOAuthFlow = 'browser' | 'device'+export type CodexSubscriptionOAuthIntent = 'connect' | 'reconnect' | 'replace'+export type CodexSubscriptionOAuthStateStatus = 'pending' | 'consumed' | 'expired' | 'cancelled'++export type CodexSubscriptionOAuthSafeState = {+ state: string+ flow: CodexSubscriptionOAuthFlow+ intent: CodexSubscriptionOAuthIntent+ status: CodexSubscriptionOAuthStateStatus+ expiresAt: Date+ consumedAt: Date | null+ cancelledAt: Date | null+ createdAt: Date+}++export type CodexSubscriptionOAuthStateWrite = {+ state: string+ flow: CodexSubscriptionOAuthFlow+ intent: CodexSubscriptionOAuthIntent+ pkceVerifier?: string+ deviceCode?: string+ expiresAt: Date+}++export type CodexSubscriptionConsumedOAuthState = {+ safe: CodexSubscriptionOAuthSafeState+ pkceVerifier?: string+ deviceCode?: string+}++type SafeOAuthStateRow = {+ state: string+ flow: CodexSubscriptionOAuthFlow+ intent: CodexSubscriptionOAuthIntent+ status: CodexSubscriptionOAuthStateStatus+ expires_at: Date | string+ consumed_at: Date | string | null+ cancelled_at: Date | string | null+ created_at: Date | string+}++type ConsumedOAuthStateRow = SafeOAuthStateRow & {+ pkce_verifier_encrypted: string | null+ device_code_encrypted: string | null+}++const SAFE_OAUTH_STATE_COLUMNS = `+ state,+ flow,+ intent,+ status,+ expires_at,+ consumed_at,+ cancelled_at,+ created_at+`++export async function applyCodexSubscriptionOAuthStateSchema(db: DbClient): Promise<void> {+ await db.query(`+ CREATE TABLE IF NOT EXISTS codex_subscription_oauth_states (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ state TEXT NOT NULL,+ flow TEXT NOT NULL CHECK (flow IN ('browser', 'device')),+ intent TEXT NOT NULL CHECK (intent IN ('connect', 'reconnect', 'replace')),+ pkce_verifier_encrypted TEXT,+ device_code_encrypted TEXT,+ status TEXT NOT NULL CHECK (status IN ('pending', 'consumed', 'expired', 'cancelled')),+ expires_at TIMESTAMPTZ NOT NULL,+ consumed_at TIMESTAMPTZ,+ cancelled_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT codex_subscription_oauth_states_state_unique UNIQUE (state),+ CONSTRAINT codex_subscription_oauth_states_flow_secrets CHECK (+ (flow = 'browser' AND pkce_verifier_encrypted IS NOT NULL)+ OR (flow = 'device' AND device_code_encrypted IS NOT NULL)+ ),+ CONSTRAINT codex_subscription_oauth_states_lifecycle CHECK (+ (status = 'pending' AND consumed_at IS NULL AND cancelled_at IS NULL)+ OR (status = 'consumed' AND consumed_at IS NOT NULL AND cancelled_at IS NULL)+ OR (status = 'cancelled' AND cancelled_at IS NOT NULL AND consumed_at IS NULL)+ OR (status = 'expired' AND consumed_at IS NULL)+ )+ );++ CREATE INDEX IF NOT EXISTS codex_subscription_oauth_states_pending_expiry_idx+ ON codex_subscription_oauth_states (expires_at)+ WHERE status = 'pending';++ REVOKE ALL PRIVILEGES ON TABLE codex_subscription_oauth_states FROM PUBLIC;+ REVOKE ALL PRIVILEGES ON TABLE codex_subscription_oauth_states+ FROM trace_maintenance_runtime, workflow_recipes_runtime;+ GRANT SELECT, INSERT, UPDATE ON TABLE codex_subscription_oauth_states TO control_api_runtime;+ REVOKE DELETE, TRUNCATE, REFERENCES, TRIGGER ON TABLE codex_subscription_oauth_states FROM control_api_runtime;+ `)+}++export async function insertCodexSubscriptionOAuthState(+ db: DbClient,+ encryptionKey: Buffer,+ input: CodexSubscriptionOAuthStateWrite+): Promise<CodexSubscriptionOAuthSafeState> {+ if (input.flow === 'browser' && !input.pkceVerifier) {+ throw new Error('browser OAuth state requires a PKCE verifier')+ }+ if (input.flow === 'device' && !input.deviceCode) {+ throw new Error('device OAuth state requires a device code')+ }+ const result = await db.query(+ `INSERT INTO codex_subscription_oauth_states (+ state,+ flow,+ intent,+ pkce_verifier_encrypted,+ device_code_encrypted,+ status,+ expires_at+ ) VALUES ($1, $2, $3, $4, $5, 'pending', $6)+ RETURNING ${SAFE_OAUTH_STATE_COLUMNS}`,+ [+ input.state,+ input.flow,+ input.intent,+ input.pkceVerifier ? encryptOAuthSecret(encryptionKey, input.pkceVerifier) : null,+ input.deviceCode ? encryptOAuthSecret(encryptionKey, input.deviceCode) : null,+ input.expiresAt,+ ]+ )+ return toSafeOAuthState(result.rows[0] as SafeOAuthStateRow)+}++export async function consumeCodexSubscriptionOAuthState(+ db: DbClient,+ encryptionKey: Buffer,+ state: string+): Promise<CodexSubscriptionConsumedOAuthState | null> {+ const result = await db.query(+ `UPDATE codex_subscription_oauth_states+ SET status = 'consumed',+ consumed_at = now()+ WHERE state = $1+ AND status = 'pending'+ AND expires_at > now()+ RETURNING ${SAFE_OAUTH_STATE_COLUMNS},+ pkce_verifier_encrypted,+ device_code_encrypted`,+ [state]+ )+ const row = result.rows[0] as ConsumedOAuthStateRow | undefined+ if (!row) return null+ return {+ safe: toSafeOAuthState(row),+ pkceVerifier: row.pkce_verifier_encrypted+ ? decryptOAuthSecret(encryptionKey, row.pkce_verifier_encrypted)+ : undefined,+ deviceCode: row.device_code_encrypted+ ? decryptOAuthSecret(encryptionKey, row.device_code_encrypted)+ : undefined,+ }+}++export async function cancelCodexSubscriptionOAuthState(+ db: DbClient,+ state: string+): Promise<boolean> {+ const result = await db.query(+ `UPDATE codex_subscription_oauth_states+ SET status = 'cancelled',+ cancelled_at = now()+ WHERE state = $1+ AND status = 'pending'`,+ [state]+ )+ return (result.rowCount ?? 0) > 0+}++function toSafeOAuthState(row: SafeOAuthStateRow): CodexSubscriptionOAuthSafeState {+ return {+ state: row.state,+ flow: row.flow,+ intent: row.intent,+ status: row.status,+ expiresAt: asDate(row.expires_at) ?? new Date(0),+ consumedAt: asDate(row.consumed_at),+ cancelledAt: asDate(row.cancelled_at),+ createdAt: asDate(row.created_at) ?? new Date(0),+ }+}++function asDate(value: Date | string | null | undefined): Date | null {+ if (value == null) return null+ return value instanceof Date ? value : new Date(value)+}diff --git a/control-api/test/db.codexSubscriptionConnection.realPostgres.integration.test.ts b/control-api/test/db.codexSubscriptionConnection.realPostgres.integration.test.tsnew file mode 100644index 000000000..6ee4a5059--- /dev/null+++ b/control-api/test/db.codexSubscriptionConnection.realPostgres.integration.test.ts@@ -0,0 +1,162 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { randomBytes } from 'node:crypto'+import { Pool } from 'pg'+import { initDb } from '../src/db.js'+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import {+ CodexSubscriptionStaleRevisionError,+ acquireCodexSubscriptionRefreshLock,+ getSafeCodexSubscriptionConnection,+ insertInitialCodexSubscriptionConnection,+ loadCodexSubscriptionSecrets,+ rotateCodexSubscriptionCredentials,+} from '../src/services/codexSubscriptionConnection.js'+import {+ cancelCodexSubscriptionOAuthState,+ consumeCodexSubscriptionOAuthState,+ insertCodexSubscriptionOAuthState,+} from '../src/services/codexSubscriptionOAuthState.js'++const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+const describeRealPostgres = adminUrl ? describe : describe.skip+const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))++function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+}++function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+}++describeRealPostgres('Codex subscription connection on real PostgreSQL', () => {+ const database = `codex_subscription_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ let adminPool: Pool+ let pool: Pool++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ pool = new Pool({ connectionString })+ await initDb({ connect: () => pool.connect() })+ }, 60_000)++ afterAll(async () => {+ await pool?.end()+ if (adminPool) {+ await adminPool+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ .catch(() => undefined)+ await adminPool.end()+ }+ })++ it('creates the connection and oauth-state tables', async () => {+ const tables = await pool.query<{ table_name: string }>(+ `SELECT table_name+ FROM information_schema.tables+ WHERE table_schema = 'public'+ AND table_name = ANY($1::text[])+ ORDER BY table_name`,+ [['codex_subscription_connections', 'codex_subscription_oauth_states']]+ )+ expect(tables.rows.map(row => row.table_name)).toEqual([+ 'codex_subscription_connections',+ 'codex_subscription_oauth_states',+ ])+ })++ it('allows only one active deployment-default connection', async () => {+ await insertInitialCodexSubscriptionConnection(pool, KEY, {+ refreshToken: 'first-refresh',+ accountFingerprint: 'fp-one',+ })+ await expect(+ insertInitialCodexSubscriptionConnection(pool, KEY, {+ refreshToken: 'second-refresh',+ accountFingerprint: 'fp-two',+ })+ ).rejects.toThrow(/duplicate|unique/i)++ const count = await pool.query<{ count: string }>(+ `SELECT COUNT(*)::text AS count FROM codex_subscription_connections WHERE revoked_at IS NULL`+ )+ expect(count.rows[0]?.count).toBe('1')+ })++ it('rejects a stale writer so it cannot overwrite a newer credential', async () => {+ const current = await getSafeCodexSubscriptionConnection(pool)+ expect(current).not.toBeNull()+ const winner = await rotateCodexSubscriptionCredentials(+ pool,+ KEY,+ current!.credentialRevision,+ {+ refreshToken: 'winner-refresh',+ accountFingerprint: 'fp-winner',+ }+ )+ await expect(+ rotateCodexSubscriptionCredentials(pool, KEY, current!.credentialRevision, {+ refreshToken: 'stale-refresh',+ accountFingerprint: 'fp-stale',+ })+ ).rejects.toBeInstanceOf(CodexSubscriptionStaleRevisionError)++ const secrets = await loadCodexSubscriptionSecrets(pool, KEY)+ expect(secrets?.refreshToken).toBe('winner-refresh')+ expect(secrets?.refreshToken).not.toBe('stale-refresh')+ expect(winner.credentialRevision).toBe(current!.credentialRevision + 1)+ const safe = await getSafeCodexSubscriptionConnection(pool)+ expect(JSON.stringify(safe)).not.toContain('winner-refresh')+ })++ it('lets only one concurrent refresh lock win', async () => {+ const [first, second] = await Promise.all([+ acquireCodexSubscriptionRefreshLock(pool, 'lock-a', 5_000),+ acquireCodexSubscriptionRefreshLock(pool, 'lock-b', 5_000),+ ])+ const winners = [first, second].filter(Boolean)+ expect(winners).toHaveLength(1)+ })++ it('consumes OAuth state/PKCE exactly once and supports cancel plus replacement intent', async () => {+ const created = await insertCodexSubscriptionOAuthState(pool, KEY, {+ state: 'state-one',+ flow: 'browser',+ intent: 'replace',+ pkceVerifier: 'pkce-secret',+ expiresAt: new Date(Date.now() + 60_000),+ })+ expect(created.intent).toBe('replace')+ expect(JSON.stringify(created)).not.toContain('pkce-secret')++ const [first, second] = await Promise.all([+ consumeCodexSubscriptionOAuthState(pool, KEY, 'state-one'),+ consumeCodexSubscriptionOAuthState(pool, KEY, 'state-one'),+ ])+ const consumed = [first, second].filter(result => result !== null)+ expect(consumed).toHaveLength(1)+ expect(consumed[0]?.pkceVerifier).toBe('pkce-secret')+ expect(JSON.stringify(consumed[0]?.safe)).not.toContain('pkce-secret')++ const replay = await consumeCodexSubscriptionOAuthState(pool, KEY, 'state-one')+ expect(replay).toBeNull()++ await insertCodexSubscriptionOAuthState(pool, KEY, {+ state: 'state-cancel',+ flow: 'device',+ intent: 'connect',+ deviceCode: 'device-secret',+ expiresAt: new Date(Date.now() + 60_000),+ })+ expect(await cancelCodexSubscriptionOAuthState(pool, 'state-cancel')).toBe(true)+ expect(await consumeCodexSubscriptionOAuthState(pool, KEY, 'state-cancel')).toBeNull()+ })+})diff --git a/control-api/test/db.codexSubscriptionMigration.test.ts b/control-api/test/db.codexSubscriptionMigration.test.tsnew file mode 100644index 000000000..67e43c747--- /dev/null+++ b/control-api/test/db.codexSubscriptionMigration.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'++function runtimeAccessProfile(): Map<string, string> {+ const source = readFileSync(+ new URL('../../deploy/scripts/control-api-runtime-access-profiles.tsv', import.meta.url),+ 'utf8'+ )+ return new Map(+ source+ .split('\n')+ .filter(line => line && !line.startsWith('#'))+ .map(line => line.split('\t') as [string, string])+ )+}++describe('00a0/00a1 Codex subscription persistence', () => {+ const dbSource = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')+ const connectionSource = readFileSync(+ new URL('../src/services/codexSubscriptionConnection.ts', import.meta.url),+ 'utf8'+ )+ const oauthStateSource = readFileSync(+ new URL('../src/services/codexSubscriptionOAuthState.ts', import.meta.url),+ 'utf8'+ )++ it('registers additive migrations after the last published GFS recovery version', () => {+ expect(dbSource).toContain("version: '0099_gfs_upload_finalizing_recovery'")+ expect(dbSource).toContain("version: '00a0_codex_subscription_connections'")+ expect(dbSource).toContain("version: '00a1_codex_subscription_oauth_states'")+ expect(dbSource).toContain('apply: applyCodexSubscriptionConnectionSchema')+ expect(dbSource).toContain('apply: applyCodexSubscriptionOAuthStateSchema')+ expect(dbSource.indexOf("version: '0099_gfs_upload_finalizing_recovery'")).toBeLessThan(+ dbSource.indexOf("version: '00a0_codex_subscription_connections'")+ )+ expect(dbSource.indexOf("version: '00a0_codex_subscription_connections'")).toBeLessThan(+ dbSource.indexOf("version: '00a1_codex_subscription_oauth_states'")+ )+ })++ it('creates a single active deployment-default connection with ciphertext and revisions', () => {+ expect(connectionSource).toContain('CREATE TABLE IF NOT EXISTS codex_subscription_connections')+ expect(connectionSource).toContain('connection_key TEXT NOT NULL')+ expect(connectionSource).toContain("CHECK (connection_key = 'deployment-default')")+ expect(connectionSource).toContain('refresh_token_encrypted TEXT')+ expect(connectionSource).toContain('access_token_encrypted TEXT')+ expect(connectionSource).toContain('credential_revision BIGINT NOT NULL')+ expect(connectionSource).toContain('catalog_revision BIGINT NOT NULL')+ expect(connectionSource).toContain('account_fingerprint TEXT')+ expect(connectionSource).toContain(+ 'CREATE UNIQUE INDEX IF NOT EXISTS codex_subscription_connections_active_key'+ )+ expect(connectionSource).toContain('WHERE revoked_at IS NULL')+ expect(connectionSource).toMatch(/AND credential_revision = \$/)+ expect(connectionSource).not.toMatch(/\brefresh_token\b(?!_encrypted)/)+ expect(connectionSource).not.toMatch(/\baccess_token\b(?!_encrypted|_expires_at)/)+ expect(connectionSource).not.toMatch(/cookie/i)+ expect(connectionSource).not.toMatch(/set-cookie/i)+ expect(connectionSource).not.toMatch(/authorization/i)+ expect(connectionSource).not.toMatch(/DROP\s+(TABLE|COLUMN)/i)+ })++ it('creates one-time OAuth state/PKCE rows with expiry, consume, cancel, and replacement intent', () => {+ expect(oauthStateSource).toContain('CREATE TABLE IF NOT EXISTS codex_subscription_oauth_states')+ expect(oauthStateSource).toContain("flow TEXT NOT NULL CHECK (flow IN ('browser', 'device'))")+ expect(oauthStateSource).toContain(+ "intent TEXT NOT NULL CHECK (intent IN ('connect', 'reconnect', 'replace'))"+ )+ expect(oauthStateSource).toContain('pkce_verifier_encrypted TEXT')+ expect(oauthStateSource).toContain('device_code_encrypted TEXT')+ expect(oauthStateSource).toContain(+ "status TEXT NOT NULL CHECK (status IN ('pending', 'consumed', 'expired', 'cancelled'))"+ )+ expect(oauthStateSource).toContain('expires_at TIMESTAMPTZ NOT NULL')+ expect(oauthStateSource).toContain('consumed_at TIMESTAMPTZ')+ expect(oauthStateSource).toContain('cancelled_at TIMESTAMPTZ')+ expect(oauthStateSource).toContain("status = 'consumed'")+ expect(oauthStateSource).toContain("status = 'pending'")+ expect(oauthStateSource).toContain('expires_at > now()')+ expect(oauthStateSource).not.toMatch(/cookie/i)+ expect(oauthStateSource).not.toMatch(/\bpkce_verifier\b(?!_encrypted)/)+ expect(oauthStateSource).not.toMatch(/\bdevice_code\b(?!_encrypted)/)+ expect(oauthStateSource).not.toMatch(/DROP\s+(TABLE|COLUMN)/i)+ })++ it('grants Control API runtime SELECT/INSERT/UPDATE only and never creates a proxy role', () => {+ const schema = `${connectionSource}\n${oauthStateSource}`+ expect(schema).toContain(+ 'REVOKE ALL PRIVILEGES ON TABLE codex_subscription_connections FROM PUBLIC'+ )+ expect(schema).toContain(+ 'REVOKE ALL PRIVILEGES ON TABLE codex_subscription_oauth_states FROM PUBLIC'+ )+ expect(schema).toContain(+ 'GRANT SELECT, INSERT, UPDATE ON TABLE codex_subscription_connections TO control_api_runtime'+ )+ expect(schema).toContain(+ 'GRANT SELECT, INSERT, UPDATE ON TABLE codex_subscription_oauth_states TO control_api_runtime'+ )+ expect(schema).toContain(+ 'REVOKE DELETE, TRUNCATE, REFERENCES, TRIGGER ON TABLE codex_subscription_connections FROM control_api_runtime'+ )+ expect(schema).toContain(+ 'REVOKE DELETE, TRUNCATE, REFERENCES, TRIGGER ON TABLE codex_subscription_oauth_states FROM control_api_runtime'+ )+ expect(schema).not.toMatch(/CREATE ROLE/i)+ expect(schema).not.toMatch(/codex.llm.proxy/i)+ expect(schema).not.toMatch(/GRANT .* TO .*proxy/i)+ })++ it('classifies the new relations as upsert in the runtime access contract', () => {+ const profile = runtimeAccessProfile()+ expect(profile.get('codex_subscription_connections')).toBe('upsert')+ expect(profile.get('codex_subscription_oauth_states')).toBe('upsert')+ })+})diff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.tsindex 628966dea..dc91bc517 100644--- a/control-api/test/db.realPostgresMigration.integration.test.ts+++ b/control-api/test/db.realPostgresMigration.integration.test.ts@@ -331,6 +331,8 @@ describeRealPostgres('control-api real Postgres migrations', () => {'llm_allowed_models','llm_allowed_models_audit','llm_catalog_sync_runs',+ 'codex_subscription_connections',+ 'codex_subscription_oauth_states','notification_deliveries','workflow_approval_requests','workflow_run_steps',@@ -342,6 +344,8 @@ describeRealPostgres('control-api real Postgres migrations', () => {expect(requiredTables.rows.map(row => row.table_name)).toEqual(['administrative_events','agent_run_events',+ 'codex_subscription_connections',+ 'codex_subscription_oauth_states','governed_approval_prompt_history','governed_event_stream','governed_run_attribution_bindings',@@ -444,6 +448,8 @@ describeRealPostgres('control-api real Postgres migrations', () => {'llm_allowed_models','llm_allowed_models_audit','llm_catalog_sync_runs',+ 'codex_subscription_connections',+ 'codex_subscription_oauth_states','gfs_desktop_operator_links','desktop_user_retirement_operations',] as const@@ -462,6 +468,8 @@ describeRealPostgres('control-api real Postgres migrations', () => {llm_allowed_models: ['DELETE', 'INSERT', 'SELECT', 'UPDATE'],llm_allowed_models_audit: ['INSERT', 'SELECT'],llm_catalog_sync_runs: ['INSERT', 'SELECT'],+ codex_subscription_connections: ['INSERT', 'SELECT', 'UPDATE'],+ codex_subscription_oauth_states: ['INSERT', 'SELECT', 'UPDATE'],gfs_desktop_operator_links: ['INSERT', 'SELECT', 'UPDATE'],desktop_user_retirement_operations: ['INSERT', 'SELECT', 'UPDATE'],}diff --git a/control-api/test/services.codexSubscriptionConnection.test.ts b/control-api/test/services.codexSubscriptionConnection.test.tsnew file mode 100644index 000000000..76ff27339--- /dev/null+++ b/control-api/test/services.codexSubscriptionConnection.test.ts@@ -0,0 +1,118 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'+import {+ CodexSubscriptionStaleRevisionError,+ getSafeCodexSubscriptionConnection,+ insertInitialCodexSubscriptionConnection,+ rotateCodexSubscriptionCredentials,+} from '../src/services/codexSubscriptionConnection.js'++const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))++function queryMock() {+ return vi.fn()+}++describe('codex subscription connection repository', () => {+ const query = queryMock()++ beforeEach(() => {+ query.mockReset()+ })++ it('returns safe metadata without ciphertext or token fields', async () => {+ const ciphertext = encryptOAuthSecret(KEY, 'refresh-secret')+ query.mockResolvedValueOnce({+ rows: [+ {+ connection_key: 'deployment-default',+ status: 'connected',+ refresh_token_encrypted: ciphertext,+ access_token_encrypted: encryptOAuthSecret(KEY, 'access-secret'),+ access_token_expires_at: new Date('2026-08-20T12:00:00.000Z'),+ credential_revision: '3',+ catalog_revision: '1',+ account_fingerprint: 'fp_abc',+ catalog_status: 'ready',+ catalog_synced_at: new Date('2026-08-20T11:00:00.000Z'),+ last_refresh_at: new Date('2026-08-20T11:30:00.000Z'),+ last_auth_at: new Date('2026-08-20T10:00:00.000Z'),+ refresh_lock_token: 'lock',+ refresh_lock_expires_at: new Date('2026-08-20T12:00:00.000Z'),+ revoked_at: null,+ created_at: new Date('2026-08-20T09:00:00.000Z'),+ updated_at: new Date('2026-08-20T11:30:00.000Z'),+ },+ ],+ rowCount: 1,+ })++ const metadata = await getSafeCodexSubscriptionConnection({ query })+ expect(metadata).toMatchObject({+ connectionKey: 'deployment-default',+ status: 'connected',+ credentialRevision: 3,+ catalogRevision: 1,+ accountFingerprint: 'fp_abc',+ catalogStatus: 'ready',+ })+ const serialized = JSON.stringify(metadata)+ expect(serialized).not.toContain(ciphertext)+ expect(serialized).not.toContain('refresh-secret')+ expect(serialized).not.toContain('access-secret')+ expect(serialized).not.toMatch(/cookie/i)+ expect(metadata).not.toHaveProperty('refreshTokenEncrypted')+ expect(metadata).not.toHaveProperty('accessTokenEncrypted')+ expect(metadata).not.toHaveProperty('refreshToken')+ expect(metadata).not.toHaveProperty('accessToken')+ })++ it('inserts encrypted credentials and never binds plaintext tokens', async () => {+ query.mockResolvedValueOnce({+ rows: [+ {+ connection_key: 'deployment-default',+ status: 'connected',+ credential_revision: '1',+ catalog_revision: '0',+ account_fingerprint: 'fp_new',+ catalog_status: 'never_synced',+ catalog_synced_at: null,+ last_refresh_at: null,+ last_auth_at: expect.anything(),+ refresh_lock_token: null,+ refresh_lock_expires_at: null,+ revoked_at: null,+ created_at: new Date(),+ updated_at: new Date(),+ },+ ],+ rowCount: 1,+ })++ const metadata = await insertInitialCodexSubscriptionConnection({ query }, KEY, {+ refreshToken: 'plain-refresh',+ accessToken: 'plain-access',+ accountFingerprint: 'fp_new',+ })+ expect(metadata.connectionKey).toBe('deployment-default')+ expect(metadata.credentialRevision).toBe(1)+ const [, params] = query.mock.calls[0] as [string, unknown[]]+ expect(params).not.toContain('plain-refresh')+ expect(params).not.toContain('plain-access')+ expect(String(params[2])).toMatch(/^v1\./)+ expect(String(params[3])).toMatch(/^v1\./)+ })++ it('rejects a stale credential_revision writer', async () => {+ query.mockResolvedValueOnce({ rows: [], rowCount: 0 })+ await expect(+ rotateCodexSubscriptionCredentials({ query }, KEY, 1, {+ refreshToken: 'next-refresh',+ accountFingerprint: 'fp_new',+ })+ ).rejects.toBeInstanceOf(CodexSubscriptionStaleRevisionError)+ const [sql] = query.mock.calls[0] as [string]+ expect(sql).toMatch(/credential_revision = \$/)+ })+})diff --git a/deploy/scripts/control-api-runtime-access-profiles.tsv b/deploy/scripts/control-api-runtime-access-profiles.tsvindex 23bbad444..beeb99c1b 100644--- a/deploy/scripts/control-api-runtime-access-profiles.tsv+++ b/deploy/scripts/control-api-runtime-access-profiles.tsv@@ -2,6 +2,8 @@administrative_events appendagent_run_events appendbudget_pending_reservations legacy_dml+codex_subscription_connections upsert+codex_subscription_oauth_states upsertcontrol_admin_deletion_audit legacy_dmlcontrol_admin_email_change_requests legacy_dmlcontrol_admin_invitations legacy_dmldiff --git a/scripts/tests/test-control-api-runtime-access-contract.sh b/scripts/tests/test-control-api-runtime-access-contract.shindex 41f3dd4b4..f7c6a23d8 100755--- a/scripts/tests/test-control-api-runtime-access-contract.sh+++ b/scripts/tests/test-control-api-runtime-access-contract.sh@@ -9,7 +9,7 @@ relation_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ { count++ } END { print couduplicate_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ { seen[$1]++ } END { for (name in seen) if (seen[name] > 1) count++ } END { print count + 0 }' "$PROFILE_FILE")"invalid_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ && (NF != 2 || $1 !~ /^[a-z][a-z0-9_]*$/ || $2 !~ /^(legacy_dml|upsert|append|read|link_lifecycle|none)$/) { count++ } END { print count + 0 }' "$PROFILE_FILE")"-[[ "$relation_count" == "82" ]]+[[ "$relation_count" == "86" ]][[ "$duplicate_count" == "0" ]][[ "$invalid_count" == "0" ]]grep -qx $'gfs_desktop_operator_links\tlink_lifecycle' "$PROFILE_FILE"diff --git a/scripts/tests/test-gcp-scripts.sh b/scripts/tests/test-gcp-scripts.shindex a2e5e0110..befd6cf48 100755--- a/scripts/tests/test-gcp-scripts.sh+++ b/scripts/tests/test-gcp-scripts.sh@@ -1466,7 +1466,7 @@ assert_control_api_runtime_access_contract_is_exact() {sequence_duplicate_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ { seen[$1]++ } END { for (name in seen) if (seen[name] > 1) count++ } END { print count + 0 }' "$sequence_profile_file")"sequence_invalid_count="$(awk -F '\t' '!/^[[:space:]]*(#|$)/ && (NF != 2 || $1 !~ /^[a-z][a-z0-9_]*$/ || $2 !~ /^(legacy_rw|consume)$/) { count++ } END { print count + 0 }' "$sequence_profile_file")"- if [[ "$relation_count" == "82" && "$duplicate_count" == "0" && "$invalid_count" == "0" ]] && \+ if [[ "$relation_count" == "86" && "$duplicate_count" == "0" && "$invalid_count" == "0" ]] && \grep -qx $'gfs_upload_parts\tnone' "$profile_file" && \grep -qx $'gfs_upload_sessions\tnone' "$profile_file" && \grep -qx $'llm_allowed_models\tlegacy_dml' "$profile_file" && \