Skip to content

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

TypeScript

fix(control-api): stop replace-inviter hand-overs from dropping team access

Jose Gabriel Ramirez Encinas110261afd976
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index f799c7af2..b57504bc4 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.649",
+ "version": "0.1.650",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.649",
+ "version": "0.1.650",
"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 be4b5b6ca..a8d045a66 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.649",
+ "version": "0.1.650",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index b33150a69..ff87c9c3b 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -3130,9 +3130,10 @@ async function applyMcpSecretRollbackPermitSchema(db: DbClient): Promise<void> {
}
// A control-admin invitation that, when accepted, hands the inviter's access to
-// the invitee and retires the inviter (completeControlAdminInvitation). Additive
-// and defaulted false, so N-1 pods that never read the column keep today's
-// behavior.
+// the invitee and retires the inviter (completeControlAdminInvitation). The
+// column is additive and defaults false. 0118 refuses acceptance of a true row
+// unless the current pod opts in, so an N-1 pod cannot turn the hand-over
+// into a plain invite.
async function applyControlAdminInvitationReplaceInviterSchema(db: DbClient): Promise<void> {
await db.query(`
ALTER TABLE control_admin_invitations
@@ -3140,6 +3141,38 @@ async function applyControlAdminInvitationReplaceInviterSchema(db: DbClient): Pr
`)
}
+// N-1 pods accept an invitation without reading replace_inviter. Without this
+// guard that acceptance commits, the departing admin stays active, and the
+// invitation cannot be replayed. Current pods set the transaction-local GUC
+// before the status update; any other updater fails and leaves the row pending.
+async function applyControlAdminReplaceInviterAcceptGuard(db: DbClient): Promise<void> {
+ await db.query(`
+ CREATE OR REPLACE FUNCTION control_admin_invitation_replace_inviter_accept_guard()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ IF NEW.replace_inviter
+ AND NEW.status = 'accepted'
+ AND OLD.status IS DISTINCT FROM 'accepted'
+ AND current_setting('evenfire.replace_inviter_handover', true) IS DISTINCT FROM 'on'
+ THEN
+ RAISE EXCEPTION 'replace_inviter_requires_current_control_api'
+ USING ERRCODE = '23514';
+ END IF;
+ RETURN NEW;
+ END;
+ $$;
+
+ DROP TRIGGER IF EXISTS control_admin_invitations_replace_inviter_accept_guard
+ ON control_admin_invitations;
+ CREATE TRIGGER control_admin_invitations_replace_inviter_accept_guard
+ BEFORE UPDATE ON control_admin_invitations
+ FOR EACH ROW
+ EXECUTE FUNCTION control_admin_invitation_replace_inviter_accept_guard();
+ `)
+}
+
// Exported (read-only) so the migration-order invariant test can assert the
// array is monotonic by version-string. Applied strictly in array order and
// tracked by full version-string in `schema_migrations`, so a non-monotonic
@@ -6223,6 +6256,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0117_control_admin_invitation_replace_inviter',
apply: applyControlAdminInvitationReplaceInviterSchema,
},
+ {
+ version: '0118_control_admin_replace_inviter_accept_guard',
+ apply: applyControlAdminReplaceInviterAcceptGuard,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/src/routes/admin/auth.ts b/control-api/src/routes/admin/auth.ts
index a02f7047f..07cd0cb7c 100644
--- a/control-api/src/routes/admin/auth.ts
+++ b/control-api/src/routes/admin/auth.ts
@@ -499,6 +499,18 @@ export function createAdminAuthRouter(): Router {
? await acceptInvitationById(validation.email, desktopAccess.id)
: null
if (acceptedDesktopAccess && 'error' in acceptedDesktopAccess) {
+ // The control-admin invitation is already committed. A failed desktop
+ // acceptance leaves that admin in place and, for a hand-over, the
+ // inviter already retired. Record the code without the invitee email.
+ rootLogger.error(
+ {
+ event: 'control_admin_desktop_acceptance_failed',
+ invitationId: validation.invitationUuid,
+ adminId: result.id,
+ errorCode: acceptedDesktopAccess.error,
+ },
+ 'desktop invitation acceptance failed after the control admin invitation committed'
+ )
res.status(409).json({ error: acceptedDesktopAccess.error })
return
}
diff --git a/control-api/src/services/adminAuthService.ts b/control-api/src/services/adminAuthService.ts
index caa2f0b18..bcd4a2fbc 100644
--- a/control-api/src/services/adminAuthService.ts
+++ b/control-api/src/services/adminAuthService.ts
@@ -34,6 +34,8 @@ export type ControlAdminListItem = {
status: 'active' | 'disabled' | 'pending_password'
passwordPending?: boolean
invitationId?: string
+ replaceInviter?: boolean
+ invitedByAdminId?: string | null
gfsOperatorLink?: {
desktopUserId: string
controlAdminId: string
@@ -744,7 +746,8 @@ export async function listControlAdmins(): Promise<{
ORDER BY a.created_at ASC`
),
pool.query(
- `SELECT id, email, expires_at, created_at, accepted_at
+ `SELECT id, email, expires_at, created_at, accepted_at,
+ invited_by_admin_id, replace_inviter
FROM control_admin_invitations
WHERE status = 'opened'
AND expires_at > NOW()
@@ -834,6 +837,8 @@ export async function listControlAdmins(): Promise<{
expires_at: Date
created_at: Date
accepted_at: Date | null
+ invited_by_admin_id: string | null
+ replace_inviter: boolean | null
}
return {
id: `invitation:${record.id}`,
@@ -843,6 +848,8 @@ export async function listControlAdmins(): Promise<{
status: 'pending_password' as const,
passwordPending: true,
invitationId: record.id,
+ replaceInviter: record.replace_inviter === true,
+ invitedByAdminId: record.invited_by_admin_id ?? null,
lastLoginAt: null,
createdAt: record.accepted_at
? record.accepted_at.toISOString()
@@ -858,7 +865,7 @@ export async function createControlAdminInvitation(
email: string,
invitedByAdminId: string,
options: { replaceInviter?: boolean } = {}
-): Promise<ControlAdminInvitationRecord | { error: 'duplicate_email' }> {
+): Promise<ControlAdminInvitationRecord | { error: 'duplicate_email' | 'inviter_not_active' }> {
const normalizedEmail = normalizeEmail(email)
const replaceInviter = options.replaceInviter === true
// Revoke expired active invitations first so the INSERT guard can treat any remaining
@@ -875,8 +882,16 @@ export async function createControlAdminInvitation(
let result
try {
result = await pool.query(
- `INSERT INTO control_admin_invitations(email, invited_by_admin_id, replace_inviter)
- SELECT $1, $2, $3::boolean
+ `WITH locked_inviter AS (
+ SELECT id
+ FROM control_admin_users
+ WHERE id = $2::uuid
+ AND status = 'active'
+ FOR UPDATE
+ )
+ INSERT INTO control_admin_invitations(email, invited_by_admin_id, replace_inviter)
+ SELECT $1, locked_inviter.id, $3::boolean
+ FROM locked_inviter
WHERE NOT EXISTS (
SELECT 1 FROM control_admin_users WHERE lower(email) = lower($1)
)
@@ -902,7 +917,14 @@ export async function createControlAdminInvitation(
throw error
}
- if ((result.rowCount ?? 0) === 0) return { error: 'duplicate_email' }
+ 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)
}
@@ -1040,6 +1062,12 @@ export async function completeControlAdminInvitation(input: {
)
const admin = mapAdminRow(inserted.rows[0] as never)
+ // 0118 rejects this update unless the current pod opts in. An N-1 pod has
+ // no such opt-in, so it cannot accept a hand-over as a plain invitation.
+ if (invitation.replaceInviter) {
+ await db.query(`SELECT set_config('evenfire.replace_inviter_handover', 'on', true)`)
+ }
+
await db.query(
`UPDATE control_admin_invitations
SET status = 'accepted',
@@ -1082,8 +1110,13 @@ const TEAM_ROLE_RANK = (column: string) =>
/**
* 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.
+ * transaction that created the invitee's control admin.
+ *
+ * An inviter that is missing or not active is left as it is. That is not an
+ * empty hand-over: deleteControlAdmin disables the control admin and can leave
+ * the desktop user, its team memberships, and its approval accounts active.
+ * Skipping avoids retiring that desktop identity again and does not transfer
+ * its roles. The skip is logged with the invitation id and the inviter id.
*/
async function replaceInviterInTransaction(
db: DbClient,
@@ -1099,50 +1132,103 @@ async function replaceInviterInTransaction(
const inviter = inviterResult.rows[0] as
| { id: string; email: string | null; status: 'active' | 'disabled' }
| undefined
- if (!inviter || inviter.status !== 'active') return null
-
- // The active operator link names the inviter's desktop user exactly; an admin
- // email change (completeControlAdminEmailChangeRequest) never updates
- // users.email. Invited admins have no link (links come only from
- // initial_setup), so the shared email is their only mapping.
- const linkedDesktop = await db.query(
- `SELECT u.id::text AS id
+ if (!inviter || inviter.status !== 'active') {
+ rootLogger.warn(
+ {
+ event: 'control_admin_replace_inviter_skipped',
+ invitationId: input.invitationId,
+ inviterAdminId: input.inviterAdminId,
+ inviterStatus: inviter?.status ?? 'missing',
+ },
+ 'replace-inviter hand-over skipped because the inviter is not active'
+ )
+ return null
+ }
+
+ // The most recent operator link names this admin's desktop user, revoked or
+ // not. An admin email change never updates users.email, and a revoked link
+ // must not fall through to that email. Email is only the mapping for an
+ // invited admin, who has no link history, and it must not select a user
+ // linked to a different admin.
+ const linkHistory = await db.query(
+ `SELECT u.id::text AS id, u.email, u.lifecycle_state
FROM gfs_desktop_operator_links link
JOIN users u ON u.id = link.user_id
WHERE link.control_admin_id = $1::uuid
- AND link.state = 'active'
- AND u.lifecycle_state = 'active'
+ ORDER BY link.generation DESC, link.created_at DESC
+ LIMIT 1
FOR UPDATE OF u`,
[inviter.id]
)
- const inviterDesktop =
- (linkedDesktop.rowCount ?? 0) > 0 || !inviter.email
- ? linkedDesktop
- : 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]
- )
- const inviterDesktopUserId = (inviterDesktop.rows[0] as { id: string } | undefined)?.id ?? null
+ const linked = linkHistory.rows[0] as
+ | { id: string; email: string | null; lifecycle_state: string }
+ | undefined
+ let inviterDesktop: { id: string; email: string | null } | undefined
+ if (linked?.lifecycle_state === 'active') {
+ inviterDesktop = linked
+ } else if (!linked && inviter.email) {
+ const emailMatch = await db.query(
+ `SELECT u.id::text AS id, u.email
+ FROM users u
+ WHERE lower(u.email) = lower($1)
+ AND u.lifecycle_state = 'active'
+ AND NOT EXISTS (
+ SELECT 1
+ FROM gfs_desktop_operator_links l
+ WHERE l.user_id = u.id
+ AND l.control_admin_id <> $2::uuid
+ )
+ ORDER BY u.id
+ LIMIT 1
+ FOR UPDATE OF u`,
+ [inviter.email, inviter.id]
+ )
+ inviterDesktop = emailMatch.rows[0] as { id: string; email: string | null } | undefined
+ }
+ const inviterDesktopUserId = inviterDesktop?.id ?? null
+ const inviterDesktopEmail = inviterDesktop?.email ?? null
// completeControlAdminInvitation always inserts the normalized invitation email.
const newAdminEmail = input.newAdmin.email ?? ''
if (inviterDesktopUserId) {
- // Retiring the inviter must not drop team access nobody receives: without a
- // desktop user or pending desktop invitation for the invitee, refuse.
+ // The invitee is the inviter's own desktop user. Copying roles onto that
+ // row and then retiring it drops the teams on the only person who held them.
+ if (
+ inviterDesktopEmail &&
+ newAdminEmail &&
+ inviterDesktopEmail.toLowerCase() === newAdminEmail.toLowerCase()
+ ) {
+ return 'replace_inviter_receiver_missing'
+ }
+
+ // Retiring the inviter must not drop team access nobody can receive. A
+ // non-active user holding the invitee email cannot accept the desktop
+ // invitation, and the inviter's own desktop user is not a receiver.
const receiver = await db.query(
`SELECT
EXISTS(SELECT 1 FROM team_members WHERE user_id = $1::uuid AND status = 'active') AS has_roles,
- EXISTS(SELECT 1 FROM users WHERE lower(email) = lower($2) AND lifecycle_state = 'active')
- OR EXISTS(SELECT 1 FROM invitations
- WHERE lower(email) = lower($2)
- AND purpose = 'admin_desktop_access'
- AND status = 'pending'
- AND expires_at > NOW()) AS has_receiver`,
+ (
+ NOT EXISTS (
+ SELECT 1 FROM users
+ WHERE lower(email) = lower($2)
+ AND lifecycle_state <> 'active'
+ )
+ AND (
+ EXISTS (
+ SELECT 1 FROM users
+ WHERE lower(email) = lower($2)
+ AND lifecycle_state = 'active'
+ AND id <> $1::uuid
+ )
+ OR EXISTS (
+ SELECT 1 FROM invitations
+ WHERE lower(email) = lower($2)
+ AND purpose = 'admin_desktop_access'
+ AND status = 'pending'
+ AND expires_at > NOW()
+ )
+ )
+ ) AS has_receiver`,
[inviterDesktopUserId, newAdminEmail]
)
const { has_roles: hasRoles, has_receiver: hasReceiver } = receiver.rows[0] as {
@@ -1159,6 +1245,7 @@ async function replaceInviterInTransaction(
JOIN users target
ON lower(target.email) = lower($2)
AND target.lifecycle_state = 'active'
+ AND target.id <> $1::uuid
WHERE source.user_id = $1::uuid
AND source.status = 'active'
ON CONFLICT (team_id, user_id) DO UPDATE
@@ -1173,8 +1260,9 @@ async function replaceInviterInTransaction(
[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.
+ // (POST /admin/auth/control-admin-invitations/complete) and upserts
+ // role = EXCLUDED.role, so the copied role has to already be on the
+ // invitation or 1a would be downgraded.
// Each copied role is the higher of the inviter's and any role the invitee's
// desktop user already holds, which acceptance would otherwise overwrite.
// Materialize a legacy single-team invitation first so adding rows cannot
@@ -1222,27 +1310,9 @@ async function replaceInviterInTransaction(
[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]
- )
+ // (2) Retire, never hard-delete, the inviter's desktop identity.
+ // retireDesktopUser disables approval medium accounts on the tombstone
+ // path as well as the hard-delete path.
await retireDesktopUserInTransaction(db, {
actor: { kind: 'control_admin', controlAdminId: input.newAdmin.id },
userId: inviterDesktopUserId,
diff --git a/control-api/src/services/directory/users.ts b/control-api/src/services/directory/users.ts
index 244616314..860bb0339 100644
--- a/control-api/src/services/directory/users.ts
+++ b/control-api/src/services/directory/users.ts
@@ -335,6 +335,29 @@ export async function updateAdminUserContext(
})
}
+/**
+ * Approval canApprove reads an enabled medium account and ignores lifecycle
+ * state, so both the hard-delete and the tombstone paths have to disable it.
+ */
+async function disableWorkflowApprovalMedium(db: DbClient, userId: string): Promise<void> {
+ 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`,
+ [userId]
+ )
+ 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`,
+ [userId]
+ )
+}
+
/**
* Retire a Desktop user under one caller-owned transaction.
*
@@ -481,22 +504,7 @@ export async function retireDesktopUser(
(history.rows[0] as { has_link_history?: unknown } | undefined)?.has_link_history === true
if (!hasLinkHistory && options.retainWithoutLinkHistory !== true) {
- 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`,
- [targetUserId]
- )
- 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`,
- [targetUserId]
- )
+ await disableWorkflowApprovalMedium(db, targetUserId)
const deleted = await db.query(
`DELETE FROM users
WHERE id = $1::uuid
@@ -561,6 +569,8 @@ export async function retireDesktopUser(
)
}
+ await disableWorkflowApprovalMedium(db, targetUserId)
+
const transitioned = await db.query(
`UPDATE users
SET lifecycle_state = 'retired',
diff --git a/control-api/test/db.controlAdminInvitationReplaceInviterMigration.test.ts b/control-api/test/db.controlAdminInvitationReplaceInviterMigration.test.ts
index d3ecd6ac7..07a50f732 100644
--- a/control-api/test/db.controlAdminInvitationReplaceInviterMigration.test.ts
+++ b/control-api/test/db.controlAdminInvitationReplaceInviterMigration.test.ts
@@ -22,4 +22,21 @@ describe('0117_control_admin_invitation_replace_inviter migration', () => {
expect(sql).toContain('ALTER TABLE control_admin_invitations')
expect(sql).toContain('ADD COLUMN IF NOT EXISTS replace_inviter BOOLEAN NOT NULL DEFAULT false')
})
+
+ it('refuses an N-1 acceptance of a replace_inviter invitation unless the current pod opts in', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const versions = CONTROL_API_MIGRATIONS.map(migration => migration.version)
+ const column = versions.indexOf('0117_control_admin_invitation_replace_inviter')
+ const guard = versions.indexOf('0118_control_admin_replace_inviter_accept_guard')
+ expect(guard).toBeGreaterThan(column)
+
+ const migration = CONTROL_API_MIGRATIONS[guard]
+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })
+ await migration!.apply({ query })
+ const sql = String(query.mock.calls[0]?.[0])
+ expect(sql).toContain('control_admin_invitation_replace_inviter_accept_guard')
+ expect(sql).toContain('replace_inviter_requires_current_control_api')
+ expect(sql).toContain("current_setting('evenfire.replace_inviter_handover', true)")
+ expect(sql).toContain('BEFORE UPDATE ON control_admin_invitations')
+ })
})
diff --git a/control-api/test/routes.adminAuth.test.ts b/control-api/test/routes.adminAuth.test.ts
index fa5a30bf5..7ccaa30e4 100644
--- a/control-api/test/routes.adminAuth.test.ts
+++ b/control-api/test/routes.adminAuth.test.ts
@@ -2,10 +2,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
import { config } from '../src/config.js'
+import { rootLogger } from '../src/observability/logger.js'
import { createAdminAuthRouter } from '../src/routes/admin/auth.js'
const directorySvc = vi.hoisted(() => ({
provisionAdminDesktopWorkspace: vi.fn(),
+ acceptInvitationById: vi.fn(),
+ getPendingMemberInvitationForEmail: vi.fn(),
+ setInvitationPasswordForUser: vi.fn(),
}))
// auth.ts imports provisionAdminDesktopWorkspace from the directory barrel; mock the barrel here.
vi.mock('../src/services/directory/index.js', () => directorySvc)
@@ -507,4 +511,54 @@ describe('routes/adminAuth', () => {
passwordHash: expect.stringMatching(/^\$2/),
})
})
+
+ it('logs a structured error when desktop acceptance fails after the admin invitation commits', async () => {
+ const invitationId = '11111111-1111-4111-8111-111111111111'
+ const adminId = '22222222-2222-4222-8222-222222222222'
+ controlAdminInvitationRegistrationSvc.validateControlAdminInvitationToken.mockResolvedValue({
+ email: '[email protected]',
+ invitationUuid: invitationId,
+ })
+ adminSvc.completeControlAdminInvitation.mockResolvedValue({
+ id: adminId,
+ username: 'new-admin',
+ email: '[email protected]',
+ passwordHash: 'hash',
+ sessionVersion: 1,
+ role: 'admin',
+ status: 'active',
+ failedAttempts: 0,
+ lockedUntil: null,
+ })
+ directorySvc.getPendingMemberInvitationForEmail.mockResolvedValue({ id: 'desk-invite' })
+ directorySvc.acceptInvitationById.mockResolvedValue({ error: 'user_retired' })
+ const errorLog = vi.spyOn(rootLogger, 'error').mockImplementation(() => undefined as never)
+
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminAuthRouter())
+
+ const res = await request(app).post('/admin/auth/control-admin-invitations/complete').send({
+ token: 'signed.jwt.value',
+ email: '[email protected]',
+ username: 'new-admin',
+ password: 'example-password',
+ })
+
+ expect(res.status).toBe(409)
+ expect(res.body).toEqual({ error: 'user_retired' })
+ expect(errorLog).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'control_admin_desktop_acceptance_failed',
+ invitationId,
+ adminId,
+ errorCode: 'user_retired',
+ }),
+ expect.any(String)
+ )
+ const payload = errorLog.mock.calls[0]?.[0] as Record<string, unknown>
+ expect(payload).not.toHaveProperty('email')
+ expect(JSON.stringify(payload)).not.toContain('[email protected]')
+ errorLog.mockRestore()
+ })
})
diff --git a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
index 25a3e7e38..c332562ca 100644
--- a/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
+++ b/control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts
@@ -4,6 +4,7 @@ import { Pool } from 'pg'
import { config } from '../src/config.js'
import { initDb, pool } from '../src/db.js'
import type { K8sGateway } from '../src/k8s.js'
+import { rootLogger } from '../src/observability/logger.js'
import type { RpcAccessClaims } from '../src/profileTypes.js'
import { authorizeRpcHostAccess } from '../src/services/access/rpcHostAccessAuthorizer.js'
import {
@@ -12,6 +13,7 @@ import {
findAdminByLogin,
getPendingControlAdminInvitation,
listControlAdmins,
+ markControlAdminInvitationOpened,
revokeControlAdminInvitation,
} from '../src/services/adminAuthService.js'
import { getCurrentTeam } from '../src/services/directory/index.js'
@@ -100,6 +102,21 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
)
}
+ async function revokeOperatorLink(adminId: string): Promise<void> {
+ await testPool.query(
+ `UPDATE gfs_desktop_operator_links
+ SET state = 'revoked',
+ revoked_at = NOW(),
+ revoked_by_type = 'control_admin',
+ revoked_by_id = $1::uuid,
+ revocation_reason = 'test revoke',
+ row_version = row_version + 1
+ WHERE control_admin_id = $1::uuid
+ AND state = 'active'`,
+ [adminId]
+ )
+ }
+
async function inviteDesktopAccess(email: string): Promise<string> {
const invitation = await createSilentInvitationForTeams({
inviteeName: email,
@@ -795,4 +812,465 @@ describeRealPostgres('control admin replace-inviter invitations on real PostgreS
)
expect(admins.rowCount).toBe(0)
}, 15_000)
+
+ it('refuses a hand-over when a retired desktop user holds the invitee email', async () => {
+ const inviter = await seedAdmin('retired-receiver-ops')
+ const inviterDesktopId = await seedDesktopUser(inviter.email)
+ const team = await seedTeam('Retired receiver')
+ await addTeamMember(team, inviterDesktopId, 'admin')
+ const clientEmail = uniqueEmail('retired-receiver')
+ const retiredReceiverId = await seedDesktopUser(clientEmail)
+ const retirer = await seedAdmin('retired-receiver-actor')
+ await retireDesktopUser(
+ { kind: 'control_admin', controlAdminId: retirer.id },
+ retiredReceiverId,
+ 'invitee already retired',
+ `retired-receiver-${retiredReceiverId}`,
+ null,
+ { retainWithoutLinkHistory: true }
+ )
+ const handover = await createControlAdminInvitation(clientEmail, inviter.id, {
+ replaceInviter: true,
+ })
+ if ('error' in handover) throw new Error(handover.error)
+ const desktopInvitationId = await inviteDesktopAccess(clientEmail)
+
+ await expect(
+ completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: handover.id,
+ username: `retired-receiver-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ ).resolves.toEqual({ error: 'replace_inviter_receiver_missing' })
+
+ expect(await adminInvitationStatus(handover.id)).toBe('pending')
+ expect(await desktopInvitationStatus(desktopInvitationId)).toBe('pending')
+ expect(await adminStatus(inviter.id)).toBe('active')
+ expect(await desktopLifecycle(inviterDesktopId)).toBe('active')
+ expect(await desktopLifecycle(retiredReceiverId)).toBe('retired')
+ expect(await teamRole(team, inviterDesktopId)).toBe('admin')
+ })
+
+ it('refuses a hand-over onto the inviter own desktop email', async () => {
+ const inviter = await seedAdmin('self-ops')
+ const desktopEmail = inviter.email
+ const inviterDesktopId = await seedDesktopUser(desktopEmail)
+ await seedOperatorLink(inviterDesktopId, inviter.id)
+ const team = await seedTeam('Self')
+ await addTeamMember(team, inviterDesktopId, 'admin')
+ await testPool.query(`UPDATE control_admin_users SET email = $2 WHERE id = $1::uuid`, [
+ inviter.id,
+ uniqueEmail('self-moved'),
+ ])
+ const handover = await createControlAdminInvitation(desktopEmail, inviter.id, {
+ replaceInviter: true,
+ })
+ if ('error' in handover) throw new Error(handover.error)
+ await inviteDesktopAccess(desktopEmail)
+
+ await expect(
+ completeControlAdminInvitation({
+ email: desktopEmail,
+ invitationId: handover.id,
+ username: `self-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ ).resolves.toEqual({ error: 'replace_inviter_receiver_missing' })
+
+ expect(await adminInvitationStatus(handover.id)).toBe('pending')
+ expect(await adminStatus(inviter.id)).toBe('active')
+ expect(await desktopLifecycle(inviterDesktopId)).toBe('active')
+ expect(await teamRole(team, inviterDesktopId)).toBe('admin')
+ const link = await testPool.query(
+ `SELECT state FROM gfs_desktop_operator_links WHERE control_admin_id = $1::uuid`,
+ [inviter.id]
+ )
+ expect(link.rows).toEqual([{ state: 'active' }])
+ })
+
+ it('retires the desktop user named by a revoked operator link', async () => {
+ const inviter = await seedAdmin('revoked-link-ops')
+ const linkedDesktopId = await seedDesktopUser(inviter.email)
+ await seedOperatorLink(linkedDesktopId, inviter.id)
+ const team = await seedTeam('Revoked link')
+ await addTeamMember(team, linkedDesktopId, 'admin')
+ await revokeOperatorLink(inviter.id)
+ await testPool.query(`UPDATE control_admin_users SET email = $2 WHERE id = $1::uuid`, [
+ inviter.id,
+ uniqueEmail('revoked-link-moved'),
+ ])
+ const clientEmail = uniqueEmail('revoked-link-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 completed = await completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: handover.id,
+ username: `revoked-link-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ if ('error' in completed) throw new Error(completed.error)
+ const accepted = await acceptInvitationById(clientEmail, clientDesktopInvitationId)
+ if ('error' in accepted) throw new Error(String(accepted.error))
+
+ expect(await adminStatus(inviter.id)).toBe('disabled')
+ expect(await desktopLifecycle(linkedDesktopId)).toBe('retired')
+ expect(await teamRole(team, accepted.data.userId)).toBe('admin')
+ })
+
+ it('does not retire a bystander when the operator link is revoked and the admin email changed', async () => {
+ const inviter = await seedAdmin('revoked-bystander-ops')
+ const linkedDesktopId = await seedDesktopUser(inviter.email)
+ await seedOperatorLink(linkedDesktopId, inviter.id)
+ const team = await seedTeam('Revoked bystander inviter')
+ await addTeamMember(team, linkedDesktopId, 'admin')
+ await revokeOperatorLink(inviter.id)
+ const movedEmail = uniqueEmail('revoked-bystander-moved')
+ await testPool.query(`UPDATE control_admin_users SET email = $2 WHERE id = $1::uuid`, [
+ inviter.id,
+ movedEmail,
+ ])
+ const bystanderId = await seedDesktopUser(movedEmail)
+ const bystanderTeam = await seedTeam('Revoked bystander')
+ await addTeamMember(bystanderTeam, bystanderId, 'member')
+ const clientEmail = uniqueEmail('revoked-bystander-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 completed = await completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: handover.id,
+ username: `revoked-bystander-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ if ('error' in completed) throw new Error(completed.error)
+ const accepted = await acceptInvitationById(clientEmail, clientDesktopInvitationId)
+ if ('error' in accepted) throw new Error(String(accepted.error))
+
+ expect(await desktopLifecycle(linkedDesktopId)).toBe('retired')
+ expect(await teamRole(team, accepted.data.userId)).toBe('admin')
+ expect(await desktopLifecycle(bystanderId)).toBe('active')
+ expect(await teamRole(bystanderTeam, bystanderId)).toBe('member')
+ expect(await teamRole(bystanderTeam, accepted.data.userId)).toBeUndefined()
+ })
+
+ it('does not retire another admin desktop user that only shares the inviter email', async () => {
+ const adminA = await seedAdmin('owner-ops')
+ const sharedEmail = adminA.email
+ const desktopX = await seedDesktopUser(sharedEmail)
+ await seedOperatorLink(desktopX, adminA.id)
+ const team = await seedTeam('Owner')
+ await addTeamMember(team, desktopX, 'admin')
+ await testPool.query(`UPDATE control_admin_users SET email = $2 WHERE id = $1::uuid`, [
+ adminA.id,
+ uniqueEmail('owner-moved'),
+ ])
+ const adminB = await seedAdmin('borrowed-ops')
+ await testPool.query(`UPDATE control_admin_users SET email = $2 WHERE id = $1::uuid`, [
+ adminB.id,
+ sharedEmail,
+ ])
+ const clientEmail = uniqueEmail('borrowed-client')
+ const handover = await createControlAdminInvitation(clientEmail, adminB.id, {
+ replaceInviter: true,
+ })
+ if ('error' in handover) throw new Error(handover.error)
+ const clientDesktopInvitationId = await inviteDesktopAccess(clientEmail)
+
+ const completed = await completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: handover.id,
+ username: `borrowed-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ if ('error' in completed) throw new Error(completed.error)
+ const accepted = await acceptInvitationById(clientEmail, clientDesktopInvitationId)
+ if ('error' in accepted) throw new Error(String(accepted.error))
+
+ expect(await adminStatus(adminB.id)).toBe('disabled')
+ expect(await adminStatus(adminA.id)).toBe('active')
+ expect(await desktopLifecycle(desktopX)).toBe('active')
+ expect(await teamRole(team, desktopX)).toBe('admin')
+ expect(await teamRole(team, accepted.data.userId)).toBeUndefined()
+ const link = await testPool.query(
+ `SELECT state FROM gfs_desktop_operator_links WHERE control_admin_id = $1::uuid`,
+ [adminA.id]
+ )
+ expect(link.rows).toEqual([{ state: 'active' }])
+ })
+
+ it('does not fall back to email when link history names a retired desktop user', async () => {
+ const inviter = await seedAdmin('history-retired-ops')
+ const linkedDesktopId = await seedDesktopUser(inviter.email)
+ await seedOperatorLink(linkedDesktopId, inviter.id)
+ const team = await seedTeam('History retired')
+ await addTeamMember(team, linkedDesktopId, 'admin')
+ await revokeOperatorLink(inviter.id)
+ const retirer = await seedAdmin('history-retired-actor')
+ await retireDesktopUser(
+ { kind: 'control_admin', controlAdminId: retirer.id },
+ linkedDesktopId,
+ 'linked user already retired',
+ `history-retired-${linkedDesktopId}`,
+ null
+ )
+ const movedEmail = uniqueEmail('history-retired-moved')
+ await testPool.query(`UPDATE control_admin_users SET email = $2 WHERE id = $1::uuid`, [
+ inviter.id,
+ movedEmail,
+ ])
+ const bystanderId = await seedDesktopUser(movedEmail)
+ const bystanderTeam = await seedTeam('History bystander')
+ await addTeamMember(bystanderTeam, bystanderId, 'member')
+ const clientEmail = uniqueEmail('history-retired-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 completed = await completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: handover.id,
+ username: `history-retired-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ if ('error' in completed) throw new Error(completed.error)
+ const accepted = await acceptInvitationById(clientEmail, clientDesktopInvitationId)
+ if ('error' in accepted) throw new Error(String(accepted.error))
+
+ expect(await adminStatus(inviter.id)).toBe('disabled')
+ expect(await desktopLifecycle(bystanderId)).toBe('active')
+ expect(await teamRole(bystanderTeam, accepted.data.userId)).toBeUndefined()
+ expect(await teamRole(team, accepted.data.userId)).toBeUndefined()
+ const retirement = await testPool.query(
+ `SELECT retirement_reason FROM users WHERE id = $1::uuid`,
+ [linkedDesktopId]
+ )
+ expect(retirement.rows).toEqual([{ retirement_reason: 'linked user already retired' }])
+ })
+
+ it('rejects a direct acceptance of a replaceInviter invitation that skips the hand-over', async () => {
+ const inviter = await seedAdmin('n1-ops')
+ const email = uniqueEmail('n1-client')
+ const invitation = await createControlAdminInvitation(email, inviter.id, {
+ replaceInviter: true,
+ })
+ if ('error' in invitation) throw new Error(invitation.error)
+
+ await expect(
+ testPool.query(
+ `UPDATE control_admin_invitations
+ SET status = 'accepted', accepted_at = NOW()
+ WHERE id = $1::uuid`,
+ [invitation.id]
+ )
+ ).rejects.toThrow(/replace_inviter_requires_current_control_api/)
+
+ expect(await adminInvitationStatus(invitation.id)).toBe('pending')
+ expect(await adminStatus(inviter.id)).toBe('active')
+ })
+
+ it('logs a skip when the inviter is already inactive and still completes', 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)
+ 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,
+ invitationId: invitation.id,
+ username: `skip-log-${randomUUID().slice(0, 8)}`,
+ 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)
+ )
+ 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()
+ })
+
+ it('revokes an opened invitation the inviter still has in progress', async () => {
+ const inviter = await seedAdmin('opened-revoke-ops')
+ const clientEmail = uniqueEmail('opened-revoke-client')
+ const handover = await createControlAdminInvitation(clientEmail, inviter.id, {
+ replaceInviter: true,
+ })
+ if ('error' in handover) throw new Error(handover.error)
+ await inviteDesktopAccess(clientEmail)
+ const openedEmail = uniqueEmail('opened-revoke-other')
+ const opened = await createControlAdminInvitation(openedEmail, inviter.id)
+ if ('error' in opened) throw new Error(opened.error)
+ const openedDesktopId = await inviteDesktopAccess(openedEmail)
+ await markControlAdminInvitationOpened(opened.id)
+ expect(await adminInvitationStatus(opened.id)).toBe('opened')
+
+ const completed = await completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: handover.id,
+ username: `opened-revoke-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ if ('error' in completed) throw new Error(completed.error)
+
+ expect(await adminInvitationStatus(opened.id)).toBe('revoked')
+ expect(await desktopInvitationStatus(openedDesktopId)).toBe('revoked')
+ })
+
+ it('completes a hand-over when the inviter has no team roles and no receiver', async () => {
+ const inviter = await seedAdmin('norole-ops')
+ const inviterDesktopId = await seedDesktopUser(inviter.email)
+ const clientEmail = uniqueEmail('norole-client')
+ 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: `norole-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+
+ expect(completed).toMatchObject({ email: clientEmail, status: 'active' })
+ expect(await adminStatus(inviter.id)).toBe('disabled')
+ expect(await desktopLifecycle(inviterDesktopId)).toBe('retired')
+ expect(await adminInvitationStatus(handover.id)).toBe('accepted')
+ })
+
+ it('does not treat an expired desktop invitation as a receiver', async () => {
+ const inviter = await seedAdmin('expired-receiver-ops')
+ const inviterDesktopId = await seedDesktopUser(inviter.email)
+ const team = await seedTeam('Expired receiver')
+ await addTeamMember(team, inviterDesktopId, 'admin')
+ const clientEmail = uniqueEmail('expired-receiver')
+ const handover = await createControlAdminInvitation(clientEmail, inviter.id, {
+ replaceInviter: true,
+ })
+ if ('error' in handover) throw new Error(handover.error)
+ const desktopInvitationId = await inviteDesktopAccess(clientEmail)
+ await testPool.query(
+ `UPDATE invitations SET expires_at = NOW() - INTERVAL '1 minute' WHERE id = $1::uuid`,
+ [desktopInvitationId]
+ )
+
+ await expect(
+ completeControlAdminInvitation({
+ email: clientEmail,
+ invitationId: handover.id,
+ username: `expired-receiver-${randomUUID().slice(0, 8)}`,
+ passwordHash: 'real-pg-replace-client',
+ })
+ ).resolves.toEqual({ error: 'replace_inviter_receiver_missing' })
+
+ expect(await adminInvitationStatus(handover.id)).toBe('pending')
+ expect(await adminStatus(inviter.id)).toBe('active')
+ expect(await desktopLifecycle(inviterDesktopId)).toBe('active')
+ expect(await teamRole(team, inviterDesktopId)).toBe('admin')
+ })
+
+ it('keeps replaceInviter on an opened invitation listed as pending password', async () => {
+ const inviter = await seedAdmin('opened-list-ops')
+ const email = uniqueEmail('opened-list-client')
+ const invitation = await createControlAdminInvitation(email, inviter.id, {
+ replaceInviter: true,
+ })
+ if ('error' in invitation) throw new Error(invitation.error)
+ await markControlAdminInvitationOpened(invitation.id)
+
+ const listed = await listControlAdmins()
+ expect(listed.invitations.find(item => item.id === invitation.id)).toBeUndefined()
+ expect(listed.admins.find(item => item.invitationId === invitation.id)).toMatchObject({
+ status: 'pending_password',
+ replaceInviter: true,
+ invitedByAdminId: inviter.id,
+ })
+ })
+
+ it('refuses a new invitation once the inviter is no longer active', async () => {
+ const inviter = await seedAdmin('inactive-create-ops')
+ await testPool.query(`UPDATE control_admin_users SET status = 'disabled' WHERE id = $1::uuid`, [
+ inviter.id,
+ ])
+ const email = uniqueEmail('inactive-create')
+
+ await expect(
+ createControlAdminInvitation(email, inviter.id, { replaceInviter: true })
+ ).resolves.toEqual({ error: 'inviter_not_active' })
+ const rows = await testPool.query(
+ `SELECT 1 FROM control_admin_invitations WHERE lower(email) = lower($1)`,
+ [email]
+ )
+ expect(rows.rowCount).toBe(0)
+ })
+
+ it('does not insert an invitation that was waiting on the inviter row lock', async () => {
+ const inviter = await seedAdmin('create-lock-ops')
+ const email = uniqueEmail('create-lock')
+ const blocker = await testPool.connect()
+ try {
+ await blocker.query('BEGIN')
+ await blocker.query(`SELECT 1 FROM control_admin_users WHERE id = $1::uuid FOR UPDATE`, [
+ inviter.id,
+ ])
+ const creating = createControlAdminInvitation(email, inviter.id, { replaceInviter: true })
+ creating.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'`,
+ [database]
+ )
+ if ((waiting.rowCount ?? 0) > 0) break
+ if (attempt >= 100) throw new Error('invitation insert never waited on the inviter lock')
+ await new Promise(resolve => setTimeout(resolve, 50))
+ }
+ await blocker.query(
+ `UPDATE control_admin_users SET status = 'disabled' WHERE id = $1::uuid`,
+ [inviter.id]
+ )
+ await blocker.query('COMMIT')
+ await expect(creating).resolves.toEqual({ error: 'inviter_not_active' })
+ } finally {
+ await blocker.query('ROLLBACK').catch(() => undefined)
+ blocker.release()
+ }
+
+ const rows = await testPool.query(
+ `SELECT 1 FROM control_admin_invitations WHERE lower(email) = lower($1)`,
+ [email]
+ )
+ expect(rows.rowCount).toBe(0)
+ }, 15_000)
})
diff --git a/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts b/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts
index 995cae0e0..1f451658a 100644
--- a/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts
+++ b/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts
@@ -111,6 +111,18 @@ describeRealPostgres('retireDesktopUser on real PostgreSQL', () => {
'active', 'initial_setup', $2::uuid, 1)`,
[userId, actorId]
)
+ 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, 'linked-approval-channel', NOW())`,
+ [userId, `tg-${userId}`]
+ )
+ await testPool.query(
+ `INSERT INTO workflow_approval_medium_challenges
+ (user_id, medium, provider_user_id, code_hash, expires_at)
+ VALUES ($1::uuid, 'telegram', $2, 'example-code-hash', NOW() + INTERVAL '10 minutes')`,
+ [userId, `tg-${userId}`]
+ )
const result = await retireDesktopUser(
{ kind: 'control_admin', controlAdminId: actorId },
@@ -174,6 +186,18 @@ describeRealPostgres('retireDesktopUser on real PostgreSQL', () => {
lifecycle_operation_id: result.operationId,
},
])
+ const approval = await testPool.query(
+ `SELECT disabled_at IS NOT NULL AS disabled
+ FROM workflow_approval_medium_accounts WHERE user_id = $1::uuid`,
+ [userId]
+ )
+ expect(approval.rows).toEqual([{ disabled: true }])
+ const challenge = await testPool.query(
+ `SELECT consumed_at IS NOT NULL AS consumed
+ FROM workflow_approval_medium_challenges WHERE user_id = $1::uuid`,
+ [userId]
+ )
+ expect(challenge.rows).toEqual([{ consumed: true }])
})
it('retires a user after the Control UI already revoked the link without changing the tombstone', async () => {
diff --git a/control-api/test/services.directory.userRetirement.test.ts b/control-api/test/services.directory.userRetirement.test.ts
index 15e66c4ab..8a8fd0262 100644
--- a/control-api/test/services.directory.userRetirement.test.ts
+++ b/control-api/test/services.directory.userRetirement.test.ts
@@ -81,6 +81,8 @@ describe('retireDesktopUser', () => {
.mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
.mockResolvedValueOnce(activeUser())
.mockResolvedValueOnce({ rows: [{ has_link_history: true }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
.mockResolvedValueOnce({ rows: [{ lifecycle_version: 2 }], rowCount: 1 })
.mockResolvedValueOnce({ rows: [], rowCount: 1 })
mocks.retireParentInTransaction.mockResolvedValueOnce(true)
@@ -112,12 +114,18 @@ describe('retireDesktopUser', () => {
operationId: OPERATION_ID,
})
)
- const userUpdate = String(mocks.txQuery.mock.calls[3]?.[0])
+ const userUpdate = String(mocks.txQuery.mock.calls[5]?.[0])
expect(userUpdate).toContain("lifecycle_state = 'retired'")
+ expect(String(mocks.txQuery.mock.calls[3]?.[0])).toContain(
+ 'UPDATE workflow_approval_medium_accounts'
+ )
+ expect(String(mocks.txQuery.mock.calls[4]?.[0])).toContain(
+ 'UPDATE workflow_approval_medium_challenges'
+ )
expect(userUpdate).toContain('retired_by_control_admin_id = $4::uuid')
expect(userUpdate).toContain('retired_by_desktop_user_id = $5::uuid')
expect(userUpdate).toContain('lifecycle_version = $8')
- expect(mocks.txQuery.mock.calls[3]?.[1]).toEqual([
+ expect(mocks.txQuery.mock.calls[5]?.[1]).toEqual([
USER_ID,
'policy retirement',
'control_admin',
@@ -135,6 +143,8 @@ describe('retireDesktopUser', () => {
.mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
.mockResolvedValueOnce(activeUser())
.mockResolvedValueOnce({ rows: [{ has_link_history: true }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
.mockResolvedValueOnce({ rows: [{ lifecycle_version: 2 }], rowCount: 1 })
.mockResolvedValueOnce({ rows: [], rowCount: 1 })
mocks.retireParentInTransaction.mockResolvedValueOnce(true)
@@ -153,7 +163,7 @@ describe('retireDesktopUser', () => {
actor: { kind: 'platform_user', desktopUserId: MANAGER_ID },
})
)
- expect(mocks.txQuery.mock.calls[3]?.[1]).toEqual([
+ expect(mocks.txQuery.mock.calls[5]?.[1]).toEqual([
USER_ID,
'manager retirement',
'platform_user',
@@ -257,6 +267,8 @@ describe('retireDesktopUser', () => {
.mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
.mockResolvedValueOnce(activeUser())
.mockResolvedValueOnce({ rows: [{ has_link_history: true }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
.mockResolvedValueOnce({ rows: [{ lifecycle_version: 2 }], rowCount: 1 })
.mockResolvedValueOnce({ rows: [], rowCount: 1 })
mocks.retireParentInTransaction.mockResolvedValueOnce(true)
@@ -323,6 +335,8 @@ describe('retireDesktopUser', () => {
.mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
.mockResolvedValueOnce(activeUser(7))
.mockResolvedValueOnce({ rows: [{ has_link_history: true }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
.mockResolvedValueOnce({ rows: [], rowCount: 0 })
mocks.retireParentInTransaction.mockResolvedValueOnce(true)
@@ -335,8 +349,8 @@ describe('retireDesktopUser', () => {
'request-cas-1'
)
).rejects.toMatchObject({ code: 'retirement_conflict' })
- expect(mocks.txQuery).toHaveBeenCalledTimes(4)
- expect(String(mocks.txQuery.mock.calls[3]?.[0])).toContain('lifecycle_version = $8')
+ expect(mocks.txQuery).toHaveBeenCalledTimes(6)
+ expect(String(mocks.txQuery.mock.calls[5]?.[0])).toContain('lifecycle_version = $8')
})
it('rejects an actor with the wrong typed identity field before opening a transaction', async () => {
@@ -361,6 +375,8 @@ describe('retireDesktopUser', () => {
.mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
.mockResolvedValueOnce(activeUser())
.mockResolvedValueOnce({ rows: [{ has_link_history: false }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
.mockResolvedValueOnce({ rows: [{ lifecycle_version: 2 }], rowCount: 1 })
.mockResolvedValueOnce({ rows: [], rowCount: 1 })
@@ -386,7 +402,9 @@ describe('retireDesktopUser', () => {
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'")
+ expect(sqls[3]).toContain('UPDATE workflow_approval_medium_accounts')
+ expect(sqls[4]).toContain('UPDATE workflow_approval_medium_challenges')
+ expect(sqls[5]).toContain("SET lifecycle_state = 'retired'")
+ expect(sqls[6]).toContain("outcome = 'retired'")
})
})
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index 70b26c2ed..3f2527607 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -642,6 +642,8 @@ export type ControlAdminListItem = {
status: 'active' | 'disabled' | 'pending_password'
passwordPending?: boolean
invitationId?: string
+ replaceInviter?: boolean
+ invitedByAdminId?: string | null
gfsOperatorLink?: {
desktopUserId: string
controlAdminId: string
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 982acfe34..6a11d5f01 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.653",
+ "version": "0.1.654",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.653",
+ "version": "0.1.654",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index 23fe01de0..956a113f2 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.653",
+ "version": "0.1.654",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",