Skip to content

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

TypeScript

feat(control-api): retire the inviting admin when a replaceInviter invitation is accepted

Jose Gabriel Ramirez Encinas24ca1ea8ba5e
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index dac8a3f72..5ec8f7bf8 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.642",
+ "version": "0.1.643",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.642",
+ "version": "0.1.643",
"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 48ff97068..3aafb96fd 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.642",
+ "version": "0.1.643",
"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 157026451..896fa7f61 100644
--- a/control-api/src/services/adminAuthService.ts
+++ b/control-api/src/services/adminAuthService.ts
@@ -1,6 +1,7 @@
import { config } from '../config.js'
import { type DbClient, pool, withTransaction } from '../db.js'
import { rootLogger } from '../observability/logger.js'
+import { retireDesktopUserInTransaction } from './directory/users.js'
import { gfsDesktopOperatorLinkService } from './gfsDesktopOperatorLinkService.js'
import { currentAdministrativeRequestContext } from './tracing/adminOperationContext.js'
import { AdministrativeEventService } from './tracing/administrativeEvents.js'
@@ -987,6 +988,21 @@ export async function completeControlAdminInvitation(input: {
const invitation = await getPendingControlAdminInvitation(db, input.invitationId, email)
if (!invitation) return { error: 'not_found' as const }
+ // Lock and re-check before creating anything: getPendingControlAdminInvitation
+ // does not lock, and the accept UPDATE below has no status guard, so a revoke
+ // that commits meanwhile (DELETE route, MCC resend/cancel, or a replace-inviter
+ // acceptance revoking this inviter's other invitations) must win here.
+ const lockedInvitation = await db.query(
+ `SELECT id
+ FROM control_admin_invitations
+ WHERE id = $1
+ AND status IN ('pending', 'opened')
+ AND expires_at > NOW()
+ FOR UPDATE`,
+ [invitation.id]
+ )
+ if ((lockedInvitation.rowCount ?? 0) === 0) return { error: 'not_found' as const }
+
const conflict = await db.query(
`SELECT
EXISTS(SELECT 1 FROM control_admin_users WHERE lower(email) = lower($1)) AS email_exists,
@@ -1014,10 +1030,179 @@ export async function completeControlAdminInvitation(input: {
[invitation.id, admin.id]
)
+ if (invitation.replaceInviter && invitation.invitedByAdminId) {
+ await replaceInviterInTransaction(db, {
+ invitationId: invitation.id,
+ inviterAdminId: invitation.invitedByAdminId,
+ newAdmin: admin,
+ })
+ }
+
return admin
})
}
+export const CONTROL_ADMIN_REPLACED_REASON = 'control_admin_replaced'
+
+// admin > inviter > member; used so a copied role never downgrades a target.
+const TEAM_ROLE_RANK = (column: string) =>
+ `(CASE ${column} WHEN 'admin' THEN 3 WHEN 'inviter' THEN 2 ELSE 1 END)`
+
+/**
+ * Hand the inviter's access to the invitee and retire the inviter, inside the
+ * transaction that created the invitee's control admin. An inviter that is
+ * gone or no longer active has nothing to hand over; the caller still commits.
+ */
+async function replaceInviterInTransaction(
+ db: DbClient,
+ input: { invitationId: string; inviterAdminId: string; newAdmin: AdminUserRecord }
+): Promise<void> {
+ const inviterResult = await db.query(
+ `SELECT id::text AS id, email, status
+ FROM control_admin_users
+ WHERE id = $1
+ FOR UPDATE`,
+ [input.inviterAdminId]
+ )
+ const inviter = inviterResult.rows[0] as
+ | { id: string; email: string | null; status: 'active' | 'disabled' }
+ | undefined
+ if (!inviter || inviter.status !== 'active') return
+
+ const inviterDesktop = inviter.email
+ ? await db.query(
+ `SELECT id::text AS id
+ FROM users
+ WHERE lower(email) = lower($1)
+ AND lifecycle_state = 'active'
+ LIMIT 1
+ FOR UPDATE`,
+ [inviter.email]
+ )
+ : { rows: [], rowCount: 0 }
+ const inviterDesktopUserId = (inviterDesktop.rows[0] as { id: string } | undefined)?.id ?? null
+ // completeControlAdminInvitation always inserts the normalized invitation email.
+ const newAdminEmail = input.newAdmin.email ?? ''
+
+ if (inviterDesktopUserId) {
+ // (1a) The invitee already has a desktop user: raise its memberships.
+ await db.query(
+ `INSERT INTO team_members(team_id, user_id, role, status)
+ SELECT source.team_id, target.id, source.role, 'active'
+ FROM team_members source
+ JOIN users target
+ ON lower(target.email) = lower($2)
+ AND target.lifecycle_state = 'active'
+ WHERE source.user_id = $1::uuid
+ AND source.status = 'active'
+ ON CONFLICT (team_id, user_id) DO UPDATE
+ SET role = CASE
+ WHEN team_members.status <> 'active' THEN EXCLUDED.role
+ WHEN ${TEAM_ROLE_RANK('EXCLUDED.role')} > ${TEAM_ROLE_RANK('team_members.role')}
+ THEN EXCLUDED.role
+ ELSE team_members.role
+ END,
+ status = 'active',
+ updated_at = NOW()`,
+ [inviterDesktopUserId, newAdminEmail]
+ )
+ // (1b) The desktop invitation is accepted after this transaction commits
+ // (auth.ts:504-507) and upserts role = EXCLUDED.role (membership.ts:319-326),
+ // so the roles must also live on the invitation or 1a would be downgraded.
+ // Materialize a legacy single-team invitation first so adding rows cannot
+ // hide its fallback team (loadInvitationTeams, membership.ts:242-267).
+ await db.query(
+ `INSERT INTO invitation_teams(invitation_id, team_id, role)
+ SELECT i.id, i.team_id, i.role
+ FROM invitations i
+ WHERE lower(i.email) = lower($1)
+ AND i.purpose = 'admin_desktop_access'
+ AND i.status = 'pending'
+ AND i.team_id IS NOT NULL
+ ON CONFLICT (invitation_id, team_id) DO NOTHING`,
+ [newAdminEmail]
+ )
+ await db.query(
+ `INSERT INTO invitation_teams(invitation_id, team_id, role)
+ SELECT i.id, source.team_id, source.role
+ FROM invitations i
+ JOIN team_members source
+ ON source.user_id = $1::uuid
+ AND source.status = 'active'
+ WHERE lower(i.email) = lower($2)
+ AND i.purpose = 'admin_desktop_access'
+ AND i.status = 'pending'
+ ON CONFLICT (invitation_id, team_id) DO UPDATE
+ SET role = CASE
+ WHEN ${TEAM_ROLE_RANK('EXCLUDED.role')} > ${TEAM_ROLE_RANK('invitation_teams.role')}
+ THEN EXCLUDED.role
+ ELSE invitation_teams.role
+ END`,
+ [inviterDesktopUserId, newAdminEmail]
+ )
+
+ // (2) Retire, never hard-delete, the inviter's desktop identity. Its approval
+ // medium accounts go first: the approval reader grants canApprove on an
+ // enabled account alone (workflowApprovalReader.ts:763-773) and never reads
+ // users.lifecycle_state; the retained tombstone path skips the disable that
+ // retireDesktopUser's hard-delete branch does (users.ts:483-499).
+ await db.query(
+ `UPDATE workflow_approval_medium_accounts
+ SET disabled_at = COALESCE(disabled_at, NOW()),
+ updated_at = NOW()
+ WHERE user_id = $1::uuid
+ AND disabled_at IS NULL`,
+ [inviterDesktopUserId]
+ )
+ await db.query(
+ `UPDATE workflow_approval_medium_challenges
+ SET consumed_at = COALESCE(consumed_at, NOW()),
+ expires_at = LEAST(expires_at, NOW())
+ WHERE user_id = $1::uuid
+ AND consumed_at IS NULL`,
+ [inviterDesktopUserId]
+ )
+ await retireDesktopUserInTransaction(db, {
+ actor: { kind: 'control_admin', controlAdminId: input.newAdmin.id },
+ userId: inviterDesktopUserId,
+ reason: CONTROL_ADMIN_REPLACED_REASON,
+ idempotencyKey: `${CONTROL_ADMIN_REPLACED_REASON}:${input.invitationId}`,
+ requestId: null,
+ retainWithoutLinkHistory: true,
+ })
+ }
+
+ // (3) Retire the inviter exactly as deleteControlAdmin does.
+ const retired = await retireControlAdminInTransaction(db, {
+ actorAdminId: input.newAdmin.id,
+ adminId: inviter.id,
+ reason: CONTROL_ADMIN_REPLACED_REASON,
+ })
+ if ('error' in retired) {
+ throw new Error('inviting control admin changed during replace-inviter acceptance')
+ }
+
+ // (4) Nothing the inviter started may outlive them. `invitations` has no
+ // inviter column (dropped by applyInvitationAndUserPasswordMigration), so the
+ // paired desktop invitations are found by the revoked admin invitations' emails.
+ await db.query(
+ `WITH revoked AS (
+ UPDATE control_admin_invitations
+ SET status = 'revoked'
+ WHERE invited_by_admin_id = $1::uuid
+ AND id <> $2::uuid
+ AND status IN ('pending', 'opened')
+ RETURNING email
+ )
+ UPDATE invitations
+ SET status = 'revoked'
+ WHERE purpose = 'admin_desktop_access'
+ AND status = 'pending'
+ AND lower(email) IN (SELECT lower(email) FROM revoked)`,
+ [inviter.id, input.invitationId]
+ )
+}
+
export async function completeControlAdminEmailChangeRequest(input: {
requestId: string
email: string
diff --git a/control-api/src/services/gfsDesktopOperatorLinkService.ts b/control-api/src/services/gfsDesktopOperatorLinkService.ts
index 0ae200c91..70db91403 100644
--- a/control-api/src/services/gfsDesktopOperatorLinkService.ts
+++ b/control-api/src/services/gfsDesktopOperatorLinkService.ts
@@ -825,8 +825,13 @@ export class GfsDesktopOperatorLinkService {
input.kind === 'desktop_user'
? { kind: 'user' as const, id: parentId }
: {
+ // The 'operator' principal kind is redacted to the literal
+ // 'operator:' ref everywhere it is disclosed
+ // (traceSafeFieldProjection.ts; append.ts's canonical-prefix
+ // check requires an exact 'operator:' match). The retired
+ // control admin's id is still fully recorded in detailRef below.
kind: 'service' as const,
- id: `control_admin:${parentId}`,
+ id: null,
principalKind: 'operator' as const,
},
sourceAuditRef: `gfs_desktop_operator_link_source:${link.source}`,
diff --git a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
index 8e0d0f69b..365fce583 100644
--- a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
+++ b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
@@ -212,4 +212,232 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
})
).resolves.toEqual({ error: 'not_found' })
})
+
+ it('hands the inviter team roles to the new admin and retires the inviter on acceptance', async () => {
+ const inviter = await seedAdmin('evenfire-ops')
+ const inviterDesktopId = await seedDesktopUser(inviter.email)
+ await seedOperatorLink(inviterDesktopId, inviter.id)
+ const defaultTeam = await seedTeam('Default')
+ const secondTeam = await seedTeam('Second')
+ await addTeamMember(defaultTeam, inviterDesktopId, 'admin')
+ await addTeamMember(secondTeam, inviterDesktopId, 'member')
+ await testPool.query(
+ `INSERT INTO workflow_approval_medium_accounts
+ (user_id, medium, provider_user_id, communication_channel_ref, verified_at)
+ VALUES ($1::uuid, 'telegram', $2, 'ops-approval-channel', NOW())`,
+ [inviterDesktopId, `tg-${inviterDesktopId}`]
+ )
+
+ const clientEmail = uniqueEmail('client')
+ const handover = await createControlAdminInvitation(clientEmail, inviter.id, {
+ replaceInviter: true,
+ })
+ if ('error' in handover) throw new Error(handover.error)
+ const clientDesktopInvitationId = await inviteDesktopAccess(clientEmail)
+ const strayEmail = uniqueEmail('stray')
+ const stray = await createControlAdminInvitation(strayEmail, inviter.id)
+ if ('error' in stray) throw new Error(stray.error)
+ const strayDesktopInvitationId = await inviteDesktopAccess(strayEmail)
+
+ const completed = await completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: handover.id,
+ username: `client-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ if ('error' in completed) throw new Error(completed.error)
+ // Same order as POST /admin/auth/control-admin-invitations/complete (auth.ts:486-510).
+ const accepted = await acceptInvitationById(clientEmail, clientDesktopInvitationId)
+ if ('error' in accepted) throw new Error(String(accepted.error))
+
+ const roles = await testPool.query(
+ `SELECT team_id::text AS team_id, role, status FROM team_members WHERE user_id = $1::uuid`,
+ [accepted.data.userId]
+ )
+ expect(roles.rows).toHaveLength(2)
+ expect(roles.rows).toEqual(
+ expect.arrayContaining([
+ { team_id: defaultTeam, role: 'admin', status: 'active' },
+ { team_id: secondTeam, role: 'member', status: 'active' },
+ ])
+ )
+
+ // Both inviter logins fail.
+ await expect(findAdminByLogin(inviter.username)).resolves.toMatchObject({
+ status: 'disabled',
+ sessionVersion: 2,
+ })
+ await expect(
+ passwordLoginData({ email: inviter.email, password: 'irrelevant' })
+ ).resolves.toEqual({ error: 'user_retired' })
+
+ const desktop = await testPool.query(
+ `SELECT lifecycle_state, lifecycle_version, retirement_reason,
+ retired_by_control_admin_id::text AS retired_by
+ FROM users WHERE id = $1::uuid`,
+ [inviterDesktopId]
+ )
+ expect(desktop.rows).toEqual([
+ {
+ lifecycle_state: 'retired',
+ lifecycle_version: '2',
+ retirement_reason: 'control_admin_replaced',
+ retired_by: completed.id,
+ },
+ ])
+ const link = await testPool.query(
+ `SELECT state, revocation_reason FROM gfs_desktop_operator_links WHERE control_admin_id = $1::uuid`,
+ [inviter.id]
+ )
+ expect(link.rows).toEqual([{ state: 'revoked', revocation_reason: 'control_admin_replaced' }])
+ const approvalMedium = await testPool.query(
+ `SELECT disabled_at IS NOT NULL AS disabled
+ FROM workflow_approval_medium_accounts WHERE user_id = $1::uuid`,
+ [inviterDesktopId]
+ )
+ expect(approvalMedium.rows).toEqual([{ disabled: true }])
+ const audit = await testPool.query(
+ `SELECT actor_admin_id::text AS actor, target_admin_id::text AS target
+ FROM control_admin_deletion_audit WHERE target_admin_id = $1::uuid`,
+ [inviter.id]
+ )
+ expect(audit.rows).toEqual([{ actor: completed.id, target: inviter.id }])
+
+ expect(await adminInvitationStatus(handover.id)).toBe('accepted')
+ expect(await desktopInvitationStatus(clientDesktopInvitationId)).toBe('accepted')
+ expect(await adminInvitationStatus(stray.id)).toBe('revoked')
+ expect(await desktopInvitationStatus(strayDesktopInvitationId)).toBe('revoked')
+ })
+
+ it('raises an existing desktop user of the new admin to the inviter roles', async () => {
+ const inviter = await seedAdmin('raise-ops')
+ const inviterDesktopId = await seedDesktopUser(inviter.email)
+ const team = await seedTeam('Raise')
+ await addTeamMember(team, inviterDesktopId, 'admin')
+ const clientEmail = uniqueEmail('existing-client')
+ const clientDesktopId = await seedDesktopUser(clientEmail)
+ await addTeamMember(team, clientDesktopId, 'member')
+ const handover = await createControlAdminInvitation(clientEmail, inviter.id, {
+ replaceInviter: true,
+ })
+ if ('error' in handover) throw new Error(handover.error)
+
+ const completed = await completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: handover.id,
+ username: `existing-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ if ('error' in completed) throw new Error(completed.error)
+
+ const role = await testPool.query(
+ `SELECT role FROM team_members WHERE team_id = $1::uuid AND user_id = $2::uuid`,
+ [team, clientDesktopId]
+ )
+ expect(role.rows).toEqual([{ role: 'admin' }])
+ expect(await desktopLifecycle(inviterDesktopId)).toBe('retired')
+ })
+
+ it('behaves as today when replaceInviter is false', async () => {
+ const inviter = await seedAdmin('plain-ops')
+ const inviterDesktopId = await seedDesktopUser(inviter.email)
+ const clientEmail = uniqueEmail('plain-client')
+ const invitation = await createControlAdminInvitation(clientEmail, inviter.id)
+ if ('error' in invitation) throw new Error(invitation.error)
+ const stray = await createControlAdminInvitation(uniqueEmail('plain-stray'), inviter.id)
+ if ('error' in stray) throw new Error(stray.error)
+
+ const completed = await completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: invitation.id,
+ username: `plain-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ if ('error' in completed) throw new Error(completed.error)
+
+ expect(await adminStatus(inviter.id)).toBe('active')
+ expect(await desktopLifecycle(inviterDesktopId)).toBe('active')
+ expect(await adminInvitationStatus(stray.id)).toBe('pending')
+ })
+
+ it('still completes when the inviter is already disabled or gone', async () => {
+ const inviter = await seedAdmin('gone-ops')
+ const inviterDesktopId = await seedDesktopUser(inviter.email)
+ const disabledEmail = uniqueEmail('after-disable')
+ const afterDisable = await createControlAdminInvitation(disabledEmail, inviter.id, {
+ replaceInviter: true,
+ })
+ if ('error' in afterDisable) throw new Error(afterDisable.error)
+ await testPool.query(`UPDATE control_admin_users SET status = 'disabled' WHERE id = $1::uuid`, [
+ inviter.id,
+ ])
+ const orphanEmail = uniqueEmail('orphan')
+ const orphan = await testPool.query(
+ `INSERT INTO control_admin_invitations (email, invited_by_admin_id, replace_inviter)
+ VALUES ($1, NULL, true) RETURNING id::text AS id`,
+ [orphanEmail]
+ )
+ const orphanId = (orphan.rows[0] as { id: string }).id
+
+ for (const [email, invitationId] of [
+ [disabledEmail, afterDisable.id],
+ [orphanEmail, orphanId],
+ ] as const) {
+ const completed = await completeControlAdminInvitation({
+ email,
+ invitationId,
+ username: `late-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ expect(completed).toMatchObject({ email, status: 'active' })
+ expect(await adminInvitationStatus(invitationId)).toBe('accepted')
+ }
+ expect(await desktopLifecycle(inviterDesktopId)).toBe('active')
+ })
+
+ it('does not complete an invitation revoked while the acceptance is in flight', async () => {
+ const inviter = await seedAdmin('race-ops')
+ const email = uniqueEmail('race-client')
+ const invitation = await createControlAdminInvitation(email, inviter.id)
+ if ('error' in invitation) throw new Error(invitation.error)
+
+ // A revoke (DELETE route, MCC cancel, or another invitation's replace step 4)
+ // holds the row while the client's acceptance starts, then commits.
+ const blocker = await testPool.connect()
+ try {
+ await blocker.query('BEGIN')
+ await blocker.query(
+ `UPDATE control_admin_invitations SET status = 'revoked' WHERE id = $1::uuid`,
+ [invitation.id]
+ )
+ const completion = completeControlAdminInvitation({
+ email,
+ invitationId: invitation.id,
+ username: `race-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ for (let attempt = 0; ; attempt += 1) {
+ const waiting = await adminPool.query(
+ `SELECT 1 FROM pg_stat_activity WHERE datname = $1 AND wait_event_type = 'Lock'`,
+ [database]
+ )
+ if ((waiting.rowCount ?? 0) > 0) break
+ if (attempt >= 100)
+ throw new Error('the acceptance never waited on the revoking transaction')
+ await new Promise(resolve => setTimeout(resolve, 50))
+ }
+ await blocker.query('COMMIT')
+ await expect(completion).resolves.toEqual({ error: 'not_found' })
+ } finally {
+ await blocker.query('ROLLBACK').catch(() => undefined)
+ blocker.release()
+ }
+
+ expect(await adminInvitationStatus(invitation.id)).toBe('revoked')
+ const admins = await testPool.query(
+ `SELECT 1 FROM control_admin_users WHERE lower(email) = lower($1)`,
+ [email]
+ )
+ expect(admins.rowCount).toBe(0)
+ })
})