Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): guard registry connection cache generation
Josué1e03a9ec0b74
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex bb7007cdb..6059fe77a 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.401",+ "version": "0.1.402","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.401",+ "version": "0.1.402","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex 4099c1caa..da67d9803 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.401",+ "version": "0.1.402","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/services/registryConnectionDb.ts b/control-api/src/services/registryConnectionDb.tsindex abe0bc9ed..842387b76 100644--- a/control-api/src/services/registryConnectionDb.ts+++ b/control-api/src/services/registryConnectionDb.ts@@ -6,7 +6,11 @@ import {deriveOAuthEncryptionKey,encryptOAuthSecret,} from '../oauth/encryption.js'-import { invalidateRegistryIdentityCaches } from './registryIdentityCache.js'+import {+ invalidateRegistryIdentityCaches,+ isRegistryIdentityCacheGenerationCurrent,+ withCurrentRegistryIdentity,+} from './registryIdentityCache.js'/*** Thrown when no voucher signing key/kid is resolvable (route maps to 500@@ -58,10 +62,12 @@ interface RawRow {// immediately on the local process.const CONNECTION_CACHE_TTL_MS = 15_000let cached: RegistryConnectionRow | null | undefined+let cachedGeneration = -1let cachedAt = 0export function __resetRegistryConnectionCacheForTests(): void {cached = undefined+ cachedGeneration = -1cachedAt = 0}@@ -72,38 +78,53 @@ function encKey(): Buffer {export async function getRegistryConnection(db: DbClient = pool): Promise<RegistryConnectionRow | null> {- if (cached !== undefined && Date.now() - cachedAt < CONNECTION_CACHE_TTL_MS) return cached- const res = await db.query(- `SELECT deployment_id, key_id, public_key_pem, private_key_encrypted, client_id,- client_secret_encrypted, org_name, requested_org_name, contact_email, status, registry_url- FROM registry_connection- ORDER BY created_at DESC- LIMIT 1`- )- const raw = res.rows[0] as RawRow | undefined- if (!raw) {- cached = null- cachedAt = Date.now()- return null- }- const key = encKey()- cached = {- deploymentId: raw.deployment_id,- keyId: raw.key_id,- publicKeyPem: raw.public_key_pem,- privateKeyPem: decryptOAuthSecret(key, raw.private_key_encrypted),- clientId: raw.client_id,- clientSecret: raw.client_secret_encrypted- ? decryptOAuthSecret(key, raw.client_secret_encrypted)- : null,- orgName: raw.org_name,- requestedOrgName: raw.requested_org_name,- contactEmail: raw.contact_email,- status: raw.status,- registryUrl: raw.registry_url,- }- cachedAt = Date.now()- return cached+ return withCurrentRegistryIdentity(async generation => {+ if (+ cached !== undefined &&+ cachedGeneration === generation &&+ Date.now() - cachedAt < CONNECTION_CACHE_TTL_MS+ ) {+ return cached+ }+ const res = await db.query(+ `SELECT deployment_id, key_id, public_key_pem, private_key_encrypted, client_id,+ client_secret_encrypted, org_name, requested_org_name, contact_email, status, registry_url+ FROM registry_connection+ ORDER BY created_at DESC+ LIMIT 1`+ )+ const raw = res.rows[0] as RawRow | undefined+ if (!raw) {+ if (isRegistryIdentityCacheGenerationCurrent(generation)) {+ cached = null+ cachedGeneration = generation+ cachedAt = Date.now()+ }+ return null+ }+ const key = encKey()+ const row = {+ deploymentId: raw.deployment_id,+ keyId: raw.key_id,+ publicKeyPem: raw.public_key_pem,+ privateKeyPem: decryptOAuthSecret(key, raw.private_key_encrypted),+ clientId: raw.client_id,+ clientSecret: raw.client_secret_encrypted+ ? decryptOAuthSecret(key, raw.client_secret_encrypted)+ : null,+ orgName: raw.org_name,+ requestedOrgName: raw.requested_org_name,+ contactEmail: raw.contact_email,+ status: raw.status,+ registryUrl: raw.registry_url,+ }+ if (isRegistryIdentityCacheGenerationCurrent(generation)) {+ cached = row+ cachedGeneration = generation+ cachedAt = Date.now()+ }+ return row+ })}export async function upsertPendingConnection(diff --git a/control-api/test/services.registryConnectionDb.test.ts b/control-api/test/services.registryConnectionDb.test.tsindex d2f9874c5..c4847ecce 100644--- a/control-api/test/services.registryConnectionDb.test.ts+++ b/control-api/test/services.registryConnectionDb.test.ts@@ -66,6 +66,16 @@ interface RawRowShape {registry_url: string | null}+function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+}+// Build a DB row whose private_key_encrypted is valid ciphertext under encKeyHex// (getRegistryConnection always decrypts it), with overridable columns.function makeRawRow(encKeyHex: string, overrides: Partial<RawRowShape> = {}): RawRowShape {@@ -183,6 +193,103 @@ describe('getRegistryConnection', () => {expect(row!.orgName).toBe('acme')expect(row!.status).toBe('connected')})++ it('does not reinstall a stale pending row after a successful connect', async () => {+ const encKey = randomBytes(32).toString('hex')+ cfg.registryConnectionMode = 'self-hosted'+ cfg.oauthEncryptionKey = encKey+ const key = deriveOAuthEncryptionKey(encKey)+ const pendingRead = deferred<{ rows: RawRowShape[]; rowCount: number }>()+ const currentRead = deferred<{ rows: RawRowShape[]; rowCount: number }>()+ const connectedRow = makeRawRow(encKey, {+ status: 'connected',+ client_id: 'cid-current',+ client_secret_encrypted: encryptOAuthSecret(key, 'secret-current'),+ org_name: 'current-org',+ })++ dbQuery.mockImplementationOnce(() => pendingRead.promise)+ const staleCaller = getRegistryConnection()++ dbQuery.mockResolvedValueOnce({ rows: [], rowCount: 1 })+ await markConnected({+ deploymentId: 'dep-1',+ clientId: 'cid-current',+ clientSecret: 'secret-current',+ orgName: 'current-org',+ })++ dbQuery.mockImplementationOnce(() => currentRead.promise)+ const currentCaller = getRegistryConnection()+ currentRead.resolve({ rows: [connectedRow], rowCount: 1 })++ await expect(currentCaller).resolves.toMatchObject({+ status: 'connected',+ clientId: 'cid-current',+ orgName: 'current-org',+ })++ pendingRead.resolve({+ rows: [+ makeRawRow(encKey, {+ status: 'pending',+ client_id: null,+ client_secret_encrypted: null,+ org_name: null,+ }),+ ],+ rowCount: 1,+ })++ await expect(staleCaller).resolves.toMatchObject({+ status: 'connected',+ clientId: 'cid-current',+ orgName: 'current-org',+ })+ expect(await isRegistryAuthActive()).toBe(true)+ expect(await getRegistryConnection()).toMatchObject({+ status: 'connected',+ clientId: 'cid-current',+ orgName: 'current-org',+ })+ })++ it('does not reinstall a stale connected row after disconnect', async () => {+ const encKey = randomBytes(32).toString('hex')+ cfg.registryConnectionMode = 'self-hosted'+ cfg.oauthEncryptionKey = encKey+ const key = deriveOAuthEncryptionKey(encKey)+ const staleRead = deferred<{ rows: RawRowShape[]; rowCount: number }>()+ const currentRead = deferred<{ rows: RawRowShape[]; rowCount: number }>()++ dbQuery.mockImplementationOnce(() => staleRead.promise)+ const staleCaller = getRegistryConnection()++ dbQuery.mockResolvedValueOnce({ rows: [], rowCount: 1 })+ await deleteConnection()++ dbQuery.mockImplementationOnce(() => currentRead.promise)+ const currentCaller = getRegistryConnection()+ currentRead.resolve({ rows: [], rowCount: 0 })++ await expect(currentCaller).resolves.toBeNull()++ staleRead.resolve({+ rows: [+ makeRawRow(encKey, {+ status: 'connected',+ client_id: 'cid-old',+ client_secret_encrypted: encryptOAuthSecret(key, 'secret-old'),+ org_name: 'old-org',+ }),+ ],+ rowCount: 1,+ })++ await expect(staleCaller).resolves.toBeNull()+ expect(await isRegistryAuthActive()).toBe(false)+ await expect(getRegistryConnection()).resolves.toBeNull()+ })})// ─── C-I3: execution coverage for the security-critical write + resolver paths ──