Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): add install identity columns to dynamic_clients and oauth_grants
Diego Zacarias6938afbd3ecd
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 47ecec061..7988b7a1c 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.663",+ "version": "0.1.664","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.663",+ "version": "0.1.664","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.jsonindex c1b2ad12b..7edfdcb20 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.663",+ "version": "0.1.664","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.tsindex 289053c39..2189577f6 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -6231,6 +6231,15 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [legacyVersions: ['0117_dynamic_clients_runtime_access'],apply: applyDynamicClientsRuntimeAccess,},+ {+ // Install-identity columns for the DCR/OAuth state (install_id + cr_uid on+ // dynamic_clients, cr_uid on oauth_grants). This branch is the first to ship+ // 0119, so no legacyVersions are needed; if a later /sync-dev collides the+ // number, this migration renumbers and the pre-renumber name moves to+ // legacyVersions (the convention below).+ version: '0119_oauth_install_identity',+ apply: applyOAuthInstallIdentity,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {@@ -6462,6 +6471,65 @@ async function applyDynamicClientsRuntimeAccess(db: DbClient): Promise<void> {`)}+async function applyOAuthInstallIdentity(db: DbClient): Promise<void> {+ // Install identity for the DCR/OAuth Postgres state. Rows in dynamic_clients+ // and oauth_grants were keyed only by (owner_kind, server_namespace,+ // server_name), so no row knew WHICH installation of the McpServer it belonged+ // to. Two columns give each row a lifetime owner:+ // - install_id: a token the remote-install saga mints before the CR exists,+ // so its own compensations only touch its own row.+ // - cr_uid: the apiserver's metadata.uid of the owning McpServer (unique per+ // object; a same-name reinstall gets a different uid), so post-uninstall+ // teardown and orphan reclaim can fence by the exact installation.+ //+ // A bound row (cr_uid set) must carry an install_id — the saga always mints one+ // before binding the CR uid, so a bound-but-install-less row is impossible.+ //+ // Greenfield/additive: dynamic_clients ships only on this branch, so no+ // backfill is possible or needed (legacy rows keep both columns NULL and the+ // decision logic treats them as name-only). ADD COLUMN is covered by the table+ // GRANTs from 0117/0118 (legacy_dml), so no new runtime-access grant is needed.+ // Idempotent: ADD COLUMN IF NOT EXISTS, and each CHECK is guarded on+ // pg_constraint (Postgres has no ADD CONSTRAINT IF NOT EXISTS).+ await db.query(`+ ALTER TABLE dynamic_clients ADD COLUMN IF NOT EXISTS install_id UUID;+ ALTER TABLE dynamic_clients ADD COLUMN IF NOT EXISTS cr_uid TEXT;+ ALTER TABLE oauth_grants ADD COLUMN IF NOT EXISTS cr_uid TEXT;++ DO $$ BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conrelid = 'dynamic_clients'::regclass+ AND conname = 'dynamic_clients_cr_uid_len'+ ) THEN+ ALTER TABLE dynamic_clients+ ADD CONSTRAINT dynamic_clients_cr_uid_len+ CHECK (cr_uid IS NULL OR char_length(cr_uid) <= 128);+ END IF;++ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conrelid = 'dynamic_clients'::regclass+ AND conname = 'dynamic_clients_bound_needs_install'+ ) THEN+ ALTER TABLE dynamic_clients+ ADD CONSTRAINT dynamic_clients_bound_needs_install+ CHECK (cr_uid IS NULL OR install_id IS NOT NULL);+ END IF;++ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conrelid = 'oauth_grants'::regclass+ AND conname = 'oauth_grants_cr_uid_len'+ ) THEN+ ALTER TABLE oauth_grants+ ADD CONSTRAINT oauth_grants_cr_uid_len+ CHECK (cr_uid IS NULL OR char_length(cr_uid) <= 128);+ END IF;+ END $$;+ `)+}+async function ensureSchemaMigrationsTable(db: DbClient): Promise<void> {await db.query(`CREATE TABLE IF NOT EXISTS schema_migrations (diff --git a/control-api/src/oauth/dynamicClientStore.ts b/control-api/src/oauth/dynamicClientStore.tsindex 9c072ac5a..1ece1d4e9 100644--- a/control-api/src/oauth/dynamicClientStore.ts+++ b/control-api/src/oauth/dynamicClientStore.ts@@ -1,4 +1,4 @@-import type { DbClient } from '../db.js'+import type { DbClient, DbTransactionClient } from '../db.js'import { decryptOAuthSecret, encryptOAuthSecret } from './encryption.js'/**@@ -53,6 +53,10 @@ export interface DynamicClientRow {clientIdIssuedAt?: Date/** RFC 7591; null (non-expiring) is mapped to undefined. */clientSecretExpiresAt?: Date+ /** Saga install token that owns the row during the install; undefined = legacy. */+ installId?: string+ /** metadata.uid of the owning McpServer once bound; undefined = pending/legacy. */+ crUid?: stringcreatedAt: DateupdatedAt: Date}@@ -81,6 +85,34 @@ function numericDateToDate(seconds: number | undefined): Date | null {return new Date(seconds * 1000)}+/**+ * Column values that carry the AS credentials of a dynamic client, encrypted and+ * date-normalized identically wherever an install-identity row is written (pending+ * insert / orphan reclaim), so the at-rest shape lives in ONE place (D4).+ */+function encodeCredentialColumns(+ encryptionKey: Buffer,+ input: UpsertDynamicClientInput+): {+ clientSecretEncrypted: string | null+ registrationAccessTokenEncrypted: string | null+ registrationClientUri: string | null+ clientIdIssuedAt: Date | null+ clientSecretExpiresAt: Date | null+} {+ return {+ clientSecretEncrypted: input.clientSecret+ ? encryptOAuthSecret(encryptionKey, input.clientSecret)+ : null,+ registrationAccessTokenEncrypted: input.registrationAccessToken+ ? encryptOAuthSecret(encryptionKey, input.registrationAccessToken)+ : null,+ registrationClientUri: input.registrationClientUri ?? null,+ clientIdIssuedAt: numericDateToDate(input.clientIdIssuedAtSec),+ clientSecretExpiresAt: numericDateToDate(input.clientSecretExpiresAtSec),+ }+}+/*** Insert (or replace) the dynamic client for a server CR. Re-registration* overwrites in place (INSERT … ON CONFLICT DO UPDATE), which is also the only@@ -147,6 +179,8 @@ interface DynamicClientDbRow {registration_client_uri: string | nullclient_id_issued_at: Date | nullclient_secret_expires_at: Date | null+ install_id: string | null+ cr_uid: string | nullcreated_at: Dateupdated_at: Date}@@ -154,7 +188,7 @@ interface DynamicClientDbRow {const SELECT_COLUMNS = `owner_kind, server_namespace, server_name, issuer, client_id, client_mode,client_secret_encrypted, registration_access_token_encrypted,registration_client_uri, client_id_issued_at, client_secret_expires_at,- created_at, updated_at`+ install_id, cr_uid, created_at, updated_at`/** Read one dynamic client, decrypting its secret and registration token. */export async function getDynamicClient(@@ -187,6 +221,8 @@ export async function getDynamicClient(registrationClientUri: row.registration_client_uri ?? undefined,clientIdIssuedAt: row.client_id_issued_at ?? undefined,clientSecretExpiresAt: row.client_secret_expires_at ?? undefined,+ installId: row.install_id ?? undefined,+ crUid: row.cr_uid ?? undefined,createdAt: row.created_at,updatedAt: row.updated_at,}@@ -258,3 +294,287 @@ export async function deleteDynamicClient(db: DbClient, key: DynamicClientKey):)return result.rowCount ?? 0}++/**+ * RFC 7592 management handle of a dynamic client: the endpoint and the bearer+ * needed to DELETE it at the AS. Present only when both were persisted.+ */+export interface DynamicClientRegistrationHandle {+ registrationClientUri: string+ registrationAccessToken: string+}++/**+ * How long a `pending` row (install_id set, cr_uid NULL) is treated as an+ * in-flight install before an unfinished saga's row becomes reclaimable. Chosen+ * above the longest possible saga (discovery + probe + DCR + create + attach,+ * each bounded ≤ 15s), so a live install never has its own row reclaimed.+ */+export const PENDING_TTL_MS = 10 * 60_000++/**+ * The three lifetimes an existing `dynamic_clients` row can have at INSERT-conflict+ * or teardown time. `in-use` and `in-progress` belong to someone and must not be+ * touched; `reclaimable` (orphan/legacy) may be taken over.+ */+export type ExistingDynamicClientClass = 'in-use' | 'in-progress' | 'reclaimable'++/**+ * Decide who owns a conflicting `dynamic_clients` row — the one rule for "whose+ * row is this?" (D4). Pure and total; the caller supplies wall-clock `now`, the+ * pending TTL, and `liveCrUid` (the uid of a live McpServer with this name, when+ * one exists at conflict time).+ *+ * A live CR owns the name unconditionally: it covers a bound-live row AND the+ * pre-check→INSERT TOCTOU race where the CR appeared after the pending INSERT.+ * With no live CR, a bound row (cr_uid set) is an orphan of a gone install, a+ * fresh pending row is another saga in flight, an expired pending row is a+ * crashed saga, and a legacy row (both NULL, no live CR) is treated by name as+ * today — all reclaimable except the fresh pending one.+ */+export function classifyExistingDynamicClient(+ row: { installId: string | null; crUid: string | null; updatedAt: Date },+ ctx: { now: Date; pendingTtlMs: number; liveCrUid?: string }+): ExistingDynamicClientClass {+ if (ctx.liveCrUid !== undefined) return 'in-use'+ if (row.crUid != null) return 'reclaimable'+ if (row.installId != null) {+ // In-progress iff `updated_at > now − TTL` (i.e. age strictly under the TTL);+ // at exactly the TTL the row is expired and reclaimable.+ const ageMs = ctx.now.getTime() - row.updatedAt.getTime()+ return ageMs < ctx.pendingTtlMs ? 'in-progress' : 'reclaimable'+ }+ return 'reclaimable'+}++/**+ * Claim the name for a new install by inserting a PENDING row (install_id set,+ * cr_uid NULL) with `ON CONFLICT (owner_kind, server_namespace, server_name) DO+ * NOTHING`. Never overwrites an existing row — that is the whole point over+ * `upsertDynamicClient`: a live server's credentials are never clobbered. Returns+ * `{ inserted: false }` on conflict so the caller can classify the existing row.+ */+export async function insertDynamicClientPending(+ db: DbClient,+ encryptionKey: Buffer,+ input: UpsertDynamicClientInput & { installId: string }+): Promise<{ inserted: boolean }> {+ const ownerKind = resolveOwnerKind(input)+ const creds = encodeCredentialColumns(encryptionKey, input)++ const result = await db.query(+ `INSERT INTO dynamic_clients (+ owner_kind, server_namespace, server_name, issuer, client_id, client_mode,+ client_secret_encrypted, registration_access_token_encrypted,+ registration_client_uri, client_id_issued_at, client_secret_expires_at,+ install_id, cr_uid, updated_at+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NULL, NOW())+ ON CONFLICT (owner_kind, server_namespace, server_name) DO NOTHING+ RETURNING id`,+ [+ ownerKind,+ input.serverNamespace,+ input.serverName,+ input.issuer,+ input.clientId,+ input.clientMode,+ creds.clientSecretEncrypted,+ creds.registrationAccessTokenEncrypted,+ creds.registrationClientUri,+ creds.clientIdIssuedAt,+ creds.clientSecretExpiresAt,+ input.installId,+ ]+ )+ return { inserted: (result.rowCount ?? 0) > 0 }+}++/**+ * Take over a `reclaimable` row (orphan or legacy) for a new install, atomically.+ * Opens a transaction, `SELECT … FOR UPDATE`s the row, re-runs+ * {@link classifyExistingDynamicClient} on the LOCKED row (its state may have+ * changed since the losing INSERT), and only if still `reclaimable` overwrites the+ * credentials with the new install's `install_id` and `cr_uid = NULL`.+ *+ * The UPDATE is a CAS on `id` + `install_id` read under the lock, so two+ * concurrent reclaims cannot both win: the second serializes behind the first,+ * re-reads a now-fresh pending row, and classifies it `in-progress` →+ * `{ reclaimed: false }`. Returns the OLD row's RFC 7592 handle (decrypted, when+ * present) so the caller can best-effort revoke the superseded client at the AS.+ *+ * No leading `db` param: all work runs inside the transaction this function owns.+ * `runInTransaction` is a REQUIRED injected runner (pass `withTransaction` from+ * db.ts) rather than a default import — this module sits on the config init path+ * (config → tokenHelper → callback → here), so importing db.ts's `withTransaction`+ * value at module top-level would close an init cycle back to `config` and leave+ * it undefined. The injection also lets tests bind the runner to a disposable pool,+ * matching the `runInTransaction` idiom in reactiveTokenHelper.+ */+export async function reclaimOrphanDynamicClient(+ encryptionKey: Buffer,+ input: {+ key: DynamicClientKey+ newCredentials: UpsertDynamicClientInput+ newInstallId: string+ ctx: { now: Date; pendingTtlMs: number; liveCrUid?: string }+ },+ runInTransaction: <T>(work: (tx: DbTransactionClient) => Promise<T>) => Promise<T>+): Promise<{ reclaimed: boolean; oldHandle?: DynamicClientRegistrationHandle }> {+ const ownerKind = resolveOwnerKind(input.key)+ const creds = encodeCredentialColumns(encryptionKey, input.newCredentials)++ return runInTransaction(async tx => {+ const locked = await tx.query(+ `SELECT id, install_id, cr_uid, updated_at,+ registration_client_uri, registration_access_token_encrypted+ FROM dynamic_clients+ WHERE owner_kind = $1 AND server_namespace = $2 AND server_name = $3+ FOR UPDATE`,+ [ownerKind, input.key.serverNamespace, input.key.serverName]+ )+ if (locked.rows.length === 0) return { reclaimed: false }+ const row = locked.rows[0] as {+ id: string+ install_id: string | null+ cr_uid: string | null+ updated_at: Date+ registration_client_uri: string | null+ registration_access_token_encrypted: string | null+ }++ const klass = classifyExistingDynamicClient(+ { installId: row.install_id, crUid: row.cr_uid, updatedAt: row.updated_at },+ input.ctx+ )+ if (klass !== 'reclaimable') return { reclaimed: false }++ const updated = await tx.query(+ `UPDATE dynamic_clients+ SET issuer = $4,+ client_id = $5,+ client_mode = $6,+ client_secret_encrypted = $7,+ registration_access_token_encrypted = $8,+ registration_client_uri = $9,+ client_id_issued_at = $10,+ client_secret_expires_at = $11,+ install_id = $12,+ cr_uid = NULL,+ updated_at = NOW()+ WHERE owner_kind = $1 AND server_namespace = $2 AND server_name = $3+ AND id = $13 AND install_id IS NOT DISTINCT FROM $14`,+ [+ ownerKind,+ input.key.serverNamespace,+ input.key.serverName,+ input.newCredentials.issuer,+ input.newCredentials.clientId,+ input.newCredentials.clientMode,+ creds.clientSecretEncrypted,+ creds.registrationAccessTokenEncrypted,+ creds.registrationClientUri,+ creds.clientIdIssuedAt,+ creds.clientSecretExpiresAt,+ input.newInstallId,+ row.id,+ row.install_id,+ ]+ )+ if ((updated.rowCount ?? 0) !== 1) return { reclaimed: false }++ const oldHandle =+ row.registration_client_uri && row.registration_access_token_encrypted+ ? {+ registrationClientUri: row.registration_client_uri,+ registrationAccessToken: decryptOAuthSecret(+ encryptionKey,+ row.registration_access_token_encrypted+ ),+ }+ : undefined+ return { reclaimed: true, oldHandle }+ })+}++/**+ * Bind a pending row to the McpServer that was just created: set its `cr_uid`,+ * guarded on `install_id = $installId AND cr_uid IS NULL` so it only ever binds+ * OUR pending row. `{ bound: false }` means the row was reclaimed out from under+ * this saga (TTL expired mid-install) — the caller must not proceed as owner.+ */+export async function bindDynamicClientToResource(+ db: DbClient,+ key: DynamicClientKey,+ installId: string,+ crUid: string+): Promise<{ bound: boolean }> {+ const ownerKind = resolveOwnerKind(key)+ const result = await db.query(+ `UPDATE dynamic_clients+ SET cr_uid = $5, updated_at = NOW()+ WHERE owner_kind = $1 AND server_namespace = $2 AND server_name = $3+ AND install_id = $4 AND cr_uid IS NULL`,+ [ownerKind, key.serverNamespace, key.serverName, installId, crUid]+ )+ return { bound: (result.rowCount ?? 0) === 1 }+}++/**+ * Compensation delete for a saga: removes ONLY the row this install owns+ * (`install_id = $installId`), so a concurrent install/reinstall of the same name+ * that already reclaimed the row is never destroyed. Returns rows removed.+ */+export async function deleteDynamicClientOwnedByInstall(+ db: DbClient,+ key: DynamicClientKey,+ installId: string+): Promise<number> {+ const ownerKind = resolveOwnerKind(key)+ const result = await db.query(+ `DELETE FROM dynamic_clients+ WHERE owner_kind = $1 AND server_namespace = $2 AND server_name = $3+ AND install_id = $4`,+ [ownerKind, key.serverNamespace, key.serverName, installId]+ )+ return result.rowCount ?? 0+}++/**+ * Teardown delete for an uninstall of CR uid `crUid`: removes the row bound to+ * THIS uid, or a legacy row (both columns NULL, from before install identity),+ * and returns its RFC 7592 handle in the SAME statement (`DELETE … RETURNING`) so+ * there is no read→await→delete window in which a concurrent reinstall could slip+ * a new row in. A pending row (reinstall in flight) or a row bound to a DIFFERENT+ * uid (reinstall already complete) does not match and is left intact.+ */+export async function claimDeleteDynamicClientForResource(+ db: DbClient,+ encryptionKey: Buffer,+ key: DynamicClientKey,+ crUid: string+): Promise<{ deleted: boolean; handle?: DynamicClientRegistrationHandle }> {+ const ownerKind = resolveOwnerKind(key)+ const result = await db.query(+ `DELETE FROM dynamic_clients+ WHERE owner_kind = $1 AND server_namespace = $2 AND server_name = $3+ AND (cr_uid = $4 OR (install_id IS NULL AND cr_uid IS NULL))+ RETURNING registration_client_uri, registration_access_token_encrypted`,+ [ownerKind, key.serverNamespace, key.serverName, crUid]+ )+ if (result.rows.length === 0) return { deleted: false }+ const row = result.rows[0] as {+ registration_client_uri: string | null+ registration_access_token_encrypted: string | null+ }+ const handle =+ row.registration_client_uri && row.registration_access_token_encrypted+ ? {+ registrationClientUri: row.registration_client_uri,+ registrationAccessToken: decryptOAuthSecret(+ encryptionKey,+ row.registration_access_token_encrypted+ ),+ }+ : undefined+ return { deleted: true, handle }+}diff --git a/control-api/test/db.oauthInstallIdentityMigration.test.ts b/control-api/test/db.oauthInstallIdentityMigration.test.tsnew file mode 100644index 000000000..8a7700d36--- /dev/null+++ b/control-api/test/db.oauthInstallIdentityMigration.test.ts@@ -0,0 +1,90 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const clientQuery = vi.fn()+const clientRelease = vi.fn()+const mockConnect = vi.fn()+const mockPoolCtor = vi.fn(function MockPool() {+ return { connect: mockConnect, query: vi.fn() }+})++vi.mock('pg', () => ({ Pool: mockPoolCtor }))++describe('0119_oauth_install_identity migration', () => {+ beforeEach(() => {+ vi.resetModules()+ vi.clearAllMocks()+ mockConnect.mockResolvedValue({ query: clientQuery, release: clientRelease })+ clientQuery.mockResolvedValue({ rows: [], rowCount: 0 })+ })++ it('is registered after the dynamic-clients table and its runtime-access grant', async () => {+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')+ const versions = CONTROL_API_MIGRATIONS.map(m => m.version)+ expect(versions).toContain('0119_oauth_install_identity')+ // The columns extend dynamic_clients, so the table (0117) and its runtime+ // grant (0118) must already exist when 0119 runs.+ expect(versions.indexOf('0117_dynamic_clients_table')).toBeLessThan(+ versions.indexOf('0119_oauth_install_identity')+ )+ expect(versions.indexOf('0118_dynamic_clients_runtime_access')).toBeLessThan(+ versions.indexOf('0119_oauth_install_identity')+ )+ })++ it('adds install_id + cr_uid to dynamic_clients and cr_uid to oauth_grants, with the bound/length CHECKs', async () => {+ const { initDb } = await import('../src/db.js')+ await initDb()+ const sqls = clientQuery.mock.calls.map(([sql]) => String(sql))+ const ddl = sqls.find(+ sql =>+ sql.includes('ALTER TABLE dynamic_clients ADD COLUMN IF NOT EXISTS install_id UUID') &&+ sql.includes('cr_uid')+ )+ expect(ddl, 'the 0119 DDL was applied').toBeDefined()+ const sql = ddl as string++ // Additive + idempotent columns.+ expect(sql).toContain('ALTER TABLE dynamic_clients ADD COLUMN IF NOT EXISTS install_id UUID')+ expect(sql).toContain('ALTER TABLE dynamic_clients ADD COLUMN IF NOT EXISTS cr_uid TEXT')+ expect(sql).toContain('ALTER TABLE oauth_grants ADD COLUMN IF NOT EXISTS cr_uid TEXT')++ // cr_uid length bound on both tables.+ expect(sql).toContain('dynamic_clients_cr_uid_len')+ expect(sql).toContain('oauth_grants_cr_uid_len')+ expect(sql).toContain('char_length(cr_uid) <= 128')++ // A bound row (cr_uid set) must carry an install_id.+ expect(sql).toContain('dynamic_clients_bound_needs_install')+ expect(sql).toContain('cr_uid IS NULL OR install_id IS NOT NULL')++ // Constraints are guarded on pg_constraint (no ADD CONSTRAINT IF NOT EXISTS+ // in Postgres) so a re-run is a no-op rather than a duplicate-object error.+ expect(sql).toContain('FROM pg_constraint')++ // Unique keys are UNCHANGED — the DDL touches no unique constraint/index.+ expect(sql).not.toContain('UNIQUE')++ const recordedVersions = clientQuery.mock.calls+ .filter(([q]) => String(q).includes('INSERT INTO schema_migrations'))+ .map(([, params]) => (Array.isArray(params) ? params[0] : undefined))+ expect(recordedVersions).toContain('0119_oauth_install_identity')+ })++ it('needs no new runtime-access grant — ADD COLUMN is covered by the table GRANTs', async () => {+ const { initDb } = await import('../src/db.js')+ await initDb()+ const sqls = clientQuery.mock.calls.map(([sql]) => String(sql))+ // No GRANT is emitted for the 0119 columns: they inherit the 0117/0118+ // table-level GRANTs. Any GRANT on dynamic_clients belongs to 0118, not here.+ const grantsInInstallIdentity = sqls.filter(+ sql => sql.includes('install_id') && sql.includes('cr_uid') && sql.includes('GRANT')+ )+ expect(grantsInInstallIdentity).toEqual([])+ })++ it('is idempotent — a second initDb re-runs the guarded DDL without error', async () => {+ const { initDb } = await import('../src/db.js')+ await initDb()+ await expect(initDb()).resolves.not.toThrow()+ })+})diff --git a/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.tsnew file mode 100644index 000000000..99782e42a--- /dev/null+++ b/control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts@@ -0,0 +1,486 @@+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, withTransaction } from '../src/db.js'+import {+ PENDING_TTL_MS,+ type UpsertDynamicClientInput,+ bindDynamicClientToResource,+ claimDeleteDynamicClientForResource,+ classifyExistingDynamicClient,+ deleteDynamicClientOwnedByInstall,+ getDynamicClient,+ insertDynamicClientPending,+ reclaimOrphanDynamicClient,+ upsertDynamicClient,+} from '../src/oauth/dynamicClientStore.js'+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'++/**+ * Install-identity store primitives, observed as SURVIVING ROWS and returned+ * handles (T4), not as SQL text. dynamic_clients had no real-PG suite; the+ * in-memory fake re-implements the SQL by hand and so cannot certify+ * `ON CONFLICT DO NOTHING`, the reclaim CAS or `DELETE … RETURNING` (T1). Every+ * seeded row is built by the REAL producers (insertDynamicClientPending / bind /+ * upsertDynamicClient for a legacy row) and read through the REAL getDynamicClient.+ *+ * Gated on a real Postgres like the other integration suites:+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432/<db> npm test -- \+ * test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts+ */+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++// classifyExistingDynamicClient is pure — cover its exhaustive table with no DB.+describe('classifyExistingDynamicClient — ownership decision table', () => {+ const now = new Date('2026-01-01T00:00:00.000Z')+ const fresh = new Date(now.getTime() - 1000)+ const expired = new Date(now.getTime() - PENDING_TTL_MS - 1000)++ it('a live CR owns the name regardless of the row state → in-use', () => {+ expect(+ classifyExistingDynamicClient(+ { installId: null, crUid: null, updatedAt: fresh },+ { now, pendingTtlMs: PENDING_TTL_MS, liveCrUid: 'uid-live' }+ )+ ).toBe('in-use')+ expect(+ classifyExistingDynamicClient(+ { installId: 'i1', crUid: 'uid-old', updatedAt: expired },+ { now, pendingTtlMs: PENDING_TTL_MS, liveCrUid: 'uid-live' }+ )+ ).toBe('in-use')+ // A live CR beats even a fresh pending row (the pre-check→INSERT TOCTOU race).+ expect(+ classifyExistingDynamicClient(+ { installId: 'i1', crUid: null, updatedAt: fresh },+ { now, pendingTtlMs: PENDING_TTL_MS, liveCrUid: 'uid-live' }+ )+ ).toBe('in-use')+ })++ it('at exactly the TTL boundary a pending row is reclaimable (in-progress is strictly under)', () => {+ const atBoundary = new Date(now.getTime() - PENDING_TTL_MS)+ expect(+ classifyExistingDynamicClient(+ { installId: 'i1', crUid: null, updatedAt: atBoundary },+ { now, pendingTtlMs: PENDING_TTL_MS }+ )+ ).toBe('reclaimable')+ })++ it('a fresh pending row with no live CR → in-progress', () => {+ expect(+ classifyExistingDynamicClient(+ { installId: 'i1', crUid: null, updatedAt: fresh },+ { now, pendingTtlMs: PENDING_TTL_MS }+ )+ ).toBe('in-progress')+ })++ it('a bound orphan (cr_uid set, no live CR) → reclaimable', () => {+ expect(+ classifyExistingDynamicClient(+ { installId: 'i1', crUid: 'uid-gone', updatedAt: fresh },+ { now, pendingTtlMs: PENDING_TTL_MS }+ )+ ).toBe('reclaimable')+ })++ it('an expired pending row → reclaimable', () => {+ expect(+ classifyExistingDynamicClient(+ { installId: 'i1', crUid: null, updatedAt: expired },+ { now, pendingTtlMs: PENDING_TTL_MS }+ )+ ).toBe('reclaimable')+ })++ it('a legacy row (both null, no live CR) → reclaimable', () => {+ expect(+ classifyExistingDynamicClient(+ { installId: null, crUid: null, updatedAt: fresh },+ { now, pendingTtlMs: PENDING_TTL_MS }+ )+ ).toBe('reclaimable')+ })+})++describeRealPostgres('dynamicClientStore install identity (real Postgres)', () => {+ const database = `control_api_dcinstallid_${randomUUID().replace(/-/g, '')}`+ let adminPool: Pool+ let dbPool: Pool+ let db: DbClient+ // A transaction runner bound to the disposable pool, injected into the reclaim+ // primitive so its FOR UPDATE + CAS run against THIS database, not the module pool.+ let runInTransaction: <T>(work: (tx: DbTransactionClient) => Promise<T>) => Promise<T>++ 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) }+ runInTransaction = work => withTransaction(work, dbPool)+ })++ 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 baseCreds = (serverName: string, overrides: Partial<UpsertDynamicClientInput> = {}) =>+ ({+ serverNamespace: NS,+ serverName,+ issuer: 'https://as.example.com',+ clientId: `cid-${serverName}`,+ clientMode: 'confidential' as const,+ clientSecret: `secret-${serverName}`,+ registrationAccessToken: `rat-${serverName}`,+ registrationClientUri: `https://as.example.com/reg/${serverName}`,+ ...overrides,+ }) satisfies UpsertDynamicClientInput++ it('insertDynamicClientPending claims an empty name and NEVER clobbers an existing row', async () => {+ const name = `srv-insert-${randomUUID().slice(0, 8)}`+ const install1 = randomUUID()++ const first = await insertDynamicClientPending(db, KEY, {+ ...baseCreds(name, { clientId: 'cid-original', clientSecret: 'secret-original' }),+ installId: install1,+ })+ expect(first.inserted).toBe(true)++ const before = await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: name })+ expect(before?.installId).toBe(install1)+ expect(before?.crUid).toBeUndefined()+ expect(before?.clientId).toBe('cid-original')+ expect(before?.clientSecret).toBe('secret-original')+ expect(before?.registrationAccessToken).toBe(`rat-${name}`)++ // A second install of the same name with DIFFERENT creds: conflict, no write.+ const install2 = randomUUID()+ const second = await insertDynamicClientPending(db, KEY, {+ ...baseCreds(name, { clientId: 'cid-attacker', clientSecret: 'secret-attacker' }),+ registrationAccessToken: 'rat-attacker',+ registrationClientUri: 'https://as.example.com/reg/attacker',+ installId: install2,+ })+ expect(second.inserted).toBe(false)++ const after = await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: name })+ // Byte-identical to `before`: the existing row is untouched.+ expect(after?.installId).toBe(install1)+ expect(after?.clientId).toBe('cid-original')+ expect(after?.clientSecret).toBe('secret-original')+ expect(after?.registrationAccessToken).toBe(`rat-${name}`)+ expect(after?.registrationClientUri).toBe(`https://as.example.com/reg/${name}`)+ })++ it('reclaimOrphanDynamicClient CAS: takes over a reclaimable row, returns the old handle, second reclaim loses', async () => {+ const name = `srv-reclaim-${randomUUID().slice(0, 8)}`+ const install1 = randomUUID()+ const uidGone = randomUUID()++ // Seed a BOUND ORPHAN via the real producers: pending insert, then bind to a+ // uid whose CR no longer exists (liveCrUid undefined at reclaim time).+ await insertDynamicClientPending(db, KEY, {+ ...baseCreds(name, { clientId: 'cid-old', clientSecret: 'secret-old' }),+ registrationAccessToken: 'rat-old',+ registrationClientUri: 'https://as.example.com/reg/old',+ installId: install1,+ })+ expect(+ (+ await bindDynamicClientToResource(+ db,+ { serverNamespace: NS, serverName: name },+ install1,+ uidGone+ )+ ).bound+ ).toBe(true)++ const install2 = randomUUID()+ const reclaim = await reclaimOrphanDynamicClient(+ KEY,+ {+ key: { serverNamespace: NS, serverName: name },+ newCredentials: baseCreds(name, { clientId: 'cid-new', clientSecret: 'secret-new' }),+ newInstallId: install2,+ ctx: { now: new Date(), pendingTtlMs: PENDING_TTL_MS, liveCrUid: undefined },+ },+ runInTransaction+ )+ expect(reclaim.reclaimed).toBe(true)+ // The old client's RFC 7592 handle comes back decrypted for revocation.+ expect(reclaim.oldHandle).toEqual({+ registrationClientUri: 'https://as.example.com/reg/old',+ registrationAccessToken: 'rat-old',+ })++ const owned = await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: name })+ expect(owned?.installId).toBe(install2)+ expect(owned?.crUid).toBeUndefined()+ expect(owned?.clientId).toBe('cid-new')+ expect(owned?.clientSecret).toBe('secret-new')++ // Row is now fresh-pending (install2). A second reclaim classifies it+ // in-progress → loses. Models the concurrent second reclaim with a stale+ // old-install expectation.+ const install3 = randomUUID()+ const second = await reclaimOrphanDynamicClient(+ KEY,+ {+ key: { serverNamespace: NS, serverName: name },+ newCredentials: baseCreds(name, { clientId: 'cid-loser' }),+ newInstallId: install3,+ ctx: { now: new Date(), pendingTtlMs: PENDING_TTL_MS, liveCrUid: undefined },+ },+ runInTransaction+ )+ expect(second.reclaimed).toBe(false)+ const afterLoser = await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: name })+ expect(afterLoser?.installId).toBe(install2)+ expect(afterLoser?.clientId).toBe('cid-new')+ })++ it('reclaimOrphanDynamicClient leaves an in-progress (fresh pending) row alone', async () => {+ const name = `srv-noreclaim-${randomUUID().slice(0, 8)}`+ const install1 = randomUUID()+ await insertDynamicClientPending(db, KEY, {+ ...baseCreds(name, { clientId: 'cid-inflight' }),+ installId: install1,+ })++ const result = await reclaimOrphanDynamicClient(+ KEY,+ {+ key: { serverNamespace: NS, serverName: name },+ newCredentials: baseCreds(name, { clientId: 'cid-would-steal' }),+ newInstallId: randomUUID(),+ ctx: { now: new Date(), pendingTtlMs: PENDING_TTL_MS, liveCrUid: undefined },+ },+ runInTransaction+ )+ expect(result.reclaimed).toBe(false)+ const row = await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: name })+ expect(row?.installId).toBe(install1)+ expect(row?.clientId).toBe('cid-inflight')+ })++ it('bindDynamicClientToResource binds our pending row and refuses a non-matching install', async () => {+ const bindName = `srv-bind-${randomUUID().slice(0, 8)}`+ const install = randomUUID()+ const uid = randomUUID()+ await insertDynamicClientPending(db, KEY, { ...baseCreds(bindName), installId: install })++ const ok = await bindDynamicClientToResource(+ db,+ { serverNamespace: NS, serverName: bindName },+ install,+ uid+ )+ expect(ok.bound).toBe(true)+ const bound = await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: bindName })+ expect(bound?.crUid).toBe(uid)++ // A fresh pending row bound with the WRONG install_id must not bind.+ const mismatchName = `srv-bind-mismatch-${randomUUID().slice(0, 8)}`+ await insertDynamicClientPending(db, KEY, {+ ...baseCreds(mismatchName),+ installId: randomUUID(),+ })+ const bad = await bindDynamicClientToResource(+ db,+ { serverNamespace: NS, serverName: mismatchName },+ randomUUID(),+ randomUUID()+ )+ expect(bad.bound).toBe(false)+ const stillPending = await getDynamicClient(db, KEY, {+ serverNamespace: NS,+ serverName: mismatchName,+ })+ expect(stillPending?.crUid).toBeUndefined()+ })++ it('deleteDynamicClientOwnedByInstall removes only the matching install, leaving other rows', async () => {+ const mine = `srv-del-mine-${randomUUID().slice(0, 8)}`+ const other = `srv-del-other-${randomUUID().slice(0, 8)}`+ const myInstall = randomUUID()+ const otherInstall = randomUUID()+ await insertDynamicClientPending(db, KEY, { ...baseCreds(mine), installId: myInstall })+ await insertDynamicClientPending(db, KEY, { ...baseCreds(other), installId: otherInstall })++ // Wrong install → nothing removed, row survives.+ expect(+ await deleteDynamicClientOwnedByInstall(+ db,+ { serverNamespace: NS, serverName: mine },+ randomUUID()+ )+ ).toBe(0)+ expect(+ await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: mine })+ ).not.toBeNull()++ // Right install → removed.+ expect(+ await deleteDynamicClientOwnedByInstall(+ db,+ { serverNamespace: NS, serverName: mine },+ myInstall+ )+ ).toBe(1)+ expect(await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: mine })).toBeNull()++ // The row owned by a DIFFERENT install is untouched.+ const survivor = await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: other })+ expect(survivor?.installId).toBe(otherInstall)+ })++ it('claimDeleteDynamicClientForResource deletes the U-bound and legacy rows, spares other-uid and pending', async () => {+ const uid = randomUUID()++ // Row bound to U (real producers) — deleted, handle returned.+ const boundName = `srv-claim-bound-${randomUUID().slice(0, 8)}`+ const boundInstall = randomUUID()+ await insertDynamicClientPending(db, KEY, {+ ...baseCreds(boundName, { clientId: 'cid-bound' }),+ registrationAccessToken: 'rat-bound',+ registrationClientUri: 'https://as.example.com/reg/bound',+ installId: boundInstall,+ })+ await bindDynamicClientToResource(+ db,+ { serverNamespace: NS, serverName: boundName },+ boundInstall,+ uid+ )++ // Legacy row (install_id NULL, cr_uid NULL) via the real legacy producer+ // upsertDynamicClient — the only writer that emits a pre-install-identity row.+ const legacyName = `srv-claim-legacy-${randomUUID().slice(0, 8)}`+ await upsertDynamicClient(db, KEY, {+ ...baseCreds(legacyName, { clientId: 'cid-legacy' }),+ registrationAccessToken: 'rat-legacy',+ registrationClientUri: 'https://as.example.com/reg/legacy',+ })++ // Row bound to a DIFFERENT uid — spared.+ const otherName = `srv-claim-other-${randomUUID().slice(0, 8)}`+ const otherInstall = randomUUID()+ await insertDynamicClientPending(db, KEY, { ...baseCreds(otherName), installId: otherInstall })+ await bindDynamicClientToResource(+ db,+ { serverNamespace: NS, serverName: otherName },+ otherInstall,+ randomUUID()+ )++ // Pending row (reinstall in flight) — spared.+ const pendingName = `srv-claim-pending-${randomUUID().slice(0, 8)}`+ await insertDynamicClientPending(db, KEY, {+ ...baseCreds(pendingName),+ installId: randomUUID(),+ })++ const boundClaim = await claimDeleteDynamicClientForResource(+ db,+ KEY,+ { serverNamespace: NS, serverName: boundName },+ uid+ )+ expect(boundClaim.deleted).toBe(true)+ expect(boundClaim.handle).toEqual({+ registrationClientUri: 'https://as.example.com/reg/bound',+ registrationAccessToken: 'rat-bound',+ })+ expect(+ await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: boundName })+ ).toBeNull()++ const legacyClaim = await claimDeleteDynamicClientForResource(+ db,+ KEY,+ { serverNamespace: NS, serverName: legacyName },+ uid+ )+ expect(legacyClaim.deleted).toBe(true)+ expect(legacyClaim.handle).toEqual({+ registrationClientUri: 'https://as.example.com/reg/legacy',+ registrationAccessToken: 'rat-legacy',+ })+ expect(+ await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: legacyName })+ ).toBeNull()++ // A claim of U against the OTHER-uid row deletes nothing.+ const otherClaim = await claimDeleteDynamicClientForResource(+ db,+ KEY,+ { serverNamespace: NS, serverName: otherName },+ uid+ )+ expect(otherClaim.deleted).toBe(false)+ expect(+ await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: otherName })+ ).not.toBeNull()++ // A claim of U against the PENDING row deletes nothing.+ const pendingClaim = await claimDeleteDynamicClientForResource(+ db,+ KEY,+ { serverNamespace: NS, serverName: pendingName },+ uid+ )+ expect(pendingClaim.deleted).toBe(false)+ expect(+ await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: pendingName })+ ).not.toBeNull()+ })++ it('migration 0119 is idempotent — re-running the guarded DDL over an already-migrated DB does not error', async () => {+ // Force applyPendingMigrations to re-run applyOAuthInstallIdentity against a DB+ // that ALREADY has the columns and CHECK constraints. This exercises the real+ // guards (ADD COLUMN IF NOT EXISTS + pg_constraint DO-blocks) end to end — a+ // mocked pg that never executes DDL cannot. A dropped guard would raise a+ // duplicate-object error here instead of resolving.+ await db.query(`DELETE FROM schema_migrations WHERE version = '0119_oauth_install_identity'`)+ await expect(initDb({ connect: () => dbPool.connect() })).resolves.not.toThrow()++ // Still exactly one copy of each object — no duplicate column or constraint.+ const cols = await db.query(+ `SELECT count(*)::int AS n FROM information_schema.columns+ WHERE table_name = 'dynamic_clients' AND column_name IN ('install_id', 'cr_uid')`+ )+ expect((cols.rows[0] as { n: number }).n).toBe(2)+ const checks = await db.query(+ `SELECT count(*)::int AS n FROM pg_constraint+ WHERE conname IN ('dynamic_clients_cr_uid_len', 'dynamic_clients_bound_needs_install', 'oauth_grants_cr_uid_len')`+ )+ expect((checks.rows[0] as { n: number }).n).toBe(3)+ })+})