Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(gfs): close adversarial review gaps
Alfredo Lopezb8b21ac44555
diff --git a/control-api/src/gfs/externalAuthority.ts b/control-api/src/gfs/externalAuthority.tsindex ae75129fe..d7fbdd79e 100644--- a/control-api/src/gfs/externalAuthority.ts+++ b/control-api/src/gfs/externalAuthority.ts@@ -57,6 +57,29 @@ function userAuthority(desktopUserId: string): ExternalGfsUserAuthority {return { kind: 'user-session', desktopUserId, tokenSubject: desktopUserId }}+async function assertDesktopUserActive(+ desktopUserId: string,+ guard: AuthorityDependencies['isDesktopUserActive'] = defaultDesktopUserLifecycleGuard+): Promise<void> {+ if (!guard) return+ try {+ if (!(await guard(desktopUserId))) {+ throw new ExternalGfsAuthorityError(403, 'desktop_user_retired')+ }+ } catch (error) {+ if (error instanceof ExternalGfsAuthorityError) throw error+ throw new ExternalGfsAuthorityError(503, 'gfs_authority_unavailable', { cause: error })+ }+}++/**+ * User-plane token minting has no operator-link resolver mounted after it, so+ * it needs the same lifecycle check explicitly before signing a token.+ */+export async function assertExternalGfsUserActive(desktopUserId: string): Promise<void> {+ await assertDesktopUserActive(desktopUserId)+}+/*** Resolve the effective GFS authority for one authenticated Desktop user.*@@ -73,16 +96,7 @@ export async function resolveExternalGfsAuthority(isDesktopUserActive: defaultDesktopUserLifecycleGuard,}): Promise<ExternalGfsAuthority> {- if (dependencies.isDesktopUserActive) {- try {- if (!(await dependencies.isDesktopUserActive(desktopUserId))) {- throw new ExternalGfsAuthorityError(403, 'desktop_user_retired')- }- } catch (error) {- if (error instanceof ExternalGfsAuthorityError) throw error- throw new ExternalGfsAuthorityError(503, 'gfs_authority_unavailable', { cause: error })- }- }+ await assertDesktopUserActive(desktopUserId, dependencies.isDesktopUserActive)if (dependencies.linkingEnabled !== true) return userAuthority(desktopUserId)let link: GfsDesktopOperatorLink | null@@ -135,3 +149,27 @@ export async function attachExternalGfsAuthority(next(error)}}++/** Session-plane guard for the user-only token endpoint. */+export async function attachExternalGfsUserLifecycle(+ req: Request,+ res: Response,+ next: NextFunction+): Promise<void> {+ const desktopUserId = (req as Request & { externalAuth?: { userId?: string } }).externalAuth+ ?.userId+ if (!desktopUserId) {+ res.status(401).json({ error: 'unauthenticated' })+ return+ }+ try {+ await assertExternalGfsUserActive(desktopUserId)+ next()+ } catch (error) {+ if (error instanceof ExternalGfsAuthorityError) {+ res.status(error.status).json({ error: error.code })+ return+ }+ next(error)+ }+}diff --git a/control-api/src/routes/admin/controlAdmins.ts b/control-api/src/routes/admin/controlAdmins.tsindex de1a21a29..3e18e995c 100644--- a/control-api/src/routes/admin/controlAdmins.ts+++ b/control-api/src/routes/admin/controlAdmins.ts@@ -509,7 +509,9 @@ export function createAdminControlAdminsRouter(): Router {}if (error instanceof GfsDesktopOperatorLinkError &&- (error.code === 'control_admin_inactive' || error.code === 'malformed_link')+ (error.code === 'control_admin_inactive' ||+ error.code === 'desktop_user_retired' ||+ error.code === 'malformed_link')) {res.status(409).json({ error: error.code })returndiff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.tsindex d8b248632..5b5758da6 100644--- a/control-api/src/routes/external/gfs.ts+++ b/control-api/src/routes/external/gfs.ts@@ -13,6 +13,7 @@ import {type ExternalGfsAuthority,type RequestWithExternalGfsAuthority,attachExternalGfsAuthority,+ attachExternalGfsUserLifecycle,} from '../../gfs/externalAuthority.js'import { isValidHostSubjectId, makeHostSubjectId } from '../../gfs/hostSubject.js'import { DbResolveStore } from '../../gfs/resolve.js'@@ -361,6 +362,7 @@ export function createExternalGfsRouter(): Router {router.post('/external/gfs/token',externalGfsTokenRouteRateLimit,+ asyncHandler(attachExternalGfsUserLifecycle),asyncHandler(async (req: ExternalAuthedRequest, res) => {const claims = req.externalAuth!const body = (req.body ?? {}) as { drive?: unknown; scopes?: unknown }diff --git a/control-api/src/services/adminAuthService.ts b/control-api/src/services/adminAuthService.tsindex 12d9ea867..65f5ee26c 100644--- a/control-api/src/services/adminAuthService.ts+++ b/control-api/src/services/adminAuthService.ts@@ -43,7 +43,7 @@ export type ControlAdminListItem = {rowVersion: number | nullrevocationReason: string | null} | null- gfsOperatorLinkStatus?: 'active' | 'inactive_admin' | 'revoked' | 'error'+ gfsOperatorLinkStatus?: 'none' | 'active' | 'inactive_admin' | 'revoked' | 'error'lastLoginAt: string | nullcreatedAt: string}@@ -769,7 +769,7 @@ export async function listControlAdmins(): Promise<{? 'active': 'inactive_admin': 'error'- : 'revoked') as 'active' | 'inactive_admin' | 'revoked' | 'error',+ : 'none') as 'none' | '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/test/routes.adminControlAdmins.test.ts b/control-api/test/routes.adminControlAdmins.test.tsindex cb209724a..b5a877d22 100644--- a/control-api/test/routes.adminControlAdmins.test.ts+++ b/control-api/test/routes.adminControlAdmins.test.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import express from 'express'import request from 'supertest'import { createAdminControlAdminsRouter } from '../src/routes/admin/controlAdmins.js'+import { GfsDesktopOperatorLinkError } from '../src/services/gfsDesktopOperatorLinkService.js'const adminSvc = vi.hoisted(() => ({createControlAdminEmailChangeRequest: vi.fn(),@@ -241,4 +242,17 @@ describe('routes/adminControlAdmins', () => {reason: 'control-ui-reactivate',})})++ it('maps a retired Desktop user reactivation refusal to a business conflict', async () => {+ operatorLinkSvc.reactivate.mockRejectedValue(+ new GfsDesktopOperatorLinkError('desktop_user_retired')+ )++ const res = await request(createTestApp())+ .post('/admin/control-admins/target-admin-id/gfs-operator-link/reactivate')+ .send({ rowVersion: 2, reason: 'control-ui-reactivate' })+ .expect(409)++ expect(res.body).toEqual({ error: 'desktop_user_retired' })+ })})diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.tsindex ac536fc02..29c0d4c4e 100644--- a/control-api/test/routes.externalGfs.test.ts+++ b/control-api/test/routes.externalGfs.test.ts@@ -19,6 +19,7 @@ const mockQuery = vi.hoisted(() => vi.fn())const mockAppendPermissionEvents = vi.hoisted(() => vi.fn())const mockWithTransaction = vi.hoisted(() => vi.fn())const mockResolveActiveLink = vi.hoisted(() => vi.fn())+const mockIsDesktopUserActive = vi.hoisted(() => vi.fn())vi.mock('../src/utils/auth/externalSessionAuthToken.js', () => ({verifyExternalSessionToken: (...a: unknown[]) => mockVerifyExternalSessionToken(...a),@@ -49,6 +50,7 @@ vi.mock('../src/config.js', () => ({vi.mock('../src/services/gfsDesktopOperatorLinkService.js', () => ({gfsDesktopOperatorLinkService: {resolveActiveLink: (...a: unknown[]) => mockResolveActiveLink(...a),+ isDesktopUserActive: (...a: unknown[]) => mockIsDesktopUserActive(...a),},GfsDesktopOperatorLinkError: class GfsDesktopOperatorLinkError extends Error {constructor(@@ -152,7 +154,9 @@ beforeEach(() => {mockAppendPermissionEvents.mockReset()mockWithTransaction.mockReset()mockResolveActiveLink.mockReset()+ mockIsDesktopUserActive.mockReset()mockResolveActiveLink.mockResolvedValue(null)+ mockIsDesktopUserActive.mockResolvedValue(true)mockWithTransaction.mockImplementation(async (work: (db: { query: typeof mockQuery }) => Promise<unknown>) =>work({ query: mockQuery })@@ -357,6 +361,21 @@ describe('POST /external/gfs/token (user mint — existing signer, sub=users.id)})})+ it('denies token minting for a retired Desktop user before signing a user-plane token', async () => {+ auth()+ mockIsDesktopUserActive.mockResolvedValue(false)+ const app = await buildApp()++ const res = await request(app)+ .post('/external/gfs/token')+ .set('x-user-session-token', 'sess')+ .send({})++ expect(res.status).toBe(403)+ expect(res.body).toEqual({ error: 'desktop_user_retired' })+ expect(mockSignGfsToken).not.toHaveBeenCalled()+ })+it('defaults to gfs.read when no scopes requested', async () => {auth()const app = await buildApp()diff --git a/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts b/control-api/test/services.directory.userRetirement.realPostgres.integration.test.tsnew file mode 100644index 000000000..c047674ae--- /dev/null+++ b/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts@@ -0,0 +1,177 @@+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import { randomBytes, randomUUID } from 'node:crypto'+import { Pool } from 'pg'+import { initDb, pool } from '../src/db.js'+import { retireDesktopUser } from '../src/services/directory/users.js'++const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+const describeRealPostgres = adminUrl ? describe : describe.skip++function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+}++function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+}++describeRealPostgres('retireDesktopUser on real PostgreSQL', () => {+ const database = `desktop_user_retirement_${randomBytes(6).toString('hex')}`+ const actorId = randomUUID()+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ let adminPool: Pool+ let testPool: Pool+ let corePoolConnectSpy: ReturnType<typeof vi.spyOn>++ async function seedDesktopUser(label: string): Promise<string> {+ const id = randomUUID()+ await testPool.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, $3)`, [+ id,+ `${label}-${id}@example.test`,+ label,+ ])+ return id+ }++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ testPool = new Pool({ connectionString })+ await initDb({ connect: () => testPool.connect() })+ corePoolConnectSpy = vi+ .spyOn(pool, 'connect')+ .mockImplementation((() => testPool.connect()) as typeof pool.connect)+ await testPool.query(+ `INSERT INTO control_admin_users (id, username, password_hash, role, status)+ VALUES ($1, $2, 'real-pg-retirement-test', 'admin', 'active')`,+ [actorId, `retirement-actor-${actorId}`]+ )+ }, 60_000)++ afterAll(async () => {+ corePoolConnectSpy?.mockRestore()+ await testPool?.end()+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ await adminPool.end()+ })++ it('persists the legacy deleted outcome and returns it on an identical replay', async () => {+ const userId = await seedDesktopUser('deleted-user')+ const input = [+ { kind: 'control_admin' as const, controlAdminId: actorId },+ userId,+ 'no operator-link history',+ 'real-pg-delete-replay-v1',+ 'retirement-delete-request-v1',+ ] as const++ const first = await retireDesktopUser(...input)+ const replay = await retireDesktopUser(...input)++ expect(first).toMatchObject({+ id: userId,+ outcome: 'deleted',+ lifecycleVersion: null,+ replayed: false,+ })+ expect(replay).toEqual({ ...first, replayed: true })+ const [user, operation] = await Promise.all([+ testPool.query(`SELECT id FROM users WHERE id = $1::uuid`, [userId]),+ testPool.query(+ `SELECT status, outcome, lifecycle_version+ FROM desktop_user_retirement_operations+ WHERE id = $1::uuid`,+ [first.operationId]+ ),+ ])+ expect(user.rowCount).toBe(0)+ expect(operation.rows).toEqual([+ { status: 'completed', outcome: 'deleted', lifecycle_version: null },+ ])+ })++ it('persists a retained linked user as retired and revokes its active generation', async () => {+ const userId = await seedDesktopUser('linked-user')+ await testPool.query(+ `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', 'initial_setup', $2::uuid, 1)`,+ [userId, actorId]+ )++ const result = await retireDesktopUser(+ { kind: 'control_admin', controlAdminId: actorId },+ userId,+ 'operator access revoked with account retirement',+ 'real-pg-retire-v1',+ 'retirement-retire-request-v1'+ )++ expect(result).toMatchObject({+ id: userId,+ outcome: 'retired',+ lifecycleVersion: 2,+ replayed: false,+ })+ const [user, link, operation] = await Promise.all([+ testPool.query(+ `SELECT lifecycle_state, lifecycle_version, retirement_reason,+ retired_by_type, retired_by_control_admin_id::text AS retired_by_control_admin_id,+ retirement_operation_id::text AS retirement_operation_id+ FROM users WHERE id = $1::uuid`,+ [userId]+ ),+ testPool.query(+ `SELECT state, row_version, revoked_by_type,+ revoked_by_control_admin_id::text AS revoked_by_control_admin_id,+ revocation_reason+ FROM gfs_desktop_operator_links WHERE user_id = $1::uuid`,+ [userId]+ ),+ testPool.query(+ `SELECT status, outcome, lifecycle_version, lifecycle_operation_id::text AS lifecycle_operation_id+ FROM desktop_user_retirement_operations WHERE id = $1::uuid`,+ [result.operationId]+ ),+ ])+ expect(user.rows).toEqual([+ {+ lifecycle_state: 'retired',+ lifecycle_version: '2',+ retirement_reason: 'operator access revoked with account retirement',+ retired_by_type: 'control_admin',+ retired_by_control_admin_id: actorId,+ retirement_operation_id: result.operationId,+ },+ ])+ expect(link.rows).toEqual([+ {+ state: 'revoked',+ row_version: 2,+ revoked_by_type: 'control_admin',+ revoked_by_control_admin_id: actorId,+ revocation_reason: 'operator access revoked with account retirement',+ },+ ])+ expect(operation.rows).toEqual([+ {+ status: 'completed',+ outcome: 'retired',+ lifecycle_version: '2',+ lifecycle_operation_id: result.operationId,+ },+ ])+ })+})diff --git a/control-ui/components/ControlAdminsPanel/index.tsx b/control-ui/components/ControlAdminsPanel/index.tsxindex 63727a088..4de5cab01 100644--- a/control-ui/components/ControlAdminsPanel/index.tsx+++ b/control-ui/components/ControlAdminsPanel/index.tsx@@ -422,7 +422,7 @@ export function ControlAdminsPanel({</div></div>) : (- <span data-testid={`gfs-operator-link-${admin.id}`}>Revoked</span>+ <span data-testid={`gfs-operator-link-${admin.id}`}>Not linked</span>)}</td><td>{formatDate(admin.lastLoginAt)}</td>diff --git a/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx b/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsxindex 71e26c80c..6517cea67 100644--- a/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx+++ b/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx@@ -139,6 +139,28 @@ describe('ControlAdminsPanel GFS operator link lifecycle', () => {expect(revokeControlAdminGfsOperatorLink).not.toHaveBeenCalled()})+ it('distinguishes a never-linked admin from a revoked operator link', async () => {+ vi.mocked(getControlAdmins).mockResolvedValueOnce({+ admins: [+ {+ id: 'admin-2',+ username: 'never-linked',+ email: '[email protected]',+ memberId: null,+ status: 'active',+ gfsOperatorLink: null,+ gfsOperatorLinkStatus: 'none',+ lastLoginAt: null,+ createdAt: '2026-08-10T11:00:00.000Z',+ },+ ],+ invitations: [],+ })++ render(<ControlAdminsPanel />)+ expect(await screen.findByTestId('gfs-operator-link-admin-2')).toHaveTextContent('Not linked')+ })+it('reactivates a retained revoked generation through the visible Control UI action', async () => {vi.mocked(getControlAdmins).mockResolvedValueOnce({admins: [diff --git a/control-ui/lib/__tests__/adminUsersApi.test.ts b/control-ui/lib/__tests__/adminUsersApi.test.tsnew file mode 100644index 000000000..0ee4c2e42--- /dev/null+++ b/control-ui/lib/__tests__/adminUsersApi.test.ts@@ -0,0 +1,40 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { deleteAdminUser } from '../api'++const USER_ID = '11111111-1111-4111-8111-111111111111'+const CORRELATION_ID = '22222222-2222-4222-8222-222222222222'++describe('deleteAdminUser', () => {+ afterEach(() => vi.unstubAllGlobals())++ it('sends the governed reason, idempotency key, and correlation id to Control API', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ deleted: true, id: USER_ID }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ )+ vi.stubGlobal('fetch', fetchMock)++ await expect(+ deleteAdminUser(USER_ID, {+ reason: 'access review complete',+ idempotencyKey: 'retire-user-v1',+ correlationId: CORRELATION_ID,+ })+ ).resolves.toEqual({ deleted: true, id: USER_ID })++ expect(fetchMock).toHaveBeenCalledWith(+ `/control-api/api/v1/admin/users/${USER_ID}`,+ expect.objectContaining({+ method: 'DELETE',+ headers: expect.objectContaining({+ 'Content-Type': 'application/json',+ 'Idempotency-Key': 'retire-user-v1',+ 'x-correlation-id': CORRELATION_ID,+ }),+ body: JSON.stringify({ reason: 'access review complete' }),+ })+ )+ })+})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex 726720f72..127eed265 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -557,7 +557,7 @@ export type ControlAdminListItem = {rowVersion?: number | nullrevocationReason?: string | null} | null- gfsOperatorLinkStatus?: 'active' | 'inactive_admin' | 'revoked' | 'error'+ gfsOperatorLinkStatus?: 'none' | 'active' | 'inactive_admin' | 'revoked' | 'error'lastLoginAt: string | nullcreatedAt: string}@@ -2157,12 +2157,51 @@ export async function deleteAdminTeam(teamId: string) {}>}+export type DeleteAdminUserRequest = {+ /** Persisted with the governed retirement operation for its audit trail. */+ reason?: string+ /** Reuse this on a transport retry of the same user action. */+ idempotencyKey?: string+ /** Connects the browser request to the Control API retirement audit row. */+ correlationId?: string+}++const UUID_ANY_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i++function generateRetirementRequestId(): string {+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {+ return crypto.randomUUID()+ }+ // The Control API accepts a correlation header only when it is UUID-shaped.+ // This compatibility branch keeps embedded/legacy browser retries traceable.+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, marker => {+ const nibble = Math.floor(Math.random() * 16)+ return (marker === 'x' ? nibble : (nibble & 0x3) | 0x8).toString(16)+ })+}+/**- * Hard-deletes the user account (CASCADE on profile and personal access).- * Team memberships cascade; teams are retained even when this leaves them with no members.+ * Retires the user through the governed lifecycle contract. A caller may retain+ * the supplied key when retrying the same action; an ordinary UI action gets a+ * new request identity and an explicit audit reason.*/-export async function deleteAdminUser(userId: string) {- return apiSend('DELETE', `/api/v1/admin/users/${encodeURIComponent(userId)}`) as Promise<{+export async function deleteAdminUser(userId: string, request: DeleteAdminUserRequest = {}) {+ const idempotencyKey = request.idempotencyKey?.trim() || generateRetirementRequestId()+ const providedCorrelationId = request.correlationId?.trim() || ''+ const correlationId = UUID_ANY_RE.test(providedCorrelationId)+ ? providedCorrelationId.toLowerCase()+ : generateRetirementRequestId()+ const reason = request.reason?.trim() || 'control_ui_user_retirement'+ return apiSend(+ 'DELETE',+ `/api/v1/admin/users/${encodeURIComponent(userId)}`,+ { reason },+ {},+ {+ 'Idempotency-Key': idempotencyKey,+ 'x-correlation-id': correlationId,+ }+ ) as Promise<{deleted: booleanid: string}>diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsxindex 0715609d6..a21d374da 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx@@ -4,7 +4,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { AuthContext, type AuthContextValue } from '@contexts/AuthContext'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, cleanup, render, screen, waitFor } from '@testing-library/react'-import { useGfsBrowserController } from '../useGfsBrowserController'+import {+ describeGfsBrowserFailure,+ isGfsSessionAuthorityFailure,+ useGfsBrowserController,+} from '../useGfsBrowserController'const userA = {id: 'user-a',@@ -77,8 +81,8 @@ function authValue(me: AuthContextValue['me'], envKey = 'env-a'): AuthContextVal}}-function Probe() {- const ctrl = useGfsBrowserController()+function Probe({ grantsListEnabled = false }: { grantsListEnabled?: boolean }) {+ const ctrl = useGfsBrowserController({ grantsListEnabled })return (<><div data-testid="current">{ctrl.current?.resourceId ?? 'none'}</div>@@ -188,6 +192,24 @@ describe('useGfsBrowserController', () => {vi.restoreAllMocks()})+ it.each([+ ['403 Forbidden: manage_acl_required', false],+ ['403 Forbidden: escalation_rejected', false],+ ['403 Forbidden: foreign_agent_forbidden', false],+ ['403 Forbidden: operator_link_inactive', true],+ ] as const)(+ 'distinguishes per-operation 403s from session authority (%s)',+ (message, expected) => {+ expect(isGfsSessionAuthorityFailure(message, 'operation')).toBe(expected)+ }+ )++ it('prioritizes an authorization verdict over generic initialization wording', () => {+ expect(describeGfsBrowserFailure('403 Forbidden: drive not initialized').kind).toBe(+ 'unauthorized'+ )+ })+it.each(['switch team', 'switch user', 'sign out'])('resets visible GFS state after %s changes the authenticated scope',async action => {@@ -468,6 +490,40 @@ describe('useGfsBrowserController', () => {expect(listAccessible).toHaveBeenCalledTimes(3)})+ it('keeps the browser session active when ACL listing is denied by resource policy', async () => {+ const rootResourceId = '11111111-1111-1111-1111-111111111111'+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible: vi.fn(async () => ({+ items: [],+ nextCursor: null,+ rootResourceId,+ view: 'operator' as const,+ })),+ resolve: vi.fn(),+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),+ affordances: vi.fn(async () => ({+ held: ['read'],+ canDelegate: false,+ grantableBits: [],+ canCreateShare: false,+ })),+ listGrants: vi.fn(async () => {+ throw new Error('403 Forbidden: manage_acl_required')+ }),+ listShares: vi.fn(async () => []),+ },+ },+ })++ render(<Probe grantsListEnabled />, { wrapper: Harness })+ await waitFor(() => expect(screen.getByTestId('operator-root').textContent).toBe('yes'))+ await waitFor(() => expect(screen.getByTestId('access-state').textContent).toBe('active'))+ expect(screen.getByTestId('current').textContent).toBe(rootResourceId)+ })+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 d7d4f426e..afc1e2dae 100644--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts@@ -92,6 +92,16 @@ function isResourceDiscoveryUnavailable(message: string): boolean {function isUninitializedDriveError(message: string): boolean {const normalized = message.toLowerCase()+ // A server authorization verdict wins over the generic wording below. For+ // example, "403 Forbidden: drive not initialized" is still an authorization+ // failure and must not be presented as a provisioning state.+ if (+ /(^|\D)(401|403)(\D|$)/.test(normalized) ||+ normalized.includes('unauthorized') ||+ normalized.includes('forbidden')+ ) {+ return false+ }return (normalized.includes('operator_root_missing') ||normalized.includes('gfs_drive_unseeded') ||@@ -103,6 +113,33 @@ function isUninitializedDriveError(message: string): boolean {)}+const SESSION_AUTHORITY_ERROR_CODES = [+ 'desktop_user_retired',+ 'operator_link_inactive',+ 'operator_link_invalid',+ 'gfs_operator_link_invalid',+] as const++/**+ * Only a session/operator authority failure may invalidate the browser's+ * session-local access state. Per-resource policy verdicts such as+ * `manage_acl_required`, `escalation_rejected`, and `foreign_agent_forbidden`+ * are expected 403s and must remain local to the attempted operation.+ */+export function isGfsSessionAuthorityFailure(+ message: string,+ surface: 'discovery' | 'operation' = 'operation'+): boolean {+ const normalized = message.toLowerCase()+ if (SESSION_AUTHORITY_ERROR_CODES.some(code => normalized.includes(code))) return true+ if (surface !== 'discovery') return false+ return (+ /(^|\D)(401|403)(\D|$)/.test(normalized) ||+ normalized.includes('unauthorized') ||+ normalized.includes('forbidden')+ )+}+/** Stable user-facing state for root/folder read failures crossing Electron IPC. */export function describeGfsBrowserFailure(message: string): GfsBrowserFailure {if (isUninitializedDriveError(message)) {@@ -324,15 +361,9 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {// remains the sole authority that can restore the operator root.setAccessState('active')}, [])- const queryAuthorizationError = [- accessibleQuery.error,- childrenQuery.error,- affordancesQuery.error,- grantsQuery.error,- sharesQuery.error,- ]+ const queryAuthorizationError = [accessibleQuery.error, childrenQuery.error].map(error => (error ? toMessage(error) : null))- .find(error => error !== null && describeGfsBrowserFailure(error).kind === 'unauthorized')+ .find(error => error !== null && isGfsSessionAuthorityFailure(error, 'discovery'))useEffect(() => {if (queryAuthorizationError && accessState !== 'revoked') revokeAccess()}, [accessState, queryAuthorizationError, revokeAccess])@@ -484,7 +515,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {return crumb} catch (error) {const message = toMessage(error)- if (describeGfsBrowserFailure(message).kind === 'unauthorized') revokeAccess()+ if (isGfsSessionAuthorityFailure(message, 'discovery')) revokeAccess()else setOpenError(message)return false} finally {diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsxindex fe07b4a3e..447cf59b6 100644--- a/desktop-app/ui/src/pages/FilesPage.tsx+++ b/desktop-app/ui/src/pages/FilesPage.tsx@@ -16,6 +16,7 @@ import { desktopQueryKeys } from '@hooks/domain/queryKeys'import {type GfsBrowserFailure,describeGfsBrowserFailure,+ isGfsSessionAuthorityFailure,useGfsBrowserController,} from '@hooks/domain/useGfsBrowserController'import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'@@ -257,7 +258,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:const surfaceContentMutationError = (mutationError: unknown) => {const raw = mutationError instanceof Error ? mutationError.message : String(mutationError)const failure = describeGfsBrowserFailure(raw)- if (failure.kind === 'unauthorized') {+ if (isGfsSessionAuthorityFailure(raw, 'operation')) {ctrl.revokeAccess()setMutationFailure(failure)pushToast?.(failure.message, 'error')@@ -311,7 +312,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:// 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()+ if (isGfsSessionAuthorityFailure(message, 'operation')) ctrl.revokeAccess()throw error}const handleGrant = async (subjectKeys: string[], bits: string[], inherit: boolean) => {@@ -333,8 +334,7 @@ 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()+ if (isGfsSessionAuthorityFailure(String(revokeError), 'operation')) ctrl.revokeAccess()pushToast?.(describeGfsGrantError(revokeError).message, 'error')}}@@ -357,8 +357,7 @@ 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()+ if (isGfsSessionAuthorityFailure(String(revokeError), 'operation')) ctrl.revokeAccess()pushToast?.(describeGfsGrantError(revokeError).message, 'error')}}diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.jsonindex a4226df63..6447f3a0b 100644--- a/external-rest-api/package-lock.json+++ b/external-rest-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-external-rest-api",- "version": "0.1.67",+ "version": "0.1.68","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-external-rest-api",- "version": "0.1.67",+ "version": "0.1.68","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/external-rest-api/package.json b/external-rest-api/package.jsonindex 109e55862..f21f91fb9 100644--- a/external-rest-api/package.json+++ b/external-rest-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-external-rest-api",- "version": "0.1.67",+ "version": "0.1.68","description": "External REST API for profile, team management, and RPC token brokerage","main": "dist/main.js","engines": {diff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.tsindex 7bddf5eac..8dd982511 100644--- a/external-rest-api/src/routes/gfs.ts+++ b/external-rest-api/src/routes/gfs.ts@@ -130,13 +130,18 @@ export function createGfsRouter(options?: { edgeLimits?: ExternalGfsEdgeLimits }const router = Router()const edgeLimits = options?.edgeLimits ?? DEFAULT_EXTERNAL_GFS_EDGE_LIMITS- const edgeLimiter = (limit: number, bucket: string) =>+ const edgeLimiter = (+ limit: number,+ bucket: string,+ options?: { keyGenerator?: (req: Request) => string }+ ) =>rateLimit({windowMs: EXTERNAL_GFS_EDGE_WINDOW_MS,limit,standardHeaders: 'draft-7',legacyHeaders: false,identifier: `gfs-edge-${bucket}`,+ ...(options?.keyGenerator ? { keyGenerator: options.keyGenerator } : {}),handler: (_req, res) => {res.status(429).json({error: 'Too Many Requests',@@ -153,7 +158,16 @@ export function createGfsRouter(options?: { edgeLimits?: ExternalGfsEdgeLimits }// sized for a shared NAT address; the token bucket remains tighter. The// Control API owns the authoritative per-user/session/actor budgets.router.use('/me/gfs', attachGfsRequestId)- router.use('/me/gfs', edgeLimiter(edgeLimits.aggregatePerMin, 'aggregate-ip'))+ router.use(+ '/me/gfs',+ edgeLimiter(edgeLimits.aggregatePerMin, 'aggregate-ip', {+ // This is intentionally a process-wide backstop, not another per-IP+ // bucket. The authenticated-IP limiter below owns client fairness;+ // keeping a constant key makes distributed source-IP floods observable+ // at this edge instead of allowing the aggregate budget to be bypassed.+ keyGenerator: () => 'gfs-edge-aggregate',+ })+ )router.use('/me/gfs', edgeLimiter(edgeLimits.authenticatedIpPerMin, 'authenticated-ip'))router.use('/me/gfs/token', edgeLimiter(edgeLimits.tokenIpPerMin, 'token-ip'))router.use('/me/gfs', requireAuth)diff --git a/external-rest-api/src/routes/members.ts b/external-rest-api/src/routes/members.tsindex 184137b91..d48c5fdee 100644--- a/external-rest-api/src/routes/members.ts+++ b/external-rest-api/src/routes/members.ts@@ -1,4 +1,5 @@import { Router } from 'express'+import { randomUUID } from 'node:crypto'import { type AuthedRequest, extractAuthToken, requireAuth } from '../middleware/auth.js'import {cancelManagedInvitation,@@ -17,6 +18,12 @@ import { TEAM_ROLES, TeamRole } from '../types.js'const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/const MAX_INVITATION_TEAM_ASSIGNMENTS = 50const MAX_INVITEE_NAME_LENGTH = 120+const UUID_ANY_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i++function retirementCorrelationId(value: unknown): string {+ const normalized = typeof value === 'string' ? value.trim() : ''+ return normalized && UUID_ANY_RE.test(normalized) ? normalized.toLowerCase() : randomUUID()+}export function createMembersRouter(): Router {const router = Router()@@ -206,7 +213,23 @@ export function createMembersRouter(): Router {router.delete('/members/:userId', requireAuth, async (req, res, next) => {try {- res.status(200).json(await deleteManagedUser(req.params.userId, extractAuthToken(req)))+ const reason = typeof req.body?.reason === 'string' ? req.body.reason.trim() : ''+ if (!reason) {+ res.status(400).json({ error: 'Retirement reason is required' })+ return+ }+ const idempotencyKey = String(req.header('Idempotency-Key') || '').trim()+ if (!idempotencyKey) {+ res.status(400).json({ error: 'Idempotency-Key header is required' })+ return+ }+ res.status(200).json(+ await deleteManagedUser(req.params.userId, extractAuthToken(req), {+ reason,+ idempotencyKey,+ correlationId: retirementCorrelationId(req.header('x-correlation-id')),+ })+ )} catch (error) {const message = error instanceof Error ? error.message : ''if (message.includes('(403)')) {diff --git a/external-rest-api/src/services/memberManagementService.ts b/external-rest-api/src/services/memberManagementService.tsindex 7f39ac6bd..6a98b9f37 100644--- a/external-rest-api/src/services/memberManagementService.ts+++ b/external-rest-api/src/services/memberManagementService.ts@@ -108,9 +108,24 @@ export async function deleteManagedMember(userId: string, teamId: string, sessio})}-export async function deleteManagedUser(userId: string, sessionToken: string) {+export type ManagedUserRetirementRequest = {+ reason: string+ idempotencyKey: string+ correlationId: string+}++export async function deleteManagedUser(+ userId: string,+ sessionToken: string,+ retirement: ManagedUserRetirementRequest+) {return controlApiRequest<unknown>('DELETE', `/external/members/${userId}`, {+ body: { reason: retirement.reason },userSessionToken: sessionToken,+ extraHeaders: {+ 'idempotency-key': retirement.idempotencyKey,+ 'x-correlation-id': retirement.correlationId,+ },})}diff --git a/external-rest-api/test/routes.gfs.test.ts b/external-rest-api/test/routes.gfs.test.tsindex 74e37c2e1..0ca5f2722 100644--- a/external-rest-api/test/routes.gfs.test.ts+++ b/external-rest-api/test/routes.gfs.test.ts@@ -514,6 +514,33 @@ describe('GET /me/gfs/shares (delegation list passthrough)', () => {expect(clientMock.controlApiRequest).not.toHaveBeenCalled()})+ it('keeps the aggregate edge backstop process-wide across source IPs', async () => {+ const app = buildApp({+ aggregatePerMin: 2,+ authenticatedIpPerMin: 100,+ tokenIpPerMin: 100,+ })+ app.set('trust proxy', 1)++ await request(app)+ .get('/me/gfs/not-classified')+ .set('authorization', 'Bearer sess-xyz')+ .set('x-forwarded-for', '198.51.100.10')+ .expect(404)+ await request(app)+ .get('/me/gfs/not-classified')+ .set('authorization', 'Bearer sess-xyz')+ .set('x-forwarded-for', '198.51.100.11')+ .expect(404)++ const exhausted = await request(app)+ .get('/me/gfs/not-classified')+ .set('authorization', 'Bearer sess-xyz')+ .set('x-forwarded-for', '198.51.100.12')+ expect(exhausted.status).toBe(429)+ expect(exhausted.body.rateLimitBucket).toBe('aggregate-ip')+ })+it.each([[401, 'unauthorized'],[403, 'manage_acl_required'],diff --git a/external-rest-api/test/routes.members.test.ts b/external-rest-api/test/routes.members.test.tsindex 5d4a4182c..2874385f4 100644--- a/external-rest-api/test/routes.members.test.ts+++ b/external-rest-api/test/routes.members.test.ts@@ -81,4 +81,40 @@ describe('routes/members', () => {expect(memberManagementMock.inviteManagedMember).not.toHaveBeenCalled()})++ it('forwards a governed member-retirement reason, replay key, and correlation id', async () => {+ authTokenMock.verifyToken.mockReturnValueOnce(claims)+ memberManagementMock.deleteManagedUser.mockResolvedValueOnce({ ok: true })++ await request(makeApp())+ .delete('/members/user-2')+ .set('authorization', 'Bearer good-token')+ .set('Idempotency-Key', 'retire-user-2-v1')+ .set('x-correlation-id', '11111111-1111-4111-8111-111111111111')+ .send({ reason: 'team access no longer required' })+ .expect(200, { ok: true })++ expect(memberManagementMock.deleteManagedUser).toHaveBeenCalledWith('user-2', 'good-token', {+ reason: 'team access no longer required',+ idempotencyKey: 'retire-user-2-v1',+ correlationId: '11111111-1111-4111-8111-111111111111',+ })+ })++ it.each([+ [{}, 'Retirement reason is required'],+ [{ reason: 'team access no longer required' }, 'Idempotency-Key header is required'],+ ])('rejects missing governed-retirement inputs', async (body, expectedError) => {+ authTokenMock.verifyToken.mockReturnValueOnce(claims)++ const requestBuilder = request(makeApp())+ .delete('/members/user-2')+ .set('authorization', 'Bearer good-token')+ .send(body)+ const response = await requestBuilder++ expect(response.status).toBe(400)+ expect(response.body).toEqual({ error: expectedError })+ expect(memberManagementMock.deleteManagedUser).not.toHaveBeenCalled()+ })})diff --git a/external-rest-api/test/services.memberManagementService.test.ts b/external-rest-api/test/services.memberManagementService.test.tsnew file mode 100644index 000000000..152795e91--- /dev/null+++ b/external-rest-api/test/services.memberManagementService.test.ts@@ -0,0 +1,37 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { deleteManagedUser } from '../src/services/memberManagementService.js'++const controlApiClientMock = vi.hoisted(() => ({+ controlApiRequest: vi.fn(),+}))++vi.mock('../src/controlApiClient.js', () => controlApiClientMock)++describe('deleteManagedUser', () => {+ beforeEach(() => controlApiClientMock.controlApiRequest.mockReset())++ it('forwards governed retirement input through the Control API boundary', async () => {+ controlApiClientMock.controlApiRequest.mockResolvedValueOnce({ ok: true })++ await expect(+ deleteManagedUser('user-2', 'user-session-token', {+ reason: 'team access no longer required',+ idempotencyKey: 'retire-user-2-v1',+ correlationId: '11111111-1111-4111-8111-111111111111',+ })+ ).resolves.toEqual({ ok: true })++ expect(controlApiClientMock.controlApiRequest).toHaveBeenCalledWith(+ 'DELETE',+ '/external/members/user-2',+ {+ body: { reason: 'team access no longer required' },+ userSessionToken: 'user-session-token',+ extraHeaders: {+ 'idempotency-key': 'retire-user-2-v1',+ 'x-correlation-id': '11111111-1111-4111-8111-111111111111',+ },+ }+ )+ })+})diff --git a/gfs-controller/src/authz/audit.ts b/gfs-controller/src/authz/audit.tsindex d7d4f3a8e..faa8eecfa 100644--- a/gfs-controller/src/authz/audit.ts+++ b/gfs-controller/src/authz/audit.ts@@ -68,18 +68,29 @@ export interface AuditSink {record(event: AuditEvent, queryable?: Queryable, budget?: DeadlineBudget): Promise<void>;}+const DESKTOP_USER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function canonicalDesktopUserId(value: string | undefined): string | null {+ if (value === undefined) return null;+ if (!DESKTOP_USER_UUID_RE.test(value)) {+ throw new Error("desktop_user_id must be a UUID");+ }+ return value.toLowerCase();+}+/** PostgreSQL-backed, INSERT-only sink for typed GFS audit evidence. */export class DbAuditSink implements AuditSink {constructor(private readonly db: Queryable & DeadlinePool) {}async record(event: AuditEvent, queryable?: Queryable, budget?: DeadlineBudget): Promise<void> {+ const desktopUserId = canonicalDesktopUserId(event.desktopUserId);const gfsUri = `gfs://${event.drive}/${event.resourceId}`;const rowHash = createHash("sha256").update(JSON.stringify([event.subject,event.actorOnBehalfOf ?? null,- event.desktopUserId ?? null,+ desktopUserId,event.authoritySource ?? null,event.op,gfsUri,@@ -114,7 +125,7 @@ export class DbAuditSink implements AuditSink {event.authorizationSource,event.cachedAuthorizationSource,event.mutationOutcome,- event.desktopUserId ?? null,+ desktopUserId,event.authoritySource ?? null,]);diff --git a/gfs-controller/src/authz/dbAuditSink.test.ts b/gfs-controller/src/authz/dbAuditSink.test.tsindex 20c199522..e855e8293 100644--- a/gfs-controller/src/authz/dbAuditSink.test.ts+++ b/gfs-controller/src/authz/dbAuditSink.test.ts@@ -104,6 +104,18 @@ describe("DbAuditSink", () => {]);});+ it("rejects a non-UUID Desktop actor before reaching the UUID audit cast", async () => {+ const db = new AuditDb();+ await expect(+ new DbAuditSink(db).record({+ ...directDecision,+ desktopUserId: "host:1st:mcp-host/invalid",+ authoritySource: "user-session",+ })+ ).rejects.toThrow("desktop_user_id must be a UUID");+ expect(db.text).toBe("");+ });+it("persists cache attribution and includes it in the deterministic hash", async () => {const first = new AuditDb();const repeated = new AuditDb();diff --git a/gfs-controller/src/authz/subjectResolver.test.ts b/gfs-controller/src/authz/subjectResolver.test.tsindex ea801dc22..924f1faf0 100644--- a/gfs-controller/src/authz/subjectResolver.test.ts+++ b/gfs-controller/src/authz/subjectResolver.test.ts@@ -130,6 +130,26 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =});});+ it("accepts uppercase UUID casing in linked-admin claims and canonicalizes the subject", async () => {+ const controlAdminId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";+ const desktopUserId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";+ const db = fakeDb({ operators: new Set([controlAdminId]) });++ const ctx = await resolveAuthzContext(db, {+ sub: controlAdminId.toUpperCase(),+ drive: "main",+ brokeredAuthority: {+ desktopUserId: desktopUserId.toUpperCase(),+ controlAdminId: controlAdminId.toUpperCase(),+ authoritySource: "linked-admin",+ },+ });++ expect(ctx.primarySubject).toBe(controlAdminId);+ expect(ctx.effectiveControlAdminId).toBe(controlAdminId);+ expect(ctx.desktopUserId).toBe(desktopUserId);+ });+it("fails closed when a signed linked-admin claim names an inactive or missing admin", async () => {const controlAdminId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";const db = fakeDb({});diff --git a/gfs-controller/src/authz/subjectResolver.ts b/gfs-controller/src/authz/subjectResolver.tsindex 9652e51b8..811302f7c 100644--- a/gfs-controller/src/authz/subjectResolver.ts+++ b/gfs-controller/src/authz/subjectResolver.ts@@ -38,6 +38,7 @@ const K8S_NAME = "[a-z0-9](?:[-a-z0-9]*[a-z0-9])?";/** A host principal's `sub` is already the canonical subject key. */const HOST_SUB = new RegExp(`^host:(1st|3rd):${K8S_NAME}\\/${K8S_NAME}$`);+const UUID_SUB = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;/** True iff `adminId` is an active cluster operator (`control_admin_users`). */async function isOperatorId(db: SubjectsDb, adminId: string): Promise<boolean> {@@ -64,19 +65,27 @@ export async function resolveAuthzContext(requestId?: string): Promise<AuthzContext> {const sub = claims.sub;+ // PostgreSQL UUIDs are canonicalized to lowercase. Keep non-UUID host+ // principals byte-for-byte stable, while making signed UUID subjects+ // independent of hex casing across verify and authorization resolution.+ const canonicalSub = UUID_SUB.test(sub) ? sub.toLowerCase() : sub;if (claims.brokeredAuthority) {const brokered = claims.brokeredAuthority;- if (brokered.controlAdminId !== sub || !(await isOperatorId(db, brokered.controlAdminId))) {+ const canonicalBrokeredAdminId = brokered.controlAdminId.toLowerCase();+ const canonicalDesktopUserId = UUID_SUB.test(brokered.desktopUserId)+ ? brokered.desktopUserId.toLowerCase()+ : brokered.desktopUserId;+ if (canonicalBrokeredAdminId !== canonicalSub || !(await isOperatorId(db, canonicalBrokeredAdminId))) {throw new Error("linked admin is not active");}return {drive: claims.drive,subjects: ["operator:"],isOperator: true,- primarySubject: sub,- effectiveControlAdminId: brokered.controlAdminId,- desktopUserId: brokered.desktopUserId,+ primarySubject: canonicalSub,+ effectiveControlAdminId: canonicalBrokeredAdminId,+ desktopUserId: canonicalDesktopUserId,authoritySource: "linked-admin",requestId,};@@ -90,26 +99,31 @@ export async function resolveAuthzContext(}if (claims.principalType === "control-admin") {- if (!(await isOperatorId(db, sub))) throw new Error("control admin is not active");+ if (!(await isOperatorId(db, canonicalSub))) throw new Error("control admin is not active");return {drive: claims.drive,subjects: ["operator:"],isOperator: true,- primarySubject: sub,+ primarySubject: canonicalSub,requestId,};}+ // Rollout ordering: control-api must stamp principalType=control-admin before+ // gfsc is exposed to brokered operator tokens. Until then an omitted marker+ // deliberately remains an ordinary user, which is safe but temporarily+ // denies operator authority rather than elevating a bare UUID.+// Every remaining bare principal is resolved conservatively as a user. An// omitted marker never probes the admin table: only an explicit signed// control-admin marker (or validated broker metadata above) can elevate.// This also keeps legacy/unmarked user tokens fail-closed during rollout.// A user resolves to itself plus every team it is an ACTIVE member of// (soft-deleted memberships excluded — deny-by-default).- const subjects = new Set<string>([`user:${sub}`]);+ const subjects = new Set<string>([`user:${canonicalSub}`]);const res = await db.query(`SELECT team_id FROM team_members WHERE user_id = $1 AND status = 'active'`,- [sub]+ [canonicalSub]);for (const row of res.rows) {subjects.add(`team:${String(row.team_id)}`);@@ -118,8 +132,8 @@ export async function resolveAuthzContext(drive: claims.drive,subjects: [...subjects],isOperator: false,- primarySubject: sub,- desktopUserId: sub,+ primarySubject: canonicalSub,+ desktopUserId: canonicalSub,authoritySource: "user-session",requestId,};diff --git a/profile-ui/lib/api.ts b/profile-ui/lib/api.tsindex dc01e2773..3649537b6 100644--- a/profile-ui/lib/api.ts+++ b/profile-ui/lib/api.ts@@ -107,10 +107,12 @@ export async function apiSend(method: 'POST' | 'PUT' | 'PATCH' | 'DELETE',path: string,body?: unknown,- q: Record<string, string | undefined> = {}+ q: Record<string, string | undefined> = {},+ extraHeaders: Record<string, string> = {}) {const headers: Record<string, string> = {'Content-Type': 'application/json',+ ...extraHeaders,}const res = await fetch(`${EXTERNAL_REST_API_BASE_URL}${path}${query(q)}`, {@@ -305,8 +307,40 @@ export async function deleteManagedMember(userId: string, teamId: string) {)}-export async function deleteManagedUser(userId: string) {- return apiSend('DELETE', `/api/v1/members/${encodeURIComponent(userId)}`)+export type DeleteManagedUserRequest = {+ reason?: string+ idempotencyKey?: string+ correlationId?: string+}++const UUID_ANY_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i++function generateRetirementRequestId(): string {+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {+ return crypto.randomUUID()+ }+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, marker => {+ const nibble = Math.floor(Math.random() * 16)+ return (marker === 'x' ? nibble : (nibble & 0x3) | 0x8).toString(16)+ })+}++export async function deleteManagedUser(userId: string, request: DeleteManagedUserRequest = {}) {+ const idempotencyKey = request.idempotencyKey?.trim() || generateRetirementRequestId()+ const providedCorrelationId = request.correlationId?.trim() || ''+ const correlationId = UUID_ANY_RE.test(providedCorrelationId)+ ? providedCorrelationId.toLowerCase()+ : generateRetirementRequestId()+ return apiSend(+ 'DELETE',+ `/api/v1/members/${encodeURIComponent(userId)}`,+ { reason: request.reason?.trim() || 'profile_ui_user_retirement' },+ {},+ {+ 'Idempotency-Key': idempotencyKey,+ 'x-correlation-id': correlationId,+ }+ )}export async function resendManagedInvitation(invitationId: string) {diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.jsonindex 728838ce2..ee80888fa 100644--- a/profile-ui/package-lock.json+++ b/profile-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-profile-ui",- "version": "0.1.120",+ "version": "0.1.121","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-profile-ui",- "version": "0.1.120",+ "version": "0.1.121","dependencies": {"@clerum/desktop-app-links": "file:../packages/desktop-app-links","next": "16.2.11",diff --git a/profile-ui/package.json b/profile-ui/package.jsonindex a42c74fed..d13d230b7 100644--- a/profile-ui/package.json+++ b/profile-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-profile-ui",- "version": "0.1.120",+ "version": "0.1.121","private": true,"scripts": {"dev": "next dev",diff --git a/profile-ui/test/memberApi.test.ts b/profile-ui/test/memberApi.test.tsnew file mode 100644index 000000000..ea1d3563e--- /dev/null+++ b/profile-ui/test/memberApi.test.ts@@ -0,0 +1,37 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { deleteManagedUser } from '../lib/api'++const USER_ID = '11111111-1111-4111-8111-111111111111'+const CORRELATION_ID = '22222222-2222-4222-8222-222222222222'++test('deleteManagedUser sends the governed retirement contract', async () => {+ const previousFetch = globalThis.fetch+ let request: { url: string; init?: RequestInit } | undefined+ globalThis.fetch = (async (input, init) => {+ request = { url: String(input), init }+ return new Response(JSON.stringify({ deleted: true, id: USER_ID }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ }) as typeof fetch+ try {+ const result = await deleteManagedUser(USER_ID, {+ reason: 'access review complete',+ idempotencyKey: 'profile-retire-v1',+ correlationId: CORRELATION_ID,+ })+ assert.deepEqual(result, { deleted: true, id: USER_ID })+ const capturedRequest = request+ assert.ok(capturedRequest)+ assert.equal(capturedRequest.init?.method, 'DELETE')+ const headers = new Headers(capturedRequest.init?.headers)+ assert.equal(headers.get('Idempotency-Key'), 'profile-retire-v1')+ assert.equal(headers.get('x-correlation-id'), CORRELATION_ID)+ assert.deepEqual(JSON.parse(String(capturedRequest.init?.body)), {+ reason: 'access review complete',+ })+ } finally {+ globalThis.fetch = previousFetch+ }+})diff --git a/scripts/tests/test-gcp-scripts.sh b/scripts/tests/test-gcp-scripts.shindex ce2c2d28f..dc20caf35 100755--- a/scripts/tests/test-gcp-scripts.sh+++ b/scripts/tests/test-gcp-scripts.sh@@ -1482,7 +1482,6 @@ assert_control_api_runtime_access_contract_is_exact() {[[ "$migration_script" == *'IS DISTINCT FROM required.allowed'* ]] && \[[ "$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', 'link_lifecycle'))"* ]] && \[[ "$migration_script" == *"('DELETE', expected.access_profile IN ('legacy_dml'))"* ]] && \[[ "$migration_script" == *"('TRUNCATE', false)"* ]] && \