Skip to content

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

TypeScript

fix(control-api): scope markConnected to its deployment and make the connection upsert atomic

Jose Ramirezd5b3616e5a49
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index ff14bc2b4..7237060ca 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.367",
+ "version": "0.1.368",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.367",
+ "version": "0.1.368",
"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.json
index 2a655b11c..96a068da6 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.367",
+ "version": "0.1.368",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/registryConnect.ts b/control-api/src/routes/admin/registryConnect.ts
index 821904d52..a363e026f 100644
--- a/control-api/src/routes/admin/registryConnect.ts
+++ b/control-api/src/routes/admin/registryConnect.ts
@@ -257,6 +257,7 @@ export function createRegistryConnectRouter(): Router {
org: string
}
await markConnected({
+ deploymentId: row.deploymentId,
clientId: claimed.client_id,
clientSecret: claimed.client_secret,
orgName: claimed.org,
diff --git a/control-api/src/services/registryConnectionDb.ts b/control-api/src/services/registryConnectionDb.ts
index 4886a4f89..4fa4a30be 100644
--- a/control-api/src/services/registryConnectionDb.ts
+++ b/control-api/src/services/registryConnectionDb.ts
@@ -1,5 +1,5 @@
import { config } from '../config.js'
-import { pool } from '../db.js'
+import { pool, withTransaction } from '../db.js'
import type { DbClient } from '../db.js'
import {
decryptOAuthSecret,
@@ -108,43 +108,60 @@ export async function upsertPendingConnection(
requestedOrgName: string
contactEmail: string
registryUrl: string
+ /** 'approved' marks a registry auto-approval whose claim has not landed yet. */
+ status?: 'pending' | 'approved'
},
- db: DbClient = pool
+ db?: DbClient
): Promise<void> {
const encPriv = encryptOAuthSecret(encKey(), input.privateKeyPem)
- // Singleton table: delete any prior row then insert. (A connect restart replaces
- // a stale pending row — the deployment keypair is regenerated fresh each request.)
- await db.query(`DELETE FROM registry_connection`)
- await db.query(
- `INSERT INTO registry_connection
- (deployment_id, key_id, public_key_pem, private_key_encrypted,
- requested_org_name, contact_email, status, registry_url)
- VALUES ($1,$2,$3,$4,$5,$6,'pending',$7)`,
- [
- input.deploymentId,
- input.keyId,
- input.publicKeyPem,
- encPriv,
- input.requestedOrgName,
- input.contactEmail,
- input.registryUrl,
- ]
- )
+ const status = input.status ?? 'pending'
+ // Singleton table: replace any prior row. DELETE + INSERT must be ATOMIC —
+ // a crash between them destroys the deployment keypair, which is the only
+ // artifact that can recover an already-approved deployment (rotate is
+ // PoP-gated). An explicit db means the caller already owns a transaction.
+ const run = async (tx: DbClient): Promise<void> => {
+ await tx.query(`DELETE FROM registry_connection`)
+ await tx.query(
+ `INSERT INTO registry_connection
+ (deployment_id, key_id, public_key_pem, private_key_encrypted,
+ requested_org_name, contact_email, status, registry_url)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`,
+ [
+ input.deploymentId,
+ input.keyId,
+ input.publicKeyPem,
+ encPriv,
+ input.requestedOrgName,
+ input.contactEmail,
+ status,
+ input.registryUrl,
+ ]
+ )
+ }
+ if (db) await run(db)
+ else await withTransaction(run)
cached = undefined
}
export async function markConnected(
- input: { clientId: string; clientSecret: string; orgName: string },
+ input: { deploymentId: string; clientId: string; clientSecret: string; orgName: string },
db: DbClient = pool
-): Promise<void> {
+): Promise<boolean> {
const encSecret = encryptOAuthSecret(encKey(), input.clientSecret)
- await db.query(
+ // Scoped to the deployment that actually claimed. Without the predicate a
+ // DELETE or a second registration landing mid-claim would either silently
+ // swallow the credentials or stamp THIS deployment's client secret onto a
+ // DIFFERENT deployment's keypair — machine creds and voucher signing key
+ // would then belong to two different deployments.
+ const res = await db.query(
`UPDATE registry_connection
SET client_id = $1, client_secret_encrypted = $2, org_name = $3,
- status = 'connected', updated_at = now()`,
- [input.clientId, encSecret, input.orgName]
+ status = 'connected', updated_at = now()
+ WHERE deployment_id = $4 AND status <> 'connected'`,
+ [input.clientId, encSecret, input.orgName, input.deploymentId]
)
cached = undefined
+ return (res.rowCount ?? 0) > 0
}
export async function deleteConnection(db: DbClient = pool): Promise<void> {
diff --git a/control-api/test/services.registryConnectionDb.test.ts b/control-api/test/services.registryConnectionDb.test.ts
index 7e4daf3c8..565feb926 100644
--- a/control-api/test/services.registryConnectionDb.test.ts
+++ b/control-api/test/services.registryConnectionDb.test.ts
@@ -36,6 +36,8 @@ vi.mock('../src/config.js', () => ({ config: cfg }))
const dbQuery = vi.fn()
vi.mock('../src/db.js', () => ({
pool: { query: (t: string, v?: unknown[]) => dbQuery(t, v) },
+ withTransaction: async (fn: (db: unknown) => Promise<unknown>) =>
+ fn({ query: (t: string, v?: unknown[]) => dbQuery(t, v) }),
}))
const keypair = () =>
@@ -222,7 +224,12 @@ describe('markConnected — writes ciphertext for the client secret (C-I3a)', ()
cfg.oauthEncryptionKey = encKeyHex
dbQuery.mockResolvedValue({ rows: [], rowCount: 0 })
- await markConnected({ clientId: 'cid-9', clientSecret: 'super-secret-xyz', orgName: 'acme' })
+ await markConnected({
+ deploymentId: 'dep-9',
+ clientId: 'cid-9',
+ clientSecret: 'super-secret-xyz',
+ orgName: 'acme',
+ })
const upd = dbQuery.mock.calls.find(([sql]) =>
String(sql).includes('UPDATE registry_connection')
@@ -323,3 +330,76 @@ describe('resolveMachineCreds (C-I3b)', () => {
expect(await resolveMachineCreds()).toBeNull()
})
})
+
+describe('upsertPendingConnection — status parameter reaches the SQL', () => {
+ it('defaults to pending', async () => {
+ cfg.oauthEncryptionKey = randomBytes(32).toString('hex')
+ dbQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ await upsertPendingConnection({
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ publicKeyPem: 'PUB',
+ privateKeyPem: keypair().privateKey,
+ requestedOrgName: 'acme',
+ contactEmail: '[email protected]',
+ registryUrl: 'https://r.example',
+ })
+ const insert = dbQuery.mock.calls.find(([sql]) =>
+ String(sql).includes('INSERT INTO registry_connection')
+ )
+ // status is a BOUND PARAMETER ($7), not a SQL literal
+ expect(String(insert![0])).not.toMatch(/'pending'/)
+ expect((insert![1] as string[])[6]).toBe('pending')
+ })
+
+ it("writes 'approved' when asked", async () => {
+ cfg.oauthEncryptionKey = randomBytes(32).toString('hex')
+ dbQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ await upsertPendingConnection({
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ publicKeyPem: 'PUB',
+ privateKeyPem: keypair().privateKey,
+ requestedOrgName: 'acme',
+ contactEmail: '[email protected]',
+ registryUrl: 'https://r.example',
+ status: 'approved',
+ })
+ const insert = dbQuery.mock.calls.find(([sql]) =>
+ String(sql).includes('INSERT INTO registry_connection')
+ )
+ expect((insert![1] as string[])[6]).toBe('approved')
+ })
+})
+
+describe('markConnected — scoped write', () => {
+ it('scopes the UPDATE to the deployment and returns true on a match', async () => {
+ cfg.oauthEncryptionKey = randomBytes(32).toString('hex')
+ dbQuery.mockResolvedValue({ rows: [], rowCount: 1 })
+ const ok = await markConnected({
+ deploymentId: 'dep-9',
+ clientId: 'cid-9',
+ clientSecret: 'super-secret-xyz',
+ orgName: 'acme',
+ })
+ expect(ok).toBe(true)
+ const upd = dbQuery.mock.calls.find(([sql]) =>
+ String(sql).includes('UPDATE registry_connection')
+ )
+ expect(String(upd![0])).toMatch(/WHERE\s+deployment_id\s*=\s*\$4/)
+ expect(String(upd![0])).toMatch(/status\s*<>\s*'connected'/)
+ expect((upd![1] as string[])[3]).toBe('dep-9')
+ })
+
+ it('returns false when no row matched (row deleted or superseded mid-claim)', async () => {
+ cfg.oauthEncryptionKey = randomBytes(32).toString('hex')
+ dbQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ const ok = await markConnected({
+ deploymentId: 'dep-9',
+ clientId: 'cid-9',
+ clientSecret: 'super-secret-xyz',
+ orgName: 'acme',
+ })
+ expect(ok).toBe(false)
+ })
+})