Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(gfs): enforce audited operator-link lifecycle
Alfredo Lopezf8dc63dc8263
diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex cfd65cd70..8fdf0ed36 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -2647,6 +2647,84 @@ async function applyGfsAuditActorCorrelationSchema(db: DbClient): Promise<void>`)}+/** Preserve operator-link history while making revocation a state transition. */+async function evolveGfsDesktopOperatorLinksToGenerations(db: DbClient): Promise<void> {+ await db.query(`+ ALTER TABLE gfs_desktop_operator_links+ ADD COLUMN IF NOT EXISTS id UUID,+ ADD COLUMN IF NOT EXISTS lineage_id UUID,+ ADD COLUMN IF NOT EXISTS generation INTEGER,+ ADD COLUMN IF NOT EXISTS predecessor_id UUID,+ ADD COLUMN IF NOT EXISTS state TEXT,+ ADD COLUMN IF NOT EXISTS created_by UUID,+ ADD COLUMN IF NOT EXISTS revoked_at TIMESTAMPTZ,+ ADD COLUMN IF NOT EXISTS revoked_by_type TEXT,+ ADD COLUMN IF NOT EXISTS revoked_by_id UUID,+ ADD COLUMN IF NOT EXISTS revocation_reason TEXT,+ ADD COLUMN IF NOT EXISTS row_version BIGINT;++ UPDATE gfs_desktop_operator_links+ SET id = COALESCE(id, gen_random_uuid()),+ lineage_id = COALESCE(lineage_id, gen_random_uuid()),+ generation = COALESCE(generation, 1),+ state = COALESCE(state, 'active'),+ created_by = COALESCE(created_by, control_admin_id),+ row_version = COALESCE(row_version, 1)+ WHERE id IS NULL OR lineage_id IS NULL OR generation IS NULL OR state IS NULL+ OR created_by IS NULL OR row_version IS NULL;++ ALTER TABLE gfs_desktop_operator_links+ ALTER COLUMN id SET NOT NULL,+ ALTER COLUMN lineage_id SET NOT NULL,+ ALTER COLUMN generation SET NOT NULL,+ ALTER COLUMN state SET NOT NULL,+ ALTER COLUMN created_by SET NOT NULL,+ ALTER COLUMN row_version SET NOT NULL;+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_pkey;+ ALTER TABLE gfs_desktop_operator_links ADD PRIMARY KEY (id);+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_user_id_key;+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_control_admin_id_key;+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_predecessor_id_fkey;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_predecessor_id_fkey+ FOREIGN KEY (predecessor_id) REFERENCES gfs_desktop_operator_links(id) ON DELETE RESTRICT;+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_user_id_fkey;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_user_id_fkey+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE RESTRICT;+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_control_admin_id_fkey;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_control_admin_id_fkey+ FOREIGN KEY (control_admin_id) REFERENCES control_admin_users(id) ON DELETE RESTRICT;+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_created_by_fkey;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_created_by_fkey+ FOREIGN KEY (created_by) REFERENCES control_admin_users(id) ON DELETE RESTRICT;+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_revoked_by_id_fkey;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_revoked_by_id_fkey+ FOREIGN KEY (revoked_by_id) REFERENCES control_admin_users(id) ON DELETE RESTRICT;+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_generation_check;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_generation_check CHECK (generation > 0);+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_row_version_check;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_row_version_check CHECK (row_version > 0);+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_state_check;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_state_check CHECK (state IN ('active', 'revoked'));+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_lifecycle_check;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_lifecycle_check CHECK (+ (state = 'active' AND revoked_at IS NULL AND revoked_by_type IS NULL AND revoked_by_id IS NULL AND revocation_reason IS NULL)+ OR (state = 'revoked' AND revoked_at IS NOT NULL AND revoked_by_type = 'control_admin' AND revoked_by_id IS NOT NULL AND revocation_reason IS NOT NULL)+ );+ ALTER TABLE gfs_desktop_operator_links DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_predecessor_check;+ ALTER TABLE gfs_desktop_operator_links ADD CONSTRAINT gfs_desktop_operator_links_predecessor_check CHECK (+ (generation = 1 AND predecessor_id IS NULL) OR (generation > 1 AND predecessor_id IS NOT NULL)+ );+ CREATE UNIQUE INDEX IF NOT EXISTS gfs_desktop_operator_links_lineage_generation_key ON gfs_desktop_operator_links(lineage_id, generation);+ CREATE UNIQUE INDEX IF NOT EXISTS gfs_desktop_operator_links_predecessor_key ON gfs_desktop_operator_links(predecessor_id) WHERE predecessor_id IS NOT NULL;+ CREATE UNIQUE INDEX IF NOT EXISTS gfs_desktop_operator_links_active_user_key ON gfs_desktop_operator_links(user_id) WHERE state = 'active';+ CREATE UNIQUE INDEX IF NOT EXISTS gfs_desktop_operator_links_active_admin_key ON gfs_desktop_operator_links(control_admin_id) WHERE state = 'active';+ CREATE INDEX IF NOT EXISTS gfs_desktop_operator_links_revoked_at_idx+ ON gfs_desktop_operator_links(revoked_at) WHERE state = 'revoked';+ GRANT SELECT, INSERT, UPDATE ON TABLE gfs_desktop_operator_links TO control_api_runtime;+ REVOKE DELETE, TRUNCATE, REFERENCES, TRIGGER ON TABLE gfs_desktop_operator_links FROM control_api_runtime;+ `)+}+// 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@@ -5517,6 +5595,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [version: '0092_gfs_audit_actor_correlation',apply: applyGfsAuditActorCorrelationSchema,},+ {+ version: '0093_gfs_desktop_operator_link_generations',+ apply: evolveGfsDesktopOperatorLinksToGenerations,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {diff --git a/control-api/src/routes/admin/auth.ts b/control-api/src/routes/admin/auth.tsindex 9685106d2..7993928a5 100644--- a/control-api/src/routes/admin/auth.ts+++ b/control-api/src/routes/admin/auth.ts@@ -181,6 +181,7 @@ export function createAdminAuthRouter(): Router {contextIds: config.adminDefaultContextIds,seedPassword: seedDesktopPassword,linkDesktopOperator: config.desktopGfsOperatorLinkingEnabled,+ requestId: req.correlationId ?? null,})} catch (err) {// Intentionally logs only err + email — never passwordHash.diff --git a/control-api/src/routes/admin/controlAdmins.ts b/control-api/src/routes/admin/controlAdmins.tsindex 211e2e9cf..de1a21a29 100644--- a/control-api/src/routes/admin/controlAdmins.ts+++ b/control-api/src/routes/admin/controlAdmins.ts@@ -326,6 +326,27 @@ export function createAdminControlAdminsRouter(): Router {}})+ router.get(+ '/admin/control-admins/:adminId/gfs-operator-link',+ async (req: UiAuthedRequest, res, next) => {+ try {+ const adminId = readString(req.params.adminId)+ if (!adminId) return void res.status(400).json({ error: 'adminId is required' })+ const link = await gfsDesktopOperatorLinkService.getLinkForControlAdmin(adminId)+ res.status(200).json({+ gfsOperatorLinkStatus: link?.state === 'active' ? 'active' : 'revoked',+ controlAdminId: adminId,+ desktopUserId: link?.desktopUserId ?? null,+ generation: link?.generation ?? null,+ rowVersion: link?.rowVersion ?? null,+ revocationReason: link?.revocationReason ?? null,+ })+ } catch (error) {+ next(error)+ }+ }+ )+router.delete('/admin/control-admin-invitations/:invitationId',requireAuthForControlUI,@@ -406,26 +427,34 @@ export function createAdminControlAdminsRouter(): Router {// Resolve the exact persisted pair server-side. The caller cannot// choose a Desktop user or ask the endpoint to create/reassign one.const link = await gfsDesktopOperatorLinkService.getLinkForControlAdmin(adminId)- if (!link) {+ if (!link || link.state === 'revoked') {res.status(200).json({revoked: false,gfsOperatorLinkStatus: 'revoked',controlAdminId: adminId,- desktopUserId: null,+ desktopUserId: link?.desktopUserId ?? null,+ generation: link?.generation ?? null,+ rowVersion: link?.rowVersion ?? null,})return}+ const requestedRowVersion =+ req.body?.rowVersion === undefined ? link.rowVersion : Number(req.body.rowVersion)const result = await gfsDesktopOperatorLinkService.unlink({desktopUserId: link.desktopUserId,controlAdminId: link.controlAdminId,operatorSub,+ rowVersion: requestedRowVersion,+ reason: readString(req.body?.reason),})res.status(200).json({revoked: result.unlinked,gfsOperatorLinkStatus: 'revoked',controlAdminId: adminId,desktopUserId: link.desktopUserId,+ generation: result.link?.generation ?? link.generation ?? null,+ rowVersion: result.link?.rowVersion ?? null,})} catch (error) {if (error instanceof GfsDesktopOperatorLinkError) {@@ -447,6 +476,56 @@ export function createAdminControlAdminsRouter(): Router {})+ router.post(+ '/admin/control-admins/:adminId/gfs-operator-link/reactivate',+ async (req: UiAuthedRequest, res, next) => {+ try {+ const operatorSub = req.adminAuth?.sub+ const adminId = readString(req.params.adminId)+ if (!operatorSub) return void res.status(401).json({ error: 'Unauthorized' })+ if (!adminId) return void res.status(400).json({ error: 'adminId is required' })+ const result = await gfsDesktopOperatorLinkService.reactivate({+ controlAdminId: adminId,+ operatorSub,+ rowVersion: Number(req.body?.rowVersion),+ reason: readString(req.body?.reason),+ })+ res.status(200).json({+ reactivated: result.reactivated,+ gfsOperatorLinkStatus: result.reactivated ? 'active' : 'revoked',+ controlAdminId: adminId,+ desktopUserId: result.link?.desktopUserId ?? null,+ generation: result.link?.generation ?? null,+ rowVersion: result.link?.rowVersion ?? null,+ })+ } catch (error) {+ if (error instanceof GfsDesktopOperatorLinkError && error.code === 'invalid_input') {+ res.status(400).json({ error: error.code })+ return+ }+ if (error instanceof GfsDesktopOperatorLinkError && error.code === 'link_conflict') {+ res.status(409).json({ error: error.code })+ return+ }+ if (+ error instanceof GfsDesktopOperatorLinkError &&+ (error.code === 'control_admin_inactive' || error.code === 'malformed_link')+ ) {+ res.status(409).json({ error: error.code })+ return+ }+ if (+ error instanceof GfsDesktopOperatorLinkError &&+ error.code === 'desktop_user_not_found'+ ) {+ res.status(404).json({ error: error.code })+ return+ }+ next(error)+ }+ }+ )+router.post('/admin/control-admins/:adminId/member', async (req: UiAuthedRequest, res, next) => {try {const currentAdminId = req.adminAuth?.subdiff --git a/control-api/src/routes/admin/users.ts b/control-api/src/routes/admin/users.tsindex bc5f536fc..d58fd4720 100644--- a/control-api/src/routes/admin/users.ts+++ b/control-api/src/routes/admin/users.ts@@ -245,8 +245,9 @@ export function createAdminUsersRouter(gateway: K8sGateway): Router {registerAdminUserAccessRoutes(router, gateway)/**- * Hard-delete user profile, memberships, and personal context/agent links (DB CASCADE).- * Teams are retained even when this leaves them with no members.+ * Retire a user through the existing account-management contract. Accounts+ * with retained GFS operator-link history are rejected here so a legacy+ * hard-delete cannot bypass the governed lifecycle or erase evidence.*/router.delete('/admin/users/:userId', async (req, res, next) => {try {@@ -256,6 +257,10 @@ export function createAdminUsersRouter(gateway: K8sGateway): Router {res.status(404).json({ error: 'not_found' })return}+ if (result.error === 'gfs_operator_link_history_retained') {+ res.status(409).json({ error: result.error })+ return+ }const exhaustive: never = result.errorthrow new Error(`Unhandled adminDeleteUser result: ${exhaustive}`)}diff --git a/control-api/src/services/adminAuthService.ts b/control-api/src/services/adminAuthService.tsindex 2c2872fe6..ce4b8f9fc 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 { gfsDesktopOperatorLinkService } from './gfsDesktopOperatorLinkService.js'import { currentAdministrativeRequestContext } from './tracing/adminOperationContext.js'import { AdministrativeEventService } from './tracing/administrativeEvents.js'import { CONTROL_API_LOCAL_ADMINISTRATIVE_PRINCIPAL_V1 } from './tracing/controlApiLocalAdministrativeBindingResolver.js'@@ -32,6 +33,17 @@ export type ControlAdminListItem = {status: 'active' | 'disabled' | 'pending_password'passwordPending?: booleaninvitationId?: string+ gfsOperatorLink?: {+ desktopUserId: string+ controlAdminId: string+ source: 'initial_setup' | 'unknown'+ createdAt: string | null+ status: 'active' | 'inactive_admin' | 'revoked' | 'error'+ generation: number | null+ rowVersion: number | null+ revocationReason: string | null+ } | null+ gfsOperatorLinkStatus?: 'active' | 'inactive_admin' | 'revoked' | 'error'lastLoginAt: string | nullcreatedAt: string}@@ -549,8 +561,15 @@ export async function deleteControlAdmin(LIMIT 1`,[actorAdminId])+ await gfsDesktopOperatorLinkService.retireParentInTransaction(db, {+ kind: 'control_admin',+ parentId: adminId,+ operatorSub: actorAdminId,+ reason: 'control_admin_retired',+ })const deletedResult = await db.query(- `DELETE FROM control_admin_users+ `UPDATE control_admin_users+ SET status = 'disabled', session_version = session_version + 1, updated_at = NOW()WHERE id = $1RETURNING id, username, email`,[adminId]@@ -652,13 +671,23 @@ export async function listControlAdmins(): Promise<{gfs_link.control_admin_id AS gfs_operator_admin_id,gfs_link.source AS gfs_operator_source,gfs_link.created_at AS gfs_operator_link_created_at,+ gfs_link.state AS gfs_operator_link_state,+ gfs_link.generation AS gfs_operator_link_generation,+ gfs_link.row_version AS gfs_operator_link_row_version,+ gfs_link.revocation_reason AS gfs_operator_link_revocation_reason,a.status,a.last_login_at,a.created_atFROM control_admin_users aLEFT JOIN users u ON lower(u.email) = lower(a.email)- LEFT JOIN gfs_desktop_operator_links gfs_link- ON gfs_link.control_admin_id = a.id+ LEFT JOIN LATERAL (+ SELECT user_id, control_admin_id, source, created_at, state, generation,+ row_version, revocation_reason+ FROM gfs_desktop_operator_links+ WHERE control_admin_id = a.id+ ORDER BY generation DESC NULLS LAST, created_at DESC+ LIMIT 1+ ) gfs_link ON TRUEORDER BY a.created_at ASC`),pool.query(@@ -688,6 +717,10 @@ export async function listControlAdmins(): Promise<{gfs_operator_admin_id: string | nullgfs_operator_source: 'initial_setup' | nullgfs_operator_link_created_at: Date | null+ gfs_operator_link_state: 'active' | 'revoked' | null+ gfs_operator_link_generation: number | null+ gfs_operator_link_row_version: number | null+ gfs_operator_link_revocation_reason: string | nullstatus: 'active' | 'disabled'last_login_at: Date | nullcreated_at: Date@@ -701,27 +734,41 @@ export async function listControlAdmins(): Promise<{? {desktopUserId: record.gfs_operator_user_id,controlAdminId: record.gfs_operator_admin_id || 'unknown',- source:- record.gfs_operator_source === 'initial_setup' ? 'initial_setup' : 'unknown',+ source: (record.gfs_operator_source === 'initial_setup'+ ? 'initial_setup'+ : 'unknown') as 'initial_setup' | 'unknown',createdAt: record.gfs_operator_link_created_at? record.gfs_operator_link_created_at.toISOString(): null,- status:- record.gfs_operator_source === 'initial_setup' &&- record.gfs_operator_link_created_at+ status: (record.gfs_operator_link_state === 'revoked'+ ? 'revoked'+ : record.gfs_operator_source === 'initial_setup' &&+ record.gfs_operator_link_created_at? record.status === 'active'? 'active': 'inactive_admin'- : 'error',+ : 'error') as 'active' | 'inactive_admin' | 'revoked' | 'error',+ generation:+ record.gfs_operator_link_generation === null+ ? null+ : Number(record.gfs_operator_link_generation),+ rowVersion:+ record.gfs_operator_link_row_version === null+ ? null+ : Number(record.gfs_operator_link_row_version),+ revocationReason: record.gfs_operator_link_revocation_reason ?? null,}: null,- gfsOperatorLinkStatus: record.gfs_operator_user_id- ? record.gfs_operator_source === 'initial_setup' && record.gfs_operator_link_created_at- ? record.status === 'active'- ? 'active'- : 'inactive_admin'- : 'error'- : 'revoked',+ gfsOperatorLinkStatus: (record.gfs_operator_user_id+ ? record.gfs_operator_link_state === 'revoked'+ ? 'revoked'+ : record.gfs_operator_source === 'initial_setup' &&+ record.gfs_operator_link_created_at+ ? record.status === 'active'+ ? 'active'+ : 'inactive_admin'+ : 'error'+ : 'revoked') as 'active' | 'inactive_admin' | 'revoked' | 'error',status: record.status,lastLoginAt: record.last_login_at ? record.last_login_at.toISOString() : null,createdAt: record.created_at.toISOString(),diff --git a/control-api/src/services/directory/adminProvisioning.ts b/control-api/src/services/directory/adminProvisioning.tsindex 11ac4be8b..305389c23 100644--- a/control-api/src/services/directory/adminProvisioning.ts+++ b/control-api/src/services/directory/adminProvisioning.ts@@ -97,6 +97,8 @@ export async function provisionAdminDesktopWorkspace(input: {contextIds: string[]/** Narrow self-hosted setup switch; false keeps the existing Desktop user path unchanged. */linkDesktopOperator: boolean+ /** Correlates the initial link event with the public setup request. */+ requestId?: string | null/** When false, skip writing users.password_hash — the desktop password then* comes only from the invitation flow (managed installs). Defaults to* true: the Control-UI human first-run keeps one credential for both apps. */@@ -138,6 +140,7 @@ export async function provisionAdminDesktopWorkspace(input: {controlAdminId: input.controlAdminId,operatorSub: input.controlAdminId,source: 'initial_setup',+ requestId: input.requestId,})}diff --git a/control-api/src/services/directory/types.ts b/control-api/src/services/directory/types.tsindex dcd9f58f0..3d75b8c9e 100644--- a/control-api/src/services/directory/types.ts+++ b/control-api/src/services/directory/types.ts@@ -86,7 +86,9 @@ export function normalizeChannels(input: unknown): ChannelMapping {}}-export type AdminDeleteUserResult = { ok: true; id: string } | { error: 'not_found' }+export type AdminDeleteUserResult =+ | { ok: true; id: string }+ | { error: 'not_found' | 'gfs_operator_link_history_retained' }export type AdminDeleteTeamResult =| { ok: true; id: string }| { error: 'not_found' | 'team_not_empty' }diff --git a/control-api/src/services/directory/users.ts b/control-api/src/services/directory/users.tsindex 255ed64c6..5ec17e9a3 100644--- a/control-api/src/services/directory/users.ts+++ b/control-api/src/services/directory/users.ts@@ -192,8 +192,9 @@ export async function updateAdminUserContext(}/**- * Hard-delete a user account. Teams are retained even when this delete leaves them with zero- * active members. Memberships are removed via CASCADE when the user row is deleted.+ * Retire a user account through the existing account-management contract.+ * Teams are retained even when this leaves them with zero active members.+ * Accounts with retained operator-link history are intentionally not purged.*/export async function adminDeleteUser(userId: string): Promise<AdminDeleteUserResult> {return withTransaction(async db => {@@ -202,6 +203,22 @@ export async function adminDeleteUser(userId: string): Promise<AdminDeleteUserRereturn { error: 'not_found' }}+ // Operator-link generations are retained for audit and are protected by+ // ON DELETE RESTRICT. Refuse the legacy hard-delete operation explicitly+ // rather than relying on a late FK error or silently erasing the lifecycle+ // history. A future actor-aware account-retirement flow must revoke the+ // active generation and use the governed retention process before purge.+ const operatorLinkHistory = await db.query(+ `SELECT 1+ FROM gfs_desktop_operator_links+ WHERE user_id = $1+ LIMIT 1`,+ [userId]+ )+ if ((operatorLinkHistory.rowCount ?? 0) > 0) {+ return { error: 'gfs_operator_link_history_retained' }+ }+await db.query(`UPDATE workflow_approval_medium_accountsSET disabled_at = COALESCE(disabled_at, NOW()),diff --git a/control-api/src/services/gfsDesktopOperatorLinkService.ts b/control-api/src/services/gfsDesktopOperatorLinkService.tsindex 5ce51593f..264867670 100644--- a/control-api/src/services/gfsDesktopOperatorLinkService.ts+++ b/control-api/src/services/gfsDesktopOperatorLinkService.ts@@ -1,4 +1,4 @@-import { type DbClient, pool } from '../db.js'+import type { DbClient } from '../db.js'import {type ControlApiPermissionChange,appendControlApiPermissionEventsInTransaction,@@ -9,10 +9,18 @@ export const GFS_DESKTOP_OPERATOR_LINK_SOURCES = ['initial_setup'] as constexport type GfsDesktopOperatorLinkSource = (typeof GFS_DESKTOP_OPERATOR_LINK_SOURCES)[number]export type GfsDesktopOperatorLink = {+ id?: string+ lineageId?: string+ generation?: number+ predecessorId?: string | nulldesktopUserId: stringcontrolAdminId: stringsource: GfsDesktopOperatorLinkSource+ state?: 'active' | 'revoked'+ rowVersion?: numbercreatedAt: Date+ revokedAt?: Date | null+ revocationReason?: string | null}export type GfsDesktopOperatorLinkErrorCode =@@ -51,6 +59,8 @@ export type LinkGfsDesktopOperatorInput = {source: GfsDesktopOperatorLinkSource/** Authenticated Control Admin responsible for this lifecycle mutation. */operatorSub: string+ /** Request correlation for the governed lifecycle event. */+ requestId?: string | null}export type UnlinkGfsDesktopOperatorInput = {@@ -58,6 +68,21 @@ export type UnlinkGfsDesktopOperatorInput = {controlAdminId: string/** Authenticated Control Admin responsible for this lifecycle mutation. */operatorSub: string+ /** Optimistic-concurrency token returned by the Control UI read surface. */+ rowVersion?: number+ reason?: string+ /** Request correlation for the governed lifecycle event. */+ requestId?: string | null+}++export type ReactivateGfsDesktopOperatorInput = {+ controlAdminId: string+ operatorSub: string+ /** The revoked generation being reactivated; prevents stale UI writes. */+ rowVersion: number+ reason: string+ /** Request correlation for the governed lifecycle event. */+ requestId?: string | null}export type LinkGfsDesktopOperatorResult = {@@ -69,6 +94,12 @@ export type UnlinkGfsDesktopOperatorResult =| { unlinked: false; link: null }| { unlinked: true; link: GfsDesktopOperatorLink }+export type ReactivateGfsDesktopOperatorResult = {+ reactivated: boolean+ link: GfsDesktopOperatorLink | null+}+export type GfsDesktopOperatorParentKind = 'desktop_user' | 'control_admin'+type TransactionRunner = <T>(work: (db: DbClient) => Promise<T>) => Promise<T>/**@@ -83,6 +114,10 @@ const defaultTransaction: TransactionRunner = async work => {return withTransaction(work)}+const defaultReadDb: Pick<DbClient, 'query'> = {+ query: (text, values) => import('../db.js').then(({ pool }) => pool.query(text, values)),+}+type GfsDesktopOperatorLinkServiceDependencies = {transaction: TransactionRunnerreadDb: Pick<DbClient, 'query'>@@ -90,12 +125,44 @@ type GfsDesktopOperatorLinkServiceDependencies = {}type StoredLinkRow = {+ id?: unknown+ lineage_id?: unknown+ generation?: unknown+ predecessor_id?: unknown+ row_version?: unknown+ state?: unknown+ revoked_at?: unknown+ revocation_reason?: unknownuser_id: unknowncontrol_admin_id: unknownsource: unknowncreated_at: unknown}+function requireRowVersion(value: unknown): number {+ const normalized =+ typeof value === 'number'+ ? value+ : typeof value === 'string' && /^\d+$/.test(value.trim())+ ? Number(value)+ : Number.NaN+ if (!Number.isSafeInteger(normalized) || normalized < 1) {+ throw new GfsDesktopOperatorLinkError('invalid_input', 'rowVersion must be a positive integer')+ }+ return normalized+}++function requireReason(value: unknown): string {+ const reason = String(value || '').trim()+ if (!reason || reason.length > 512) {+ throw new GfsDesktopOperatorLinkError(+ 'invalid_input',+ 'reason is required and must be at most 512 characters'+ )+ }+ return reason+}+type ResolvedLinkRow = StoredLinkRow & {desktop_user_exists?: unknowncontrol_admin_exists?: unknown@@ -154,17 +221,63 @@ function mapStoredLink(row: unknown): GfsDesktopOperatorLink {) {throw new GfsDesktopOperatorLinkError('malformed_link', 'operator-link row is malformed')}+ const id =+ stored.id === undefined || stored.id === null ? undefined : requireUuid(String(stored.id), 'id')+ const lineageId =+ stored.lineage_id === undefined || stored.lineage_id === null+ ? undefined+ : requireUuid(String(stored.lineage_id), 'lineageId')+ const predecessorId =+ stored.predecessor_id === undefined || stored.predecessor_id === null+ ? null+ : requireUuid(String(stored.predecessor_id), 'predecessorId')+ const generation =+ stored.generation === undefined || stored.generation === null+ ? undefined+ : requireRowVersion(stored.generation)+ const rowVersion =+ stored.row_version === undefined || stored.row_version === null+ ? undefined+ : requireRowVersion(stored.row_version)+ const state = stored.state === undefined || stored.state === null ? undefined : stored.state+ if (state !== undefined && state !== 'active' && state !== 'revoked') {+ throw new GfsDesktopOperatorLinkError('malformed_link', 'operator-link state is malformed')+ }+ const revokedAt =+ stored.revoked_at === undefined || stored.revoked_at === null+ ? null+ : stored.revoked_at instanceof Date+ ? stored.revoked_at+ : null+ if (stored.revoked_at !== undefined && stored.revoked_at !== null && !revokedAt) {+ throw new GfsDesktopOperatorLinkError(+ 'malformed_link',+ 'operator-link revocation timestamp is malformed'+ )+ }return {+ ...(id ? { id } : {}),+ ...(lineageId ? { lineageId } : {}),+ ...(generation === undefined ? {} : { generation }),+ ...(stored.predecessor_id === undefined ? {} : { predecessorId }),desktopUserId,controlAdminId,source: stored.source,+ ...(state === undefined ? {} : { state }),+ ...(rowVersion === undefined ? {} : { rowVersion }),createdAt,+ ...(stored.revoked_at === undefined ? {} : { revokedAt }),+ ...(stored.revocation_reason === undefined+ ? {}+ : { revocationReason: stored.revocation_reason as string | null }),}}function lifecycleChange(action: 'grant' | 'revoke',- link: GfsDesktopOperatorLink+ link: GfsDesktopOperatorLink,+ reason?: string,+ lifecycleEvent?: 'link.created' | 'link.revoked' | 'link.reactivated' | 'parent.retired'): ControlApiPermissionChange {return {action,@@ -173,7 +286,18 @@ function lifecycleChange(subject: { kind: 'user', id: link.desktopUserId },sourceAuditRef: `gfs_desktop_operator_link_source:${link.source}`,status: action === 'grant' ? 'linked' : 'unlinked',- detailRef: `desktop_user_id:${link.desktopUserId};control_admin_id:${link.controlAdminId};source:${link.source}`,+ detailRef: [+ lifecycleEvent ? `event:${lifecycleEvent}` : null,+ `desktop_user_id:${link.desktopUserId}`,+ `control_admin_id:${link.controlAdminId}`,+ `source:${link.source}`,+ link.lineageId ? `lineage_id:${link.lineageId}` : null,+ link.generation === undefined ? null : `generation:${link.generation}`,+ link.predecessorId ? `predecessor_id:${link.predecessorId}` : null,+ reason ? `reason:${reason}` : null,+ ]+ .filter(Boolean)+ .join(';'),}}@@ -225,7 +349,7 @@ export class GfsDesktopOperatorLinkService {constructor(dependencies: Partial<GfsDesktopOperatorLinkServiceDependencies> = {}) {this.dependencies = {transaction: dependencies.transaction ?? defaultTransaction,- readDb: dependencies.readDb ?? pool,+ readDb: dependencies.readDb ?? defaultReadDb,appendPermissionEvents:dependencies.appendPermissionEvents ?? appendControlApiPermissionEventsInTransaction,}@@ -275,31 +399,36 @@ export class GfsDesktopOperatorLinkService {}const current = await db.query(- `SELECT user_id::text AS user_id,+ `SELECT id::text AS id, lineage_id::text AS lineage_id, generation,+ predecessor_id::text AS predecessor_id, state, row_version,+ revoked_at, revocation_reason,+ user_id::text AS user_id,control_admin_id::text AS control_admin_id,source,created_at- FROM gfs_desktop_operator_links- WHERE user_id = $1::uuid- OR control_admin_id = $2::uuid+ FROM gfs_desktop_operator_links+ WHERE (user_id = $1::uuid+ OR control_admin_id = $2::uuid)ORDER BY user_id::text, control_admin_id::textFOR UPDATE`,[desktopUserId, controlAdminId])const links = current.rows.map(mapStoredLink)- const exact = links.find(+ const activeLinks = links.filter(link => link.state === undefined || link.state === 'active')+ const revokedLinks = links.filter(link => link.state === 'revoked')+ const exact = activeLinks.find(link => link.desktopUserId === desktopUserId && link.controlAdminId === controlAdminId)- if (exact && links.length === 1) return { created: false, link: exact }- if (exact || links.length > 2) {+ if (exact && activeLinks.length === 1) return { created: false, link: exact }+ if (exact || activeLinks.length > 2) {throw new GfsDesktopOperatorLinkError('malformed_link','operator-link uniqueness invariant is violated')}- const desktopUserConflict = links.some(link => link.desktopUserId === desktopUserId)- const controlAdminConflict = links.some(link => link.controlAdminId === controlAdminId)+ const desktopUserConflict = activeLinks.some(link => link.desktopUserId === desktopUserId)+ const controlAdminConflict = activeLinks.some(link => link.controlAdminId === controlAdminId)if (desktopUserConflict || controlAdminConflict) {const conflictIdentity: GfsDesktopOperatorLinkConflictIdentity =desktopUserConflict && controlAdminConflict@@ -313,15 +442,23 @@ export class GfsDesktopOperatorLinkService {{ conflictIdentity })}+ if (revokedLinks.length > 0) {+ throw new GfsDesktopOperatorLinkError(+ 'link_conflict',+ 'GFS Desktop operator-link history already exists; use explicit reactivation'+ )+ }const inserted = await db.query(- `INSERT INTO gfs_desktop_operator_links(user_id, control_admin_id, source)- VALUES($1::uuid, $2::uuid, $3)- RETURNING user_id::text AS user_id,+ `INSERT INTO gfs_desktop_operator_links(id, lineage_id, generation, user_id, control_admin_id, state, source, created_by, row_version)+ VALUES(gen_random_uuid(), gen_random_uuid(), 1, $1::uuid, $2::uuid, 'active', $3, $4::uuid, 1)+ RETURNING id::text AS id, lineage_id::text AS lineage_id, generation,+ state, row_version,+ user_id::text AS user_id,control_admin_id::text AS control_admin_id,source,created_at`,- [desktopUserId, controlAdminId, source]+ [desktopUserId, controlAdminId, source, operatorSub])if (inserted.rows.length !== 1) {throw new GfsDesktopOperatorLinkError(@@ -333,7 +470,8 @@ export class GfsDesktopOperatorLinkService {await this.dependencies.appendPermissionEvents(db, {operatorSub,operatorKind: 'control_admin',- changes: [lifecycleChange('grant', link)],+ requestId: input.requestId,+ changes: [lifecycleChange('grant', link, undefined, 'link.created')],})return { created: true, link }}@@ -345,13 +483,17 @@ export class GfsDesktopOperatorLinkService {return this.dependencies.transaction(async db => {const current = await db.query(- `SELECT user_id::text AS user_id,+ `SELECT id::text AS id, lineage_id::text AS lineage_id, generation,+ predecessor_id::text AS predecessor_id, state, row_version,+ revoked_at, revocation_reason,+ user_id::text AS user_id,control_admin_id::text AS control_admin_id,source,created_atFROM gfs_desktop_operator_links- WHERE user_id = $1::uuid- OR control_admin_id = $2::uuid+ WHERE (user_id = $1::uuid+ OR control_admin_id = $2::uuid)+ AND state = 'active'ORDER BY user_id::text, control_admin_id::textFOR UPDATE`,[desktopUserId, controlAdminId]@@ -378,34 +520,243 @@ export class GfsDesktopOperatorLinkService {)}- // Evidence is appended before current state is removed. Both operations- // still commit atomically because they share this transaction.+ const rowVersion =+ input.rowVersion === undefined+ ? exact.rowVersion === undefined+ ? 1+ : exact.rowVersion+ : requireRowVersion(input.rowVersion)+ const reason = input.reason === undefined ? 'operator_revoked' : requireReason(input.reason)+ // Evidence is appended before the immutable generation is revoked. Both+ // operations still commit atomically because they share this transaction.await this.dependencies.appendPermissionEvents(db, {operatorSub,operatorKind: 'control_admin',- changes: [lifecycleChange('revoke', exact)],+ requestId: input.requestId,+ changes: [lifecycleChange('revoke', exact, reason, 'link.revoked')],})const removed = await db.query(- `DELETE FROM gfs_desktop_operator_links+ `UPDATE gfs_desktop_operator_links+ SET state = 'revoked',+ revoked_at = NOW(),+ revoked_by_type = 'control_admin',+ revoked_by_id = $3::uuid,+ revocation_reason = $4,+ row_version = row_version + 1WHERE user_id = $1::uuid- AND control_admin_id = $2::uuid`,- [desktopUserId, controlAdminId]+ AND control_admin_id = $2::uuid+ AND state = 'active'+ AND row_version = $5`,+ [desktopUserId, controlAdminId, operatorSub, reason, rowVersion])if (removed.rowCount !== 1) {throw new GfsDesktopOperatorLinkError('malformed_link',- 'operator-link disappeared during unlink'+ 'operator-link was changed by another request'+ )+ }+ return {+ unlinked: true as const,+ link: {+ ...exact,+ state: 'revoked' as const,+ rowVersion: rowVersion + 1,+ revokedAt: new Date(),+ revocationReason: reason,+ },+ }+ })+ }++ /**+ * Reactivation always creates a successor generation; the revoked row is+ * retained as the predecessor and is never modified again.+ */+ async reactivate(+ input: ReactivateGfsDesktopOperatorInput+ ): Promise<ReactivateGfsDesktopOperatorResult> {+ const controlAdminId = requireUuid(input.controlAdminId, 'controlAdminId')+ const operatorSub = requireUuid(input.operatorSub, 'operatorSub')+ const rowVersion = requireRowVersion(input.rowVersion)+ const reason = requireReason(input.reason)+ return this.dependencies.transaction(async db => {+ // A replay after a committed reactivation is idempotent. Lock the active+ // row before reading the tombstone so no second successor can be made.+ const active = await db.query(+ `SELECT id::text AS id, lineage_id::text AS lineage_id, generation,+ predecessor_id::text AS predecessor_id, state, row_version,+ user_id::text AS user_id, control_admin_id::text AS control_admin_id,+ source, created_at+ FROM gfs_desktop_operator_links+ WHERE control_admin_id = $1::uuid AND state = 'active'+ LIMIT 1 FOR UPDATE`,+ [controlAdminId]+ )+ if (active.rows.length === 1) {+ const activeLink = mapStoredLink(active.rows[0])+ // A replay is idempotent only when it names the tombstone that+ // produced the currently active successor. A stale request for a+ // different generation must not be silently accepted.+ if (!activeLink.predecessorId) {+ return { reactivated: false, link: activeLink }+ }+ const predecessor = await db.query(+ `SELECT state, row_version+ FROM gfs_desktop_operator_links+ WHERE id = $1::uuid+ FOR UPDATE`,+ [activeLink.predecessorId])+ const predecessorRow = predecessor.rows[0] as+ | { state?: unknown; row_version?: unknown }+ | undefined+ if (+ predecessorRow?.state !== 'revoked' ||+ requireRowVersion(predecessorRow.row_version) !== rowVersion+ ) {+ throw new GfsDesktopOperatorLinkError(+ 'link_conflict',+ 'operator-link reactivation replay is stale'+ )+ }+ return { reactivated: true, link: activeLink }}- return { unlinked: true as const, link: exact }+ const prior = await db.query(+ `SELECT id::text AS id, lineage_id::text AS lineage_id, generation,+ predecessor_id::text AS predecessor_id, state, row_version, revoked_at,+ revocation_reason, user_id::text AS user_id, control_admin_id::text AS control_admin_id,+ source, created_at+ FROM gfs_desktop_operator_links+ WHERE control_admin_id = $1::uuid AND state = 'revoked'+ ORDER BY generation DESC+ LIMIT 1 FOR UPDATE`,+ [controlAdminId]+ )+ if (prior.rows.length === 0) return { reactivated: false, link: null }+ const previous = prior.rows[0] as StoredLinkRow+ const link = mapStoredLink(previous)+ if (requireRowVersion(previous.row_version) !== rowVersion) {+ throw new GfsDesktopOperatorLinkError(+ 'link_conflict',+ 'operator-link was changed by another request'+ )+ }+ const predecessorId = requireUuid(String(previous.id || ''), 'predecessorId')+ const lineageId = requireUuid(String(previous.lineage_id || ''), 'lineageId')+ const generation = requireRowVersion(previous.generation) + 1+ const parents = await db.query(+ `SELECT u.id IS NOT NULL AS desktop_user_exists, a.status AS control_admin_status+ FROM users u CROSS JOIN control_admin_users a+ WHERE u.id = $1::uuid AND a.id = $2::uuid+ FOR UPDATE`,+ [link.desktopUserId, controlAdminId]+ )+ const parentState = parents.rows[0] as+ | { desktop_user_exists?: unknown; control_admin_status?: unknown }+ | undefined+ if (parentState?.desktop_user_exists !== true) {+ throw new GfsDesktopOperatorLinkError(+ 'desktop_user_not_found',+ 'Desktop user does not exist'+ )+ }+ if (parentState.control_admin_status !== 'active') {+ throw new GfsDesktopOperatorLinkError(+ 'control_admin_inactive',+ 'Control Admin is not active'+ )+ }+ const inserted = await db.query(+ `INSERT INTO gfs_desktop_operator_links+ (id, lineage_id, generation, predecessor_id, user_id, control_admin_id, state, source, created_by, row_version)+ VALUES (gen_random_uuid(), $1::uuid, $2, $3::uuid, $4::uuid, $5::uuid, 'active', 'initial_setup', $6::uuid, 1)+ RETURNING id::text AS id, lineage_id::text AS lineage_id, generation,+ predecessor_id::text AS predecessor_id, state, row_version,+ user_id::text AS user_id, control_admin_id::text AS control_admin_id,+ source, created_at`,+ [lineageId, generation, predecessorId, link.desktopUserId, controlAdminId, operatorSub]+ )+ const successor = mapStoredLink(inserted.rows[0])+ await this.dependencies.appendPermissionEvents(db, {+ operatorSub,+ operatorKind: 'control_admin',+ requestId: input.requestId,+ changes: [lifecycleChange('grant', successor, reason, 'link.reactivated')],+ })+ return { reactivated: true, link: successor }})}+ /** Shared parent-retirement seam: evidence precedes every tombstone update. */+ async retireParentInTransaction(+ db: DbClient,+ input: {+ kind: GfsDesktopOperatorParentKind+ parentId: string+ operatorSub: string+ reason: string+ requestId?: string | null+ }+ ): Promise<boolean> {+ const parentId = requireUuid(input.parentId, 'parentId')+ const operatorSub = requireUuid(input.operatorSub, 'operatorSub')+ const reason = requireReason(input.reason)+ const column = input.kind === 'desktop_user' ? 'user_id' : 'control_admin_id'+ const rows = await db.query(+ `SELECT id::text AS id, lineage_id::text AS lineage_id, generation,+ predecessor_id::text AS predecessor_id, state, row_version,+ user_id::text AS user_id, control_admin_id::text AS control_admin_id,+ source, created_at+ FROM gfs_desktop_operator_links+ WHERE ${column} = $1::uuid AND state = 'active'+ LIMIT 1 FOR UPDATE`,+ [parentId]+ )+ if (rows.rows.length === 0) return false+ const link = mapStoredLink(rows.rows[0])+ await this.dependencies.appendPermissionEvents(db, {+ operatorSub,+ operatorKind: 'control_admin',+ requestId: input.requestId,+ changes: [+ lifecycleChange('revoke', link, reason, 'link.revoked'),+ {+ action: 'revoke',+ resourceClass: `gfs_desktop_operator_${input.kind}`,+ resourceRef: `${input.kind}:${parentId}`,+ subject:+ input.kind === 'desktop_user'+ ? { kind: 'user', id: parentId }+ : { kind: 'service', id: `control_admin:${parentId}`, principalKind: 'operator' },+ sourceAuditRef: `gfs_desktop_operator_link_source:${link.source}`,+ status: 'retired',+ detailRef: `event:parent.retired;desktop_user_id:${link.desktopUserId};control_admin_id:${link.controlAdminId};source:${link.source};reason:${reason}`,+ },+ ],+ })+ const updated = await db.query(+ `UPDATE gfs_desktop_operator_links+ SET state = 'revoked', revoked_at = NOW(), revoked_by_type = 'control_admin',+ revoked_by_id = $2::uuid, revocation_reason = $3, row_version = row_version + 1+ WHERE ${column} = $1::uuid AND state = 'active' AND row_version = $4`,+ [parentId, operatorSub, reason, link.rowVersion ?? 1]+ )+ if (updated.rowCount !== 1)+ throw new GfsDesktopOperatorLinkError(+ 'link_conflict',+ 'parent link changed during retirement'+ )+ return true+ }+async resolveActiveLink(desktopUserIdInput: string): Promise<GfsDesktopOperatorLink | null> {const desktopUserId = requireUuid(desktopUserIdInput, 'desktopUserId')try {const result = await this.dependencies.readDb.query(- `SELECT links.user_id::text AS user_id,+ `SELECT links.id::text AS id, links.lineage_id::text AS lineage_id,+ links.generation, links.predecessor_id::text AS predecessor_id,+ links.state, links.row_version, links.revoked_at, links.revocation_reason,+ links.user_id::text AS user_id,links.control_admin_id::text AS control_admin_id,links.source,links.created_at,@@ -415,7 +766,8 @@ export class GfsDesktopOperatorLinkService {FROM gfs_desktop_operator_links linksLEFT JOIN users ON users.id = links.user_idLEFT JOIN control_admin_users admins ON admins.id = links.control_admin_id- WHERE links.user_id = $1::uuid`,+ WHERE links.user_id = $1::uuid+ AND links.state = 'active'`,[desktopUserId])if (result.rows.length === 0) return null@@ -444,7 +796,15 @@ export class GfsDesktopOperatorLinkService {const controlAdminId = requireUuid(controlAdminIdInput, 'controlAdminId')try {const result = await this.dependencies.readDb.query(- `SELECT links.user_id::text AS user_id,+ `SELECT links.id::text AS id,+ links.lineage_id::text AS lineage_id,+ links.generation,+ links.predecessor_id::text AS predecessor_id,+ links.state,+ links.row_version,+ links.revoked_at,+ links.revocation_reason,+ links.user_id::text AS user_id,links.control_admin_id::text AS control_admin_id,links.source,links.created_at,@@ -452,9 +812,11 @@ export class GfsDesktopOperatorLinkService {admins.id IS NOT NULL AS control_admin_exists,admins.status AS control_admin_statusFROM gfs_desktop_operator_links links- LEFT JOIN users ON users.id = links.user_id- LEFT JOIN control_admin_users admins ON admins.id = links.control_admin_id- WHERE links.control_admin_id = $1::uuid`,+ LEFT JOIN users ON users.id = links.user_id+ LEFT JOIN control_admin_users admins ON admins.id = links.control_admin_id+ WHERE links.control_admin_id = $1::uuid+ ORDER BY links.generation DESC+ LIMIT 1`,[controlAdminId])if (result.rows.length === 0) return null@@ -478,10 +840,9 @@ export class GfsDesktopOperatorLinkService {'operator link references a missing Control Admin')}- // Status reads deliberately preserve a structurally valid link for a- // disabled admin so the authenticated revoke path can remove stale- // current state. Request-time authority still uses resolveActiveLink(),- // which rejects every non-active admin.+ // Status reads deliberately preserve a structurally valid tombstone for+ // the Control UI. Request-time authority still uses resolveActiveLink(),+ // which rejects every non-active generation or admin.return link} catch (error) {if (error instanceof GfsDesktopOperatorLinkError) throw error@@ -492,6 +853,19 @@ export class GfsDesktopOperatorLinkService {)}}++ async getActiveRowVersionForControlAdmin(controlAdminIdInput: string): Promise<number | null> {+ const controlAdminId = requireUuid(controlAdminIdInput, 'controlAdminId')+ const result = await this.dependencies.readDb.query(+ `SELECT row_version+ FROM gfs_desktop_operator_links+ WHERE control_admin_id = $1::uuid AND state = 'active'+ LIMIT 1`,+ [controlAdminId]+ )+ if (result.rows.length === 0) return null+ return requireRowVersion((result.rows[0] as { row_version?: unknown }).row_version)+ }}export const gfsDesktopOperatorLinkService = new GfsDesktopOperatorLinkService()diff --git a/control-api/test/db.gfsAuditActorCorrelationMigration.test.ts b/control-api/test/db.gfsAuditActorCorrelationMigration.test.tsindex dddcfb8f4..0174ecf04 100644--- a/control-api/test/db.gfsAuditActorCorrelationMigration.test.ts+++ b/control-api/test/db.gfsAuditActorCorrelationMigration.test.ts@@ -13,8 +13,19 @@ describe('0092_gfs_audit_actor_correlation migration', () => {candidate => candidate.version === '0092_gfs_audit_actor_correlation')expect(migration).toBeDefined()- expect(CONTROL_API_MIGRATIONS.at(-2)?.version).toBe('0091_gfs_desktop_operator_links')- expect(CONTROL_API_MIGRATIONS.at(-1)?.version).toBe(migration?.version)+ const linkMigrationIndex = CONTROL_API_MIGRATIONS.findIndex(+ candidate => candidate.version === '0091_gfs_desktop_operator_links'+ )+ const auditMigrationIndex = CONTROL_API_MIGRATIONS.findIndex(+ candidate => candidate.version === '0092_gfs_audit_actor_correlation'+ )+ const generationsMigrationIndex = CONTROL_API_MIGRATIONS.findIndex(+ candidate => candidate.version === '0093_gfs_desktop_operator_link_generations'+ )+ expect(linkMigrationIndex).toBeGreaterThanOrEqual(0)+ expect(auditMigrationIndex).toBe(linkMigrationIndex + 1)+ expect(generationsMigrationIndex).toBe(auditMigrationIndex + 1)+ expect(CONTROL_API_MIGRATIONS[auditMigrationIndex]?.version).toBe(migration?.version)const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })await migration!.apply({ query })diff --git a/control-api/test/db.gfsDesktopOperatorLinkGenerationsMigration.test.ts b/control-api/test/db.gfsDesktopOperatorLinkGenerationsMigration.test.tsnew file mode 100644index 000000000..f525d7117--- /dev/null+++ b/control-api/test/db.gfsDesktopOperatorLinkGenerationsMigration.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it, vi } from 'vitest'++vi.mock('pg', () => ({+ Pool: vi.fn(function MockPool() {+ return { connect: vi.fn(), query: vi.fn() }+ }),+}))++describe('0093_gfs_desktop_operator_link_generations migration', () => {+ it('evolves links into immutable stateful generations with restricted parents', async () => {+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')+ const migration = CONTROL_API_MIGRATIONS.find(+ candidate => candidate.version === '0093_gfs_desktop_operator_link_generations'+ )+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })+ await migration!.apply({ query })+ const sql = String(query.mock.calls[0]?.[0])++ expect(sql).toContain('ADD COLUMN IF NOT EXISTS lineage_id UUID')+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS generation INTEGER')+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS row_version BIGINT')+ expect(sql).toContain('created_by = COALESCE(created_by, control_admin_id)')+ expect(sql).toContain('ALTER COLUMN created_by SET NOT NULL')+ expect(sql).toContain("CHECK (state IN ('active', 'revoked'))")+ expect(sql).toContain('REFERENCES users(id) ON DELETE RESTRICT')+ expect(sql).toContain('REFERENCES control_admin_users(id) ON DELETE RESTRICT')+ expect(sql).not.toContain('gfs_desktop_operator_links(id) ON DELETE CASCADE')+ expect(sql).toContain('gfs_desktop_operator_links_active_user_key')+ expect(sql).toContain('gfs_desktop_operator_links_active_admin_key')+ expect(sql).toContain('gfs_desktop_operator_links_revoked_at_idx')+ expect(sql).toContain("revoked_by_type = 'control_admin'")+ expect(sql).toContain('REVOKE DELETE, TRUNCATE, REFERENCES, TRIGGER')+ })+})diff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.tsindex 84f6d267f..f87aac7c6 100644--- a/control-api/test/db.realPostgresMigration.integration.test.ts+++ b/control-api/test/db.realPostgresMigration.integration.test.ts@@ -403,7 +403,7 @@ describeRealPostgres('control-api real Postgres migrations', () => {llm_allowed_models: ['DELETE', 'INSERT', 'SELECT', 'UPDATE'],llm_allowed_models_audit: ['INSERT', 'SELECT'],llm_catalog_sync_runs: ['INSERT', 'SELECT'],- gfs_desktop_operator_links: ['DELETE', 'INSERT', 'SELECT'],+ gfs_desktop_operator_links: ['INSERT', 'SELECT', 'UPDATE'],}for (const relation of exactControlApiRelations) {expectPrivileges(@@ -447,19 +447,20 @@ describeRealPostgres('control-api real Postgres migrations', () => {ORDER BY privilege.privilege_name`)expect(privilegeState.rows).toEqual([- { privilege_name: 'DELETE', allowed: true },+ { privilege_name: 'DELETE', allowed: false },{ privilege_name: 'INSERT', allowed: true },{ privilege_name: 'REFERENCES', allowed: false },{ privilege_name: 'SELECT', allowed: true },{ privilege_name: 'TRIGGER', allowed: false },{ privilege_name: 'TRUNCATE', allowed: false },- { privilege_name: 'UPDATE', allowed: false },+ { privilege_name: 'UPDATE', allowed: true },])await linkRuntimeClient.query('SET LOCAL ROLE control_api_runtime')await linkRuntimeClient.query(- `INSERT INTO gfs_desktop_operator_links (user_id, control_admin_id, source)- VALUES ($1, $2, 'initial_setup')`,+ `INSERT INTO gfs_desktop_operator_links+ (id, lineage_id, generation, user_id, control_admin_id, state, source, created_by, row_version)+ VALUES (gen_random_uuid(), gen_random_uuid(), 1, $1, $2, 'active', 'initial_setup', $2, 1)`,[linkUserId, linkAdminId])const linked = await linkRuntimeClient.query<{ user_id: string; control_admin_id: string }>(@@ -470,16 +471,13 @@ describeRealPostgres('control-api real Postgres migrations', () => {)expect(linked.rows).toEqual([{ user_id: linkUserId, control_admin_id: linkAdminId }])- await linkRuntimeClient.query('SAVEPOINT deny_link_update')- await expect(- linkRuntimeClient.query(- `UPDATE gfs_desktop_operator_links- SET source = 'initial_setup'- WHERE user_id = $1`,- [linkUserId]- )- ).rejects.toThrow(/permission denied/)- await linkRuntimeClient.query('ROLLBACK TO SAVEPOINT deny_link_update')+ await linkRuntimeClient.query(+ `UPDATE gfs_desktop_operator_links+ SET state = 'revoked', revoked_at = NOW(), revoked_by_type = 'control_admin',+ revoked_by_id = $2, revocation_reason = 'privilege-test', row_version = row_version + 1+ WHERE user_id = $1`,+ [linkUserId, linkAdminId]+ )await linkRuntimeClient.query('SAVEPOINT deny_link_truncate')await expect(@@ -487,11 +485,13 @@ describeRealPostgres('control-api real Postgres migrations', () => {).rejects.toThrow(/permission denied/)await linkRuntimeClient.query('ROLLBACK TO SAVEPOINT deny_link_truncate')- await linkRuntimeClient.query(- `DELETE FROM gfs_desktop_operator_links- WHERE user_id = $1`,- [linkUserId]- )+ await linkRuntimeClient.query('SAVEPOINT deny_link_delete')+ await expect(+ linkRuntimeClient.query(`DELETE FROM gfs_desktop_operator_links WHERE user_id = $1`, [+ linkUserId,+ ])+ ).rejects.toThrow(/permission denied/)+ await linkRuntimeClient.query('ROLLBACK TO SAVEPOINT deny_link_delete')} finally {await linkRuntimeClient.query('ROLLBACK')linkRuntimeClient.release()diff --git a/control-api/test/gfsReadiness.realPostgres.integration.test.ts b/control-api/test/gfsReadiness.realPostgres.integration.test.tsindex 7efce15e9..7ed0dd48c 100644--- a/control-api/test/gfsReadiness.realPostgres.integration.test.ts+++ b/control-api/test/gfsReadiness.realPostgres.integration.test.ts@@ -95,6 +95,19 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL readiness', () => {}})+ it('fails GFSC readiness while the 0092 audit actor-correlation constraint is absent', async () => {+ const client = await pool.connect()+ try {+ await client.query('BEGIN')+ await client.query('ALTER TABLE gfs_audit DROP CONSTRAINT gfs_audit_actor_correlation_valid')+ await client.query('SET LOCAL ROLE gfs_controller')+ await expect(probeAs(client)()).rejects.toThrow(/audit actor-correlation|0092/i)+ } finally {+ await client.query('ROLLBACK').catch(() => undefined)+ client.release()+ }+ })+it('passes GFSC writer readiness under the migrated runtime role', async () => {const client = await pool.connect()try {diff --git a/control-api/test/routes.adminControlAdmins.test.ts b/control-api/test/routes.adminControlAdmins.test.tsindex e8225c7d5..cb209724a 100644--- a/control-api/test/routes.adminControlAdmins.test.ts+++ b/control-api/test/routes.adminControlAdmins.test.ts@@ -25,7 +25,9 @@ const controlAdminInvitationRegistrationSvc = vi.hoisted(() => ({const operatorLinkSvc = vi.hoisted(() => ({getLinkForControlAdmin: vi.fn(),+ getActiveRowVersionForControlAdmin: vi.fn(),unlink: vi.fn(),+ reactivate: vi.fn(),}))const uiAuth = vi.hoisted(() => ({@@ -122,6 +124,9 @@ describe('routes/adminControlAdmins', () => {controlAdminId: targetAdminId,source: 'initial_setup',createdAt: new Date('2026-08-10T12:00:00.000Z'),+ state: 'active',+ rowVersion: 1,+ generation: 1,})operatorLinkSvc.unlink.mockResolvedValue({unlinked: true,@@ -135,7 +140,7 @@ describe('routes/adminControlAdmins', () => {const res = await request(createTestApp()).delete(`/admin/control-admins/${targetAdminId}/gfs-operator-link`)- .send({ desktopUserId: 'client-supplied-id' })+ .send({ desktopUserId: 'client-supplied-id', rowVersion: 1, reason: 'test-revoke' }).expect(200)expect(res.body).toEqual({@@ -143,12 +148,42 @@ describe('routes/adminControlAdmins', () => {gfsOperatorLinkStatus: 'revoked',controlAdminId: targetAdminId,desktopUserId,+ generation: 1,+ rowVersion: null,})expect(operatorLinkSvc.getLinkForControlAdmin).toHaveBeenCalledWith(targetAdminId)expect(operatorLinkSvc.unlink).toHaveBeenCalledWith({desktopUserId,controlAdminId: targetAdminId,operatorSub: 'current-admin-id',+ rowVersion: 1,+ reason: 'test-revoke',+ })+ })++ it('exposes the latest generation and tombstone version to the Control UI', async () => {+ operatorLinkSvc.getLinkForControlAdmin.mockResolvedValue({+ desktopUserId: 'desktop-user-id',+ controlAdminId: 'target-admin-id',+ source: 'initial_setup',+ createdAt: new Date('2026-08-10T12:00:00.000Z'),+ state: 'revoked',+ generation: 1,+ rowVersion: 2,+ revocationReason: 'control-ui-revoke',+ })++ const res = await request(createTestApp())+ .get('/admin/control-admins/target-admin-id/gfs-operator-link')+ .expect(200)++ expect(res.body).toEqual({+ gfsOperatorLinkStatus: 'revoked',+ controlAdminId: 'target-admin-id',+ desktopUserId: 'desktop-user-id',+ generation: 1,+ rowVersion: 2,+ revocationReason: 'control-ui-revoke',})})@@ -166,7 +201,44 @@ describe('routes/adminControlAdmins', () => {gfsOperatorLinkStatus: 'revoked',controlAdminId: targetAdminId,desktopUserId: null,+ generation: null,+ rowVersion: null,})expect(operatorLinkSvc.unlink).not.toHaveBeenCalled()})++ it('reactivates the server-resolved revoked generation with its row version', async () => {+ operatorLinkSvc.reactivate.mockResolvedValue({+ reactivated: true,+ link: {+ desktopUserId: 'desktop-user-id',+ controlAdminId: 'target-admin-id',+ source: 'initial_setup',+ createdAt: new Date('2026-08-10T12:00:00.000Z'),+ state: 'active',+ generation: 2,+ rowVersion: 1,+ },+ })++ const res = await request(createTestApp())+ .post('/admin/control-admins/target-admin-id/gfs-operator-link/reactivate')+ .send({ rowVersion: 2, reason: 'control-ui-reactivate' })+ .expect(200)++ expect(res.body).toEqual({+ reactivated: true,+ gfsOperatorLinkStatus: 'active',+ controlAdminId: 'target-admin-id',+ desktopUserId: 'desktop-user-id',+ generation: 2,+ rowVersion: 1,+ })+ expect(operatorLinkSvc.reactivate).toHaveBeenCalledWith({+ controlAdminId: 'target-admin-id',+ operatorSub: 'current-admin-id',+ rowVersion: 2,+ reason: 'control-ui-reactivate',+ })+ })})diff --git a/control-api/test/services.directory.teams.test.ts b/control-api/test/services.directory.teams.test.tsindex ffa3146c5..734ab3208 100644--- a/control-api/test/services.directory.teams.test.ts+++ b/control-api/test/services.directory.teams.test.ts@@ -262,6 +262,7 @@ describe('services/directory team management unit tests', () => {dbMocks.txQuery.mockResolvedValueOnce({ rows: [{ x: 1 }], rowCount: 1 })dbMocks.txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })dbMocks.txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })+ dbMocks.txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })dbMocks.txQuery.mockResolvedValueOnce({ rows: [{ id: 'u1' }], rowCount: 1 })await expect(adminDeleteUser('u1')).resolves.toEqual({ ok: true, id: 'u1' })@@ -273,22 +274,41 @@ describe('services/directory team management unit tests', () => {dbMocks.txQuery.mockResolvedValueOnce({ rows: [{ x: 1 }], rowCount: 1 })dbMocks.txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })dbMocks.txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })+ dbMocks.txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })dbMocks.txQuery.mockResolvedValueOnce({ rows: [{ id: 'u1' }], rowCount: 1 })await expect(adminDeleteUser('u1')).resolves.toEqual({ ok: true, id: 'u1' })expect(dbMocks.txQuery).toHaveBeenNthCalledWith(2,- expect.stringContaining('UPDATE workflow_approval_medium_accounts'),+ expect.stringContaining('FROM gfs_desktop_operator_links'),['u1'])expect(dbMocks.txQuery).toHaveBeenNthCalledWith(3,- expect.stringContaining('UPDATE workflow_approval_medium_challenges'),+ expect.stringContaining('UPDATE workflow_approval_medium_accounts'),['u1'])expect(dbMocks.txQuery).toHaveBeenNthCalledWith(4,+ expect.stringContaining('UPDATE workflow_approval_medium_challenges'),+ ['u1']+ )+ expect(dbMocks.txQuery).toHaveBeenNthCalledWith(+ 5,expect.stringContaining('DELETE FROM users'),['u1'])})++ it('refuses the legacy hard-delete when operator-link history is retained', async () => {+ dbMocks.txQuery.mockResolvedValueOnce({ rows: [{ x: 1 }], rowCount: 1 })+ dbMocks.txQuery.mockResolvedValueOnce({ rows: [{ '?column?': 1 }], rowCount: 1 })++ await expect(adminDeleteUser('u1')).resolves.toEqual({+ error: 'gfs_operator_link_history_retained',+ })+ expect(dbMocks.txQuery).toHaveBeenCalledTimes(2)+ expect(dbMocks.txQuery).not.toHaveBeenCalledWith(expect.stringContaining('DELETE FROM users'), [+ 'u1',+ ])+ })})diff --git a/control-api/test/services.gfsDesktopOperatorLinkService.test.ts b/control-api/test/services.gfsDesktopOperatorLinkService.test.tsindex d78838d90..89e24bcde 100644--- a/control-api/test/services.gfsDesktopOperatorLinkService.test.ts+++ b/control-api/test/services.gfsDesktopOperatorLinkService.test.ts@@ -59,6 +59,7 @@ describe('GfsDesktopOperatorLinkService', () => {controlAdminId: CONTROL_ADMIN_ID,operatorSub: OPERATOR_ID,source: 'initial_setup',+ requestId: 'request-1',})expect(result).toEqual({@@ -78,6 +79,7 @@ describe('GfsDesktopOperatorLinkService', () => {expect(appendPermissionEvents).toHaveBeenCalledWith(expect.anything(), {operatorSub: OPERATOR_ID,operatorKind: 'control_admin',+ requestId: 'request-1',changes: [{action: 'grant',@@ -86,7 +88,7 @@ describe('GfsDesktopOperatorLinkService', () => {subject: { kind: 'user', id: DESKTOP_USER_ID },sourceAuditRef: 'gfs_desktop_operator_link_source:initial_setup',status: 'linked',- detailRef: `desktop_user_id:${DESKTOP_USER_ID};control_admin_id:${CONTROL_ADMIN_ID};source:initial_setup`,+ detailRef: `event:link.created;desktop_user_id:${DESKTOP_USER_ID};control_admin_id:${CONTROL_ADMIN_ID};source:initial_setup`,},],})@@ -121,6 +123,86 @@ describe('GfsDesktopOperatorLinkService', () => {expect(appendPermissionEvents).not.toHaveBeenCalled()})+ it('does not recreate a generation from retained history; reactivation is explicit', async () => {+ txQuery+ .mockResolvedValueOnce({ rows: [{ id: DESKTOP_USER_ID }], rowCount: 1 })+ .mockResolvedValueOnce({ rows: [{ id: CONTROL_ADMIN_ID, status: 'active' }], rowCount: 1 })+ .mockResolvedValueOnce({+ rows: [+ {+ ...storedLink(),+ id: '66666666-6666-4666-8666-666666666666',+ lineage_id: '77777777-7777-4777-8777-777777777777',+ generation: 1,+ state: 'revoked',+ row_version: 2,+ revoked_at: new Date('2026-08-10T12:05:00.000Z'),+ revocation_reason: 'control_ui_revoke',+ },+ ],+ rowCount: 1,+ })++ await expect(+ service.link({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ source: 'initial_setup',+ })+ ).rejects.toMatchObject({ code: 'link_conflict' })+ expect(appendPermissionEvents).not.toHaveBeenCalled()+ expect(txQuery).toHaveBeenCalledTimes(3)+ })++ it('retires a parent only after appending the governed revoke evidence', async () => {+ txQuery+ .mockResolvedValueOnce({+ rows: [+ {+ ...storedLink(),+ id: '88888888-8888-4888-8888-888888888888',+ lineage_id: '99999999-9999-4999-8999-999999999999',+ generation: 1,+ state: 'active',+ row_version: 1,+ },+ ],+ rowCount: 1,+ })+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })++ await expect(+ service.retireParentInTransaction({ query: txQuery } as DbClient, {+ kind: 'desktop_user',+ parentId: DESKTOP_USER_ID,+ operatorSub: OPERATOR_ID,+ reason: 'account_retired',+ requestId: 'request-2',+ })+ ).resolves.toBe(true)++ expect(appendPermissionEvents).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ operatorSub: OPERATOR_ID,+ requestId: 'request-2',+ changes: expect.arrayContaining([+ expect.objectContaining({+ detailRef: expect.stringContaining('event:link.revoked'),+ }),+ expect.objectContaining({+ detailRef: expect.stringContaining('event:parent.retired'),+ }),+ ]),+ })+ )+ expect(appendPermissionEvents.mock.invocationCallOrder[0]).toBeLessThan(+ txQuery.mock.invocationCallOrder[1]!+ )+ expect(txQuery.mock.calls[1]?.[0]).toContain('row_version = $4')+ })+it.each([{label: 'Desktop user',@@ -347,6 +429,40 @@ describe('GfsDesktopOperatorLinkService', () => {})})+ it('preserves generation metadata and normalizes PostgreSQL bigint row versions', async () => {+ const tombstoneId = '66666666-6666-4666-8666-666666666666'+ const lineageId = '77777777-7777-4777-8777-777777777777'+ readQuery.mockResolvedValueOnce({+ rows: [+ {+ id: tombstoneId,+ lineage_id: lineageId,+ generation: 2,+ predecessor_id: '88888888-8888-4888-8888-888888888888',+ row_version: '3',+ state: 'revoked',+ revoked_at: new Date('2026-08-10T12:30:00.000Z'),+ revocation_reason: 'control_ui_revoke',+ ...storedLink(),+ desktop_user_exists: true,+ control_admin_exists: true,+ control_admin_status: 'active',+ },+ ],+ rowCount: 1,+ })++ await expect(service.getLinkForControlAdmin(CONTROL_ADMIN_ID)).resolves.toMatchObject({+ id: tombstoneId,+ lineageId,+ generation: 2,+ predecessorId: '88888888-8888-4888-8888-888888888888',+ state: 'revoked',+ rowVersion: 3,+ revocationReason: 'control_ui_revoke',+ })+ })+it('returns null for an unlinked Control Admin and fails closed on a mismatched row', async () => {readQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })await expect(service.getLinkForControlAdmin(CONTROL_ADMIN_ID)).resolves.toBeNull()@@ -367,7 +483,7 @@ describe('GfsDesktopOperatorLinkService', () => {})})- it('appends the governed unlink evidence before deleting current state', async () => {+ it('appends governed revoke evidence before transitioning the active generation to revoked', async () => {txQuery.mockResolvedValueOnce({ rows: [storedLink()], rowCount: 1 }).mockResolvedValueOnce({ rows: [], rowCount: 1 })@@ -378,13 +494,16 @@ describe('GfsDesktopOperatorLinkService', () => {controlAdminId: CONTROL_ADMIN_ID,operatorSub: OPERATOR_ID,})- ).resolves.toEqual({+ ).resolves.toMatchObject({unlinked: true,link: {desktopUserId: DESKTOP_USER_ID,controlAdminId: CONTROL_ADMIN_ID,source: 'initial_setup',createdAt: CREATED_AT,+ state: 'revoked',+ rowVersion: 2,+ revocationReason: 'operator_revoked',},})@@ -405,7 +524,8 @@ describe('GfsDesktopOperatorLinkService', () => {expect(appendPermissionEvents.mock.invocationCallOrder[0]).toBeLessThan(txQuery.mock.invocationCallOrder[1]!)- expect(txQuery.mock.calls[1]?.[0]).toContain('DELETE FROM gfs_desktop_operator_links')+ expect(txQuery.mock.calls[1]?.[0]).toContain('UPDATE gfs_desktop_operator_links')+ expect(txQuery.mock.calls[1]?.[0]).toContain("state = 'revoked'")})it('does not delete current state when governed unlink evidence fails', async () => {@@ -435,4 +555,111 @@ describe('GfsDesktopOperatorLinkService', () => {expect(appendPermissionEvents).not.toHaveBeenCalled()expect(txQuery).toHaveBeenCalledTimes(1)})++ it('reactivates from the latest tombstone by inserting generation N+1', async () => {+ const tombstoneId = '66666666-6666-4666-8666-666666666666'+ const lineageId = '77777777-7777-4777-8777-777777777777'+ const successorId = '99999999-9999-4999-8999-999999999999'+ txQuery+ .mockResolvedValueOnce({ rows: [], rowCount: 0 })+ .mockResolvedValueOnce({+ rows: [+ {+ id: tombstoneId,+ lineage_id: lineageId,+ generation: 1,+ row_version: '2',+ user_id: DESKTOP_USER_ID,+ control_admin_id: CONTROL_ADMIN_ID,+ source: 'initial_setup',+ state: 'revoked',+ created_at: CREATED_AT,+ },+ ],+ rowCount: 1,+ })+ .mockResolvedValueOnce({+ rows: [{ desktop_user_exists: true, control_admin_status: 'active' }],+ rowCount: 1,+ })+ .mockResolvedValueOnce({+ rows: [+ {+ id: successorId,+ lineage_id: lineageId,+ generation: 2,+ predecessor_id: tombstoneId,+ row_version: 1,+ user_id: DESKTOP_USER_ID,+ control_admin_id: CONTROL_ADMIN_ID,+ source: 'initial_setup',+ state: 'active',+ created_at: CREATED_AT,+ },+ ],+ rowCount: 1,+ })++ await expect(+ service.reactivate({+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ rowVersion: 2,+ reason: 'control_ui_reactivate',+ })+ ).resolves.toMatchObject({+ reactivated: true,+ link: {+ id: successorId,+ lineageId,+ generation: 2,+ predecessorId: tombstoneId,+ state: 'active',+ rowVersion: 1,+ },+ })+ expect(txQuery.mock.calls[3]?.[0]).toContain('INSERT INTO gfs_desktop_operator_links')+ expect(appendPermissionEvents).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ operatorSub: OPERATOR_ID,+ changes: [+ expect.objectContaining({ detailRef: expect.stringContaining('event:link.reactivated') }),+ ],+ })+ )+ })++ it('rejects a stale reactivation replay after a successor is already active', async () => {+ const predecessorId = '66666666-6666-4666-8666-666666666666'+ txQuery+ .mockResolvedValueOnce({+ rows: [+ {+ id: '99999999-9999-4999-8999-999999999999',+ lineage_id: '77777777-7777-4777-8777-777777777777',+ generation: 2,+ predecessor_id: predecessorId,+ row_version: 1,+ state: 'active',+ user_id: DESKTOP_USER_ID,+ control_admin_id: CONTROL_ADMIN_ID,+ source: 'initial_setup',+ created_at: CREATED_AT,+ },+ ],+ rowCount: 1,+ })+ .mockResolvedValueOnce({ rows: [{ state: 'revoked', row_version: '4' }], rowCount: 1 })++ await expect(+ service.reactivate({+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ rowVersion: 2,+ reason: 'control_ui_reactivate',+ })+ ).rejects.toMatchObject({ code: 'link_conflict' })+ expect(appendPermissionEvents).not.toHaveBeenCalled()+ })})diff --git a/control-ui/components/ControlAdminsPanel/index.tsx b/control-ui/components/ControlAdminsPanel/index.tsxindex 6addc4d06..63727a088 100644--- a/control-ui/components/ControlAdminsPanel/index.tsx+++ b/control-ui/components/ControlAdminsPanel/index.tsx@@ -16,6 +16,7 @@ import {cancelControlAdminInvitation,deleteControlAdmin,getControlAdmins,+ reactivateControlAdminGfsOperatorLink,revokeControlAdminGfsOperatorLink,} from '@lib/api'import type { ControlAdminsPanelProps } from './types'@@ -47,6 +48,7 @@ export function ControlAdminsPanel({const [cancellingInvitationId, setCancellingInvitationId] = useState<string | null>(null)const [deletingAdminId, setDeletingAdminId] = useState<string | null>(null)const [revokingGfsLinkAdminId, setRevokingGfsLinkAdminId] = useState<string | null>(null)+ const [reactivatingGfsLinkAdminId, setReactivatingGfsLinkAdminId] = useState<string | null>(null)const [error, setError] = useState('')const normalizedSearch = searchInput.trim().toLowerCase()@@ -195,13 +197,27 @@ export function ControlAdminsPanel({setRevokingGfsLinkAdminId(admin.id)setError('')try {- const result = await revokeControlAdminGfsOperatorLink(admin.id)+ const link = admin.gfsOperatorLink+ if (!link || link.status !== 'active' || !Number.isInteger(link.rowVersion)) {+ throw new Error('The current GFS operator-link version is unavailable; refresh and retry.')+ }+ const result = await revokeControlAdminGfsOperatorLink(admin.id, {+ rowVersion: link.rowVersion,+ reason: 'control_ui_revoke',+ })setAdmins(current =>current.map(item =>item.id === admin.id? {...item,- gfsOperatorLink: null,+ gfsOperatorLink: item.gfsOperatorLink+ ? {+ ...item.gfsOperatorLink,+ status: 'revoked',+ rowVersion:+ result.rowVersion ?? Number(item.gfsOperatorLink.rowVersion ?? 0) + 1,+ }+ : null,gfsOperatorLinkStatus: 'revoked',}: item@@ -224,6 +240,63 @@ export function ControlAdminsPanel({}}+ async function handleReactivateGfsOperatorLink(admin: ControlAdminListItem) {+ const label = admin.email ? `${admin.username} (${admin.email})` : admin.username+ const shouldReactivate = await confirm({+ title: 'Reactivate Desktop GFS operator access',+ message: `Reactivate Desktop GFS operator access for ${label}? This creates a new audited link generation without changing passwords or unrelated access.`,+ confirmLabel: 'Reactivate access',+ tone: 'default',+ })+ if (!shouldReactivate) return++ const link = admin.gfsOperatorLink+ if (!link || link.status !== 'revoked' || !Number.isInteger(link.rowVersion)) {+ setError('The revoked GFS operator-link version is unavailable; refresh and retry.')+ return+ }+ setReactivatingGfsLinkAdminId(admin.id)+ setError('')+ try {+ const result = await reactivateControlAdminGfsOperatorLink(admin.id, {+ rowVersion: link.rowVersion,+ reason: 'control_ui_reactivate',+ })+ setAdmins(current =>+ current.map(item =>+ item.id === admin.id+ ? {+ ...item,+ gfsOperatorLink: item.gfsOperatorLink+ ? {+ ...item.gfsOperatorLink,+ status: result.gfsOperatorLinkStatus === 'active' ? 'active' : 'revoked',+ generation: result.generation ?? item.gfsOperatorLink.generation,+ rowVersion: result.rowVersion ?? item.gfsOperatorLink.rowVersion,+ }+ : null,+ gfsOperatorLinkStatus: result.gfsOperatorLinkStatus,+ }+ : item+ )+ )+ showToast(+ result.reactivated+ ? 'Desktop GFS operator access reactivated.'+ : 'Desktop GFS operator access remains revoked.',+ { tone: 'success' }+ )+ } catch (reactivateError) {+ setError(+ reactivateError instanceof Error+ ? reactivateError.message+ : 'Failed to reactivate Desktop GFS operator access'+ )+ } finally {+ setReactivatingGfsLinkAdminId(null)+ }+ }+function openMemberAccess(admin: ControlAdminListItem) {if (admin.memberId) {router.push(CONTROL_ROUTES.usersAndTeams.user(admin.memberId))@@ -331,7 +404,9 @@ export function ControlAdminsPanel({? 'Active': admin.gfsOperatorLink.status === 'inactive_admin'? 'Inactive admin'- : 'Error'}+ : admin.gfsOperatorLink.status === 'revoked'+ ? 'Revoked'+ : 'Error'}</div><div className="cu-table__cell-muted">Desktop user: {admin.gfsOperatorLink.desktopUserId}@@ -342,6 +417,9 @@ export function ControlAdminsPanel({<div className="cu-table__cell-muted">Source: {admin.gfsOperatorLink.source}</div>+ <div className="cu-table__cell-muted">+ Generation: {admin.gfsOperatorLink.generation ?? 'Unknown'}+ </div></div>) : (<span data-testid={`gfs-operator-link-${admin.id}`}>Revoked</span>@@ -372,7 +450,7 @@ export function ControlAdminsPanel({><IconUsers /></button>- {admin.gfsOperatorLink && admin.gfsOperatorLink.status !== 'error' ? (+ {admin.gfsOperatorLink?.status === 'active' ? (<buttontype="button"className="cu-btn cu-btn--danger"@@ -388,6 +466,24 @@ export function ControlAdminsPanel({{revokingGfsLinkAdminId === admin.id ? 'Revoking...' : 'Revoke GFS'}</button>) : null}+ {admin.gfsOperatorLink?.status === 'revoked' ? (+ <button+ type="button"+ className="cu-btn"+ disabled={reactivatingGfsLinkAdminId === admin.id}+ onClick={() => void handleReactivateGfsOperatorLink(admin)}+ aria-label={+ reactivatingGfsLinkAdminId === admin.id+ ? `Reactivating Desktop GFS operator access for ${label}`+ : `Reactivate Desktop GFS operator access for ${label}`+ }+ title="Create a new audited GFS operator-link generation"+ >+ {reactivatingGfsLinkAdminId === admin.id+ ? 'Reactivating...'+ : 'Reactivate GFS'}+ </button>+ ) : null}{currentAdmin ? (<buttontype="button"diff --git a/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx b/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsxindex f215be260..71e26c80c 100644--- a/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx+++ b/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx@@ -1,6 +1,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'-import { getControlAdmins, revokeControlAdminGfsOperatorLink } from '@lib/api'+import {+ getControlAdmins,+ reactivateControlAdminGfsOperatorLink,+ revokeControlAdminGfsOperatorLink,+} from '@lib/api'import { ControlAdminsPanel } from '../ControlAdminsPanel'const confirmMock = vi.hoisted(() => vi.fn())@@ -35,6 +39,7 @@ vi.mock('@lib/api', async () => {return {...actual,getControlAdmins: vi.fn(),+ reactivateControlAdminGfsOperatorLink: vi.fn(),revokeControlAdminGfsOperatorLink: vi.fn(),}})@@ -45,6 +50,9 @@ const LINK = {source: 'initial_setup' as const,createdAt: '2026-08-10T12:00:00.000Z',status: 'active' as const,+ generation: 1,+ rowVersion: 1,+ revocationReason: null,}describe('ControlAdminsPanel GFS operator link lifecycle', () => {@@ -71,6 +79,16 @@ describe('ControlAdminsPanel GFS operator link lifecycle', () => {gfsOperatorLinkStatus: 'revoked',controlAdminId: 'admin-1',desktopUserId: LINK.desktopUserId,+ generation: 1,+ rowVersion: 2,+ })+ vi.mocked(reactivateControlAdminGfsOperatorLink).mockResolvedValue({+ reactivated: true,+ gfsOperatorLinkStatus: 'active',+ controlAdminId: 'admin-1',+ desktopUserId: LINK.desktopUserId,+ generation: 2,+ rowVersion: 1,})})@@ -96,7 +114,12 @@ describe('ControlAdminsPanel GFS operator link lifecycle', () => {}))- await waitFor(() => expect(revokeControlAdminGfsOperatorLink).toHaveBeenCalledWith('admin-1'))+ await waitFor(() =>+ expect(revokeControlAdminGfsOperatorLink).toHaveBeenCalledWith('admin-1', {+ rowVersion: 1,+ reason: 'control_ui_revoke',+ })+ )expect(showToastMock).toHaveBeenCalledWith('Desktop GFS operator access revoked.', {tone: 'success',})@@ -115,4 +138,40 @@ describe('ControlAdminsPanel GFS operator link lifecycle', () => {await waitFor(() => expect(confirmMock).toHaveBeenCalled())expect(revokeControlAdminGfsOperatorLink).not.toHaveBeenCalled()})++ it('reactivates a retained revoked generation through the visible Control UI action', async () => {+ vi.mocked(getControlAdmins).mockResolvedValueOnce({+ admins: [+ {+ id: 'admin-1',+ username: 'initial-admin',+ email: '[email protected]',+ memberId: LINK.desktopUserId,+ status: 'active',+ gfsOperatorLink: { ...LINK, status: 'revoked', rowVersion: 2 },+ gfsOperatorLinkStatus: 'revoked',+ lastLoginAt: null,+ createdAt: '2026-08-10T11:00:00.000Z',+ },+ ],+ invitations: [],+ })++ render(<ControlAdminsPanel />)+ const reactivateButton = await screen.findByRole('button', {+ name: 'Reactivate Desktop GFS operator access for initial-admin ([email protected])',+ })+ fireEvent.click(reactivateButton)++ await waitFor(() =>+ expect(reactivateControlAdminGfsOperatorLink).toHaveBeenCalledWith('admin-1', {+ rowVersion: 2,+ reason: 'control_ui_reactivate',+ })+ )+ expect(showToastMock).toHaveBeenCalledWith('Desktop GFS operator access reactivated.', {+ tone: 'success',+ })+ expect(screen.getByTestId('gfs-operator-link-admin-1')).toHaveTextContent('Active')+ })})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex 09696fe0a..726720f72 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -552,7 +552,10 @@ export type ControlAdminListItem = {controlAdminId: stringsource: 'initial_setup' | 'unknown'createdAt: string | null- status: 'active' | 'inactive_admin' | 'error'+ status: 'active' | 'inactive_admin' | 'revoked' | 'error'+ generation?: number | null+ rowVersion?: number | null+ revocationReason?: string | null} | nullgfsOperatorLinkStatus?: 'active' | 'inactive_admin' | 'revoked' | 'error'lastLoginAt: string | null@@ -644,20 +647,53 @@ export async function deleteControlAdmin(adminId: string): Promise<{ deleted: tr}>}-export async function revokeControlAdminGfsOperatorLink(adminId: string): Promise<{+export async function revokeControlAdminGfsOperatorLink(+ adminId: string,+ payload: { rowVersion?: number | null; reason?: string } = {}+): Promise<{revoked: booleangfsOperatorLinkStatus: 'revoked'controlAdminId: stringdesktopUserId: string | null+ generation?: number | null+ rowVersion?: number | null}> {return apiSend('DELETE',- `/api/v1/admin/control-admins/${encodeURIComponent(adminId)}/gfs-operator-link`+ `/api/v1/admin/control-admins/${encodeURIComponent(adminId)}/gfs-operator-link`,+ payload) as Promise<{revoked: booleangfsOperatorLinkStatus: 'revoked'controlAdminId: stringdesktopUserId: string | null+ generation?: number | null+ rowVersion?: number | null+ }>+}++export async function reactivateControlAdminGfsOperatorLink(+ adminId: string,+ payload: { rowVersion: number; reason: string }+): Promise<{+ reactivated: boolean+ gfsOperatorLinkStatus: 'active' | 'revoked'+ controlAdminId: string+ desktopUserId: string | null+ generation?: number | null+ rowVersion?: number | null+}> {+ return apiSend(+ 'POST',+ `/api/v1/admin/control-admins/${encodeURIComponent(adminId)}/gfs-operator-link/reactivate`,+ payload+ ) as Promise<{+ reactivated: boolean+ gfsOperatorLinkStatus: 'active' | 'revoked'+ controlAdminId: string+ desktopUserId: string | null+ generation?: number | null+ rowVersion?: number | null}>}diff --git a/deploy/scripts/run-control-api-db-migration.sh b/deploy/scripts/run-control-api-db-migration.shindex 52ded6871..642b1e78f 100755--- a/deploy/scripts/run-control-api-db-migration.sh+++ b/deploy/scripts/run-control-api-db-migration.sh@@ -583,13 +583,14 @@ verify_runtime_access_contract() {FROM expected_access expectedJOIN actual_relations actual USING (relation_name)CROSS JOIN LATERAL (- -- link_lifecycle deliberately permits only the explicit create/revoke- -- operations for current-state identity links; UPDATE stays denied.+ -- link_lifecycle deliberately permits create plus governed tombstone+ -- transitions. Physical DELETE remains denied so history cannot be+ -- erased by the runtime role.VALUES('SELECT', expected.access_profile != 'none'),('INSERT', expected.access_profile IN ('legacy_dml', 'upsert', 'append', 'link_lifecycle')),- ('UPDATE', expected.access_profile IN ('legacy_dml', 'upsert')),- ('DELETE', expected.access_profile IN ('legacy_dml', 'link_lifecycle')),+ ('UPDATE', expected.access_profile IN ('legacy_dml', 'upsert', 'link_lifecycle')),+ ('DELETE', expected.access_profile IN ('legacy_dml')),('TRUNCATE', false),('REFERENCES', false),('TRIGGER', false)diff --git a/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.global-setup.ts b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.global-setup.tsindex d81f4103c..a6f259c7f 100644--- a/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.global-setup.ts+++ b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.global-setup.ts@@ -3,8 +3,10 @@ import { createHash } from 'node:crypto'import fs from 'node:fs'import path from 'node:path'import {+ GFS_OPERATOR_SETUP_PATH,gfsOperatorRuntimeEvidencePath,requireGfsOperatorRunId,+ reserveGfsOperatorEvidenceRun,writeJsonAtomically,} from './gfsDesktopOperatorParityContract'import { validateBaseUrls } from './global-setup'@@ -100,6 +102,7 @@ function assertRepositoryHarness(): Array<{export default async function globalSetup(): Promise<void> {const runId = requireGfsOperatorRunId()+ reserveGfsOperatorEvidenceRun(runId)const profile = requiredEnvironment('MINIKUBE_PROFILE', [process.env.MINIKUBE_PROFILE])const context = requiredEnvironment('E2E_K8S_CONTEXT', [process.env.E2E_K8S_CONTEXT])if (profile !== context) {@@ -248,7 +251,7 @@ export default async function globalSetup(): Promise<void> {files: artifactFiles,},bootstrap: {- entryPoint: '/admin/auth/setup',+ entryPoint: GFS_OPERATOR_SETUP_PATH,expectedStatus: 200,singleUse: true,positiveUiEvidence: false,diff --git a/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.ts b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.tsindex 699227a55..86a98c812 100644--- a/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.ts+++ b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.ts@@ -1,5 +1,6 @@import type { Locator, Page } from '@playwright/test'import { UUID_RE } from '../../../tests/e2e/gfsFixtureCore'+import { GFS_OPERATOR_SETUP_PATH } from './gfsDesktopOperatorParityContract'import { type GfsResourceRow, expect, test } from './helpers/gfsDesktopOperatorParityFixtures'async function expectToast(page: Page, message: string): Promise<void> {@@ -81,7 +82,7 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {.poll(() => operatorJourney.readOperatorLink(), {timeout: 30_000,intervals: [250, 500, 1_000],- message: 'waiting for /admin/auth/setup to persist its exact Desktop operator link',+ message: `waiting for ${GFS_OPERATOR_SETUP_PATH} to persist its exact Desktop operator link`,}).toMatchObject({ controlAdminId: setup.controlAdminId, source: 'initial_setup' })@@ -428,18 +429,27 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {await expect.poll(() => operatorJourney.operatorLinkCount()).toBe(0)operatorJourney.deniedAuditFloor = operatorJourney.auditFloor()- await page.getByTestId('gfs-create-folder-action').click()- const form = page.getByRole('form', { name: 'Create folder' })- await form.getByLabel('Folder name').fill(operatorJourney.names.deniedFolder)- await form.getByRole('button', { name: 'Create folder' }).click()- const denial = page.getByTestId('gfs-mutation-error-unauthorized')+ // Keep the user-visible direct-access dialog open across the Control UI+ // action. Its resolve request is the next same-session Desktop request and+ // must close the dialog while clearing all stale operator controls.+ await page.getByRole('button', { name: 'Open GFS link' }).click()+ const linkDialog = page.getByRole('dialog', { name: 'Open GFS link' })+ await expect(linkDialog).toBeVisible()+ await linkDialog+ .getByLabel('gfs URI')+ .fill(`gfs://main/${operatorJourney.rootResourceId!.replace(/-/g, '')}`)+ await linkDialog.getByRole('button', { name: 'Open', exact: true }).click()++ const denial = page.getByTestId('gfs-error-unauthorized')await expect(denial).toBeVisible({ timeout: 30_000 })await expect(denial).toHaveAttribute('aria-label', 'File access is not authorized')await expect(denial).toContainText('Your current Desktop session cannot access this location. Sign in again or contact an administrator.')+ await expect(linkDialog).toHaveCount(0)await expect(page.getByTestId('gfs-create-folder-action')).toHaveCount(0)await expect(page.getByTestId('gfs-upload-action')).toHaveCount(0)+ await expect(page.getByTestId('gfs-manage-access-action')).toHaveCount(0)await expect.poll(() =>operatorJourney.readResource(@@ -448,15 +458,67 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {)).toBeNull()++ const reactivate = controlPage.getByRole('button', {+ name: `Reactivate Desktop GFS operator access for ${operatorJourney.operatorUsername} (${operatorJourney.operatorEmail})`,+ })+ await expect(reactivate).toBeVisible()+ await reactivate.click()+ const reactivateConfirm = controlPage.getByRole('alertdialog', {+ name: 'Reactivate Desktop GFS operator access',+ })+ await expect(reactivateConfirm).toBeVisible()+ await reactivateConfirm.getByRole('button', { name: 'Reactivate access', exact: true }).click()+ await expect(+ controlPage.getByText('Desktop GFS operator access reactivated.', { exact: true })+ ).toBeVisible({ timeout: 30_000 })+ await expect(controlPage.getByTestId(`gfs-operator-link-${link.controlAdminId}`)).toHaveText(+ 'Active'+ )++ // Retry is the user-visible next Desktop request. It cannot restore a+ // client capability; the reactivated server link must return the root.+ await page.getByTestId('gfs-retry-access-action').click()+ await expect(page.getByTestId('gfs-view-operator')).toBeVisible({ timeout: 30_000 })+ await expect(page.getByTestId('gfs-root-operator')).toHaveAttribute(+ 'data-resource-id',+ operatorJourney.rootResourceId!+ )+ await expect(page.getByTestId('gfs-create-folder-action')).toBeVisible()+ const restoredFolder = await createRootFolder(+ page,+ operatorJourney.names.auditDeniedFolder,+ () =>+ operatorJourney.readResource(+ operatorJourney.rootResourceId!,+ operatorJourney.names.auditDeniedFolder+ )+ )+ operatorJourney.resources.set('auditDeniedFolder', restoredFolder)++ const secondRevoke = controlPage.getByRole('button', {+ name: `Revoke Desktop GFS operator access for ${operatorJourney.operatorUsername} (${operatorJourney.operatorEmail})`,+ })+ await expect(secondRevoke).toBeVisible()+ await secondRevoke.click()+ await controlPage+ .getByRole('alertdialog', { name: 'Revoke Desktop GFS operator access' })+ .getByRole('button', { name: 'Revoke access', exact: true })+ .click()+ await expect(+ controlPage.getByText('Desktop GFS operator access revoked.', { exact: true })+ ).toBeVisible({ timeout: 30_000 })+ await expect(controlPage.getByTestId(`gfs-operator-link-${link.controlAdminId}`)).toHaveText(+ 'Revoked'+ )+ await expect.poll(() => operatorJourney.operatorLinkCount()).toBe(0)})test('@gfs-operator/audit-correlation successful and denied Desktop requests preserve exact actor and request IDs', async ({operatorJourney,}) => {const link = operatorJourney.operatorLink!- const page = operatorJourney.operatorPage!const controlPage = operatorJourney.controlPage!- await expect(page.getByTestId('gfs-mutation-error-unauthorized')).toBeVisible()await expect(controlPage).toHaveURL(/\/users-and-teams\/admins(?:\?|$)/)await expect(controlPage.getByTestId(`gfs-operator-link-${link.controlAdminId}`)).toHaveText('Revoked'@@ -510,7 +572,7 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {row.actorOnBehalfOf === null &&row.desktopUserId === link.desktopUserId &&row.authoritySource === 'user-session' &&- row.op === 'write' &&+ row.op === 'read' &&row.outcome === 'deny' &&row.recordType === 'authorization_decision' &&row.mutationOutcome === null &&diff --git a/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts b/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.tsindex 8c20c9d9d..a50072d6f 100644--- a/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts+++ b/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts@@ -36,6 +36,7 @@ export interface GfsOperatorContractVerdict {}const RUN_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/+export const GFS_OPERATOR_SETUP_PATH = '/api/v1/admin/auth/setup'export function requireGfsOperatorRunId(value = process.env.E2E_GFS_OPERATOR_RUN_ID): string {const runId = value?.trim() ?? ''@@ -64,6 +65,34 @@ export function gfsOperatorResultSummaryPath(runId = requireGfsOperatorRunId()):return path.join(gfsOperatorEvidenceDirectory(runId), 'required-scenarios.json')}+/**+ * Creates the evidence directory exactly once. A run id is an immutable+ * reservation, not a filename prefix: reusing it must fail before a browser,+ * runtime-evidence record, or Playwright report can replace prior evidence.+ */+export function reserveGfsOperatorEvidenceRun(runId = requireGfsOperatorRunId()): string {+ const evidenceDirectory = gfsOperatorEvidenceDirectory(runId)+ fs.mkdirSync(path.dirname(evidenceDirectory), { recursive: true })+ try {+ fs.mkdirSync(evidenceDirectory)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {+ throw new Error(+ `[GFS-OPERATOR-E2E] evidence run id ${runId} is already reserved at ${evidenceDirectory}; choose a new E2E_GFS_OPERATOR_RUN_ID.`+ )+ }+ throw error+ }+ writeJsonAtomically(path.join(evidenceDirectory, 'attempt-manifest.json'), {+ schemaVersion: 1,+ suite: 'gfs-desktop-operator-parity',+ runId,+ reservedAt: new Date().toISOString(),+ immutable: true,+ })+ return evidenceDirectory+}+export function scenarioIdFromTitle(title: string): GfsOperatorScenarioId | null {const matches = GFS_OPERATOR_REQUIRED_SCENARIOS.filter(id => title === id || title.startsWith(`${id} `)@@ -120,8 +149,16 @@ export function evaluateGfsOperatorScenarioResults(}export function writeJsonAtomically(filePath: string, value: unknown): void {- fs.mkdirSync(path.dirname(filePath), { recursive: true })const temporaryPath = `${filePath}.${process.pid}.tmp`- fs.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })- fs.renameSync(temporaryPath, filePath)+ try {+ fs.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, {+ mode: 0o600,+ flag: 'wx',+ })+ // `link` provides an exclusive finalization step. Unlike rename(2), it+ // never replaces a pre-existing destination if a second attempt races us.+ fs.linkSync(temporaryPath, filePath)+ } finally {+ if (fs.existsSync(temporaryPath)) fs.unlinkSync(temporaryPath)+ }}diff --git a/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts b/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.tsindex 0a8b9d929..6a367b5f4 100644--- a/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts+++ b/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts@@ -21,7 +21,10 @@ import {sqlLiteral,} from '../../../../tests/e2e/gfsFixtureCore'import { cleanupGfsFixture } from '../../../../tests/e2e/gfsResourceFixtures'-import { requireGfsOperatorRunId } from '../gfsDesktopOperatorParityContract'+import {+ GFS_OPERATOR_SETUP_PATH,+ requireGfsOperatorRunId,+} from '../gfsDesktopOperatorParityContract'import { openResourcesNavItem } from '../navigationHelpers'const DESKTOP_APP_ROOT = path.resolve(__dirname, '../../..')@@ -239,7 +242,7 @@ export class GfsDesktopOperatorJourney {// The service base remains root-scoped so the global setup can probe// /health; application routes are mounted under the production /api/v1// prefix and must use that supported path explicitly.- const response = await fetch(`${this.controlApiUrl}/api/v1/admin/auth/setup`, {+ const response = await fetch(`${this.controlApiUrl}${GFS_OPERATOR_SETUP_PATH}`, {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({@@ -256,12 +259,12 @@ export class GfsDesktopOperatorJourney {}if (response.status === 409) {throw new Error(- '[GFS-OPERATOR-E2E] /admin/auth/setup returned 409. This one-shot journey requires a fresh, branch-owned profile whose bootstrap has not been consumed; no database reset or link insertion is performed by the suite.'+ `[GFS-OPERATOR-E2E] ${GFS_OPERATOR_SETUP_PATH} returned 409. This one-shot journey requires a fresh, branch-owned profile whose bootstrap has not been consumed; no database reset or link insertion is performed by the suite.`)}if (response.status !== 200 || !UUID_RE.test(body.me?.id ?? '')) {throw new Error(- `[GFS-OPERATOR-E2E] /admin/auth/setup returned HTTP ${response.status}: ${body.error ?? JSON.stringify(body)}`+ `[GFS-OPERATOR-E2E] ${GFS_OPERATOR_SETUP_PATH} returned HTTP ${response.status}: ${body.error ?? JSON.stringify(body)}`)}expect(body.me).toMatchObject({diff --git a/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts b/desktop-app/test/gfsDesktopOperatorParityRunner.test.tsindex c384dd842..dffbadda5 100644--- a/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts+++ b/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts@@ -1,12 +1,24 @@-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'import {GFS_OPERATOR_REQUIRED_SCENARIOS,type GfsOperatorScenarioResult,evaluateGfsOperatorScenarioResults,+ gfsOperatorEvidenceDirectory,requireGfsOperatorRunId,+ reserveGfsOperatorEvidenceRun,scenarioIdFromTitle,} from './e2e-playwright/gfsDesktopOperatorParityContract'+const evidenceRoots: string[] = []++afterEach(() => {+ for (const root of evidenceRoots.splice(0)) fs.rmSync(root, { recursive: true, force: true })+ delete process.env.E2E_GFS_OPERATOR_EVIDENCE_DIR+})+function passedResults(): GfsOperatorScenarioResult[] {return GFS_OPERATOR_REQUIRED_SCENARIOS.map(id => ({ id, status: 'passed', title: id }))}@@ -19,6 +31,23 @@ describe('GFS Desktop operator Playwright gate', () => {expect(requireGfsOperatorRunId('run_1-fresh')).toBe('run_1-fresh')})+ it('reserves an immutable evidence run and rejects a colliding run id before execution', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gfs-operator-e2e-'))+ evidenceRoots.push(root)+ process.env.E2E_GFS_OPERATOR_EVIDENCE_DIR = root++ const directory = reserveGfsOperatorEvidenceRun('collision-proof')+ expect(directory).toBe(gfsOperatorEvidenceDirectory('collision-proof'))+ expect(fs.existsSync(path.join(directory, 'attempt-manifest.json'))).toBe(true)+ expect(() => reserveGfsOperatorEvidenceRun('collision-proof')).toThrow(/already reserved/)+ expect(+ JSON.parse(fs.readFileSync(path.join(directory, 'attempt-manifest.json'), 'utf8'))+ ).toMatchObject({+ runId: 'collision-proof',+ immutable: true,+ })+ })+it('recognizes only one exact required scenario prefix', () => {expect(scenarioIdFromTitle('@gfs-operator/setup-linked-operator visible login')).toBe('@gfs-operator/setup-linked-operator'diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsxindex 862cf99c0..0715609d6 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx@@ -86,6 +86,7 @@ function Probe() {<div data-testid="current-version">{ctrl.current?.version ?? 'none'}</div><div data-testid="crumbs">{ctrl.crumbs.map(crumb => crumb.name).join(' / ')}</div><div data-testid="view">{ctrl.view}</div>+ <div data-testid="access-state">{ctrl.accessState}</div><div data-testid="operator-root">{ctrl.isOperatorRoot ? 'yes' : 'no'}</div><div data-testid="accessible-count">{ctrl.accessibleResources.length}</div><div data-testid="accessible-error">{ctrl.accessibleError ?? 'none'}</div>@@ -110,6 +111,9 @@ function Probe() {<button type="button" onClick={() => ctrl.reset()}>reset browser</button>+ <button type="button" onClick={() => ctrl.retryAccess()}>+ retry access+ </button><button type="button" onClick={() => void ctrl.createFolder('Root docs')}>create folder current</button>@@ -421,6 +425,49 @@ describe('useGfsBrowserController', () => {expect(screen.getByTestId('current').textContent).toBe('none')})+ it('clears cached operator state after a 403 and retries only through fresh server discovery', async () => {+ const rootResourceId = '11111111-1111-1111-1111-111111111111'+ let active = true+ const listAccessible = vi.fn(async () => {+ if (!active) throw new Error('403 operator_link_inactive')+ return { items: [], nextCursor: null, rootResourceId, view: 'operator' as const }+ })+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible,+ resolve: vi.fn(),+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),+ affordances: vi.fn(async () => ({+ held: ['read', 'write'],+ canDelegate: true,+ grantableBits: ['read', 'write'],+ canCreateShare: true,+ })),+ },+ },+ })++ render(<Probe />, { wrapper: Harness })+ await waitFor(() => expect(screen.getByTestId('operator-root').textContent).toBe('yes'))++ active = false+ await act(async () => {+ screen.getByRole('button', { name: 'reset browser' }).click()+ })+ await waitFor(() => expect(screen.getByTestId('access-state').textContent).toBe('revoked'))+ expect(screen.getByTestId('current').textContent).toBe('none')+ expect(screen.getByTestId('accessible-count').textContent).toBe('0')++ active = true+ await act(async () => {+ screen.getByRole('button', { name: 'retry access' }).click()+ })+ await waitFor(() => expect(screen.getByTestId('operator-root').textContent).toBe('yes'))+ expect(listAccessible).toHaveBeenCalledTimes(3)+ })+it('refreshes cached affordances after permissions change outside Desktop', async () => {let held = ['read']const affordances = vi.fn(async () => ({diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.tsindex ce93d587a..d7d4f426e 100644--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts@@ -54,6 +54,7 @@ export interface GfsCrumb {}export type GfsBrowserView = 'operator' | 'shared'+export type GfsBrowserAccessState = 'active' | 'revoked'export interface GfsBrowserFailure {kind: 'uninitialized' | 'unauthorized' | 'upstream'@@ -158,6 +159,9 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {const [crumbs, setCrumbs] = useState<GfsCrumb[]>([])const [openError, setOpenError] = useState<string | null>(null)const [resolving, setResolving] = useState(false)+ // This is deliberately session-local. A 403 never becomes a persisted client+ // capability decision: a later server-backed request is the only way out.+ const [accessState, setAccessState] = useState<GfsBrowserAccessState>('active')const previousSessionScopeRef = useRef<string | null>(null)const current = crumbs.length ? crumbs[crumbs.length - 1] : null@@ -179,6 +183,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {if (previous !== null) {setCrumbs([])setOpenError(null)+ setAccessState('active')void queryClient.removeQueries({ queryKey: [...desktopQueryKeys.gfsRoot, previous] })}}, [queryClient, sessionScope])@@ -192,7 +197,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {}return listAccessible(DRIVE, pageParam)},- enabled: Boolean(sessionScope) && canListAccessibleResources,+ enabled: Boolean(sessionScope) && canListAccessibleResources && accessState === 'active',initialPageParam: undefined as string | undefined,getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,})@@ -243,7 +248,11 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {queryFn: ({ pageParam }) =>window.clerum.gfs.listChildren(current!.resourceId, DRIVE, pageParam),enabled:- Boolean(sessionScope) && Boolean(current) && currentIsDirectory && !current?.isDriveRoot,+ Boolean(sessionScope) &&+ Boolean(current) &&+ currentIsDirectory &&+ !current?.isDriveRoot &&+ accessState === 'active',initialPageParam: undefined as string | undefined,getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,})@@ -255,7 +264,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {DRIVE),queryFn: () => window.clerum.gfs.affordances(current!.resourceId, DRIVE),- enabled: Boolean(sessionScope) && Boolean(current),+ enabled: Boolean(sessionScope) && Boolean(current) && accessState === 'active',})const refreshAffordances = useCallback(async () => {const resourceId = current?.resourceId@@ -275,7 +284,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {DRIVE),queryFn: () => window.clerum.gfs.listGrants(current!.resourceId, DRIVE),- enabled: Boolean(sessionScope) && Boolean(current) && grantsListEnabled,+ enabled:+ Boolean(sessionScope) && Boolean(current) && grantsListEnabled && accessState === 'active',})const refreshGrants = useCallback(async () => {const resourceId = current?.resourceId@@ -296,8 +306,36 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {DRIVE),queryFn: () => window.clerum.gfs.listShares(current!.resourceId, DRIVE),- enabled: Boolean(sessionScope) && Boolean(current) && grantsListEnabled,+ enabled:+ Boolean(sessionScope) && Boolean(current) && grantsListEnabled && accessState === 'active',})+ const revokeAccess = useCallback(() => {+ setAccessState('revoked')+ setCrumbs([])+ setOpenError(null)+ // Remove every GFS response for this Desktop session. In particular, never+ // leave an operator root, ACL list, or affordance cached after a server+ // revocation response.+ queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })+ }, [queryClient])+ const retryAccess = useCallback(() => {+ // This does not restore a local capability. It only permits the normal+ // discovery request to run again, so an explicit server-side reactivation+ // remains the sole authority that can restore the operator root.+ setAccessState('active')+ }, [])+ const queryAuthorizationError = [+ accessibleQuery.error,+ childrenQuery.error,+ affordancesQuery.error,+ grantsQuery.error,+ sharesQuery.error,+ ]+ .map(error => (error ? toMessage(error) : null))+ .find(error => error !== null && describeGfsBrowserFailure(error).kind === 'unauthorized')+ useEffect(() => {+ if (queryAuthorizationError && accessState !== 'revoked') revokeAccess()+ }, [accessState, queryAuthorizationError, revokeAccess])const refreshShares = useCallback(async () => {const resourceId = current?.resourceIdif (!resourceId) return@@ -379,7 +417,9 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {const grants = useMemo<GfsGrantListItem[]>(() => grantsQuery.data ?? [], [grantsQuery.data])const shares = useMemo<GfsShareListItem[]>(() => sharesQuery.data ?? [], [sharesQuery.data])const accessibleErrorMessage =- rootContractError ?? (accessibleQuery.error ? toMessage(accessibleQuery.error) : null)+ accessState === 'revoked'+ ? 'operator_link_inactive'+ : (rootContractError ?? (accessibleQuery.error ? toMessage(accessibleQuery.error) : null))const accessibleNotice =sessionScope && !canListAccessibleResources? 'Automatic GFS discovery is not available in this desktop runtime. You can still open any GFS link you have.'@@ -443,13 +483,15 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {)return crumb} catch (error) {- setOpenError(toMessage(error))+ const message = toMessage(error)+ if (describeGfsBrowserFailure(message).kind === 'unauthorized') revokeAccess()+ else setOpenError(message)return false} finally {setResolving(false)}},- [operatorRoot]+ [operatorRoot, revokeAccess])const openChild = useCallback((child: GfsBrowserChild) => {@@ -523,6 +565,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {crumbs,current,view,+ accessState,isOperatorRoot: Boolean(current?.isDriveRoot),accessibleResources,items,@@ -553,6 +596,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {openChild,goToCrumb,reset,+ revokeAccess,+ retryAccess,refreshAffordances,grant,grants,diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsxindex d1ce8c8d2..1951f661c 100644--- a/desktop-app/ui/src/pages/FilesPage.tsx+++ b/desktop-app/ui/src/pages/FilesPage.tsx@@ -207,8 +207,10 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:[ctrl.sharesError])const mutationUnauthorized = mutationFailure?.kind === 'unauthorized'- const canWriteCurrent = !mutationUnauthorized && hasBit(affordances, 'write')- const canDeleteCurrent = !mutationUnauthorized && !isOperatorRoot && hasBit(affordances, 'delete')+ const accessRevoked = ctrl.accessState === 'revoked'+ const canWriteCurrent = !accessRevoked && !mutationUnauthorized && hasBit(affordances, 'write')+ const canDeleteCurrent =+ !accessRevoked && !mutationUnauthorized && !isOperatorRoot && hasBit(affordances, 'delete')const currentIsFolder = current?.kind === 'directory'const currentIsFile = current?.kind === 'file'const currentPreviewAvailable = currentIsFile && isGfsPreviewFile(current?.name ?? '')@@ -240,10 +242,23 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:setMutationFailure(null)}, [current?.resourceId, view])+ useEffect(() => {+ if (!accessRevoked) return+ // A permission transition invalidates every operator-only surface in this+ // Electron session. A later retry is server-backed through the controller.+ setManageOpen(false)+ setOpenLinkOpen(false)+ setCreateFolderOpen(false)+ setRenameOpen(false)+ setDeleteOpen(false)+ setFilePreview(null)+ }, [accessRevoked])+const surfaceContentMutationError = (mutationError: unknown) => {const raw = mutationError instanceof Error ? mutationError.message : String(mutationError)const failure = describeGfsBrowserFailure(raw)if (failure.kind === 'unauthorized') {+ ctrl.revokeAccess()setMutationFailure(failure)pushToast?.(failure.message, 'error')return@@ -290,11 +305,22 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:// One atomic bulk grant for every selected subject — the server grants all or// none (a `subjects_invalid` rejects the whole request), so there is no- // partial-success outcome. People, teams, and agents share a single picker;- // agents are capped to read/write inside the panel. Inherit is honored for- // directories (default ON) and forced false for files.+<<<<<<< HEAD+ // partial-success outcome. A failure propagates to the panel's catch, which+ // maps the server verdict via describeGfsGrantError. People, teams, and+ // agents share a single picker; inherit is honored for directories and is+ // forced false for files by the panel.+ const failClosedOnAuthorizationError = (error: unknown): never => {+ const message = error instanceof Error ? error.message : String(error)+ if (describeGfsBrowserFailure(message).kind === 'unauthorized') ctrl.revokeAccess()+ throw error+ }const handleGrant = async (subjectKeys: string[], bits: string[], inherit: boolean) => {- await ctrl.grant(subjectKeys, bits, inherit)+ try {+ await ctrl.grant(subjectKeys, bits, inherit)+ } catch (error) {+ failClosedOnAuthorizationError(error)+ }pushToast?.(`Access granted to ${subjectKeys.length} ${subjectKeys.length === 1 ? 'subject' : 'subjects'}`,'success'@@ -308,12 +334,18 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:await ctrl.revokeGrant(grantId)pushToast?.(`Access revoked for ${label}`, 'success')} catch (revokeError) {+ if (describeGfsBrowserFailure(String(revokeError)).kind === 'unauthorized')+ ctrl.revokeAccess()pushToast?.(describeGfsGrantError(revokeError).message, 'error')}}const handleCreateShare = async (subjectKeys: string[]) => {- await ctrl.createShare(subjectKeys)+ try {+ await ctrl.createShare(subjectKeys)+ } catch (error) {+ failClosedOnAuthorizationError(error)+ }pushToast?.(`${subjectKeys.length} ${subjectKeys.length === 1 ? 'share' : 'shares'} created`,'success'@@ -326,6 +358,8 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:await ctrl.revokeShare(shareId)pushToast?.(`Shared access revoked for ${label}`, 'success')} catch (revokeError) {+ if (describeGfsBrowserFailure(String(revokeError)).kind === 'unauthorized')+ ctrl.revokeAccess()pushToast?.(describeGfsGrantError(revokeError).message, 'error')}}@@ -530,7 +564,11 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:: !current? accessibleError: null- const visibleFailure = visibleError ? describeGfsBrowserFailure(visibleError) : null+ const visibleFailure = accessRevoked+ ? describeGfsBrowserFailure('operator_link_inactive')+ : visibleError+ ? describeGfsBrowserFailure(visibleError)+ : nullconst hasMoreVisible = isOperatorRoot? ctrl.hasMoreAccessible: currentIsFolder@@ -735,6 +773,16 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:aria-label={visibleFailure.title}><EmptyState title={visibleFailure.title} body={visibleFailure.message} />+ {accessRevoked ? (+ <Button+ data-testid="gfs-retry-access-action"+ onClick={() => ctrl.retryAccess()}+ size="sm"+ variant="outline"+ >+ Retry file access+ </Button>+ ) : null}</div>) : visibleLoading ? (<divdiff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsxindex faa1d5c0b..4e99e8980 100644--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx@@ -24,6 +24,7 @@ function baseController() {current: null,crumbs: [],view: 'shared' as const,+ accessState: 'active' as const,isOperatorRoot: false,accessibleResources: [],items: [],@@ -68,6 +69,8 @@ function baseController() {deleteResource: vi.fn(),mutating: false,reset: vi.fn(),+ revokeAccess: vi.fn(),+ retryAccess: vi.fn(),refreshAffordances: vi.fn(),}}@@ -136,6 +139,35 @@ describe('FilesPage', () => {expect(screen.queryByText(/Error invoking remote method/i)).toBeNull()})+ it('renders a stable revoked state without cached operator controls and retries through the controller', () => {+ const retryAccess = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ view: 'operator',+ accessState: 'revoked',+ isOperatorRoot: false,+ accessibleResources: [],+ affordances: {+ held: ['read', 'write', 'delete', 'manage_acl', 'share'],+ canDelegate: true,+ grantableBits: ['read', 'write', 'delete', 'manage_acl', 'share'],+ canCreateShare: true,+ },+ retryAccess,+ })++ renderFilesPage()++ expect(screen.getByTestId('gfs-error-unauthorized').getAttribute('aria-label')).toBe(+ 'File access is not authorized'+ )+ expect(screen.queryByTestId('gfs-create-folder-action')).toBeNull()+ expect(screen.queryByTestId('gfs-upload-action')).toBeNull()+ expect(screen.queryByTestId('gfs-manage-access-action')).toBeNull()+ fireEvent.click(screen.getByTestId('gfs-retry-access-action'))+ expect(retryAccess).toHaveBeenCalledOnce()+ })+it('renders the real operator root with visible root create and upload actions', async () => {const rootResourceId = '11111111-1111-1111-1111-111111111111'const createFolder = vi.fn(async () => undefined)diff --git a/docs/concepts/open-core-and-hosted.md b/docs/concepts/open-core-and-hosted.mdindex 9c3fed8b6..047963733 100644--- a/docs/concepts/open-core-and-hosted.md+++ b/docs/concepts/open-core-and-hosted.md@@ -22,8 +22,9 @@ and not held back:packaging to ship the desktop app to your users.- **Self-hosted initial-admin GFS parity** — the Desktop identity created forthe first Control Admin during setup is linked directly for GFS operator- access, and that link can be revoked from Control UI without changing the- admin account or its credentials.+ access. Control UI can revoke that authority without changing the admin+ account or its credentials and can explicitly reactivate it as a new audited+ link generation when the retained identities remain active.- The **registry client**: connect to a registry to install and publishconnectors and recipes.- The **cluster E2E suites**.diff --git a/docs/how-to/desktop-setup-and-updates.md b/docs/how-to/desktop-setup-and-updates.mdindex 34c8b9974..213b2c4ad 100644--- a/docs/how-to/desktop-setup-and-updates.md+++ b/docs/how-to/desktop-setup-and-updates.md@@ -23,8 +23,12 @@ provisioned for that admin is linked directly for GFS operator access when theself-hosted deployment enables the operator-link setting. Control UI displaysthe exact pair and provides **Revoke/disable Desktop GFS operator access**;revoking it removes only GFS authority and preserves the admin account,-passwords, identities, and unrelated permissions. Invitations and ordinary-member provisioning do not create or repair this link.+passwords, identities, and unrelated permissions. The same surface provides an+explicit **Reactivate Desktop GFS operator access** action that creates a new+generation from retained history; it never restores a revoked row in place.+Retiring the linked Control Admin revokes the active generation before the+admin is disabled. Invitations and ordinary member provisioning do not create,+repair, or reassign this link.## The environment modeldiff --git a/docs/surfaces/desktop-app.md b/docs/surfaces/desktop-app.mdindex 8efb55c95..da93088c6 100644--- a/docs/surfaces/desktop-app.md+++ b/docs/surfaces/desktop-app.md@@ -81,6 +81,14 @@ identity, or alter unrelated Control Plane permissions. The next GFS requestfrom the Desktop session is denied, while ordinary user behavior remainssubject to its existing user-plane authorization.+Revocation is a retained lifecycle state, not a row deletion. The same Control+UI surface may explicitly **Reactivate Desktop GFS operator access** after a+confirmation; reactivation creates the next link generation and preserves the+revoked generation and its audit evidence. A stale generation or retired parent+is rejected rather than silently recreated or reassigned. Retiring a linked+Control Admin revokes its active generation and disables the admin in the same+transaction; physical purge is a separately governed retention operation.+This initial-setup link is deliberately separate from invitations and ordinarymember provisioning. Those flows do not create, repair, or reassign an operatorlink.diff --git a/gfs-controller/src/authz/storeProbe.test.ts b/gfs-controller/src/authz/storeProbe.test.tsindex af5d969ad..c00f76b54 100644--- a/gfs-controller/src/authz/storeProbe.test.ts+++ b/gfs-controller/src/authz/storeProbe.test.ts@@ -253,7 +253,7 @@ describe("createPermissionStoreProbe", () => {});it.each(["reader", "writer"] as const)(- "rejects a %s when migration 0070 audit columns are missing",+ "rejects a %s when migration 0092 audit actor-correlation columns are missing",async (storageRole) => {const { factory } = fakeClientFactory({ auditSchemaReady: false });const probe = createPermissionStoreProbe({@@ -264,12 +264,12 @@ describe("createPermissionStoreProbe", () => {clientFactory: factory,now: () => 0,});- await expect(probe()).rejects.toThrow(/migration 0070/);+ await expect(probe()).rejects.toThrow(/migration 0092/);});it.each(["reader", "writer"] as const)(- "rejects a %s when migration 0070 audit constraints are missing or unvalidated",+ "rejects a %s when migration 0092 audit actor-correlation constraints are missing or unvalidated",async (storageRole) => {const { factory } = fakeClientFactory({ auditConstraintsReady: false });const probe = createPermissionStoreProbe({@@ -280,7 +280,7 @@ describe("createPermissionStoreProbe", () => {clientFactory: factory,now: () => 0,});- await expect(probe()).rejects.toThrow(/migration 0070/);+ await expect(probe()).rejects.toThrow(/migration 0092/);});@@ -330,6 +330,9 @@ describe("createPermissionStoreProbe", () => {expect(sql).toMatch(/gfs_resources'\s*,\s*'UPDATE'/);expect(sql).toContain("FROM pg_attribute");expect(sql).toContain("'record_type'");+ expect(sql).toContain("'actor_on_behalf_of'");+ expect(sql).toContain("'desktop_user_id'");+ expect(sql).toContain("'authority_source'");expect(sql).toContain("'matched_subject'");expect(sql).toContain("'authorization_source'");expect(sql).toContain("'cached_authorization_source'");@@ -339,6 +342,7 @@ describe("createPermissionStoreProbe", () => {expect(sql).toContain("gfs_audit_cached_authorization_source_valid");expect(sql).toContain("gfs_audit_mutation_outcome_valid");expect(sql).toContain("gfs_audit_record_type_fields_valid");+ expect(sql).toContain("gfs_audit_actor_correlation_valid");expect(sql).toContain("convalidated");expect(sql).not.toContain("can_mutate_resources");expect(sql).not.toContain("can_update_audit_sequence");diff --git a/gfs-controller/src/authz/storeProbe.ts b/gfs-controller/src/authz/storeProbe.tsindex 09a52cc8f..2fc30067c 100644--- a/gfs-controller/src/authz/storeProbe.ts+++ b/gfs-controller/src/authz/storeProbe.ts@@ -89,12 +89,14 @@ const BASE_COHERENCE_SQL ="has_column_privilege(current_user, 'gfs_resources', 'blob_key', 'SELECT') AS can_read_blob_key, " +"has_column_privilege(current_user, 'gfs_resources', 'content_sha256', 'SELECT') AS can_read_digest, " +"EXISTS (SELECT 1 FROM (SELECT blob_key, content_sha256 FROM gfs_resources WHERE false) AS resource_probe) = false AS resource_schema_ready, " +- "(SELECT count(*) = 5 AND bool_and(atttypid = 'text'::regtype) " ++ "(SELECT count(*) = 8 " ++ "AND bool_and(attname <> 'desktop_user_id' OR atttypid = 'uuid'::regtype) " ++ "AND bool_and(attname = 'desktop_user_id' OR atttypid = 'text'::regtype) " +"AND bool_and(attname <> 'record_type' OR attnotnull) FROM pg_attribute " +"WHERE attrelid = 'gfs_audit'::regclass AND attnum > 0 AND NOT attisdropped " +- "AND attname = ANY (ARRAY['record_type', 'matched_subject', 'authorization_source', 'cached_authorization_source', 'mutation_outcome'])) AS audit_schema_ready, " +- "(SELECT count(*) = 5 FROM pg_constraint WHERE conrelid = 'gfs_audit'::regclass " +- "AND conname = ANY (ARRAY['gfs_audit_record_type_valid', 'gfs_audit_authorization_source_valid', 'gfs_audit_cached_authorization_source_valid', 'gfs_audit_mutation_outcome_valid', 'gfs_audit_record_type_fields_valid']) " ++ "AND attname = ANY (ARRAY['actor_on_behalf_of', 'desktop_user_id', 'authority_source', 'record_type', 'matched_subject', 'authorization_source', 'cached_authorization_source', 'mutation_outcome'])) AS audit_schema_ready, " ++ "(SELECT count(*) = 6 FROM pg_constraint WHERE conrelid = 'gfs_audit'::regclass " ++ "AND conname = ANY (ARRAY['gfs_audit_actor_correlation_valid', 'gfs_audit_record_type_valid', 'gfs_audit_authorization_source_valid', 'gfs_audit_cached_authorization_source_valid', 'gfs_audit_mutation_outcome_valid', 'gfs_audit_record_type_fields_valid']) " +"AND contype = 'c' AND convalidated) AS audit_constraints_ready";// The reader is deliberately read-only except for append-only audit records.@@ -223,8 +225,8 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi}if (row?.audit_schema_ready !== true || row?.audit_constraints_ready !== true) {throw new Error(- "permission store coherence check failed: GFS audit decision evidence schema is missing " +- "(control-api migration 0070 not applied?)"+ "permission store coherence check failed: GFS audit actor-correlation schema is missing " ++ "(control-api migration 0092 not applied?)");}if (diff --git a/scripts/tests/test-control-api-runtime-access-contract.sh b/scripts/tests/test-control-api-runtime-access-contract.shindex c579eaf33..7f526bf0b 100755--- a/scripts/tests/test-control-api-runtime-access-contract.sh+++ b/scripts/tests/test-control-api-runtime-access-contract.sh@@ -16,8 +16,8 @@ grep -qx $'gfs_desktop_operator_links\tlink_lifecycle' "$PROFILE_FILE"grep -Fq '$2 !~ /^(legacy_dml|upsert|append|read|link_lifecycle|none)$/' "$MIGRATION_SCRIPT"grep -Fq "('INSERT', expected.access_profile IN ('legacy_dml', 'upsert', 'append', 'link_lifecycle'))" "$MIGRATION_SCRIPT"-grep -Fq "('UPDATE', expected.access_profile IN ('legacy_dml', 'upsert'))" "$MIGRATION_SCRIPT"-grep -Fq "('DELETE', expected.access_profile IN ('legacy_dml', 'link_lifecycle'))" "$MIGRATION_SCRIPT"+grep -Fq "('UPDATE', expected.access_profile IN ('legacy_dml', 'upsert', 'link_lifecycle'))" "$MIGRATION_SCRIPT"+grep -Fq "('DELETE', expected.access_profile IN ('legacy_dml'))" "$MIGRATION_SCRIPT"grep -Fq "('TRUNCATE', false)" "$MIGRATION_SCRIPT"grep -Fq "('REFERENCES', false)" "$MIGRATION_SCRIPT"grep -Fq "('TRIGGER', false)" "$MIGRATION_SCRIPT"diff --git a/scripts/tests/test-gcp-scripts.sh b/scripts/tests/test-gcp-scripts.shindex 1f834a1e4..66cd71f20 100755--- a/scripts/tests/test-gcp-scripts.sh+++ b/scripts/tests/test-gcp-scripts.sh@@ -1482,7 +1482,8 @@ assert_control_api_runtime_access_contract_is_exact() {[[ "$migration_script" == *'has_sequence_privilege('* ]] && \[[ "$migration_script" == *"expected.access_profile IN ('legacy_dml', 'upsert', 'append', 'link_lifecycle')"* ]] && \[[ "$migration_script" == *"expected.access_profile IN ('legacy_dml', 'link_lifecycle')"* ]] && \- [[ "$migration_script" == *"('UPDATE', expected.access_profile IN ('legacy_dml', 'upsert'))"* ]] && \+ [[ "$migration_script" == *"('UPDATE', expected.access_profile IN ('legacy_dml', 'upsert', 'link_lifecycle'))"* ]] && \+ [[ "$migration_script" == *"('DELETE', expected.access_profile IN ('legacy_dml'))"* ]] && \[[ "$migration_script" == *"('TRUNCATE', false)"* ]] && \[[ "$migration_script" == *"('REFERENCES', false)"* ]] && \[[ "$migration_script" == *"('TRIGGER', false)"* ]]; then