Skip to content

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

TypeScript

fix(control-api): revoke invites when admin inviter retires (R1-L2)

Josué18f1d022b67e
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index be6075d51..e97b9716a 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.833",
+ "version": "0.1.834",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.833",
+ "version": "0.1.834",
"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 7850bbcdb..36c5de1c6 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.833",
+ "version": "0.1.834",
"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/controlAdmins.ts b/control-api/src/routes/admin/controlAdmins.ts
index 9259e6dd7..756ecf029 100644
--- a/control-api/src/routes/admin/controlAdmins.ts
+++ b/control-api/src/routes/admin/controlAdmins.ts
@@ -23,10 +23,7 @@ import {
findMemberByEmail,
provisionMemberFromAdmin,
} from '../../services/directory/adminProvisioning.js'
-import {
- createSilentInvitationForTeams,
- revokePendingInvitation,
-} from '../../services/directory/index.js'
+import { revokePendingInvitation } from '../../services/directory/index.js'
import { normalizeTeamRoleInput } from '../../services/directory/types.js'
import {
GfsDesktopOperatorLinkError,
@@ -268,14 +265,6 @@ export function createAdminControlAdminsRouter(): Router {
res.status(400).json({ error: 'replaceInviter must be a boolean' })
return
}
- const invitation = await createControlAdminInvitation(email, invitedByAdminId, {
- replaceInviter: replaceInviterInput === true,
- })
- if ('error' in invitation) {
- res.status(409).json({ error: invitation.error })
- return
- }
-
const createDesktopAccess = req.body?.createDesktopAccess === true
const teamsInput: unknown[] =
createDesktopAccess && Array.isArray(req.body?.teams) ? req.body.teams : []
@@ -289,19 +278,18 @@ export function createAdminControlAdminsRouter(): Router {
.filter((item): item is { teamId: string; role: 'admin' | 'inviter' | 'member' } =>
Boolean(item)
)
- let desktopInvitation: Awaited<ReturnType<typeof createSilentInvitationForTeams>> | null =
- null
+ const created = await createControlAdminInvitation(email, invitedByAdminId, {
+ replaceInviter: replaceInviterInput === true,
+ ...(createDesktopAccess ? { desktopAccess: { teamAssignments } } : {}),
+ })
+ if ('error' in created) {
+ res.status(409).json({ error: created.error })
+ return
+ }
+ const invitation = 'invitation' in created ? created.invitation : created
+ const desktopInvitation = 'desktopInvitation' in created ? created.desktopInvitation : null
try {
- if (createDesktopAccess) {
- desktopInvitation = await createSilentInvitationForTeams({
- inviteeName: email,
- email,
- teamAssignments,
- fallbackRole: 'member',
- purpose: 'admin_desktop_access',
- })
- }
await registerAndSendControlAdminInvitation(
invitation.email,
invitation.id,
diff --git a/control-api/src/services/adminAuthService.ts b/control-api/src/services/adminAuthService.ts
index 11f4cdd40..459388269 100644
--- a/control-api/src/services/adminAuthService.ts
+++ b/control-api/src/services/adminAuthService.ts
@@ -1,7 +1,12 @@
import { config } from '../config.js'
import { type DbClient, pool, withTransaction } from '../db.js'
import { rootLogger } from '../observability/logger.js'
-import { INVITATION_TTL_HOURS } from './directory/invitationStore.js'
+import {
+ INVITATION_TTL_HOURS,
+ type InvitationTeamAssignment,
+ insertInvitationForTeams,
+ invitationForTeamsResponse,
+} from './directory/invitationStore.js'
import { retireDesktopUserInTransaction } from './directory/users.js'
import { gfsDesktopOperatorLinkService } from './gfsDesktopOperatorLinkService.js'
import { currentAdministrativeRequestContext } from './tracing/adminOperationContext.js'
@@ -629,6 +634,8 @@ export async function retireControlAdminInTransaction(
if ((deletedResult.rowCount ?? 0) === 0) return { error: 'not_found' as const }
+ await revokeControlAdminInvitations(db, { invitedByAdminId: adminId })
+
const actor = actorResult.rows[0] as
| { id: string; username: string; email: string | null }
| undefined
@@ -865,8 +872,26 @@ export async function listControlAdmins(): Promise<{
export async function createControlAdminInvitation(
email: string,
invitedByAdminId: string,
- options: { replaceInviter?: boolean } = {}
-): Promise<ControlAdminInvitationRecord | { error: 'duplicate_email' | 'inviter_not_active' }> {
+ options: {
+ replaceInviter?: boolean
+ desktopAccess?: { teamAssignments: readonly InvitationTeamAssignment[] }
+ } = {}
+): Promise<
+ | ControlAdminInvitationRecord
+ | {
+ invitation: ControlAdminInvitationRecord
+ desktopInvitation: ReturnType<typeof invitationForTeamsResponse>
+ }
+ | { error: 'duplicate_email' | 'inviter_not_active' }
+> {
+ type CreationResult =
+ | { error: 'duplicate_email' | 'inviter_not_active' }
+ | { invitation: ControlAdminInvitationRecord }
+ | {
+ invitation: ControlAdminInvitationRecord
+ desktopInvitation: ReturnType<typeof invitationForTeamsResponse>
+ }
+
const normalizedEmail = normalizeEmail(email)
const replaceInviter = options.replaceInviter === true
// Revoke expired active invitations first so the INSERT guard can treat any remaining
@@ -880,31 +905,55 @@ export async function createControlAdminInvitation(
[normalizedEmail]
)
- let result
+ let created: CreationResult
try {
- result = await pool.query(
- `WITH locked_inviter AS (
- SELECT id
+ created = await withTransaction<CreationResult>(async db => {
+ const inviter = await db.query(
+ `SELECT id
FROM control_admin_users
- WHERE id = $2::uuid
+ WHERE id = $1::uuid
AND status = 'active'
- FOR UPDATE
- )
- INSERT INTO control_admin_invitations(email, invited_by_admin_id, replace_inviter, expires_at)
- SELECT $1, locked_inviter.id, $3::boolean,
- NOW() + ($4::int * INTERVAL '1 hour')
- FROM locked_inviter
- WHERE NOT EXISTS (
- SELECT 1 FROM control_admin_users WHERE lower(email) = lower($1)
- )
- AND NOT EXISTS (
- SELECT 1 FROM control_admin_invitations
- WHERE lower(email) = lower($1)
- AND status IN ('pending', 'opened')
+ FOR UPDATE`,
+ [invitedByAdminId]
+ )
+ if ((inviter.rowCount ?? 0) === 0) return { error: 'inviter_not_active' as const }
+
+ const result = await db.query(
+ `INSERT INTO control_admin_invitations(email, invited_by_admin_id, replace_inviter, expires_at)
+ SELECT $1, $2::uuid, $3::boolean,
+ NOW() + ($4::int * INTERVAL '1 hour')
+ WHERE NOT EXISTS (
+ SELECT 1 FROM control_admin_users WHERE lower(email) = lower($1)
)
- RETURNING ${INVITATION_COLUMNS}`,
- [normalizedEmail, invitedByAdminId, replaceInviter, INVITATION_TTL_HOURS]
- )
+ AND NOT EXISTS (
+ SELECT 1 FROM control_admin_invitations
+ WHERE lower(email) = lower($1)
+ AND status IN ('pending', 'opened')
+ )
+ RETURNING ${INVITATION_COLUMNS}`,
+ [normalizedEmail, invitedByAdminId, replaceInviter, INVITATION_TTL_HOURS]
+ )
+ if ((result.rowCount ?? 0) === 0) return { error: 'duplicate_email' as const }
+
+ const invitation = mapInvitationRow(result.rows[0] as never)
+ if (!options.desktopAccess) return { invitation }
+
+ const desktopInvitation = await insertInvitationForTeams(db, {
+ inviteeName: normalizedEmail,
+ email: normalizedEmail,
+ teamAssignments: options.desktopAccess.teamAssignments,
+ fallbackRole: 'member',
+ purpose: 'admin_desktop_access',
+ status: 'pending',
+ })
+ return {
+ invitation,
+ desktopInvitation: invitationForTeamsResponse(
+ desktopInvitation.invitation,
+ desktopInvitation.teams
+ ),
+ }
+ })
} catch (error) {
if (
error &&
@@ -919,27 +968,30 @@ export async function createControlAdminInvitation(
throw error
}
- if ((result.rowCount ?? 0) === 0) {
- const inviter = await pool.query(`SELECT status FROM control_admin_users WHERE id = $1::uuid`, [
- invitedByAdminId,
- ])
- const status = (inviter.rows[0] as { status?: string } | undefined)?.status
- if (status !== 'active') return { error: 'inviter_not_active' }
- return { error: 'duplicate_email' }
- }
- return mapInvitationRow(result.rows[0] as never)
+ if ('error' in created) return created
+ if ('desktopInvitation' in created) return created
+ return created.invitation
}
export async function revokeControlAdminInvitation(invitationId: string): Promise<void> {
- // One statement: the admin invitation and the silent desktop invitation the
- // POST route paired with it (same email, purpose admin_desktop_access) are
- // revoked together, so a caller never strands a desktop invitation that would
- // still grant team membership on its own.
- await pool.query(
+ await revokeControlAdminInvitations(pool, { invitationId })
+}
+
+async function revokeControlAdminInvitations(
+ db: DbClient,
+ selector: { invitationId: string } | { invitedByAdminId: string }
+): Promise<void> {
+ // The admin invitation and its paired silent Desktop invitation share the
+ // email and are revoked in one statement, so no paired Desktop access remains.
+ const predicate =
+ 'invitedByAdminId' in selector ? 'invited_by_admin_id = $1::uuid' : 'id = $1::uuid'
+ const id = 'invitedByAdminId' in selector ? selector.invitedByAdminId : selector.invitationId
+
+ await db.query(
`WITH revoked AS (
UPDATE control_admin_invitations
SET status = 'revoked'
- WHERE id = $1
+ WHERE ${predicate}
AND status IN ('pending', 'opened')
RETURNING email
)
@@ -948,7 +1000,7 @@ export async function revokeControlAdminInvitation(invitationId: string): Promis
WHERE purpose = 'admin_desktop_access'
AND status = 'pending'
AND lower(email) IN (SELECT lower(email) FROM revoked)`,
- [invitationId]
+ [id]
)
}
@@ -1022,13 +1074,19 @@ export async function completeControlAdminInvitation(input: {
const invitation = await getPendingControlAdminInvitation(db, input.invitationId, email)
if (!invitation) return { error: 'not_found' as const }
- // A replace-inviter acceptance locks the inviter before its invitation, so
- // two acceptances from one inviter queue here instead of deadlocking when
- // step (4) revokes the other's invitation.
- if (invitation.replaceInviter && invitation.invitedByAdminId) {
- await db.query(`SELECT 1 FROM control_admin_users WHERE id = $1 FOR UPDATE`, [
- invitation.invitedByAdminId,
- ])
+ // Retirement locks the inviter before revoking their pending invitations.
+ // Taking that same lock before the invitation serializes redemption against
+ // retirement and keeps the lock order consistent for replacement handovers.
+ if (invitation.invitedByAdminId) {
+ const inviterResult = await db.query(
+ `SELECT status FROM control_admin_users WHERE id = $1::uuid FOR UPDATE`,
+ [invitation.invitedByAdminId]
+ )
+ const inviterStatus = (inviterResult.rows[0] as { status?: string } | undefined)?.status
+ if (inviterStatus !== 'active') {
+ await revokeControlAdminInvitations(db, { invitationId: invitation.id })
+ return { error: 'not_found' as const }
+ }
}
// Lock and re-check before creating anything: getPendingControlAdminInvitation
@@ -1336,25 +1394,8 @@ async function replaceInviterInTransaction(
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]
- )
+ // retireControlAdminInTransaction revokes the inviter's other outstanding
+ // Control Admin invitations and their paired Desktop invitations atomically.
return null
}
diff --git a/control-api/test/routes.adminControlAdmins.test.ts b/control-api/test/routes.adminControlAdmins.test.ts
index 696265d9d..b1c82a876 100644
--- a/control-api/test/routes.adminControlAdmins.test.ts
+++ b/control-api/test/routes.adminControlAdmins.test.ts
@@ -62,7 +62,6 @@ vi.mock(
vi.mock('../src/middleware/controlUIAuth.js', () => uiAuth)
const directorySvc = vi.hoisted(() => ({
- createSilentInvitationForTeams: vi.fn(),
revokePendingInvitation: vi.fn(),
}))
vi.mock('../src/services/directory/index.js', async importOriginal => ({
@@ -280,11 +279,13 @@ describe('routes/adminControlAdmins', () => {
})
it('stores replaceInviter and echoes the stored flag on the 201 body', async () => {
- adminSvc.createControlAdminInvitation.mockResolvedValue(storedInvitation(true))
- directorySvc.createSilentInvitationForTeams.mockResolvedValue({
- id: 'desktop-invitation-id',
- team_id: null,
- teams: [],
+ adminSvc.createControlAdminInvitation.mockResolvedValue({
+ invitation: storedInvitation(true),
+ desktopInvitation: {
+ id: 'desktop-invitation-id',
+ team_id: null,
+ teams: [],
+ },
})
controlAdminInvitationRegistrationSvc.registerAndSendControlAdminInvitation.mockResolvedValue(
undefined
@@ -298,7 +299,7 @@ describe('routes/adminControlAdmins', () => {
expect(adminSvc.createControlAdminInvitation).toHaveBeenCalledWith(
'current-admin-id',
- { replaceInviter: true }
+ { replaceInviter: true, desktopAccess: { teamAssignments: [] } }
)
expect(res.body).toEqual({
invitation: {
@@ -312,6 +313,25 @@ describe('routes/adminControlAdmins', () => {
})
})
+ it('does not send a Desktop invitation when retirement wins the atomic creation lock', async () => {
+ adminSvc.createControlAdminInvitation.mockResolvedValue({ error: 'inviter_not_active' })
+
+ const res = await request(createTestApp())
+ .post('/admin/control-admin-invitations')
+ .send({ email: '[email protected]', createDesktopAccess: true })
+ .expect(409)
+
+ expect(res.body).toEqual({ error: 'inviter_not_active' })
+ expect(adminSvc.createControlAdminInvitation).toHaveBeenCalledWith(
+ 'current-admin-id',
+ { replaceInviter: false, desktopAccess: { teamAssignments: [] } }
+ )
+ expect(
+ controlAdminInvitationRegistrationSvc.registerAndSendControlAdminInvitation
+ ).not.toHaveBeenCalled()
+ })
+
it('defaults replaceInviter to false when the body omits it', async () => {
adminSvc.createControlAdminInvitation.mockResolvedValue(storedInvitation(false))
controlAdminInvitationRegistrationSvc.registerAndSendControlAdminInvitation.mockResolvedValue(
diff --git a/control-api/test/services.adminAuthDelete.test.ts b/control-api/test/services.adminAuthDelete.test.ts
index ff7b5e89e..70d026165 100644
--- a/control-api/test/services.adminAuthDelete.test.ts
+++ b/control-api/test/services.adminAuthDelete.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const state = vi.hoisted(() => ({
targetStatus: 'active' as 'active' | 'disabled',
queries: [] as string[],
+ calls: [] as Array<{ text: string; values?: unknown[] }>,
}))
const linkService = vi.hoisted(() => ({
@@ -41,8 +42,10 @@ vi.mock('../src/services/tracing/environment.js', () => ({
canonicalTracingEnvironment: vi.fn(() => 'test'),
}))
-function queryResult(text: string) {
+function queryResult(text: string, values?: unknown[]) {
state.queries.push(text)
+ state.calls.push({ text, values })
+ if (text.includes('WITH revoked AS')) return { rows: [], rowCount: 0 }
if (text.includes('FOR UPDATE') && text.includes('status')) {
return {
rows:
@@ -90,9 +93,10 @@ describe('deleteControlAdmin lifecycle transition', () => {
beforeEach(() => {
state.targetStatus = 'active'
state.queries = []
+ state.calls = []
db.withTransaction.mockImplementation(
async (callback: (tx: { query: typeof queryResult }) => unknown) =>
- callback({ query: async (text: string) => queryResult(text) })
+ callback({ query: async (text: string, values?: unknown[]) => queryResult(text, values) })
)
linkService.retireParentInTransaction.mockReset().mockResolvedValue(true)
eventService.appendInTransaction.mockReset().mockResolvedValue(undefined)
@@ -119,7 +123,7 @@ describe('deleteControlAdmin lifecycle transition', () => {
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) }
+ const tx = { query: async (text: string, values?: unknown[]) => queryResult(text, values) }
await expect(
retireControlAdminInTransaction(tx, {
@@ -138,4 +142,23 @@ describe('deleteControlAdmin lifecycle transition', () => {
})
expect(eventService.appendInTransaction).toHaveBeenCalledOnce()
})
+
+ it('revokes the retiring admin invitations and paired desktop links in the same transaction', async () => {
+ const { retireControlAdminInTransaction } = await import('../src/services/adminAuthService.js')
+ const tx = { query: async (text: string, values?: unknown[]) => queryResult(text, values) }
+
+ await expect(
+ retireControlAdminInTransaction(tx, {
+ actorAdminId: 'actor-admin',
+ adminId: 'target-admin',
+ reason: 'control_admin_retired',
+ })
+ ).resolves.toEqual({ deleted: true })
+
+ const revocation = state.calls.find(call => call.text.includes('WITH revoked AS'))
+ expect(revocation?.text).toContain('invited_by_admin_id = $1::uuid')
+ expect(revocation?.text).toContain("status IN ('pending', 'opened')")
+ expect(revocation?.text).toContain("purpose = 'admin_desktop_access'")
+ expect(revocation?.values).toEqual(['target-admin'])
+ })
})
diff --git a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
index f455d2c80..101904d76 100644
--- a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
+++ b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
@@ -10,10 +10,12 @@ import { authorizeRpcHostAccess } from '../src/services/access/rpcHostAccessAuth
import {
completeControlAdminInvitation,
createControlAdminInvitation,
+ deleteControlAdmin,
findAdminByLogin,
getPendingControlAdminInvitation,
listControlAdmins,
markControlAdminInvitationOpened,
+ retireControlAdminInTransaction,
revokeControlAdminInvitation,
} from '../src/services/adminAuthService.js'
import { getCurrentTeam } from '../src/services/directory/index.js'
@@ -130,6 +132,24 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
return invitation.id
}
+ async function createControlAdminInvitationWithDesktopAccess(
+ email: string,
+ inviterId: string
+ ): Promise<{ invitation: { id: string; email: string }; desktopInvitationId: string }> {
+ const created = await createControlAdminInvitation(email, inviterId, {
+ desktopAccess: { teamAssignments: [] },
+ })
+ expect(created).toHaveProperty('invitation')
+ expect(created).toHaveProperty('desktopInvitation')
+ if (!('invitation' in created) || !('desktopInvitation' in created)) {
+ throw new Error('paired Control Admin invitation was not created atomically')
+ }
+ return {
+ invitation: created.invitation,
+ desktopInvitationId: created.desktopInvitation.id,
+ }
+ }
+
async function teamRole(teamId: string, userId: string): Promise<string | undefined> {
const result = await testPool.query(
`SELECT role FROM team_members WHERE team_id = $1::uuid AND user_id = $2::uuid AND status = 'active'`,
@@ -785,7 +805,156 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
expect(await adminInvitationStatus(stray.id)).toBe('pending')
})
- it('still completes when the inviter is already disabled or gone', async () => {
+ it('revokes pending and opened invitations with their paired Desktop links on retirement', async () => {
+ const actor = await seedAdmin('retirement-actor')
+ const retiring = await seedAdmin('retiring-inviter')
+ const unrelated = await seedAdmin('unrelated-inviter')
+
+ const pendingEmail = uniqueEmail('retirement-pending')
+ const pendingPair = await createControlAdminInvitationWithDesktopAccess(
+ pendingEmail,
+ retiring.id
+ )
+ const pending = pendingPair.invitation
+
+ const openedEmail = uniqueEmail('retirement-opened')
+ const openedPair = await createControlAdminInvitationWithDesktopAccess(openedEmail, retiring.id)
+ const opened = openedPair.invitation
+ await markControlAdminInvitationOpened(opened.id)
+
+ const unrelatedEmail = uniqueEmail('unrelated-pending')
+ const unrelatedPair = await createControlAdminInvitationWithDesktopAccess(
+ unrelatedEmail,
+ unrelated.id
+ )
+ const unrelatedInvitation = unrelatedPair.invitation
+ const memberInvitation = await createSilentInvitationForTeams({
+ inviteeName: 'Preserved member invitation',
+ email: pendingEmail,
+ teamAssignments: [],
+ fallbackRole: 'member',
+ purpose: 'member_invitation',
+ })
+
+ await expect(deleteControlAdmin(actor.id, retiring.id)).resolves.toEqual({ deleted: true })
+
+ expect(await adminStatus(retiring.id)).toBe('disabled')
+ expect(await adminInvitationStatus(pending.id)).toBe('revoked')
+ expect(await adminInvitationStatus(opened.id)).toBe('revoked')
+ expect(await desktopInvitationStatus(pendingPair.desktopInvitationId)).toBe('revoked')
+ expect(await desktopInvitationStatus(openedPair.desktopInvitationId)).toBe('revoked')
+ expect(await adminInvitationStatus(unrelatedInvitation.id)).toBe('pending')
+ expect(await desktopInvitationStatus(unrelatedPair.desktopInvitationId)).toBe('pending')
+ expect(await desktopInvitationStatus(memberInvitation.id)).toBe('pending')
+
+ for (const [email, invitationId] of [
+ [pendingEmail, pending.id],
+ [openedEmail, opened.id],
+ ] as const) {
+ await expect(
+ completeControlAdminInvitation({
+ email,
+ invitationId,
+ username: `retired-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-retired-inviter',
+ })
+ ).resolves.toEqual({ error: 'not_found' })
+ const admins = await testPool.query(
+ `SELECT 1 FROM control_admin_users WHERE lower(email) = lower($1)`,
+ [email]
+ )
+ expect(admins.rowCount).toBe(0)
+ }
+ })
+
+ it('revokes a legacy paired Desktop invitation when its Control Admin inviter retires', async () => {
+ const actor = await seedAdmin('legacy-retirement-actor')
+ const retiring = await seedAdmin('legacy-retiring-inviter')
+ const email = uniqueEmail('legacy-retirement')
+ const invitation = await createControlAdminInvitation(email, retiring.id)
+ if ('error' in invitation) throw new Error(invitation.error)
+ const desktopInvitationId = await inviteDesktopAccess(email)
+
+ await expect(deleteControlAdmin(actor.id, retiring.id)).resolves.toEqual({ deleted: true })
+
+ expect(await adminInvitationStatus(invitation.id)).toBe('revoked')
+ expect(await desktopInvitationStatus(desktopInvitationId)).toBe('revoked')
+ await expect(
+ completeControlAdminInvitation({
+ email,
+ invitationId: invitation.id,
+ username: `legacy-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-retired-inviter',
+ })
+ ).resolves.toEqual({ error: 'not_found' })
+ })
+
+ it('serializes paired invitation creation with inviter retirement', async () => {
+ const actor = await seedAdmin('paired-race-actor')
+ const inviter = await seedAdmin('paired-race-ops')
+ const email = uniqueEmail('paired-race-client')
+ const blocker = await testPool.connect()
+ let creation: ReturnType<typeof createControlAdminInvitation> | undefined
+ let retirement: ReturnType<typeof deleteControlAdmin> | undefined
+ try {
+ await blocker.query('BEGIN')
+ await blocker.query('LOCK TABLE invitations IN ACCESS EXCLUSIVE MODE')
+
+ // Creation locks the inviter before inserting the Control Admin row, then
+ // blocks on the Desktop table while keeping that inviter lock open.
+ creation = createControlAdminInvitation(email, inviter.id, {
+ desktopAccess: { teamAssignments: [] },
+ })
+ creation.catch(() => undefined)
+ 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'
+ AND query ILIKE '%INSERT INTO invitations%'`,
+ [database]
+ )
+ if ((waiting.rowCount ?? 0) > 0) break
+ if (attempt >= 100)
+ throw new Error('paired invitation insert did not wait on the table lock')
+ await new Promise(resolve => setTimeout(resolve, 50))
+ }
+
+ retirement = deleteControlAdmin(actor.id, inviter.id)
+ retirement.catch(() => undefined)
+ 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'
+ AND query ILIKE '%control_admin_users%'
+ AND query ILIKE '%FOR UPDATE%'`,
+ [database]
+ )
+ if ((waiting.rowCount ?? 0) > 0) break
+ if (attempt >= 100) throw new Error('retirement did not wait on the inviter row lock')
+ await new Promise(resolve => setTimeout(resolve, 50))
+ }
+
+ await blocker.query('COMMIT')
+ const created = await creation
+ if ('error' in created || !('desktopInvitation' in created)) {
+ throw new Error('paired invitation creation failed before retirement')
+ }
+ await expect(retirement).resolves.toEqual({ deleted: true })
+
+ expect(await adminInvitationStatus(created.invitation.id)).toBe('revoked')
+ expect(await desktopInvitationStatus(created.desktopInvitation.id)).toBe('revoked')
+ } finally {
+ await blocker.query('ROLLBACK').catch(() => undefined)
+ blocker.release()
+ await Promise.allSettled([creation, retirement].filter(Boolean))
+ }
+ }, 20_000)
+
+ it('rejects stale invitations from disabled inviters but keeps legacy orphan invites redeemable', async () => {
const inviter = await seedAdmin('gone-ops')
const inviterDesktopId = await seedDesktopUser(inviter.email)
const disabledEmail = uniqueEmail('after-disable')
@@ -793,6 +962,7 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
replaceInviter: true,
})
if ('error' in afterDisable) throw new Error(afterDisable.error)
+ const disabledDesktopId = await inviteDesktopAccess(disabledEmail)
await testPool.query(`UPDATE control_admin_users SET status = 'disabled' WHERE id = $1::uuid`, [
inviter.id,
])
@@ -804,37 +974,49 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
)
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,
+ await expect(
+ completeControlAdminInvitation({
+ email: disabledEmail,
+ invitationId: afterDisable.id,
username: `late-${randomUUID().slice(0, 8)}`,
- passwordHash: 'real-pg-replace-client',
+ passwordHash: 'real-pg-retired-inviter',
})
- expect(completed).toMatchObject({ email, status: 'active' })
- expect(await adminInvitationStatus(invitationId)).toBe('accepted')
- }
+ ).resolves.toEqual({ error: 'not_found' })
+ expect(await adminInvitationStatus(afterDisable.id)).toBe('revoked')
+ expect(await desktopInvitationStatus(disabledDesktopId)).toBe('revoked')
+ const disabledAdmins = await testPool.query(
+ `SELECT 1 FROM control_admin_users WHERE lower(email) = lower($1)`,
+ [disabledEmail]
+ )
+ expect(disabledAdmins.rowCount).toBe(0)
+
+ const orphanCompleted = await completeControlAdminInvitation({
+ email: orphanEmail,
+ invitationId: orphanId,
+ username: `late-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ expect(orphanCompleted).toMatchObject({ email: orphanEmail, status: 'active' })
+ expect(await adminInvitationStatus(orphanId)).toBe('accepted')
expect(await desktopLifecycle(inviterDesktopId)).toBe('active')
})
- it('does not complete an invitation revoked while the acceptance is in flight', async () => {
+ it('serializes ordinary invitation redemption with inviter retirement', async () => {
+ const actor = await seedAdmin('retirement-race-actor')
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)
+ const desktopInvitationId = await inviteDesktopAccess(email)
// A revoke (DELETE route, MCC cancel, or another invitation's replace step 4)
- // holds the row while the client's acceptance starts, then commits.
+ // holds the inviter row while an ordinary invite redemption starts.
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]
- )
+ await blocker.query(`SELECT id FROM control_admin_users WHERE id = $1::uuid FOR UPDATE`, [
+ inviter.id,
+ ])
const completion = completeControlAdminInvitation({
email,
invitationId: invitation.id,
@@ -850,9 +1032,14 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
)
if ((waiting.rowCount ?? 0) > 0) break
if (attempt >= 100)
- throw new Error('the acceptance never waited on the revoking transaction')
+ throw new Error('the acceptance never waited on the inviter retirement lock')
await new Promise(resolve => setTimeout(resolve, 50))
}
+ await retireControlAdminInTransaction(blocker, {
+ actorAdminId: actor.id,
+ adminId: inviter.id,
+ reason: 'control_admin_retired',
+ })
await blocker.query('COMMIT')
await expect(completion).resolves.toEqual({ error: 'not_found' })
} finally {
@@ -861,6 +1048,7 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
}
expect(await adminInvitationStatus(invitation.id)).toBe('revoked')
+ expect(await desktopInvitationStatus(desktopInvitationId)).toBe('revoked')
const admins = await testPool.query(
`SELECT 1 FROM control_admin_users WHERE lower(email) = lower($1)`,
[email]
@@ -1133,18 +1321,17 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
expect(await adminStatus(inviter.id)).toBe('active')
})
- it('logs a skip when the inviter is already inactive and still completes', async () => {
+ it('rejects stale replace-inviter links from a previously retired inviter', async () => {
const inviter = await seedAdmin('skip-log-ops')
- const inviterDesktopId = await seedDesktopUser(inviter.email)
const email = uniqueEmail('skip-log-client')
const invitation = await createControlAdminInvitation(email, inviter.id, {
replaceInviter: true,
})
if ('error' in invitation) throw new Error(invitation.error)
+ const desktopInvitationId = await inviteDesktopAccess(email)
await testPool.query(`UPDATE control_admin_users SET status = 'disabled' WHERE id = $1::uuid`, [
inviter.id,
])
- const warn = vi.spyOn(rootLogger, 'warn').mockImplementation(() => undefined as never)
const completed = await completeControlAdminInvitation({
email,
@@ -1153,27 +1340,14 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
passwordHash: 'real-pg-replace-client',
})
- expect(completed).toMatchObject({ email, status: 'active' })
- expect(await desktopLifecycle(inviterDesktopId)).toBe('active')
- expect(await adminInvitationStatus(invitation.id)).toBe('accepted')
- expect(warn).toHaveBeenCalledWith(
- expect.objectContaining({
- event: 'control_admin_replace_inviter_skipped',
- invitationId: invitation.id,
- inviterAdminId: inviter.id,
- }),
- expect.any(String)
+ expect(completed).toEqual({ error: 'not_found' })
+ expect(await adminInvitationStatus(invitation.id)).toBe('revoked')
+ expect(await desktopInvitationStatus(desktopInvitationId)).toBe('revoked')
+ const admins = await testPool.query(
+ `SELECT 1 FROM control_admin_users WHERE lower(email) = lower($1)`,
+ [email]
)
- const payload = warn.mock.calls.find(
- call =>
- call[0] &&
- typeof call[0] === 'object' &&
- (call[0] as { event?: string }).event === 'control_admin_replace_inviter_skipped'
- )?.[0] as Record<string, unknown>
- expect(payload).not.toHaveProperty('email')
- expect(JSON.stringify(payload)).not.toContain(email)
- expect(JSON.stringify(payload)).not.toContain(inviter.email)
- warn.mockRestore()
+ expect(admins.rowCount).toBe(0)
})
it('revokes an opened invitation the inviter still has in progress', async () => {