Skip to content

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

TypeScript

refactor(control-api): expose in-transaction desktop user and control admin retirement

Jose Gabriel Ramirez Encinasd7eb8340fe1d
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 4847ffa76..dac8a3f72 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.641",
+ "version": "0.1.642",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.641",
+ "version": "0.1.642",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index 26cc03598..48ff97068 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.641",
+ "version": "0.1.642",
"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/adminAuthService.ts b/control-api/src/services/adminAuthService.ts
index 3339b77a1..157026451 100644
--- a/control-api/src/services/adminAuthService.ts
+++ b/control-api/src/services/adminAuthService.ts
@@ -565,58 +565,77 @@ export async function deleteControlAdmin(
actorAdminId: string,
adminId: string
): Promise<{ deleted: true } | { error: 'not_found' }> {
- return withTransaction(async db => {
- const actorResult = await db.query(
- `SELECT id, username, email
+ return withTransaction(db =>
+ retireControlAdminInTransaction(db, {
+ actorAdminId,
+ adminId,
+ reason: 'control_admin_retired',
+ })
+ )
+}
+
+/**
+ * Retire an active control admin inside the caller's transaction: operator
+ * link retired, status disabled, sessions invalidated (session_version + 1),
+ * deletion audit and governed administrative event appended. A target that is
+ * missing or not active is a stable not_found.
+ */
+export async function retireControlAdminInTransaction(
+ db: DbClient,
+ input: { actorAdminId: string; adminId: string; reason: string }
+): Promise<{ deleted: true } | { error: 'not_found' }> {
+ const { actorAdminId, adminId } = input
+ const actorResult = await db.query(
+ `SELECT id, username, email
FROM control_admin_users
WHERE id = $1
LIMIT 1`,
- [actorAdminId]
- )
+ [actorAdminId]
+ )
- // Serialize retirement against a concurrent delete/disable. The lifecycle
- // transition is active -> disabled; a replay must be a stable not-found
- // result and must not revoke another generation or append duplicate audit.
- const targetResult = await db.query(
- `SELECT id, username, email, status
+ // Serialize retirement against a concurrent delete/disable. The lifecycle
+ // transition is active -> disabled; a replay must be a stable not-found
+ // result and must not revoke another generation or append duplicate audit.
+ const targetResult = await db.query(
+ `SELECT id, username, email, status
FROM control_admin_users
WHERE id = $1
FOR UPDATE`,
- [adminId]
- )
- const target = targetResult.rows[0] as
- | { id: string; username: string; email: string | null; status: 'active' | 'disabled' }
- | undefined
- if (!target || target.status !== 'active') return { error: 'not_found' as const }
-
- await gfsDesktopOperatorLinkService.retireParentInTransaction(db, {
- kind: 'control_admin',
- parentId: adminId,
- actor: { kind: 'control_admin', controlAdminId: actorAdminId },
- reason: 'control_admin_retired',
- })
- const deletedResult = await db.query(
- `UPDATE control_admin_users
+ [adminId]
+ )
+ const target = targetResult.rows[0] as
+ | { id: string; username: string; email: string | null; status: 'active' | 'disabled' }
+ | undefined
+ if (!target || target.status !== 'active') return { error: 'not_found' as const }
+
+ await gfsDesktopOperatorLinkService.retireParentInTransaction(db, {
+ kind: 'control_admin',
+ parentId: adminId,
+ actor: { kind: 'control_admin', controlAdminId: actorAdminId },
+ reason: input.reason,
+ })
+ const deletedResult = await db.query(
+ `UPDATE control_admin_users
SET status = 'disabled', session_version = session_version + 1, updated_at = NOW()
WHERE id = $1
AND status = 'active'
RETURNING id, username, email`,
- [adminId]
- )
+ [adminId]
+ )
- if ((deletedResult.rowCount ?? 0) === 0) return { error: 'not_found' as const }
+ if ((deletedResult.rowCount ?? 0) === 0) return { error: 'not_found' as const }
- const actor = actorResult.rows[0] as
- | { id: string; username: string; email: string | null }
- | undefined
- const deleted = deletedResult.rows[0] as {
- id: string
- username: string
- email: string | null
- }
+ const actor = actorResult.rows[0] as
+ | { id: string; username: string; email: string | null }
+ | undefined
+ const deleted = deletedResult.rows[0] as {
+ id: string
+ username: string
+ email: string | null
+ }
- const auditResult = await db.query(
- `INSERT INTO control_admin_deletion_audit (
+ const auditResult = await db.query(
+ `INSERT INTO control_admin_deletion_audit (
actor_admin_id,
actor_username,
actor_email,
@@ -626,64 +645,63 @@ export async function deleteControlAdmin(
)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id::text AS id`,
- [
- actor?.id ?? actorAdminId,
- actor?.username ?? null,
- actor?.email ?? null,
- deleted.id,
- deleted.username,
- deleted.email,
- ]
- )
+ [
+ actor?.id ?? actorAdminId,
+ actor?.username ?? null,
+ actor?.email ?? null,
+ deleted.id,
+ deleted.username,
+ deleted.email,
+ ]
+ )
- const audit = auditResult.rows[0] as { id: string } | undefined
- if (!audit?.id) throw new Error('control admin deletion audit insert did not return an id')
- const requestContext = currentAdministrativeRequestContext()
- await administrativeEvents.appendInTransaction(
- db,
- CONTROL_API_LOCAL_ADMINISTRATIVE_PRINCIPAL_V1,
- {
- action: 'control_admin_deleted',
- outcome: 'committed',
- operatorSub: actor?.id ?? actorAdminId,
- operatorUserId: actor?.id ?? actorAdminId,
- operationId: audit.id,
- relatedRunId: null,
- requestId:
- requestContext?.operatorSub === (actor?.id ?? actorAdminId)
- ? requestContext.requestId
- : null,
- targetType: 'control_admin',
- targetRef: `control_admin:${deleted.id}`,
- environment: canonicalTracingEnvironment(),
- tenantId: null,
- teamId: null,
- namespace: null,
- sourceAuditRef: `control_admin_deletion_audit:${audit.id}`,
- identityIssuer: config.adminJwtIssuer,
- resourceAud: config.adminJwtAudience,
- effectiveScopes: [],
- authorizationDecision: 'allow',
- decisionActorSub: actor?.id ?? actorAdminId,
- targetIdentityIssuer: config.adminJwtIssuer,
- targetHumanSub: deleted.id,
- targetUserId: null,
+ const audit = auditResult.rows[0] as { id: string } | undefined
+ if (!audit?.id) throw new Error('control admin deletion audit insert did not return an id')
+ const requestContext = currentAdministrativeRequestContext()
+ await administrativeEvents.appendInTransaction(
+ db,
+ CONTROL_API_LOCAL_ADMINISTRATIVE_PRINCIPAL_V1,
+ {
+ action: 'control_admin_deleted',
+ outcome: 'committed',
+ operatorSub: actor?.id ?? actorAdminId,
+ operatorUserId: actor?.id ?? actorAdminId,
+ operationId: audit.id,
+ relatedRunId: null,
+ requestId:
+ requestContext?.operatorSub === (actor?.id ?? actorAdminId)
+ ? requestContext.requestId
+ : null,
+ targetType: 'control_admin',
+ targetRef: `control_admin:${deleted.id}`,
+ environment: canonicalTracingEnvironment(),
+ tenantId: null,
+ teamId: null,
+ namespace: null,
+ sourceAuditRef: `control_admin_deletion_audit:${audit.id}`,
+ identityIssuer: config.adminJwtIssuer,
+ resourceAud: config.adminJwtAudience,
+ effectiveScopes: [],
+ authorizationDecision: 'allow',
+ decisionActorSub: actor?.id ?? actorAdminId,
+ targetIdentityIssuer: config.adminJwtIssuer,
+ targetHumanSub: deleted.id,
+ targetUserId: null,
+ },
+ {
+ kind: 'service_action',
+ sourceEventId: `control_admin_deletion_audit:${audit.id}`,
+ occurredAt: new Date().toISOString(),
+ reasonCode: 'control_admin_access_revoked',
+ payload: {
+ resource_class: 'control_admin_access',
+ status: 'revoked',
+ target_label: deleted.username,
},
- {
- kind: 'service_action',
- sourceEventId: `control_admin_deletion_audit:${audit.id}`,
- occurredAt: new Date().toISOString(),
- reasonCode: 'control_admin_access_revoked',
- payload: {
- resource_class: 'control_admin_access',
- status: 'revoked',
- target_label: deleted.username,
- },
- }
- )
+ }
+ )
- return { deleted: true as const }
- })
+ return { deleted: true as const }
}
export async function listControlAdmins(): Promise<{
diff --git a/control-api/src/services/directory/users.ts b/control-api/src/services/directory/users.ts
index f267df578..244616314 100644
--- a/control-api/src/services/directory/users.ts
+++ b/control-api/src/services/directory/users.ts
@@ -1,5 +1,5 @@
import { createHash } from 'node:crypto'
-import { pool, withTransaction } from '../../db.js'
+import { type DbClient, pool, withTransaction } from '../../db.js'
import {
type GfsDesktopOperatorLifecycleActor,
GfsDesktopOperatorLinkError,
@@ -349,7 +349,8 @@ export async function retireDesktopUser(
userIdInput: string,
reasonInput: string,
idempotencyKeyInput: string,
- requestIdInput: string | null | undefined
+ requestIdInput: string | null | undefined,
+ options: { db?: DbClient; retainWithoutLinkHistory?: boolean } = {}
): Promise<RetireDesktopUserResult> {
const actor = normalizeRetirementActor(actorInput)
const targetUserId = requireUuid(userIdInput, 'userId')
@@ -370,7 +371,7 @@ export async function retireDesktopUser(
const actorColumn =
actor.kind === 'control_admin' ? 'actor_control_admin_id' : 'actor_desktop_user_id'
- return withTransaction(async db => {
+ const run = async (db: DbClient): Promise<RetireDesktopUserResult> => {
const claim = await db.query(
`INSERT INTO desktop_user_retirement_operations(
operation,
@@ -479,7 +480,7 @@ export async function retireDesktopUser(
const hasLinkHistory =
(history.rows[0] as { has_link_history?: unknown } | undefined)?.has_link_history === true
- if (!hasLinkHistory) {
+ if (!hasLinkHistory && options.retainWithoutLinkHistory !== true) {
await db.query(
`UPDATE workflow_approval_medium_accounts
SET disabled_at = COALESCE(disabled_at, NOW()),
@@ -553,7 +554,7 @@ export async function retireDesktopUser(
}
throw error
}
- if (!revoked) {
+ if (hasLinkHistory && !revoked) {
throw new DesktopUserRetirementError(
'retirement_conflict',
'operator-link history has no active generation to retire'
@@ -620,7 +621,37 @@ export async function retireDesktopUser(
lifecycleVersion: nextLifecycleVersion,
replayed: false,
}
- })
+ }
+ return options.db ? run(options.db) : withTransaction(run)
+}
+
+export type RetireDesktopUserInTransactionInput = {
+ actor: DesktopUserRetirementActor
+ userId: string
+ reason: string
+ idempotencyKey: string
+ requestId: string | null
+ /**
+ * Always leave a `retired` tombstone, even without operator-link history
+ * (where retireDesktopUser hard-deletes). A hand-over needs the tombstone and
+ * must not fail on FKs that a hard delete could hit.
+ */
+ retainWithoutLinkHistory?: boolean
+}
+
+/** Same lifecycle as retireDesktopUser, inside the caller's transaction. */
+export async function retireDesktopUserInTransaction(
+ db: DbClient,
+ input: RetireDesktopUserInTransactionInput
+): Promise<RetireDesktopUserResult> {
+ return retireDesktopUser(
+ input.actor,
+ input.userId,
+ input.reason,
+ input.idempotencyKey,
+ input.requestId,
+ { db, retainWithoutLinkHistory: input.retainWithoutLinkHistory === true }
+ )
}
/**
diff --git a/control-api/test/services.adminAuthDelete.test.ts b/control-api/test/services.adminAuthDelete.test.ts
index 18d7387ae..ff7b5e89e 100644
--- a/control-api/test/services.adminAuthDelete.test.ts
+++ b/control-api/test/services.adminAuthDelete.test.ts
@@ -115,4 +115,27 @@ describe('deleteControlAdmin lifecycle transition', () => {
expect(linkService.retireParentInTransaction).toHaveBeenCalledOnce()
expect(eventService.appendInTransaction).toHaveBeenCalledOnce()
})
+
+ it('retires inside the caller transaction with the caller reason', async () => {
+ const { retireControlAdminInTransaction } = await import('../src/services/adminAuthService.js')
+ db.withTransaction.mockClear()
+ const tx = { query: async (text: string) => queryResult(text) }
+
+ await expect(
+ retireControlAdminInTransaction(tx, {
+ actorAdminId: 'actor-admin',
+ adminId: 'target-admin',
+ reason: 'control_admin_replaced',
+ })
+ ).resolves.toEqual({ deleted: true })
+
+ expect(db.withTransaction).not.toHaveBeenCalled()
+ expect(linkService.retireParentInTransaction).toHaveBeenCalledWith(tx, {
+ kind: 'control_admin',
+ parentId: 'target-admin',
+ actor: { kind: 'control_admin', controlAdminId: 'actor-admin' },
+ reason: 'control_admin_replaced',
+ })
+ expect(eventService.appendInTransaction).toHaveBeenCalledOnce()
+ })
})
diff --git a/control-api/test/services.directory.userRetirement.test.ts b/control-api/test/services.directory.userRetirement.test.ts
index 6a64d6b35..15e66c4ab 100644
--- a/control-api/test/services.directory.userRetirement.test.ts
+++ b/control-api/test/services.directory.userRetirement.test.ts
@@ -353,4 +353,40 @@ describe('retireDesktopUser', () => {
).rejects.toMatchObject({ code: 'invalid_input' })
expect(mocks.withTransaction).not.toHaveBeenCalled()
})
+
+ it('retains an unlinked user as retired inside the caller transaction when asked to', async () => {
+ const { retireDesktopUserInTransaction } = await import('../src/services/directory/users.js')
+ mocks.retireParentInTransaction.mockResolvedValueOnce(false)
+ mocks.txQuery
+ .mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
+ .mockResolvedValueOnce(activeUser())
+ .mockResolvedValueOnce({ rows: [{ has_link_history: false }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [{ lifecycle_version: 2 }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+
+ await expect(
+ retireDesktopUserInTransaction(
+ { query: mocks.txQuery },
+ {
+ actor: { kind: 'control_admin', controlAdminId: ADMIN_ID },
+ userId: USER_ID,
+ reason: 'control_admin_replaced',
+ idempotencyKey: 'control_admin_replaced:invitation-1',
+ requestId: null,
+ retainWithoutLinkHistory: true,
+ }
+ )
+ ).resolves.toEqual({
+ id: USER_ID,
+ outcome: 'retired',
+ operationId: OPERATION_ID,
+ lifecycleVersion: 2,
+ replayed: false,
+ })
+ expect(mocks.withTransaction).not.toHaveBeenCalled()
+ const sqls = mocks.txQuery.mock.calls.map(([sql]) => String(sql))
+ expect(sqls.some(sql => sql.includes('DELETE FROM users'))).toBe(false)
+ expect(sqls[3]).toContain("SET lifecycle_state = 'retired'")
+ expect(sqls[4]).toContain("outcome = 'retired'")
+ })
})