Skip to content

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

TypeScript

fix(gfs): complete audited operator lifecycle and rate boundary

Alfredo Lopez8d4f9e304605
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index d78421ad4..7d2c353a9 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -133,6 +133,11 @@ type Config = {
approvalRlExternalPerMin: number
oauthBrokerRlPerMin: number
adminPublicTokenRlPerMin: number
+ // External Desktop GFS is a separate authority plane. These values are the
+ // approved fixed budgets for its pre-resolution and resolved-operation gates.
+ externalGfsTokenUserRlPerMin: number
+ externalGfsIpRlPerMin: number
+ externalGfsOperationRlPerMin: number
// Stateless-agent wake endpoint: per-host wake rate limit + server-side
// coalescence window for the wake-annotation projection.
hostWakeRlPerMin: number
@@ -728,6 +733,12 @@ export const config: Config = {
approvalRlExternalPerMin: Number(process.env.APPROVAL_RL_EXTERNAL_PER_MIN || 60),
oauthBrokerRlPerMin: Number(process.env.CONTROL_API_OAUTH_BROKER_RL_PER_MIN || 60),
adminPublicTokenRlPerMin: Number(process.env.CONTROL_API_ADMIN_PUBLIC_TOKEN_RL_PER_MIN || 20),
+ // Approved GFS authority-boundary budgets. Keep them fixed here rather than
+ // accepting an unreviewed environment override: token minting is 10/min per
+ // Desktop user and 30/min per source IP; every other operation class is 30/min.
+ externalGfsTokenUserRlPerMin: 10,
+ externalGfsIpRlPerMin: 30,
+ externalGfsOperationRlPerMin: 30,
// Default derived from the wake mechanism's worst case, not picked ad hoc.
// rpc-proxy's wake-and-hold loop re-triggers POST /rpc/hosts/:hostRef/wake
// every wakeRetriggerMs=15000 for up to wakeMaxHoldMs=90000 (defaults in
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index 8fdf0ed36..971e662e3 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -2725,6 +2725,204 @@ async function evolveGfsDesktopOperatorLinksToGenerations(db: DbClient): Promise
`)
}
+/**
+ * Governed Desktop-user retirement is a state transition, not a destructive
+ * shortcut around retained operator-link history. This remains additive so
+ * historical users are explicitly backfilled into the active lifecycle state.
+ */
+async function applyDesktopUserRetirementLifecycleSchema(db: DbClient): Promise<void> {
+ await db.query(`
+ ALTER TABLE users
+ ADD COLUMN IF NOT EXISTS lifecycle_state TEXT,
+ ADD COLUMN IF NOT EXISTS retired_at TIMESTAMPTZ,
+ ADD COLUMN IF NOT EXISTS retirement_reason TEXT,
+ ADD COLUMN IF NOT EXISTS retired_by_type TEXT,
+ ADD COLUMN IF NOT EXISTS retired_by_control_admin_id UUID,
+ ADD COLUMN IF NOT EXISTS retired_by_desktop_user_id UUID,
+ ADD COLUMN IF NOT EXISTS retirement_request_id TEXT,
+ ADD COLUMN IF NOT EXISTS retirement_operation_id UUID,
+ ADD COLUMN IF NOT EXISTS lifecycle_version BIGINT;
+
+ -- Fresh and already-existing users are both active until an explicit
+ -- governed retirement transition records actor, reason, and outcome.
+ UPDATE users
+ SET lifecycle_state = COALESCE(lifecycle_state, 'active'),
+ lifecycle_version = COALESCE(lifecycle_version, 1)
+ WHERE lifecycle_state IS NULL OR lifecycle_version IS NULL;
+
+ ALTER TABLE users
+ ALTER COLUMN lifecycle_state SET DEFAULT 'active',
+ ALTER COLUMN lifecycle_state SET NOT NULL,
+ ALTER COLUMN lifecycle_version SET DEFAULT 1,
+ ALTER COLUMN lifecycle_version SET NOT NULL;
+
+ CREATE TABLE IF NOT EXISTS desktop_user_retirement_operations (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ operation TEXT NOT NULL DEFAULT 'retire_desktop_user'
+ CHECK (operation = 'retire_desktop_user'),
+ actor_type TEXT NOT NULL CHECK (actor_type IN ('control_admin', 'platform_user')),
+ actor_control_admin_id UUID NULL,
+ actor_desktop_user_id UUID NULL,
+ target_user_id UUID NOT NULL,
+ idempotency_key_hash TEXT NOT NULL CHECK (idempotency_key_hash ~ '^[0-9a-f]{64}$'),
+ request_fingerprint TEXT NOT NULL CHECK (request_fingerprint ~ '^[0-9a-f]{64}$'),
+ reason TEXT NOT NULL CHECK (char_length(reason) BETWEEN 1 AND 512),
+ request_id TEXT NULL CHECK (request_id IS NULL OR char_length(request_id) <= 256),
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'completed')),
+ outcome TEXT NULL CHECK (outcome IS NULL OR outcome IN ('retired', 'deleted')),
+ lifecycle_version BIGINT NULL CHECK (lifecycle_version IS NULL OR lifecycle_version > 0),
+ lifecycle_operation_id UUID NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ completed_at TIMESTAMPTZ NULL,
+ CHECK (
+ (actor_type = 'control_admin'
+ AND actor_control_admin_id IS NOT NULL
+ AND actor_desktop_user_id IS NULL)
+ OR
+ (actor_type = 'platform_user'
+ AND actor_control_admin_id IS NULL
+ AND actor_desktop_user_id IS NOT NULL)
+ ),
+ CHECK (
+ (status = 'pending'
+ AND outcome IS NULL
+ AND lifecycle_version IS NULL
+ AND lifecycle_operation_id IS NULL
+ AND completed_at IS NULL)
+ OR
+ (status = 'completed'
+ AND outcome IS NOT NULL
+ AND completed_at IS NOT NULL
+ AND (
+ (outcome = 'retired' AND lifecycle_version IS NOT NULL AND lifecycle_operation_id IS NOT NULL)
+ OR
+ (outcome = 'deleted' AND lifecycle_version IS NULL AND lifecycle_operation_id IS NULL)
+ ))
+ )
+ );
+
+ -- The target deliberately has no FK: a legacy-compatible hard-delete for
+ -- a user with no link history must still leave an idempotent outcome record.
+ -- Actor columns remain separate; no caller identity is inferred from UUID shape.
+ CREATE UNIQUE INDEX IF NOT EXISTS desktop_user_retirement_operations_control_admin_key
+ ON desktop_user_retirement_operations
+ (operation, actor_control_admin_id, target_user_id, idempotency_key_hash)
+ WHERE actor_type = 'control_admin';
+ CREATE UNIQUE INDEX IF NOT EXISTS desktop_user_retirement_operations_platform_user_key
+ ON desktop_user_retirement_operations
+ (operation, actor_desktop_user_id, target_user_id, idempotency_key_hash)
+ WHERE actor_type = 'platform_user';
+ CREATE INDEX IF NOT EXISTS desktop_user_retirement_operations_target_idx
+ ON desktop_user_retirement_operations (target_user_id, completed_at DESC);
+
+ ALTER TABLE users
+ DROP CONSTRAINT IF EXISTS users_retired_by_control_admin_id_fkey;
+ ALTER TABLE users
+ ADD CONSTRAINT users_retired_by_control_admin_id_fkey
+ FOREIGN KEY (retired_by_control_admin_id)
+ REFERENCES control_admin_users(id) ON DELETE RESTRICT;
+ ALTER TABLE users
+ DROP CONSTRAINT IF EXISTS users_retired_by_desktop_user_id_fkey;
+ ALTER TABLE users
+ ADD CONSTRAINT users_retired_by_desktop_user_id_fkey
+ FOREIGN KEY (retired_by_desktop_user_id)
+ REFERENCES users(id) ON DELETE RESTRICT;
+ ALTER TABLE users
+ DROP CONSTRAINT IF EXISTS users_retirement_operation_id_fkey;
+ ALTER TABLE users
+ ADD CONSTRAINT users_retirement_operation_id_fkey
+ FOREIGN KEY (retirement_operation_id)
+ REFERENCES desktop_user_retirement_operations(id) ON DELETE RESTRICT;
+ ALTER TABLE users
+ DROP CONSTRAINT IF EXISTS users_lifecycle_version_check;
+ ALTER TABLE users
+ ADD CONSTRAINT users_lifecycle_version_check CHECK (lifecycle_version > 0);
+ ALTER TABLE users
+ DROP CONSTRAINT IF EXISTS users_lifecycle_state_check;
+ ALTER TABLE users
+ ADD CONSTRAINT users_lifecycle_state_check CHECK (
+ (lifecycle_state = 'active'
+ AND retired_at IS NULL
+ AND retirement_reason IS NULL
+ AND retired_by_type IS NULL
+ AND retired_by_control_admin_id IS NULL
+ AND retired_by_desktop_user_id IS NULL
+ AND retirement_request_id IS NULL
+ AND retirement_operation_id IS NULL)
+ OR
+ (lifecycle_state = 'retired'
+ AND retired_at IS NOT NULL
+ AND char_length(retirement_reason) BETWEEN 1 AND 512
+ AND retirement_operation_id IS NOT NULL
+ AND (
+ (retired_by_type = 'control_admin'
+ AND retired_by_control_admin_id IS NOT NULL
+ AND retired_by_desktop_user_id IS NULL)
+ OR
+ (retired_by_type = 'platform_user'
+ AND retired_by_control_admin_id IS NULL
+ AND retired_by_desktop_user_id IS NOT NULL)
+ ))
+ );
+ CREATE INDEX IF NOT EXISTS users_lifecycle_state_idx ON users (lifecycle_state);
+
+ ALTER TABLE gfs_desktop_operator_links
+ ADD COLUMN IF NOT EXISTS revoked_by_control_admin_id UUID,
+ ADD COLUMN IF NOT EXISTS revoked_by_desktop_user_id UUID;
+
+ -- 0093 could only record a Control Admin in revoked_by_id. Preserve that
+ -- exact historic actor in the typed column before broadening the union.
+ UPDATE gfs_desktop_operator_links
+ SET revoked_by_control_admin_id = revoked_by_id
+ WHERE state = 'revoked'
+ AND revoked_by_type = 'control_admin'
+ AND revoked_by_control_admin_id IS NULL;
+
+ ALTER TABLE gfs_desktop_operator_links
+ DROP CONSTRAINT IF EXISTS gfs_desktop_operator_links_revoked_by_control_admin_id_fkey;
+ ALTER TABLE gfs_desktop_operator_links
+ ADD CONSTRAINT gfs_desktop_operator_links_revoked_by_control_admin_id_fkey
+ FOREIGN KEY (revoked_by_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_revoked_by_desktop_user_id_fkey;
+ ALTER TABLE gfs_desktop_operator_links
+ ADD CONSTRAINT gfs_desktop_operator_links_revoked_by_desktop_user_id_fkey
+ FOREIGN KEY (revoked_by_desktop_user_id)
+ REFERENCES users(id) ON DELETE RESTRICT;
+ 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 revoked_by_control_admin_id IS NULL
+ AND revoked_by_desktop_user_id IS NULL
+ AND revocation_reason IS NULL)
+ OR
+ (state = 'revoked'
+ AND revoked_at IS NOT NULL
+ AND revocation_reason IS NOT NULL
+ AND (
+ (revoked_by_type = 'control_admin'
+ AND revoked_by_id IS NOT NULL
+ AND revoked_by_control_admin_id = revoked_by_id
+ AND revoked_by_desktop_user_id IS NULL)
+ OR
+ (revoked_by_type = 'platform_user'
+ AND revoked_by_id IS NULL
+ AND revoked_by_control_admin_id IS NULL
+ AND revoked_by_desktop_user_id IS NOT NULL)
+ ))
+ );
+
+ GRANT SELECT, INSERT, UPDATE ON TABLE desktop_user_retirement_operations TO control_api_runtime;
+ REVOKE DELETE, TRUNCATE, REFERENCES, TRIGGER ON TABLE desktop_user_retirement_operations 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
@@ -5599,6 +5797,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0093_gfs_desktop_operator_link_generations',
apply: evolveGfsDesktopOperatorLinksToGenerations,
},
+ {
+ version: '0094_desktop_user_retirement_lifecycle',
+ apply: applyDesktopUserRetirementLifecycleSchema,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/src/gfs/externalAuthority.ts b/control-api/src/gfs/externalAuthority.ts
index 60a19ef47..ae75129fe 100644
--- a/control-api/src/gfs/externalAuthority.ts
+++ b/control-api/src/gfs/externalAuthority.ts
@@ -25,7 +25,10 @@ export type ExternalGfsAuthority = ExternalGfsUserAuthority | ExternalGfsLinkedA
export class ExternalGfsAuthorityError extends Error {
constructor(
readonly status: 403 | 503,
- readonly code: 'gfs_operator_link_invalid' | 'gfs_authority_unavailable',
+ readonly code:
+ | 'desktop_user_retired'
+ | 'gfs_operator_link_invalid'
+ | 'gfs_authority_unavailable',
options?: { cause?: unknown }
) {
super(code, options?.cause === undefined ? undefined : { cause: options.cause })
@@ -36,8 +39,20 @@ export class ExternalGfsAuthorityError extends Error {
type AuthorityDependencies = {
linkingEnabled: boolean
resolveActiveLink(desktopUserId: string): Promise<GfsDesktopOperatorLink | null>
+ /** Optional only for isolated tests; production always supplies this guard. */
+ isDesktopUserActive?(desktopUserId: string): Promise<boolean>
}
+// The production singleton always implements the lifecycle guard. The runtime
+// structural check keeps isolated callers that provide the historic read-only
+// link double from being misclassified as a database outage; it is not a
+// production fallback for a failed lifecycle lookup (those still return 503).
+const defaultDesktopUserLifecycleGuard =
+ typeof (gfsDesktopOperatorLinkService as Partial<typeof gfsDesktopOperatorLinkService>)
+ .isDesktopUserActive === 'function'
+ ? (id: string) => gfsDesktopOperatorLinkService.isDesktopUserActive(id)
+ : undefined
+
function userAuthority(desktopUserId: string): ExternalGfsUserAuthority {
return { kind: 'user-session', desktopUserId, tokenSubject: desktopUserId }
}
@@ -45,18 +60,29 @@ function userAuthority(desktopUserId: string): ExternalGfsUserAuthority {
/**
* Resolve the effective GFS authority for one authenticated Desktop user.
*
- * The feature flag is checked before the persisted link is read. A disabled or
- * missing flag therefore cannot elevate a request. An absent row means an
- * ordinary user session, while any malformed, conflicting, missing-admin, or
- * inactive-admin row fails closed instead of falling back to user authority.
+ * A retired user is denied before the feature flag can select ordinary
+ * user-session authority. The flag is otherwise checked before the persisted
+ * link is read. An absent row means an ordinary user session, while any
+ * malformed, conflicting, missing-admin, or inactive-admin row fails closed.
*/
export async function resolveExternalGfsAuthority(
desktopUserId: string,
dependencies: AuthorityDependencies = {
linkingEnabled: config.desktopGfsOperatorLinkingEnabled === true,
resolveActiveLink: id => gfsDesktopOperatorLinkService.resolveActiveLink(id),
+ 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 })
+ }
+ }
if (dependencies.linkingEnabled !== true) return userAuthority(desktopUserId)
let link: GfsDesktopOperatorLink | null
diff --git a/control-api/src/middleware/externalGfsRateLimit.ts b/control-api/src/middleware/externalGfsRateLimit.ts
new file mode 100644
index 000000000..5745c7bec
--- /dev/null
+++ b/control-api/src/middleware/externalGfsRateLimit.ts
@@ -0,0 +1,318 @@
+import type { NextFunction, Request, Response } from 'express'
+import { createHash } from 'node:crypto'
+import { isIP } from 'node:net'
+import { config } from '../config.js'
+import type { ExternalGfsAuthority } from '../gfs/externalAuthority.js'
+import { rootLogger } from '../observability/logger.js'
+import {
+ externalGfsRateLimitDurationSeconds,
+ externalGfsRateLimitRequestsTotal,
+} from '../observability/metrics.js'
+import { type RateLimitCheck, checkAndIncrement } from '../services/rateLimiterService.js'
+
+/**
+ * The external Desktop GFS surface has a small, explicit operation matrix.
+ * Keeping the classifier here makes a newly added handler fail review/tests
+ * until it is assigned to a bounded class; there is no route-level default
+ * that can silently bypass the authority-resolution DoS boundary.
+ */
+export type ExternalGfsOperationClass =
+ | 'token'
+ | 'resource'
+ | 'proxy-read'
+ | 'resource-mutation'
+ | 'grants'
+ | 'shares'
+
+export type ExternalGfsOperation = {
+ operationClass: ExternalGfsOperationClass
+ route: string
+}
+
+type ExternalGfsRateLimitPhase = 'pre-resolution' | 'resolved-operation'
+type Bucket = { key: string; maxPerMinute: number }
+
+type ExternalGfsAuthedRequest = Request & {
+ externalAuth?: { userId?: string }
+ gfsAuthority?: ExternalGfsAuthority
+}
+
+const GFS_PREFIX = '/external/gfs'
+
+function pathWithinExternalGfs(req: Request): string {
+ // At this router's middleware layer Express has already removed the route
+ // prefix from req.path, while req.baseUrl retains it. This reconstruction
+ // works both when the router is mounted beneath /api/v1 in production and
+ // when it is mounted directly in a focused route test.
+ const mountedPath = `${req.baseUrl ?? ''}${req.path ?? ''}`
+ const marker = mountedPath.lastIndexOf(GFS_PREFIX)
+ if (marker >= 0) return mountedPath.slice(marker + GFS_PREFIX.length) || '/'
+
+ const originalPath = String(req.originalUrl ?? '').split('?', 1)[0]
+ const originalMarker = originalPath.lastIndexOf(GFS_PREFIX)
+ if (originalMarker >= 0) return originalPath.slice(originalMarker + GFS_PREFIX.length) || '/'
+
+ return req.path || '/'
+}
+
+/** Map every external GFS handler to exactly one approved rate class. */
+export function externalGfsOperationFor(
+ req: Pick<Request, 'method' | 'baseUrl' | 'path' | 'originalUrl'>
+): ExternalGfsOperation | null {
+ const path = pathWithinExternalGfs(req as Request)
+ const method = req.method.toUpperCase()
+
+ if (method === 'POST' && path === '/token') {
+ return { operationClass: 'token', route: `${GFS_PREFIX}/token` }
+ }
+ if (path === '/resolve' && method === 'GET') {
+ return { operationClass: 'resource', route: `${GFS_PREFIX}/resolve` }
+ }
+ if (path === '/resources' && method === 'GET') {
+ return { operationClass: 'resource', route: `${GFS_PREFIX}/resources` }
+ }
+ if (/^\/resources\/[^/]+\/affordances$/.test(path) && method === 'GET') {
+ return { operationClass: 'resource', route: `${GFS_PREFIX}/resources/:id/affordances` }
+ }
+ if (/^\/resources\/[^/]+\/children$/.test(path)) {
+ return method === 'GET'
+ ? { operationClass: 'resource', route: `${GFS_PREFIX}/resources/:id/children` }
+ : method === 'POST'
+ ? { operationClass: 'resource-mutation', route: `${GFS_PREFIX}/resources/:id/children` }
+ : null
+ }
+ if (/^\/resources\/[^/]+\/content$/.test(path) && method === 'PUT') {
+ return { operationClass: 'resource-mutation', route: `${GFS_PREFIX}/resources/:id/content` }
+ }
+ if (/^\/resources\/[^/]+$/.test(path)) {
+ return method === 'PATCH' || method === 'DELETE'
+ ? { operationClass: 'resource-mutation', route: `${GFS_PREFIX}/resources/:id` }
+ : null
+ }
+ if (/^\/proxy\/[^/]+$/.test(path) && method === 'GET') {
+ return { operationClass: 'proxy-read', route: `${GFS_PREFIX}/proxy/:rid` }
+ }
+ if (path === '/grants' && (method === 'GET' || method === 'PUT')) {
+ return { operationClass: 'grants', route: `${GFS_PREFIX}/grants` }
+ }
+ if (/^\/grants\/[^/]+$/.test(path) && method === 'DELETE') {
+ return { operationClass: 'grants', route: `${GFS_PREFIX}/grants/:id` }
+ }
+ if (path === '/shares' && (method === 'GET' || method === 'POST')) {
+ return { operationClass: 'shares', route: `${GFS_PREFIX}/shares` }
+ }
+ if (/^\/shares\/[^/]+$/.test(path) && method === 'DELETE') {
+ return { operationClass: 'shares', route: `${GFS_PREFIX}/shares/:id` }
+ }
+ return null
+}
+
+function digest(value: string): string {
+ return createHash('sha256').update(value).digest('hex')
+}
+
+function authenticatedSessionDigest(req: Request): string | null {
+ const token = req.header('x-user-session-token')?.trim()
+ return token ? digest(token) : null
+}
+
+function sourceIpDigest(req: Request): string {
+ // The app-level /external gate accepts only the authenticated
+ // external-rest-api service. That service overwrites X-Forwarded-For with
+ // its proxy-attested client address; profile-control-funnel then appends its
+ // pod peer. Read the validated first element so the pre-resolution IP bucket
+ // remains per client rather than collapsing every Desktop installation into
+ // the funnel's address. Direct/test callers fall back to Express's normal
+ // proxy-aware address.
+ const forwardedIp = req.header('x-forwarded-for')?.split(',', 1)[0]?.trim()
+ const ip =
+ forwardedIp && isIP(forwardedIp) !== 0
+ ? forwardedIp
+ : req.ip || req.socket.remoteAddress || '__unknown_peer__'
+ return digest(ip)
+}
+
+function applyRateLimitHeaders(
+ res: Response,
+ result: RateLimitCheck,
+ maxPerMinute: number
+): number {
+ const retryAfterSeconds = Math.max(1, Math.ceil((result.resetMs - Date.now()) / 1000))
+ res.setHeader('Retry-After', String(retryAfterSeconds))
+ res.setHeader('X-RateLimit-Limit', String(maxPerMinute))
+ res.setHeader('X-RateLimit-Remaining', '0')
+ res.setHeader('X-RateLimit-Reset', String(Math.floor(result.resetMs / 1000)))
+ return retryAfterSeconds
+}
+
+function applyAllowedRateHeaders(
+ res: Response,
+ result: RateLimitCheck,
+ maxPerMinute: number
+): void {
+ res.setHeader('X-RateLimit-Limit', String(maxPerMinute))
+ res.setHeader('X-RateLimit-Remaining', String(result.remaining))
+ res.setHeader('X-RateLimit-Reset', String(Math.floor(result.resetMs / 1000)))
+}
+
+function reportDecision(input: {
+ bucket: Bucket
+ operation: ExternalGfsOperation
+ phase: ExternalGfsRateLimitPhase
+ outcome: 'allowed' | 'denied'
+ latencyMs: number
+ authorityResolutionAvoided: boolean
+}): void {
+ const labels = {
+ operation_class: input.operation.operationClass,
+ route: input.operation.route,
+ outcome: input.outcome,
+ phase: input.phase,
+ authority_resolution_avoided: input.authorityResolutionAvoided ? 'true' : 'false',
+ }
+ externalGfsRateLimitRequestsTotal.inc(labels)
+ externalGfsRateLimitDurationSeconds.observe(labels, input.latencyMs / 1_000)
+
+ // The hash gives operators a join key for a single limiter identity without
+ // exposing session tokens, source IPs, or stable internal IDs in logs.
+ const fields = {
+ event: 'external_gfs_rate_limit',
+ operationClass: input.operation.operationClass,
+ route: input.operation.route,
+ outcome: input.outcome,
+ phase: input.phase,
+ hashedKey: digest(input.bucket.key),
+ latencyMs: input.latencyMs,
+ authorityResolutionAvoided: input.authorityResolutionAvoided,
+ }
+ if (input.outcome === 'denied') {
+ rootLogger.warn(fields, 'external GFS rate limit denied')
+ } else {
+ rootLogger.debug(fields, 'external GFS rate limit checked')
+ }
+}
+
+async function enforceBuckets(input: {
+ req: Request
+ res: Response
+ operation: ExternalGfsOperation
+ phase: ExternalGfsRateLimitPhase
+ buckets: readonly Bucket[]
+}): Promise<boolean> {
+ for (const bucket of input.buckets) {
+ const startedAt = performance.now()
+ const result = await checkAndIncrement(bucket.key, bucket.maxPerMinute)
+ const latencyMs = performance.now() - startedAt
+ const allowed = result.allowed
+ reportDecision({
+ bucket,
+ operation: input.operation,
+ phase: input.phase,
+ outcome: allowed ? 'allowed' : 'denied',
+ latencyMs,
+ authorityResolutionAvoided: input.phase === 'pre-resolution' && !allowed,
+ })
+ if (!allowed) {
+ const retryAfterSeconds = applyRateLimitHeaders(input.res, result, bucket.maxPerMinute)
+ input.res.status(429).json({ error: 'Too Many Requests', retryAfterSeconds })
+ return false
+ }
+ applyAllowedRateHeaders(input.res, result, bucket.maxPerMinute)
+ }
+ return true
+}
+
+/**
+ * First rate gate: runs immediately after the external Session-JWT check and
+ * before attachExternalGfsAuthority can touch the link resolver or any
+ * authority database path. Token mint intentionally remains user-only, so its
+ * stable per-user + per-IP limits are complete at this phase.
+ */
+export function externalGfsPreResolutionRateLimit(
+ req: Request,
+ res: Response,
+ next: NextFunction
+): void {
+ void (async () => {
+ const operation = externalGfsOperationFor(req)
+ if (!operation) {
+ // Do not let an unclassified path fall through to the global authority
+ // resolver. Besides preserving the ordinary external API 404 shape, this
+ // makes the route matrix exhaustive at the authority boundary: a new
+ // handler must be classified before it can reach any DB-backed work.
+ res.status(404).json({ error: 'Not Found' })
+ return
+ }
+ const externalReq = req as ExternalGfsAuthedRequest
+ const desktopUserId = externalReq.externalAuth?.userId
+ const sessionDigest = authenticatedSessionDigest(req)
+ if (!desktopUserId || !sessionDigest) {
+ res.status(401).json({ error: 'Unauthorized' })
+ return
+ }
+
+ const buckets: Bucket[] =
+ operation.operationClass === 'token'
+ ? [
+ {
+ key: `gfs-ext:pre:token:user:${desktopUserId}`,
+ maxPerMinute: config.externalGfsTokenUserRlPerMin,
+ },
+ {
+ key: `gfs-ext:pre:token:ip:${sourceIpDigest(req)}`,
+ maxPerMinute: config.externalGfsIpRlPerMin,
+ },
+ ]
+ : [
+ {
+ key: `gfs-ext:pre:${operation.operationClass}:session:${sessionDigest}`,
+ maxPerMinute: config.externalGfsOperationRlPerMin,
+ },
+ {
+ key: `gfs-ext:pre:${operation.operationClass}:ip:${sourceIpDigest(req)}`,
+ maxPerMinute: config.externalGfsOperationRlPerMin,
+ },
+ ]
+
+ if (await enforceBuckets({ req, res, operation, phase: 'pre-resolution', buckets })) next()
+ })().catch(next)
+}
+
+/**
+ * Second rate gate: runs only after the server-derived authority is attached.
+ * It is keyed by the effective actor and operation class, so refreshing or
+ * reminting a public user token cannot evade the brokered-operation budget.
+ */
+export function externalGfsResolvedOperationRateLimit(
+ req: Request,
+ res: Response,
+ next: NextFunction
+): void {
+ void (async () => {
+ const operation = externalGfsOperationFor(req)
+ if (!operation || operation.operationClass === 'token') {
+ next()
+ return
+ }
+ const authority = (req as ExternalGfsAuthedRequest).gfsAuthority
+ if (!authority) {
+ res.status(401).json({ error: 'unauthenticated' })
+ return
+ }
+ const bucket: Bucket = {
+ key: `gfs-ext:resolved:${operation.operationClass}:actor:${authority.kind}:${authority.tokenSubject}`,
+ maxPerMinute: config.externalGfsOperationRlPerMin,
+ }
+ if (
+ await enforceBuckets({
+ req,
+ res,
+ operation,
+ phase: 'resolved-operation',
+ buckets: [bucket],
+ })
+ ) {
+ next()
+ }
+ })().catch(next)
+}
diff --git a/control-api/src/observability/metrics.ts b/control-api/src/observability/metrics.ts
index dc4bed2bc..cb77feecf 100644
--- a/control-api/src/observability/metrics.ts
+++ b/control-api/src/observability/metrics.ts
@@ -254,6 +254,42 @@ export const rateLimitHitsTotal = getOrCreateCounter({
labelNames: ['bucket_type', 'result'] as const as Array<'bucket_type' | 'result'>,
})
+// ─── External GFS rate-boundary metrics ────────────────────────────────────
+//
+// The rate-limit bucket key is deliberately *not* a Prometheus label: even a
+// one-way digest is unbounded cardinality and would turn the metrics endpoint
+// into a durable identity side channel. The middleware emits the digest in its
+// structured event instead, while these metrics retain the bounded route and
+// operation dimensions needed for alerting.
+export const externalGfsRateLimitRequestsTotal = getOrCreateCounter({
+ name: 'external_gfs_rate_limit_requests_total',
+ help: 'External GFS rate-boundary decisions by operation class, route, phase, and outcome.',
+ labelNames: [
+ 'operation_class',
+ 'route',
+ 'outcome',
+ 'phase',
+ 'authority_resolution_avoided',
+ ] as const as Array<
+ 'operation_class' | 'route' | 'outcome' | 'phase' | 'authority_resolution_avoided'
+ >,
+})
+
+export const externalGfsRateLimitDurationSeconds = getOrCreateHistogram({
+ name: 'external_gfs_rate_limit_duration_seconds',
+ help: 'External GFS rate-boundary decision latency by bounded operation dimensions.',
+ labelNames: [
+ 'operation_class',
+ 'route',
+ 'outcome',
+ 'phase',
+ 'authority_resolution_avoided',
+ ] as const as Array<
+ 'operation_class' | 'route' | 'outcome' | 'phase' | 'authority_resolution_avoided'
+ >,
+ buckets: [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1],
+})
+
// ─── Workflow-run archival cron metrics (DB-first, replaces CRD reaper) ──
export const workflowRunsArchiveRunsTotal = getOrCreateCounter({
name: 'workflow_runs_archive_runs_total',
diff --git a/control-api/src/routes/admin/users.ts b/control-api/src/routes/admin/users.ts
index d58fd4720..5941dfd97 100644
--- a/control-api/src/routes/admin/users.ts
+++ b/control-api/src/routes/admin/users.ts
@@ -1,13 +1,15 @@
import { Router } from 'express'
import type { K8sGateway } from '../../k8s.js'
+import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
import {
- adminDeleteUser,
+ DesktopUserRetirementError,
createAdminUser,
createPasswordSetupInvitationForUser,
findMembership,
getAdminUserContext,
listTeams,
listUsers,
+ retireDesktopUser,
updateAdminUserContext,
} from '../../services/directory/index.js'
import { disableVerifiedMediumAccount } from '../../services/workflowApprovalMediumIdentityService.js'
@@ -244,28 +246,33 @@ export function createAdminUsersRouter(gateway: K8sGateway): Router {
registerAdminUserAccessRoutes(router, gateway)
- /**
- * 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) => {
+ /** Governed retirement requires the authenticated Control Admin and replay key. */
+ router.delete('/admin/users/:userId', async (req: UiAuthedRequest, res, next) => {
try {
- const result = await adminDeleteUser(req.params.userId)
- if ('error' in result) {
- if (result.error === 'not_found') {
- 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.error
- throw new Error(`Unhandled adminDeleteUser result: ${exhaustive}`)
+ const controlAdminId = req.adminAuth?.sub
+ if (!controlAdminId) {
+ return res.status(401).json({ error: 'Unauthorized' })
}
- res.status(200).json({ deleted: true, id: result.id })
+ const reason = typeof req.body?.reason === 'string' ? req.body.reason.trim() : ''
+ if (!reason) return res.status(400).json({ error: 'reason_required' })
+ const idempotencyKey = String(req.header('Idempotency-Key') || '').trim()
+ if (!idempotencyKey) return res.status(400).json({ error: 'idempotency_key_required' })
+ const result = await retireDesktopUser(
+ { kind: 'control_admin', controlAdminId },
+ req.params.userId,
+ reason,
+ idempotencyKey,
+ req.correlationId ?? null
+ )
+ return res.status(200).json({ deleted: true, id: result.id })
} catch (error) {
+ if (error instanceof DesktopUserRetirementError) {
+ if (error.code === 'not_found') return res.status(404).json({ error: 'not_found' })
+ if (error.code === 'invalid_input') {
+ return res.status(400).json({ error: 'invalid_retirement_input' })
+ }
+ return res.status(409).json({ error: error.code })
+ }
next(error)
}
})
diff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.ts
index 1dea0cc4e..71709f62d 100644
--- a/control-api/src/routes/external/gfs.ts
+++ b/control-api/src/routes/external/gfs.ts
@@ -24,6 +24,10 @@ import {
listChildrenPaged,
} from '../../gfs/tree.js'
import { asyncHandler } from '../../http/asyncHandler.js'
+import {
+ externalGfsPreResolutionRateLimit,
+ externalGfsResolvedOperationRateLimit,
+} from '../../middleware/externalGfsRateLimit.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -219,6 +223,11 @@ export function createExternalGfsRouter(): Router {
// (x-user-session-token, forwarded by external-rest-api) is required.
router.use('/external/gfs', requireValidExternalSessionToken)
router.use('/external/gfs', attachExternalGfsRequestId)
+ // This boundary deliberately precedes attachExternalGfsAuthority. A rate
+ // rejection therefore performs no operator-link lookup or route-specific
+ // database/handler work; see externalGfsRateLimit.ts for the complete
+ // session/IP and effective-actor operation-class matrix.
+ router.use('/external/gfs', externalGfsPreResolutionRateLimit)
// Per-user token bucket on the DELEGATION plane only (grants + shares),
// mirroring the admin plane's grantsRateLimit but in a DISTINCT bucket so the
@@ -273,6 +282,7 @@ export function createExternalGfsRouter(): Router {
// Public token mint above is deliberately user-only. Effective linked-admin
// authority is resolved only for the internal broker routes below.
router.use('/external/gfs', asyncHandler(attachExternalGfsAuthority))
+ router.use('/external/gfs', externalGfsResolvedOperationRateLimit)
// ── delegation: reuse the EXISTING grant/share handlers (caller-agnostic) ──
// resolveCaller(req) reads req.externalAuth → user:<id> plus all active team
diff --git a/control-api/src/routes/external/members.ts b/control-api/src/routes/external/members.ts
index ba07b87bb..54822ebdb 100644
--- a/control-api/src/routes/external/members.ts
+++ b/control-api/src/routes/external/members.ts
@@ -187,7 +187,15 @@ export function createExternalMembersRouter(): Router {
try {
const managerUserId = currentUserId(req)
if (!managerUserId) return res.status(403).json({ error: 'Forbidden' })
- const result = await deleteManagedUserForUser(managerUserId, req.params.userId)
+ const reason = typeof req.body?.reason === 'string' ? req.body.reason.trim() : ''
+ if (!reason) return res.status(400).json({ error: 'reason_required' })
+ const idempotencyKey = String(req.header('Idempotency-Key') || '').trim()
+ if (!idempotencyKey) return res.status(400).json({ error: 'idempotency_key_required' })
+ const result = await deleteManagedUserForUser(managerUserId, req.params.userId, {
+ reason,
+ idempotencyKey,
+ requestId: req.correlationId ?? null,
+ })
if ('error' in result) {
if (result.error === 'forbidden_uncontrolled_teams') {
return res.status(403).json({ error: 'forbidden_uncontrolled_teams' })
@@ -195,6 +203,12 @@ export function createExternalMembersRouter(): Router {
if (result.error === 'invalid_target') {
return res.status(400).json({ error: 'invalid_target' })
}
+ if (result.error === 'invalid_retirement_input') {
+ return res.status(400).json({ error: 'invalid_retirement_input' })
+ }
+ if (result.error === 'idempotency_conflict' || result.error === 'retirement_conflict') {
+ return res.status(409).json({ error: result.error })
+ }
return res.status(404).json({ error: 'not_found' })
}
return res.status(200).json(result.deleted)
diff --git a/control-api/src/services/adminAuthService.ts b/control-api/src/services/adminAuthService.ts
index ce4b8f9fc..c721add4e 100644
--- a/control-api/src/services/adminAuthService.ts
+++ b/control-api/src/services/adminAuthService.ts
@@ -564,7 +564,7 @@ export async function deleteControlAdmin(
await gfsDesktopOperatorLinkService.retireParentInTransaction(db, {
kind: 'control_admin',
parentId: adminId,
- operatorSub: actorAdminId,
+ actor: { kind: 'control_admin', controlAdminId: actorAdminId },
reason: 'control_admin_retired',
})
const deletedResult = await db.query(
diff --git a/control-api/src/services/directory/index.ts b/control-api/src/services/directory/index.ts
index 156fd7932..59e4b4461 100644
--- a/control-api/src/services/directory/index.ts
+++ b/control-api/src/services/directory/index.ts
@@ -6,10 +6,18 @@ export { googleLoginData, passwordLoginData, verifyUserPassword } from './login.
export {
adminDeleteUser,
createAdminUser,
+ DesktopUserRetirementError,
getAdminUserContext,
listUsers,
+ retireDesktopUser,
updateAdminUserContext,
} from './users.js'
+export type {
+ DesktopUserRetirementActor,
+ DesktopUserRetirementErrorCode,
+ DesktopUserRetirementOutcome,
+ RetireDesktopUserResult,
+} from './users.js'
export {
adminDeleteTeam,
diff --git a/control-api/src/services/directory/membership.ts b/control-api/src/services/directory/membership.ts
index 952cd5642..742634aca 100644
--- a/control-api/src/services/directory/membership.ts
+++ b/control-api/src/services/directory/membership.ts
@@ -9,7 +9,7 @@ import {
roleCanDeleteMembers,
roleCanInviteMembers,
} from './types.js'
-import { adminDeleteUser } from './users.js'
+import { DesktopUserRetirementError, retireDesktopUser } from './users.js'
export const INVITATION_TTL_HOURS = 48
const DRAFT_INVITATION_CLEANUP_HOURS = 24
@@ -1756,7 +1756,11 @@ export async function deleteManagedMemberForUser(
return { deleted }
}
-export async function deleteManagedUserForUser(managerUserId: string, targetUserId: string) {
+export async function deleteManagedUserForUser(
+ managerUserId: string,
+ targetUserId: string,
+ retirement: { reason: string; idempotencyKey: string; requestId: string | null }
+) {
const normalizedManagerUserId = managerUserId.trim()
const normalizedTargetUserId = targetUserId.trim()
if (!normalizedManagerUserId || !normalizedTargetUserId) {
@@ -1782,11 +1786,24 @@ export async function deleteManagedUserForUser(managerUserId: string, targetUser
return { error: 'forbidden_uncontrolled_teams' as const }
}
- const deleted = await adminDeleteUser(normalizedTargetUserId)
- if ('error' in deleted) {
- return { error: 'not_found' as const }
+ try {
+ const outcome = await retireDesktopUser(
+ { kind: 'platform_user', desktopUserId: normalizedManagerUserId },
+ normalizedTargetUserId,
+ retirement.reason,
+ retirement.idempotencyKey,
+ retirement.requestId
+ )
+ return { deleted: { ok: true as const, id: outcome.id }, outcome }
+ } catch (error) {
+ if (error instanceof DesktopUserRetirementError) {
+ if (error.code === 'not_found') return { error: 'not_found' as const }
+ if (error.code === 'invalid_input') return { error: 'invalid_retirement_input' as const }
+ if (error.code === 'idempotency_conflict') return { error: 'idempotency_conflict' as const }
+ return { error: 'retirement_conflict' as const }
+ }
+ throw error
}
- return { deleted }
}
export async function resendManagedInvitationForUser(managerUserId: string, invitationId: string) {
diff --git a/control-api/src/services/directory/users.ts b/control-api/src/services/directory/users.ts
index 5ec17e9a3..f267df578 100644
--- a/control-api/src/services/directory/users.ts
+++ b/control-api/src/services/directory/users.ts
@@ -1,7 +1,151 @@
+import { createHash } from 'node:crypto'
import { pool, withTransaction } from '../../db.js'
+import {
+ type GfsDesktopOperatorLifecycleActor,
+ GfsDesktopOperatorLinkError,
+ gfsDesktopOperatorLinkService,
+} from '../gfsDesktopOperatorLinkService.js'
import type { AdminDeleteUserResult } from './types.js'
import { normalizeChannels } from './types.js'
+export type DesktopUserRetirementActor = GfsDesktopOperatorLifecycleActor
+export type DesktopUserRetirementOutcome = 'retired' | 'deleted'
+
+export type RetireDesktopUserResult = {
+ id: string
+ outcome: DesktopUserRetirementOutcome
+ operationId: string
+ lifecycleVersion: number | null
+ replayed: boolean
+}
+
+export type DesktopUserRetirementErrorCode =
+ | 'invalid_input'
+ | 'not_found'
+ | 'idempotency_conflict'
+ | 'retirement_conflict'
+
+export class DesktopUserRetirementError extends Error {
+ constructor(
+ readonly code: DesktopUserRetirementErrorCode,
+ message: string = code
+ ) {
+ super(message)
+ this.name = 'DesktopUserRetirementError'
+ }
+}
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+const RETIREMENT_OPERATION = 'retire_desktop_user'
+
+function requireUuid(value: unknown, field: string): string {
+ const normalized = String(value ?? '')
+ .trim()
+ .toLowerCase()
+ if (!UUID_PATTERN.test(normalized)) {
+ throw new DesktopUserRetirementError('invalid_input', `${field} must be a UUID`)
+ }
+ return normalized
+}
+
+function normalizeRetirementActor(actor: DesktopUserRetirementActor): DesktopUserRetirementActor {
+ if (!actor || typeof actor !== 'object') {
+ throw new DesktopUserRetirementError('invalid_input', 'actor is required')
+ }
+ if (actor.kind === 'control_admin') {
+ return {
+ kind: 'control_admin',
+ controlAdminId: requireUuid(actor.controlAdminId, 'actor.controlAdminId'),
+ }
+ }
+ if (actor.kind === 'platform_user') {
+ return {
+ kind: 'platform_user',
+ desktopUserId: requireUuid(actor.desktopUserId, 'actor.desktopUserId'),
+ }
+ }
+ throw new DesktopUserRetirementError('invalid_input', 'actor kind is not supported')
+}
+
+function retirementActorId(actor: DesktopUserRetirementActor): string {
+ return actor.kind === 'control_admin' ? actor.controlAdminId : actor.desktopUserId
+}
+
+function requireRetirementReason(value: unknown): string {
+ const normalized = String(value ?? '').trim()
+ if (!normalized || normalized.length > 512) {
+ throw new DesktopUserRetirementError(
+ 'invalid_input',
+ 'reason is required and must be at most 512 characters'
+ )
+ }
+ return normalized
+}
+
+function requireIdempotencyKey(value: unknown): string {
+ const normalized = String(value ?? '').trim()
+ if (!normalized || normalized.length > 256 || /[\u0000-\u001f\u007f]/.test(normalized)) {
+ throw new DesktopUserRetirementError(
+ 'invalid_input',
+ 'Idempotency-Key is required and must be a printable value of at most 256 characters'
+ )
+ }
+ return normalized
+}
+
+function normalizeRequestId(value: string | null | undefined): string | null {
+ if (value === null || value === undefined) return null
+ const normalized = value.trim()
+ if (!normalized) return null
+ if (normalized.length > 256 || /[\u0000-\u001f\u007f]/.test(normalized)) {
+ throw new DesktopUserRetirementError(
+ 'invalid_input',
+ 'requestId must be a printable value of at most 256 characters'
+ )
+ }
+ return normalized
+}
+
+function sha256(value: string): string {
+ return createHash('sha256').update(value).digest('hex')
+}
+
+function requireLifecycleVersion(value: unknown): number {
+ const normalized = typeof value === 'number' ? value : Number(value)
+ if (!Number.isSafeInteger(normalized) || normalized < 1) {
+ throw new DesktopUserRetirementError('retirement_conflict', 'user lifecycle version is invalid')
+ }
+ return normalized
+}
+
+type RetirementOperationRow = {
+ id: string
+ request_fingerprint: string
+ status: string
+ outcome: DesktopUserRetirementOutcome | null
+ lifecycle_version: string | number | null
+}
+
+function completedReplay(
+ row: RetirementOperationRow,
+ targetUserId: string
+): RetireDesktopUserResult {
+ if (row.status !== 'completed' || (row.outcome !== 'retired' && row.outcome !== 'deleted')) {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'retirement operation is not terminal'
+ )
+ }
+ return {
+ id: targetUserId,
+ outcome: row.outcome,
+ operationId: String(row.id),
+ lifecycleVersion:
+ row.outcome === 'retired' ? requireLifecycleVersion(row.lifecycle_version) : null,
+ replayed: true,
+ }
+}
+
type AdminUserRow = {
id: string
email: string
@@ -191,6 +335,294 @@ export async function updateAdminUserContext(
})
}
+/**
+ * Retire a Desktop user under one caller-owned transaction.
+ *
+ * A user with operator-link history is retained as a lifecycle tombstone. The
+ * legacy physical delete remains available only when no such history exists,
+ * and its durable operation row makes retries safe even after the user row is
+ * gone. Every non-terminal failure throws so the transaction rolls back the
+ * pending operation, governed events, link state, and user mutation together.
+ */
+export async function retireDesktopUser(
+ actorInput: DesktopUserRetirementActor,
+ userIdInput: string,
+ reasonInput: string,
+ idempotencyKeyInput: string,
+ requestIdInput: string | null | undefined
+): Promise<RetireDesktopUserResult> {
+ const actor = normalizeRetirementActor(actorInput)
+ const targetUserId = requireUuid(userIdInput, 'userId')
+ const reason = requireRetirementReason(reasonInput)
+ const idempotencyKey = requireIdempotencyKey(idempotencyKeyInput)
+ const requestId = normalizeRequestId(requestIdInput)
+ const actorId = retirementActorId(actor)
+ const idempotencyKeyHash = sha256(idempotencyKey)
+ const requestFingerprint = sha256(
+ JSON.stringify({
+ operation: RETIREMENT_OPERATION,
+ actor,
+ targetUserId,
+ reason,
+ idempotencyKeyHash,
+ })
+ )
+ const actorColumn =
+ actor.kind === 'control_admin' ? 'actor_control_admin_id' : 'actor_desktop_user_id'
+
+ return withTransaction(async db => {
+ const claim = await db.query(
+ `INSERT INTO desktop_user_retirement_operations(
+ operation,
+ actor_type,
+ actor_control_admin_id,
+ actor_desktop_user_id,
+ target_user_id,
+ idempotency_key_hash,
+ request_fingerprint,
+ reason,
+ request_id
+ )
+ VALUES (
+ '${RETIREMENT_OPERATION}',
+ $1,
+ $2::uuid,
+ $3::uuid,
+ $4::uuid,
+ $5,
+ $6,
+ $7,
+ $8
+ )
+ ON CONFLICT DO NOTHING
+ RETURNING id::text AS id`,
+ [
+ actor.kind,
+ actor.kind === 'control_admin' ? actor.controlAdminId : null,
+ actor.kind === 'platform_user' ? actor.desktopUserId : null,
+ targetUserId,
+ idempotencyKeyHash,
+ requestFingerprint,
+ reason,
+ requestId,
+ ]
+ )
+
+ if ((claim.rowCount ?? 0) === 0) {
+ const existing = await db.query(
+ `SELECT id::text AS id,
+ request_fingerprint,
+ status,
+ outcome,
+ lifecycle_version
+ FROM desktop_user_retirement_operations
+ WHERE operation = '${RETIREMENT_OPERATION}'
+ AND ${actorColumn} = $1::uuid
+ AND target_user_id = $2::uuid
+ AND idempotency_key_hash = $3
+ FOR UPDATE`,
+ [actorId, targetUserId, idempotencyKeyHash]
+ )
+ const row = existing.rows[0] as RetirementOperationRow | undefined
+ if (!row) {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'retirement operation could not be resolved after an idempotency conflict'
+ )
+ }
+ if (row.request_fingerprint !== requestFingerprint) {
+ throw new DesktopUserRetirementError(
+ 'idempotency_conflict',
+ 'Idempotency-Key was reused with a different retirement request'
+ )
+ }
+ return completedReplay(row, targetUserId)
+ }
+
+ const operationId = String((claim.rows[0] as { id?: unknown } | undefined)?.id ?? '')
+ if (!UUID_PATTERN.test(operationId)) {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'retirement operation id is invalid'
+ )
+ }
+
+ const userResult = await db.query(
+ `SELECT id::text AS id, lifecycle_state, lifecycle_version
+ FROM users
+ WHERE id = $1::uuid
+ FOR UPDATE`,
+ [targetUserId]
+ )
+ const user = userResult.rows[0] as
+ | { id?: unknown; lifecycle_state?: unknown; lifecycle_version?: unknown }
+ | undefined
+ if (!user || user.id !== targetUserId) {
+ throw new DesktopUserRetirementError('not_found', 'Desktop user does not exist')
+ }
+ if (user.lifecycle_state !== 'active') {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'Desktop user is not in the active lifecycle state'
+ )
+ }
+ const lifecycleVersion = requireLifecycleVersion(user.lifecycle_version)
+
+ const history = await db.query(
+ `SELECT EXISTS(
+ SELECT 1
+ FROM gfs_desktop_operator_links
+ WHERE user_id = $1::uuid
+ ) AS has_link_history`,
+ [targetUserId]
+ )
+ const hasLinkHistory =
+ (history.rows[0] as { has_link_history?: unknown } | undefined)?.has_link_history === true
+
+ if (!hasLinkHistory) {
+ await db.query(
+ `UPDATE workflow_approval_medium_accounts
+ SET disabled_at = COALESCE(disabled_at, NOW()),
+ updated_at = NOW()
+ WHERE user_id = $1::uuid
+ AND disabled_at IS NULL`,
+ [targetUserId]
+ )
+ await db.query(
+ `UPDATE workflow_approval_medium_challenges
+ SET consumed_at = COALESCE(consumed_at, NOW()),
+ expires_at = LEAST(expires_at, NOW())
+ WHERE user_id = $1::uuid
+ AND consumed_at IS NULL`,
+ [targetUserId]
+ )
+ const deleted = await db.query(
+ `DELETE FROM users
+ WHERE id = $1::uuid
+ AND lifecycle_state = 'active'
+ AND lifecycle_version = $2
+ RETURNING id::text AS id`,
+ [targetUserId, lifecycleVersion]
+ )
+ if ((deleted.rowCount ?? 0) !== 1) {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'Desktop user changed during retirement'
+ )
+ }
+ const completed = await db.query(
+ `UPDATE desktop_user_retirement_operations
+ SET status = 'completed',
+ outcome = 'deleted',
+ completed_at = NOW()
+ WHERE id = $1::uuid
+ AND status = 'pending'`,
+ [operationId]
+ )
+ if ((completed.rowCount ?? 0) !== 1) {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'retirement operation changed before completion'
+ )
+ }
+ return {
+ id: targetUserId,
+ outcome: 'deleted',
+ operationId,
+ lifecycleVersion: null,
+ replayed: false,
+ }
+ }
+
+ let revoked = false
+ try {
+ revoked = await gfsDesktopOperatorLinkService.retireParentInTransaction(db, {
+ kind: 'desktop_user',
+ parentId: targetUserId,
+ actor,
+ reason,
+ requestId,
+ operationId,
+ })
+ } catch (error) {
+ if (error instanceof GfsDesktopOperatorLinkError && error.code === 'link_conflict') {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'operator link changed during retirement'
+ )
+ }
+ throw error
+ }
+ if (!revoked) {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'operator-link history has no active generation to retire'
+ )
+ }
+
+ const transitioned = await db.query(
+ `UPDATE users
+ SET lifecycle_state = 'retired',
+ retired_at = NOW(),
+ retirement_reason = $2,
+ retired_by_type = $3,
+ retired_by_control_admin_id = $4::uuid,
+ retired_by_desktop_user_id = $5::uuid,
+ retirement_request_id = $6,
+ retirement_operation_id = $7::uuid,
+ lifecycle_version = lifecycle_version + 1,
+ updated_at = NOW()
+ WHERE id = $1::uuid
+ AND lifecycle_state = 'active'
+ AND lifecycle_version = $8
+ RETURNING lifecycle_version`,
+ [
+ targetUserId,
+ reason,
+ actor.kind,
+ actor.kind === 'control_admin' ? actor.controlAdminId : null,
+ actor.kind === 'platform_user' ? actor.desktopUserId : null,
+ requestId,
+ operationId,
+ lifecycleVersion,
+ ]
+ )
+ if ((transitioned.rowCount ?? 0) !== 1) {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'Desktop user changed during retirement'
+ )
+ }
+ const nextLifecycleVersion = requireLifecycleVersion(
+ (transitioned.rows[0] as { lifecycle_version?: unknown } | undefined)?.lifecycle_version
+ )
+ const completed = await db.query(
+ `UPDATE desktop_user_retirement_operations
+ SET status = 'completed',
+ outcome = 'retired',
+ lifecycle_version = $2,
+ lifecycle_operation_id = $1::uuid,
+ completed_at = NOW()
+ WHERE id = $1::uuid
+ AND status = 'pending'`,
+ [operationId, nextLifecycleVersion]
+ )
+ if ((completed.rowCount ?? 0) !== 1) {
+ throw new DesktopUserRetirementError(
+ 'retirement_conflict',
+ 'retirement operation changed before completion'
+ )
+ }
+ return {
+ id: targetUserId,
+ outcome: 'retired',
+ operationId,
+ lifecycleVersion: nextLifecycleVersion,
+ replayed: false,
+ }
+ })
+}
+
/**
* Retire a user account through the existing account-management contract.
* Teams are retained even when this leaves them with zero active members.
diff --git a/control-api/src/services/gfsDesktopOperatorLinkService.ts b/control-api/src/services/gfsDesktopOperatorLinkService.ts
index 264867670..2a5c47d28 100644
--- a/control-api/src/services/gfsDesktopOperatorLinkService.ts
+++ b/control-api/src/services/gfsDesktopOperatorLinkService.ts
@@ -26,6 +26,7 @@ export type GfsDesktopOperatorLink = {
export type GfsDesktopOperatorLinkErrorCode =
| 'invalid_input'
| 'desktop_user_not_found'
+ | 'desktop_user_retired'
| 'control_admin_not_found'
| 'control_admin_inactive'
| 'link_conflict'
@@ -100,6 +101,14 @@ export type ReactivateGfsDesktopOperatorResult = {
}
export type GfsDesktopOperatorParentKind = 'desktop_user' | 'control_admin'
+/**
+ * Lifecycle callers name their principal explicitly. The two actor IDs are
+ * deliberately separate so a UUID is never reinterpreted as another kind.
+ */
+export type GfsDesktopOperatorLifecycleActor =
+ | { kind: 'control_admin'; controlAdminId: string }
+ | { kind: 'platform_user'; desktopUserId: string }
+
type TransactionRunner = <T>(work: (db: DbClient) => Promise<T>) => Promise<T>
/**
@@ -181,6 +190,31 @@ function requireUuid(value: string, field: string): string {
return normalized
}
+function requireLifecycleActor(
+ input: GfsDesktopOperatorLifecycleActor
+): GfsDesktopOperatorLifecycleActor {
+ if (!input || typeof input !== 'object') {
+ throw new GfsDesktopOperatorLinkError('invalid_input', 'actor is required')
+ }
+ if (input.kind === 'control_admin') {
+ return {
+ kind: 'control_admin',
+ controlAdminId: requireUuid(input.controlAdminId, 'actor.controlAdminId'),
+ }
+ }
+ if (input.kind === 'platform_user') {
+ return {
+ kind: 'platform_user',
+ desktopUserId: requireUuid(input.desktopUserId, 'actor.desktopUserId'),
+ }
+ }
+ throw new GfsDesktopOperatorLinkError('invalid_input', 'actor kind is not supported')
+}
+
+function lifecycleActorId(actor: GfsDesktopOperatorLifecycleActor): string {
+ return actor.kind === 'control_admin' ? actor.controlAdminId : actor.desktopUserId
+}
+
function isLinkSource(value: unknown): value is GfsDesktopOperatorLinkSource {
return (
typeof value === 'string' &&
@@ -277,7 +311,8 @@ function lifecycleChange(
action: 'grant' | 'revoke',
link: GfsDesktopOperatorLink,
reason?: string,
- lifecycleEvent?: 'link.created' | 'link.revoked' | 'link.reactivated' | 'parent.retired'
+ lifecycleEvent?: 'link.created' | 'link.revoked' | 'link.reactivated' | 'parent.retired',
+ actor?: GfsDesktopOperatorLifecycleActor
): ControlApiPermissionChange {
return {
action,
@@ -294,6 +329,9 @@ function lifecycleChange(
link.lineageId ? `lineage_id:${link.lineageId}` : null,
link.generation === undefined ? null : `generation:${link.generation}`,
link.predecessorId ? `predecessor_id:${link.predecessorId}` : null,
+ actor ? `actor_type:${actor.kind}` : null,
+ actor?.kind === 'control_admin' ? `actor_control_admin_id:${actor.controlAdminId}` : null,
+ actor?.kind === 'platform_user' ? `actor_desktop_user_id:${actor.desktopUserId}` : null,
reason ? `reason:${reason}` : null,
]
.filter(Boolean)
@@ -370,7 +408,7 @@ export class GfsDesktopOperatorLinkService {
const source = requireSource(input.source)
const user = await db.query(
- `SELECT id::text AS id
+ `SELECT id::text AS id, lifecycle_state
FROM users
WHERE id = $1::uuid
FOR UPDATE`,
@@ -379,6 +417,12 @@ export class GfsDesktopOperatorLinkService {
if (user.rows.length !== 1) {
throw new GfsDesktopOperatorLinkError('desktop_user_not_found', 'Desktop user does not exist')
}
+ if ((user.rows[0] as { lifecycle_state?: unknown }).lifecycle_state === 'retired') {
+ throw new GfsDesktopOperatorLinkError(
+ 'desktop_user_retired',
+ 'retired Desktop users cannot receive an operator link'
+ )
+ }
const admin = await db.query(
`SELECT id::text AS id, status
@@ -541,6 +585,8 @@ export class GfsDesktopOperatorLinkService {
revoked_at = NOW(),
revoked_by_type = 'control_admin',
revoked_by_id = $3::uuid,
+ revoked_by_control_admin_id = $3::uuid,
+ revoked_by_desktop_user_id = NULL,
revocation_reason = $4,
row_version = row_version + 1
WHERE user_id = $1::uuid
@@ -645,14 +691,20 @@ export class GfsDesktopOperatorLinkService {
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
+ `SELECT u.id IS NOT NULL AS desktop_user_exists,
+ u.lifecycle_state AS desktop_user_lifecycle_state,
+ 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 }
+ | {
+ desktop_user_exists?: unknown
+ desktop_user_lifecycle_state?: unknown
+ control_admin_status?: unknown
+ }
| undefined
if (parentState?.desktop_user_exists !== true) {
throw new GfsDesktopOperatorLinkError(
@@ -660,6 +712,12 @@ export class GfsDesktopOperatorLinkService {
'Desktop user does not exist'
)
}
+ if (parentState.desktop_user_lifecycle_state === 'retired') {
+ throw new GfsDesktopOperatorLinkError(
+ 'desktop_user_retired',
+ 'retired Desktop users cannot receive an operator link'
+ )
+ }
if (parentState.control_admin_status !== 'active') {
throw new GfsDesktopOperatorLinkError(
'control_admin_inactive',
@@ -693,13 +751,16 @@ export class GfsDesktopOperatorLinkService {
input: {
kind: GfsDesktopOperatorParentKind
parentId: string
- operatorSub: string
+ actor: GfsDesktopOperatorLifecycleActor
reason: string
requestId?: string | null
+ /** Reuses the retirement-operation id as the governed audit operation. */
+ operationId?: string
}
): Promise<boolean> {
const parentId = requireUuid(input.parentId, 'parentId')
- const operatorSub = requireUuid(input.operatorSub, 'operatorSub')
+ const actor = requireLifecycleActor(input.actor)
+ const operatorSub = lifecycleActorId(actor)
const reason = requireReason(input.reason)
const column = input.kind === 'desktop_user' ? 'user_id' : 'control_admin_id'
const rows = await db.query(
@@ -716,10 +777,11 @@ export class GfsDesktopOperatorLinkService {
const link = mapStoredLink(rows.rows[0])
await this.dependencies.appendPermissionEvents(db, {
operatorSub,
- operatorKind: 'control_admin',
+ operatorKind: actor.kind,
requestId: input.requestId,
+ operationId: input.operationId,
changes: [
- lifecycleChange('revoke', link, reason, 'link.revoked'),
+ lifecycleChange('revoke', link, reason, 'link.revoked', actor),
{
action: 'revoke',
resourceClass: `gfs_desktop_operator_${input.kind}`,
@@ -730,16 +792,40 @@ export class GfsDesktopOperatorLinkService {
: { 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}`,
+ detailRef: [
+ 'event:parent.retired',
+ `desktop_user_id:${link.desktopUserId}`,
+ `control_admin_id:${link.controlAdminId}`,
+ `source:${link.source}`,
+ `actor_type:${actor.kind}`,
+ actor.kind === 'control_admin'
+ ? `actor_control_admin_id:${actor.controlAdminId}`
+ : `actor_desktop_user_id:${actor.desktopUserId}`,
+ `reason:${reason}`,
+ ].join(';'),
},
],
})
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]
+ SET state = 'revoked',
+ revoked_at = NOW(),
+ revoked_by_type = $2,
+ revoked_by_id = $3::uuid,
+ revoked_by_control_admin_id = $4::uuid,
+ revoked_by_desktop_user_id = $5::uuid,
+ revocation_reason = $6,
+ row_version = row_version + 1
+ WHERE ${column} = $1::uuid AND state = 'active' AND row_version = $7`,
+ [
+ parentId,
+ actor.kind,
+ actor.kind === 'control_admin' ? actor.controlAdminId : null,
+ actor.kind === 'control_admin' ? actor.controlAdminId : null,
+ actor.kind === 'platform_user' ? actor.desktopUserId : null,
+ reason,
+ link.rowVersion ?? 1,
+ ]
)
if (updated.rowCount !== 1)
throw new GfsDesktopOperatorLinkError(
@@ -789,6 +875,33 @@ export class GfsDesktopOperatorLinkService {
}
}
+ /**
+ * The external-authority boundary checks lifecycle before it can fall back
+ * to ordinary user-session authority after a link is revoked.
+ */
+ async isDesktopUserActive(desktopUserIdInput: string): Promise<boolean> {
+ const desktopUserId = requireUuid(desktopUserIdInput, 'desktopUserId')
+ try {
+ const result = await this.dependencies.readDb.query(
+ `SELECT lifecycle_state
+ FROM users
+ WHERE id = $1::uuid
+ LIMIT 1`,
+ [desktopUserId]
+ )
+ return (
+ (result.rows[0] as { lifecycle_state?: unknown } | undefined)?.lifecycle_state === 'active'
+ )
+ } catch (error) {
+ if (error instanceof GfsDesktopOperatorLinkError) throw error
+ throw new GfsDesktopOperatorLinkError(
+ 'resolution_failed',
+ 'failed to resolve Desktop user lifecycle state',
+ { cause: error }
+ )
+ }
+ }
+
/** Read-only exact-pair seam for the authenticated Control UI revoke surface. */
async getLinkForControlAdmin(
controlAdminIdInput: string
diff --git a/control-api/test/db.desktopUserRetirementLifecycleMigration.test.ts b/control-api/test/db.desktopUserRetirementLifecycleMigration.test.ts
new file mode 100644
index 000000000..fc43b9ae1
--- /dev/null
+++ b/control-api/test/db.desktopUserRetirementLifecycleMigration.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('pg', () => ({
+ Pool: vi.fn(function MockPool() {
+ return { connect: vi.fn(), query: vi.fn() }
+ }),
+}))
+
+describe('0094_desktop_user_retirement_lifecycle migration', () => {
+ it('is ordered after operator-link generations and backfills an additive active lifecycle', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const versions = CONTROL_API_MIGRATIONS.map(migration => migration.version)
+ expect(versions.indexOf('0094_desktop_user_retirement_lifecycle')).toBeGreaterThan(
+ versions.indexOf('0093_gfs_desktop_operator_link_generations')
+ )
+
+ const migration = CONTROL_API_MIGRATIONS.find(
+ candidate => candidate.version === '0094_desktop_user_retirement_lifecycle'
+ )
+ 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 lifecycle_state TEXT')
+ expect(sql).toContain("lifecycle_state = COALESCE(lifecycle_state, 'active')")
+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS lifecycle_version BIGINT')
+ expect(sql).toContain("lifecycle_state = 'retired'")
+ expect(sql).toContain('retired_by_control_admin_id')
+ expect(sql).toContain('retired_by_desktop_user_id')
+ expect(sql).toContain('retirement_operation_id')
+ })
+
+ it('stores only scoped, hashed idempotency outcomes with separated actor identities', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const migration = CONTROL_API_MIGRATIONS.find(
+ candidate => candidate.version === '0094_desktop_user_retirement_lifecycle'
+ )
+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })
+ await migration!.apply({ query })
+ const sql = String(query.mock.calls[0]?.[0])
+
+ expect(sql).toContain('CREATE TABLE IF NOT EXISTS desktop_user_retirement_operations')
+ expect(sql).toContain("operation = 'retire_desktop_user'")
+ expect(sql).toContain("actor_type IN ('control_admin', 'platform_user')")
+ expect(sql).toContain("idempotency_key_hash ~ '^[0-9a-f]{64}$'")
+ expect(sql).toContain("request_fingerprint ~ '^[0-9a-f]{64}$'")
+ expect(sql).toContain("outcome IN ('retired', 'deleted')")
+ expect(sql).toContain('desktop_user_retirement_operations_control_admin_key')
+ expect(sql).toContain('desktop_user_retirement_operations_platform_user_key')
+ expect(sql).toContain('a legacy-compatible hard-delete for')
+ expect(sql).not.toContain('idempotency_key TEXT NOT NULL')
+ })
+
+ it('preserves restricted lifecycle parents and broadens link revocation without cascade', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const migration = CONTROL_API_MIGRATIONS.find(
+ candidate => candidate.version === '0094_desktop_user_retirement_lifecycle'
+ )
+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })
+ await migration!.apply({ query })
+ const sql = String(query.mock.calls[0]?.[0])
+
+ expect(sql).toContain('REFERENCES control_admin_users(id) ON DELETE RESTRICT')
+ expect(sql).toContain('REFERENCES users(id) ON DELETE RESTRICT')
+ expect(sql).toContain('revoked_by_control_admin_id')
+ expect(sql).toContain('revoked_by_desktop_user_id')
+ expect(sql).toContain("revoked_by_type = 'platform_user'")
+ expect(sql).toContain('REVOKE DELETE, TRUNCATE, REFERENCES, TRIGGER')
+ expect(sql).not.toContain('desktop_user_retirement_operations(id) ON DELETE CASCADE')
+ })
+})
diff --git a/control-api/test/db.initDb.test.ts b/control-api/test/db.initDb.test.ts
index b4e431e7b..1f71a1117 100644
--- a/control-api/test/db.initDb.test.ts
+++ b/control-api/test/db.initDb.test.ts
@@ -939,6 +939,37 @@ describe('db.initDb', () => {
expect(clientRelease).toHaveBeenCalledTimes(1)
})
+ it('rolls back the desktop-user retirement migration without recording it when its DDL fails', async () => {
+ const { CONTROL_API_MIGRATIONS, initDb } = await import('../src/db.js')
+ const priorVersions = CONTROL_API_MIGRATIONS.filter(
+ migration => migration.version !== '0094_desktop_user_retirement_lifecycle'
+ ).map(migration => ({ version: migration.version }))
+
+ clientQuery.mockImplementation(async (sql: string) => {
+ if (sql.includes('SELECT version FROM schema_migrations')) {
+ return { rows: priorVersions, rowCount: priorVersions.length }
+ }
+ if (sql.includes('CREATE TABLE IF NOT EXISTS desktop_user_retirement_operations')) {
+ throw new Error('retirement ledger ddl failed')
+ }
+ return { rows: [], rowCount: 0 }
+ })
+
+ await expect(initDb()).rejects.toThrow('retirement ledger ddl failed')
+
+ const sqls = clientQuery.mock.calls.map(([sql]) => String(sql).trim())
+ expect(sqls).toContainEqual(
+ expect.stringContaining('CREATE TABLE IF NOT EXISTS desktop_user_retirement_operations')
+ )
+ expect(sqls).toContain('ROLLBACK')
+ expect(sqls).not.toContain('COMMIT')
+ const retirementRecord = clientQuery.mock.calls.find(
+ ([, params]) =>
+ Array.isArray(params) && params[0] === '0094_desktop_user_retirement_lifecycle'
+ )
+ expect(retirementRecord).toBeUndefined()
+ })
+
it('deduplicates pending control-admin invitations before creating the opened-status unique index', async () => {
clientQuery.mockImplementation(async (sql: string) => {
if (sql.includes('SELECT version FROM schema_migrations')) {
diff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.ts
index f87aac7c6..6af125649 100644
--- a/control-api/test/db.realPostgresMigration.integration.test.ts
+++ b/control-api/test/db.realPostgresMigration.integration.test.ts
@@ -185,6 +185,9 @@ describeRealPostgres('control-api real Postgres migrations', () => {
expect(secondVersions.rows.map(row => row.version)).toContain(
'0067_llm_runtime_access_profiles'
)
+ expect(secondVersions.rows.map(row => row.version)).toContain(
+ '0094_desktop_user_retirement_lifecycle'
+ )
await dbPool.query(`
DELETE FROM schema_migrations
@@ -387,6 +390,7 @@ describeRealPostgres('control-api real Postgres migrations', () => {
'llm_allowed_models_audit',
'llm_catalog_sync_runs',
'gfs_desktop_operator_links',
+ 'desktop_user_retirement_operations',
] as const
const controlApiRelations = await relationPrivileges(dbPool, 'control_api_runtime')
const expectedControlApiRelations: Record<string, string[]> = {
@@ -404,6 +408,7 @@ describeRealPostgres('control-api real Postgres migrations', () => {
llm_allowed_models_audit: ['INSERT', 'SELECT'],
llm_catalog_sync_runs: ['INSERT', 'SELECT'],
gfs_desktop_operator_links: ['INSERT', 'SELECT', 'UPDATE'],
+ desktop_user_retirement_operations: ['INSERT', 'SELECT', 'UPDATE'],
}
for (const relation of exactControlApiRelations) {
expectPrivileges(
@@ -471,14 +476,52 @@ describeRealPostgres('control-api real Postgres migrations', () => {
)
expect(linked.rows).toEqual([{ user_id: linkUserId, control_admin_id: linkAdminId }])
+ const lifecycle = await linkRuntimeClient.query<{
+ lifecycle_state: string
+ lifecycle_version: string
+ }>(
+ `SELECT lifecycle_state, lifecycle_version::text AS lifecycle_version
+ FROM users
+ WHERE id = $1`,
+ [linkUserId]
+ )
+ expect(lifecycle.rows).toEqual([{ lifecycle_state: 'active', lifecycle_version: '1' }])
+
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
+ revoked_by_id = $2, revoked_by_control_admin_id = $2,
+ revoked_by_desktop_user_id = NULL,
+ revocation_reason = 'privilege-test', row_version = row_version + 1
WHERE user_id = $1`,
[linkUserId, linkAdminId]
)
+ const operation = await linkRuntimeClient.query<{ id: string }>(
+ `INSERT INTO desktop_user_retirement_operations(
+ actor_type,
+ actor_control_admin_id,
+ target_user_id,
+ idempotency_key_hash,
+ request_fingerprint,
+ reason,
+ request_id
+ )
+ VALUES ('control_admin', $1, $2, repeat('a', 64), repeat('b', 64), 'privilege-test', 'request-1')
+ RETURNING id::text AS id`,
+ [linkAdminId, linkUserId]
+ )
+ await linkRuntimeClient.query(
+ `UPDATE desktop_user_retirement_operations
+ SET status = 'completed',
+ outcome = 'retired',
+ lifecycle_version = 2,
+ lifecycle_operation_id = id,
+ completed_at = NOW()
+ WHERE id = $1::uuid`,
+ [operation.rows[0]!.id]
+ )
+
await linkRuntimeClient.query('SAVEPOINT deny_link_truncate')
await expect(
linkRuntimeClient.query('TRUNCATE TABLE gfs_desktop_operator_links')
diff --git a/control-api/test/gfs.externalAuthority.test.ts b/control-api/test/gfs.externalAuthority.test.ts
index 0565e46bc..6e7660e45 100644
--- a/control-api/test/gfs.externalAuthority.test.ts
+++ b/control-api/test/gfs.externalAuthority.test.ts
@@ -49,6 +49,21 @@ describe('resolveExternalGfsAuthority', () => {
expect(resolveActiveLink).not.toHaveBeenCalled()
})
+ it('denies a retired Desktop user before the flag can fall back to user-session authority', async () => {
+ const resolveActiveLink = vi.fn()
+ await expect(
+ resolveExternalGfsAuthority(DESKTOP_USER_ID, {
+ linkingEnabled: false,
+ resolveActiveLink,
+ isDesktopUserActive: vi.fn().mockResolvedValue(false),
+ })
+ ).rejects.toMatchObject<Partial<ExternalGfsAuthorityError>>({
+ status: 403,
+ code: 'desktop_user_retired',
+ })
+ expect(resolveActiveLink).not.toHaveBeenCalled()
+ })
+
it('keeps an unlinked Desktop session on ordinary user authority', async () => {
await expect(
resolveExternalGfsAuthority(DESKTOP_USER_ID, {
diff --git a/control-api/test/gfsReadiness.realPostgres.integration.test.ts b/control-api/test/gfsReadiness.realPostgres.integration.test.ts
index 7ed0dd48c..881c9544d 100644
--- a/control-api/test/gfsReadiness.realPostgres.integration.test.ts
+++ b/control-api/test/gfsReadiness.realPostgres.integration.test.ts
@@ -108,6 +108,22 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL readiness', () => {
}
})
+ it.each(['actor_on_behalf_of', 'desktop_user_id', 'authority_source'] as const)(
+ 'fails GFSC readiness before 0092 when the required %s audit column is absent',
+ async column => {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ await client.query(`ALTER TABLE gfs_audit DROP COLUMN ${column} CASCADE`)
+ 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/middleware.externalGfsRateLimit.test.ts b/control-api/test/middleware.externalGfsRateLimit.test.ts
new file mode 100644
index 000000000..8ac4d957c
--- /dev/null
+++ b/control-api/test/middleware.externalGfsRateLimit.test.ts
@@ -0,0 +1,319 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import { createHash } from 'node:crypto'
+import request from 'supertest'
+import {
+ externalGfsOperationFor,
+ externalGfsPreResolutionRateLimit,
+ externalGfsResolvedOperationRateLimit,
+} from '../src/middleware/externalGfsRateLimit.js'
+
+const checkAndIncrement = vi.hoisted(() => vi.fn())
+const metrics = vi.hoisted(() => ({
+ externalGfsRateLimitRequestsTotal: { inc: vi.fn() },
+ externalGfsRateLimitDurationSeconds: { observe: vi.fn() },
+}))
+const logger = vi.hoisted(() => ({
+ rootLogger: { debug: vi.fn(), warn: vi.fn() },
+}))
+
+vi.mock('../src/config.js', () => ({
+ config: {
+ externalGfsTokenUserRlPerMin: 10,
+ externalGfsIpRlPerMin: 30,
+ externalGfsOperationRlPerMin: 30,
+ },
+}))
+vi.mock('../src/services/rateLimiterService.js', () => ({
+ checkAndIncrement: (...args: unknown[]) => checkAndIncrement(...args),
+}))
+vi.mock('../src/observability/metrics.js', () => metrics)
+vi.mock('../src/observability/logger.js', () => logger)
+
+const DESKTOP_USER_ID = '11111111-aaaa-4aaa-8aaa-111111111111'
+const CONTROL_ADMIN_ID = '22222222-bbbb-4bbb-8bbb-222222222222'
+const RESOURCE_ID = '33333333-cccc-4ccc-8ccc-333333333333'
+
+function allowed(remaining = 29) {
+ return {
+ allowed: true,
+ remaining,
+ resetMs: Date.now() + 60_000,
+ windowStartMs: Date.now(),
+ count: 30 - remaining,
+ }
+}
+
+function denied(limit = 30) {
+ return {
+ allowed: false,
+ remaining: 0,
+ resetMs: Date.now() + 30_000,
+ windowStartMs: Date.now(),
+ count: limit + 1,
+ }
+}
+
+function buildApp() {
+ const resolver = vi.fn()
+ const handler = vi.fn()
+ const app = express()
+
+ app.use('/external/gfs', (req, _res, next) => {
+ ;(req as typeof req & { externalAuth?: { userId: string } }).externalAuth = {
+ userId: DESKTOP_USER_ID,
+ }
+ next()
+ })
+ app.use('/external/gfs', externalGfsPreResolutionRateLimit)
+ app.use('/external/gfs', (req, _res, next) => {
+ resolver()
+ ;(
+ req as typeof req & {
+ gfsAuthority?: {
+ kind: 'linked-admin'
+ tokenSubject: string
+ desktopUserId: string
+ controlAdminId: string
+ authoritySource: 'initial_setup'
+ }
+ }
+ ).gfsAuthority = {
+ kind: 'linked-admin',
+ tokenSubject: CONTROL_ADMIN_ID,
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ authoritySource: 'initial_setup',
+ }
+ next()
+ })
+ app.use('/external/gfs', externalGfsResolvedOperationRateLimit)
+ app.use('/external/gfs', (_req, res) => {
+ handler()
+ res.status(204).end()
+ })
+
+ return { app, resolver, handler }
+}
+
+describe('external GFS rate boundary', () => {
+ beforeEach(() => {
+ checkAndIncrement.mockReset()
+ checkAndIncrement.mockResolvedValue(allowed())
+ metrics.externalGfsRateLimitRequestsTotal.inc.mockReset()
+ metrics.externalGfsRateLimitDurationSeconds.observe.mockReset()
+ logger.rootLogger.debug.mockReset()
+ logger.rootLogger.warn.mockReset()
+ })
+
+ it.each([
+ ['POST', '/token', 'token', '/external/gfs/token'],
+ ['GET', '/resolve', 'resource', '/external/gfs/resolve'],
+ ['GET', '/resources', 'resource', '/external/gfs/resources'],
+ [
+ 'GET',
+ `/resources/${RESOURCE_ID}/children`,
+ 'resource',
+ '/external/gfs/resources/:id/children',
+ ],
+ [
+ 'GET',
+ `/resources/${RESOURCE_ID}/affordances`,
+ 'resource',
+ '/external/gfs/resources/:id/affordances',
+ ],
+ ['GET', `/proxy/${RESOURCE_ID}`, 'proxy-read', '/external/gfs/proxy/:rid'],
+ ['PATCH', `/resources/${RESOURCE_ID}`, 'resource-mutation', '/external/gfs/resources/:id'],
+ [
+ 'POST',
+ `/resources/${RESOURCE_ID}/children`,
+ 'resource-mutation',
+ '/external/gfs/resources/:id/children',
+ ],
+ [
+ 'PUT',
+ `/resources/${RESOURCE_ID}/content`,
+ 'resource-mutation',
+ '/external/gfs/resources/:id/content',
+ ],
+ ['DELETE', `/resources/${RESOURCE_ID}`, 'resource-mutation', '/external/gfs/resources/:id'],
+ ['GET', '/grants', 'grants', '/external/gfs/grants'],
+ ['PUT', '/grants', 'grants', '/external/gfs/grants'],
+ ['DELETE', `/grants/${RESOURCE_ID}`, 'grants', '/external/gfs/grants/:id'],
+ ['GET', '/shares', 'shares', '/external/gfs/shares'],
+ ['POST', '/shares', 'shares', '/external/gfs/shares'],
+ ['DELETE', `/shares/${RESOURCE_ID}`, 'shares', '/external/gfs/shares/:id'],
+ ] as const)('classifies %s /external/gfs%s as %s', (method, path, operationClass, route) => {
+ expect(
+ externalGfsOperationFor({
+ method,
+ baseUrl: '/external/gfs',
+ path,
+ originalUrl: `/external/gfs${path}`,
+ })
+ ).toEqual({ operationClass, route })
+ })
+
+ it('keeps unclassified paths outside the authority resolver', async () => {
+ const { app, resolver, handler } = buildApp()
+
+ const response = await request(app)
+ .post('/external/gfs/unclassified')
+ .set('x-user-session-token', 'session-one')
+
+ expect(response.status).toBe(404)
+ expect(response.body).toEqual({ error: 'Not Found' })
+ expect(checkAndIncrement).not.toHaveBeenCalled()
+ expect(resolver).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it('rejects before resolution and handler work when the pre-resolution session bucket is exhausted', async () => {
+ checkAndIncrement.mockResolvedValueOnce(denied())
+ const { app, resolver, handler } = buildApp()
+
+ const response = await request(app)
+ .get('/external/gfs/resources')
+ .set('x-user-session-token', 'session-one')
+
+ expect(response.status).toBe(429)
+ expect(response.headers['x-ratelimit-limit']).toBe('30')
+ expect(checkAndIncrement).toHaveBeenCalledWith(
+ expect.stringMatching(/^gfs-ext:pre:resource:session:[0-9a-f]{64}$/),
+ 30
+ )
+ expect(resolver).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ expect(metrics.externalGfsRateLimitRequestsTotal.inc).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operation_class: 'resource',
+ route: '/external/gfs/resources',
+ outcome: 'denied',
+ phase: 'pre-resolution',
+ authority_resolution_avoided: 'true',
+ })
+ )
+ expect(metrics.externalGfsRateLimitDurationSeconds.observe).toHaveBeenCalledWith(
+ expect.objectContaining({ phase: 'pre-resolution', outcome: 'denied' }),
+ expect.any(Number)
+ )
+ expect(logger.rootLogger.warn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operationClass: 'resource',
+ route: '/external/gfs/resources',
+ outcome: 'denied',
+ phase: 'pre-resolution',
+ hashedKey: expect.stringMatching(/^[0-9a-f]{64}$/),
+ latencyMs: expect.any(Number),
+ authorityResolutionAvoided: true,
+ }),
+ 'external GFS rate limit denied'
+ )
+ })
+
+ it('enforces the fixed 10/min user ceiling before minting a GFS token', async () => {
+ checkAndIncrement.mockResolvedValueOnce(denied(10))
+ const { app, resolver, handler } = buildApp()
+
+ const response = await request(app)
+ .post('/external/gfs/token')
+ .set('x-user-session-token', 'session-one')
+
+ expect(response.status).toBe(429)
+ expect(response.headers['x-ratelimit-limit']).toBe('10')
+ expect(checkAndIncrement).toHaveBeenCalledWith(`gfs-ext:pre:token:user:${DESKTOP_USER_ID}`, 10)
+ expect(resolver).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it('enforces the fixed 30/min source-IP ceiling after an allowed token user bucket', async () => {
+ checkAndIncrement.mockResolvedValueOnce(allowed(9)).mockResolvedValueOnce(denied())
+ const { app, resolver, handler } = buildApp()
+
+ const response = await request(app)
+ .post('/external/gfs/token')
+ .set('x-user-session-token', 'session-one')
+
+ expect(response.status).toBe(429)
+ expect(response.headers['x-ratelimit-limit']).toBe('30')
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 1,
+ `gfs-ext:pre:token:user:${DESKTOP_USER_ID}`,
+ 10
+ )
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 2,
+ expect.stringMatching(/^gfs-ext:pre:token:ip:[0-9a-f]{64}$/),
+ 30
+ )
+ expect(resolver).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it('uses the authenticated external-rest client IP before the funnel-appended peer address', async () => {
+ checkAndIncrement.mockResolvedValueOnce(allowed(9)).mockResolvedValueOnce(denied())
+ const { app } = buildApp()
+ const clientIp = '203.0.113.42'
+ const clientIpDigest = createHash('sha256').update(clientIp).digest('hex')
+
+ const response = await request(app)
+ .post('/external/gfs/token')
+ .set('x-user-session-token', 'session-one')
+ .set('x-forwarded-for', `${clientIp}, 10.42.0.18`)
+
+ expect(response.status).toBe(429)
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 2,
+ `gfs-ext:pre:token:ip:${clientIpDigest}`,
+ 30
+ )
+ })
+
+ it('uses distinct session, source-IP, and effective-actor buckets for each operation class', async () => {
+ const { app } = buildApp()
+
+ await request(app).get('/external/gfs/resources').set('x-user-session-token', 'session-one')
+ await request(app)
+ .get(`/external/gfs/proxy/${RESOURCE_ID}`)
+ .set('x-user-session-token', 'session-two')
+
+ const keys = checkAndIncrement.mock.calls.map(call => String(call[0]))
+ expect(keys).toContainEqual(
+ expect.stringMatching(/^gfs-ext:pre:resource:session:[0-9a-f]{64}$/)
+ )
+ expect(keys).toContainEqual(expect.stringMatching(/^gfs-ext:pre:resource:ip:[0-9a-f]{64}$/))
+ expect(keys).toContain(`gfs-ext:resolved:resource:actor:linked-admin:${CONTROL_ADMIN_ID}`)
+ expect(keys).toContainEqual(
+ expect.stringMatching(/^gfs-ext:pre:proxy-read:session:[0-9a-f]{64}$/)
+ )
+ expect(keys).toContainEqual(expect.stringMatching(/^gfs-ext:pre:proxy-read:ip:[0-9a-f]{64}$/))
+ expect(keys).toContain(`gfs-ext:resolved:proxy-read:actor:linked-admin:${CONTROL_ADMIN_ID}`)
+ expect(new Set(keys).size).toBe(keys.length)
+ })
+
+ it('keeps the resolved actor bucket stable when a Desktop session is renewed', async () => {
+ checkAndIncrement.mockImplementation((key: string) =>
+ key.startsWith('gfs-ext:resolved:resource:actor:') ? denied() : allowed()
+ )
+ const { app, resolver, handler } = buildApp()
+
+ const first = await request(app)
+ .get('/external/gfs/resources')
+ .set('x-user-session-token', 'session-before-renewal')
+ const second = await request(app)
+ .get('/external/gfs/resources')
+ .set('x-user-session-token', 'session-after-renewal')
+
+ expect(first.status).toBe(429)
+ expect(second.status).toBe(429)
+ const resolvedKeys = checkAndIncrement.mock.calls
+ .map(call => String(call[0]))
+ .filter(key => key.startsWith('gfs-ext:resolved:resource:actor:'))
+ expect(resolvedKeys).toEqual([
+ `gfs-ext:resolved:resource:actor:linked-admin:${CONTROL_ADMIN_ID}`,
+ `gfs-ext:resolved:resource:actor:linked-admin:${CONTROL_ADMIN_ID}`,
+ ])
+ expect(resolver).toHaveBeenCalledTimes(2)
+ expect(handler).not.toHaveBeenCalled()
+ })
+})
diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.ts
index 0a3b385af..508532079 100644
--- a/control-api/test/routes.externalGfs.test.ts
+++ b/control-api/test/routes.externalGfs.test.ts
@@ -38,6 +38,9 @@ vi.mock('../src/config.js', () => ({
// The eligibility guard maps caller agent names to 1st:<hostsNamespace>/<name>.
hostsNamespace: 'mcp-host',
desktopGfsOperatorLinkingEnabled: false,
+ externalGfsTokenUserRlPerMin: 10,
+ externalGfsIpRlPerMin: 30,
+ externalGfsOperationRlPerMin: 30,
},
}))
vi.mock('../src/services/gfsDesktopOperatorLinkService.js', () => ({
@@ -453,8 +456,53 @@ describe('linked Desktop operator authority contract', () => {
expect(res.status).toBe(403)
expect(res.body).toEqual({ error: 'gfs_operator_link_invalid' })
+ // The boundary rate limiter is deliberately the only DB-backed work that
+ // precedes the authority resolver. A resolver failure must not invoke a
+ // route handler or any of its database queries.
+ expect(mockQuery.mock.calls.every(call => String(call[0]).includes('rate_limit_buckets'))).toBe(
+ true
+ )
+ expect(mockSignGfsToken).not.toHaveBeenCalled()
+ })
+
+ it('returns 404 for an unclassified GFS path without resolving authority', async () => {
+ auth()
+ ;(config as { desktopGfsOperatorLinkingEnabled: boolean }).desktopGfsOperatorLinkingEnabled =
+ true
+ mockResolveActiveLink.mockResolvedValue(ACTIVE_LINK)
+
+ const res = await request(await buildApp())
+ .post('/external/gfs/not-classified')
+ .set('x-user-session-token', 'sess')
+ .send({})
+
+ expect(res.status).toBe(404)
+ expect(res.body).toEqual({ error: 'Not Found' })
+ expect(mockResolveActiveLink).not.toHaveBeenCalled()
expect(mockQuery).not.toHaveBeenCalled()
+ })
+
+ it('rejects a pre-resolution rate limit before resolver or route work', async () => {
+ auth()
+ ;(config as { desktopGfsOperatorLinkingEnabled: boolean }).desktopGfsOperatorLinkingEnabled =
+ true
+ mockResolveActiveLink.mockResolvedValue(ACTIVE_LINK)
+ mockQuery.mockImplementation(async (text: string) => {
+ if (text.includes('rate_limit_buckets')) return { rows: [{ count: 31 }] }
+ throw new Error(`unexpected route query: ${text}`)
+ })
+
+ const res = await request(await buildApp())
+ .get('/external/gfs/resources')
+ .set('x-user-session-token', 'sess')
+
+ expect(res.status).toBe(429)
+ expect(res.body.error).toBe('Too Many Requests')
+ expect(res.headers['x-ratelimit-limit']).toBe('30')
+ expect(mockResolveActiveLink).not.toHaveBeenCalled()
expect(mockSignGfsToken).not.toHaveBeenCalled()
+ expect(mockQuery.mock.calls).toHaveLength(1)
+ expect(mockQuery.mock.calls[0]?.[1]?.[0]).toMatch(/^gfs-ext:pre:resource:session:[0-9a-f]{64}$/)
})
it('does not resolve or elevate when the feature flag is off', async () => {
@@ -1602,7 +1650,7 @@ describe('per-agent delegation surface (guard + list + rate limit)', () => {
expect(res.body.error).toBe('manage_acl_required')
})
- it('rate limits the delegation plane per user with retryAfterSeconds', async () => {
+ it('rate limits the grants operation class before authority resolution', async () => {
auth()
authority(['manage_acl', 'read'], { rateLimitCount: 31 })
const app = await buildApp()
@@ -1610,10 +1658,12 @@ describe('per-agent delegation surface (guard + list + rate limit)', () => {
expect(res.status).toBe(429)
expect(res.body.error).toBe('Too Many Requests')
expect(res.body.retryAfterSeconds).toBeGreaterThanOrEqual(1)
- const bucketCall = mockQuery.mock.calls.find(call =>
- String(call[0]).includes('rate_limit_buckets')
+ const bucketCall = mockQuery.mock.calls.find(
+ call =>
+ String(call[0]).includes('rate_limit_buckets') &&
+ String(call[1]?.[0]).startsWith('gfs-ext:pre:grants:session:')
)
- expect(bucketCall?.[1]?.[0]).toBe(`gfsgrants-ext:user:${U1}`)
+ expect(bucketCall?.[1]?.[0]).toMatch(/^gfs-ext:pre:grants:session:[0-9a-f]{64}$/)
})
it('keys the external delegation plane in a bucket DISTINCT from the admin plane for the same subject', async () => {
@@ -1627,8 +1677,10 @@ describe('per-agent delegation surface (guard + list + rate limit)', () => {
authority(['manage_acl', 'read'])
const externalApp = await buildApp()
await putGrants(externalApp, { subject: { type: 'user', id: U2 } })
- const externalKey = mockQuery.mock.calls.find(call =>
- String(call[0]).includes('rate_limit_buckets')
+ const externalKey = mockQuery.mock.calls.find(
+ call =>
+ String(call[0]).includes('rate_limit_buckets') &&
+ String(call[1]?.[0]).startsWith('gfsgrants-ext:')
)?.[1]?.[0]
// Admin (operator) grants plane keyed off adminAuth.sub === U1 (same id).
diff --git a/control-api/test/routes.externalMembers.test.ts b/control-api/test/routes.externalMembers.test.ts
index 20d85c932..40d4caa90 100644
--- a/control-api/test/routes.externalMembers.test.ts
+++ b/control-api/test/routes.externalMembers.test.ts
@@ -33,6 +33,11 @@ vi.mock('../src/services/directory/index.js', () => directoryMock)
function makeApp() {
const app = express()
app.use(express.json())
+ app.use((req, _res, next) => {
+ ;(req as express.Request & { correlationId?: string }).correlationId =
+ 'request-external-members'
+ next()
+ })
app.use(createExternalMembersRouter())
return app
}
@@ -76,4 +81,50 @@ describe('external members routes', () => {
expect(directoryMock.createManagedInvitationForUser).not.toHaveBeenCalled()
})
+
+ it('requires an explicit reason and Idempotency-Key before retiring a managed user', async () => {
+ await request(makeApp())
+ .delete('/external/members/target-1')
+ .expect(400, { error: 'reason_required' })
+ expect(directoryMock.deleteManagedUserForUser).not.toHaveBeenCalled()
+
+ await request(makeApp())
+ .delete('/external/members/target-1')
+ .send({ reason: 'manager retirement' })
+ .expect(400, { error: 'idempotency_key_required' })
+ expect(directoryMock.deleteManagedUserForUser).not.toHaveBeenCalled()
+ })
+
+ it('passes the authenticated platform actor inputs, idempotency key, and correlation id to managed retirement', async () => {
+ directoryMock.deleteManagedUserForUser.mockResolvedValueOnce({
+ deleted: { ok: true, id: 'target-1' },
+ outcome: { outcome: 'retired', operationId: 'op-1' },
+ })
+
+ await request(makeApp())
+ .delete('/external/members/target-1')
+ .set('Idempotency-Key', 'external-delete-1')
+ .send({ reason: 'manager retirement' })
+ .expect(200, { ok: true, id: 'target-1' })
+
+ expect(directoryMock.deleteManagedUserForUser).toHaveBeenCalledWith('manager-1', 'target-1', {
+ reason: 'manager retirement',
+ idempotencyKey: 'external-delete-1',
+ requestId: 'request-external-members',
+ })
+ })
+
+ it.each([
+ ['invalid_retirement_input', 400],
+ ['idempotency_conflict', 409],
+ ['retirement_conflict', 409],
+ ] as const)('maps governed retirement error %s to its route contract', async (error, status) => {
+ directoryMock.deleteManagedUserForUser.mockResolvedValueOnce({ error })
+
+ await request(makeApp())
+ .delete('/external/members/target-1')
+ .set('Idempotency-Key', `external-${error}`)
+ .send({ reason: 'manager retirement' })
+ .expect(status, { error })
+ })
})
diff --git a/control-api/test/routes.profileAdmin.test.ts b/control-api/test/routes.profileAdmin.test.ts
index 559e8cba5..df47009c6 100644
--- a/control-api/test/routes.profileAdmin.test.ts
+++ b/control-api/test/routes.profileAdmin.test.ts
@@ -26,6 +26,7 @@ const svc = vi.hoisted(() => ({
listPendingInvitationsForTeam: vi.fn(),
listTeams: vi.fn(),
renameTeam: vi.fn(),
+ retireDesktopUser: vi.fn(),
resendInvitation: vi.fn(),
revokePendingInvitation: vi.fn(),
setTeamAgents: vi.fn(),
@@ -39,11 +40,17 @@ const svc = vi.hoisted(() => ({
const serviceErrors = vi.hoisted(() => ({
AgentGrantPreconditionError: class AgentGrantPreconditionError extends Error {},
+ DesktopUserRetirementError: class DesktopUserRetirementError extends Error {
+ constructor(readonly code: string) {
+ super(code)
+ }
+ },
}))
vi.mock('../src/services/directory/index.js', () => ({
...svc,
AgentGrantPreconditionError: serviceErrors.AgentGrantPreconditionError,
+ DesktopUserRetirementError: serviceErrors.DesktopUserRetirementError,
}))
const TEST_ADMIN_SUB = '11111111-1111-4111-8111-111111111111'
@@ -393,16 +400,68 @@ describe('routes/profileAdmin', () => {
}
})
- it('DELETE /admin/users/:userId returns 200 or 404', async () => {
+ it('DELETE /admin/users/:userId forwards the authenticated actor, reason, idempotency key, and correlation id', async () => {
+ const unauthenticated = express()
+ unauthenticated.use(express.json())
+ unauthenticated.use(createAuthenticatedAdminRouter(gatewayStub as unknown as K8sGateway))
+ await request(unauthenticated)
+ .delete('/admin/users/u1')
+ .set('Idempotency-Key', 'admin-delete-unauthenticated')
+ .send({ reason: 'policy retirement' })
+ .expect(401, { error: 'Unauthorized' })
+ expect(svc.retireDesktopUser).not.toHaveBeenCalled()
+
const app = express()
app.use(express.json())
- app.use(createAdminRouter(gatewayStub as unknown as K8sGateway))
+ app.use((req, _res, next) => {
+ ;(req as unknown as { adminAuth: { sub: string }; correlationId: string }).adminAuth = {
+ sub: TEST_ADMIN_SUB,
+ }
+ ;(req as unknown as { correlationId: string }).correlationId = 'request-admin-route'
+ next()
+ })
+ app.use(createAuthenticatedAdminRouter(gatewayStub as unknown as K8sGateway))
- svc.adminDeleteUser.mockResolvedValueOnce({ ok: true, id: 'u1' })
- const ok = await request(app).delete('/admin/users/u1').expect(200)
+ svc.retireDesktopUser.mockResolvedValueOnce({ id: 'u1', outcome: 'retired' })
+ const ok = await request(app)
+ .delete('/admin/users/u1')
+ .set('Idempotency-Key', 'admin-delete-1')
+ .send({ reason: 'policy retirement' })
+ .expect(200)
expect(ok.body).toEqual({ deleted: true, id: 'u1' })
+ expect(svc.retireDesktopUser).toHaveBeenCalledWith(
+ { kind: 'control_admin', controlAdminId: TEST_ADMIN_SUB },
+ 'u1',
+ 'policy retirement',
+ 'admin-delete-1',
+ 'request-admin-route'
+ )
- svc.adminDeleteUser.mockResolvedValueOnce({ error: 'not_found' })
- await request(app).delete('/admin/users/missing').expect(404)
+ const missingReason = await request(app).delete('/admin/users/u1').expect(400)
+ expect(missingReason.body).toEqual({ error: 'reason_required' })
+
+ const missingKey = await request(app)
+ .delete('/admin/users/u1')
+ .send({ reason: 'policy retirement' })
+ .expect(400)
+ expect(missingKey.body).toEqual({ error: 'idempotency_key_required' })
+
+ svc.retireDesktopUser.mockRejectedValueOnce(
+ new serviceErrors.DesktopUserRetirementError('not_found')
+ )
+ await request(app)
+ .delete('/admin/users/missing')
+ .set('Idempotency-Key', 'admin-delete-not-found')
+ .send({ reason: 'policy retirement' })
+ .expect(404, { error: 'not_found' })
+
+ svc.retireDesktopUser.mockRejectedValueOnce(
+ new serviceErrors.DesktopUserRetirementError('idempotency_conflict')
+ )
+ await request(app)
+ .delete('/admin/users/u1')
+ .set('Idempotency-Key', 'admin-delete-conflict')
+ .send({ reason: 'policy retirement' })
+ .expect(409, { error: 'idempotency_conflict' })
})
})
diff --git a/control-api/test/services.directory.userRetirement.test.ts b/control-api/test/services.directory.userRetirement.test.ts
new file mode 100644
index 000000000..aea7e7aae
--- /dev/null
+++ b/control-api/test/services.directory.userRetirement.test.ts
@@ -0,0 +1,349 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createHash } from 'node:crypto'
+import type { DbClient } from '../src/db.js'
+
+const USER_ID = '11111111-1111-4111-8111-111111111111'
+const ADMIN_ID = '22222222-2222-4222-8222-222222222222'
+const MANAGER_ID = '33333333-3333-4333-8333-333333333333'
+const OPERATION_ID = '44444444-4444-4444-8444-444444444444'
+
+const mocks = vi.hoisted(() => {
+ const txQuery = vi.fn()
+ return {
+ txQuery,
+ withTransaction: vi.fn(
+ async <T>(work: (db: DbClient) => Promise<T>): Promise<T> => work({ query: txQuery })
+ ),
+ retireParentInTransaction: vi.fn(),
+ }
+})
+
+vi.mock('../src/db.js', () => ({
+ pool: { query: vi.fn() },
+ withTransaction: mocks.withTransaction,
+}))
+
+vi.mock('../src/services/gfsDesktopOperatorLinkService.js', () => {
+ class GfsDesktopOperatorLinkError extends Error {
+ constructor(
+ readonly code: string,
+ message: string
+ ) {
+ super(message)
+ this.name = 'GfsDesktopOperatorLinkError'
+ }
+ }
+ return {
+ GfsDesktopOperatorLinkError,
+ gfsDesktopOperatorLinkService: {
+ retireParentInTransaction: mocks.retireParentInTransaction,
+ },
+ }
+})
+
+function hash(value: string): string {
+ return createHash('sha256').update(value).digest('hex')
+}
+
+function fingerprint(actor: object, reason: string, idempotencyKey: string): string {
+ const idempotencyKeyHash = hash(idempotencyKey)
+ return hash(
+ JSON.stringify({
+ operation: 'retire_desktop_user',
+ actor,
+ targetUserId: USER_ID,
+ reason,
+ idempotencyKeyHash,
+ })
+ )
+}
+
+function activeUser(version = 1) {
+ return {
+ rows: [{ id: USER_ID, lifecycle_state: 'active', lifecycle_version: version }],
+ rowCount: 1,
+ }
+}
+
+describe('retireDesktopUser', () => {
+ beforeEach(() => {
+ mocks.txQuery.mockReset()
+ mocks.retireParentInTransaction.mockReset()
+ mocks.withTransaction.mockReset()
+ mocks.withTransaction.mockImplementation(
+ async <T>(work: (db: DbClient) => Promise<T>): Promise<T> => work({ query: mocks.txQuery })
+ )
+ })
+
+ it('retires an active linked user atomically with exact control-admin actor and audit correlation', async () => {
+ const { retireDesktopUser } = await import('../src/services/directory/users.js')
+ mocks.txQuery
+ .mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
+ .mockResolvedValueOnce(activeUser())
+ .mockResolvedValueOnce({ rows: [{ has_link_history: true }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [{ lifecycle_version: 2 }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+ mocks.retireParentInTransaction.mockResolvedValueOnce(true)
+
+ await expect(
+ retireDesktopUser(
+ { kind: 'control_admin', controlAdminId: ADMIN_ID },
+ USER_ID,
+ 'policy retirement',
+ 'idem-admin-1',
+ 'request-admin-1'
+ )
+ ).resolves.toEqual({
+ id: USER_ID,
+ outcome: 'retired',
+ operationId: OPERATION_ID,
+ lifecycleVersion: 2,
+ replayed: false,
+ })
+
+ expect(mocks.retireParentInTransaction).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ kind: 'desktop_user',
+ parentId: USER_ID,
+ actor: { kind: 'control_admin', controlAdminId: ADMIN_ID },
+ reason: 'policy retirement',
+ requestId: 'request-admin-1',
+ operationId: OPERATION_ID,
+ })
+ )
+ const userUpdate = String(mocks.txQuery.mock.calls[3]?.[0])
+ expect(userUpdate).toContain("lifecycle_state = 'retired'")
+ expect(userUpdate).toContain('retired_by_control_admin_id = $4::uuid')
+ expect(userUpdate).toContain('retired_by_desktop_user_id = $5::uuid')
+ expect(userUpdate).toContain('lifecycle_version = $8')
+ expect(mocks.txQuery.mock.calls[3]?.[1]).toEqual([
+ USER_ID,
+ 'policy retirement',
+ 'control_admin',
+ ADMIN_ID,
+ null,
+ 'request-admin-1',
+ OPERATION_ID,
+ 1,
+ ])
+ })
+
+ it('keeps a platform-user actor distinct from a Control Admin', async () => {
+ const { retireDesktopUser } = await import('../src/services/directory/users.js')
+ mocks.txQuery
+ .mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
+ .mockResolvedValueOnce(activeUser())
+ .mockResolvedValueOnce({ rows: [{ has_link_history: true }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [{ lifecycle_version: 2 }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+ mocks.retireParentInTransaction.mockResolvedValueOnce(true)
+
+ await retireDesktopUser(
+ { kind: 'platform_user', desktopUserId: MANAGER_ID },
+ USER_ID,
+ 'manager retirement',
+ 'idem-user-1',
+ 'request-user-1'
+ )
+
+ expect(mocks.retireParentInTransaction).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ actor: { kind: 'platform_user', desktopUserId: MANAGER_ID },
+ })
+ )
+ expect(mocks.txQuery.mock.calls[3]?.[1]).toEqual([
+ USER_ID,
+ 'manager retirement',
+ 'platform_user',
+ null,
+ MANAGER_ID,
+ 'request-user-1',
+ OPERATION_ID,
+ 1,
+ ])
+ })
+
+ it('returns the stored terminal outcome for an identical idempotency retry without re-emitting events', async () => {
+ const { retireDesktopUser } = await import('../src/services/directory/users.js')
+ const actor = { kind: 'control_admin' as const, controlAdminId: ADMIN_ID }
+ mocks.txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 }).mockResolvedValueOnce({
+ rows: [
+ {
+ id: OPERATION_ID,
+ request_fingerprint: fingerprint(actor, 'policy retirement', 'idem-retry-1'),
+ status: 'completed',
+ outcome: 'retired',
+ lifecycle_version: 2,
+ },
+ ],
+ rowCount: 1,
+ })
+
+ await expect(
+ retireDesktopUser(actor, USER_ID, 'policy retirement', 'idem-retry-1', 'request-retry-2')
+ ).resolves.toEqual({
+ id: USER_ID,
+ outcome: 'retired',
+ operationId: OPERATION_ID,
+ lifecycleVersion: 2,
+ replayed: true,
+ })
+ expect(mocks.retireParentInTransaction).not.toHaveBeenCalled()
+ expect(String(mocks.txQuery.mock.calls[0]?.[0])).toContain('ON CONFLICT DO NOTHING')
+ expect(String(mocks.txQuery.mock.calls[1]?.[0])).toContain('FOR UPDATE')
+ })
+
+ it('fails a stale or conflicting replay closed before it can re-emit lifecycle evidence', async () => {
+ const { retireDesktopUser, DesktopUserRetirementError } =
+ await import('../src/services/directory/users.js')
+ const actor = { kind: 'control_admin' as const, controlAdminId: ADMIN_ID }
+ mocks.txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 }).mockResolvedValueOnce({
+ rows: [
+ {
+ id: OPERATION_ID,
+ request_fingerprint: fingerprint(actor, 'first reason', 'idem-conflict-1'),
+ status: 'completed',
+ outcome: 'retired',
+ lifecycle_version: 2,
+ },
+ ],
+ rowCount: 1,
+ })
+
+ await expect(
+ retireDesktopUser(actor, USER_ID, 'different reason', 'idem-conflict-1', 'request-conflict')
+ ).rejects.toMatchObject<Partial<InstanceType<typeof DesktopUserRetirementError>>>({
+ code: 'idempotency_conflict',
+ })
+ expect(mocks.retireParentInTransaction).not.toHaveBeenCalled()
+ })
+
+ it('keeps the legacy hard-delete only for users with no operator-link history and persists its replay result', async () => {
+ const { retireDesktopUser } = await import('../src/services/directory/users.js')
+ mocks.txQuery
+ .mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
+ .mockResolvedValueOnce(activeUser())
+ .mockResolvedValueOnce({ rows: [{ has_link_history: false }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [{ id: USER_ID }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })
+
+ await expect(
+ retireDesktopUser(
+ { kind: 'control_admin', controlAdminId: ADMIN_ID },
+ USER_ID,
+ 'no link history',
+ 'idem-delete-1',
+ 'request-delete-1'
+ )
+ ).resolves.toEqual({
+ id: USER_ID,
+ outcome: 'deleted',
+ operationId: OPERATION_ID,
+ lifecycleVersion: null,
+ replayed: false,
+ })
+ expect(mocks.retireParentInTransaction).not.toHaveBeenCalled()
+ expect(String(mocks.txQuery.mock.calls[5]?.[0])).toContain('DELETE FROM users')
+ expect(String(mocks.txQuery.mock.calls[6]?.[0])).toContain("outcome = 'deleted'")
+ })
+
+ it('fails closed for retained tombstone history with no active generation', async () => {
+ const { retireDesktopUser } = await import('../src/services/directory/users.js')
+ mocks.txQuery
+ .mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
+ .mockResolvedValueOnce(activeUser())
+ .mockResolvedValueOnce({ rows: [{ has_link_history: true }], rowCount: 1 })
+ mocks.retireParentInTransaction.mockResolvedValueOnce(false)
+
+ await expect(
+ retireDesktopUser(
+ { kind: 'control_admin', controlAdminId: ADMIN_ID },
+ USER_ID,
+ 'tombstone cannot be retired twice',
+ 'idem-tombstone-1',
+ 'request-tombstone-1'
+ )
+ ).rejects.toMatchObject({ code: 'retirement_conflict' })
+ expect(mocks.txQuery).toHaveBeenCalledTimes(3)
+ expect(mocks.txQuery.mock.calls.map(([sql]) => String(sql))).not.toEqual(
+ expect.arrayContaining([expect.stringContaining("lifecycle_state = 'retired'")])
+ )
+ })
+
+ it('rolls the whole operation back when governed evidence fails before the CAS user transition', async () => {
+ const { retireDesktopUser } = await import('../src/services/directory/users.js')
+ const transactionState = { committed: false, rolledBack: false }
+ mocks.withTransaction.mockImplementationOnce(
+ async <T>(work: (db: DbClient) => Promise<T>): Promise<T> => {
+ try {
+ const value = await work({ query: mocks.txQuery })
+ transactionState.committed = true
+ return value
+ } catch (error) {
+ transactionState.rolledBack = true
+ throw error
+ }
+ }
+ )
+ mocks.txQuery
+ .mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
+ .mockResolvedValueOnce(activeUser())
+ .mockResolvedValueOnce({ rows: [{ has_link_history: true }], rowCount: 1 })
+ mocks.retireParentInTransaction.mockRejectedValueOnce(new Error('audit unavailable'))
+
+ await expect(
+ retireDesktopUser(
+ { kind: 'control_admin', controlAdminId: ADMIN_ID },
+ USER_ID,
+ 'evidence must commit',
+ 'idem-rollback-1',
+ 'request-rollback-1'
+ )
+ ).rejects.toThrow('audit unavailable')
+ expect(transactionState).toEqual({ committed: false, rolledBack: true })
+ expect(mocks.txQuery.mock.calls.map(([sql]) => String(sql))).not.toContain(
+ expect.stringContaining("lifecycle_state = 'retired'")
+ )
+ })
+
+ it('fails closed on a stale lifecycle row version and does not complete the outcome record', async () => {
+ const { retireDesktopUser } = await import('../src/services/directory/users.js')
+ mocks.txQuery
+ .mockResolvedValueOnce({ rows: [{ id: OPERATION_ID }], rowCount: 1 })
+ .mockResolvedValueOnce(activeUser(7))
+ .mockResolvedValueOnce({ rows: [{ has_link_history: true }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [], rowCount: 0 })
+ mocks.retireParentInTransaction.mockResolvedValueOnce(true)
+
+ await expect(
+ retireDesktopUser(
+ { kind: 'control_admin', controlAdminId: ADMIN_ID },
+ USER_ID,
+ 'stale lifecycle',
+ 'idem-cas-1',
+ 'request-cas-1'
+ )
+ ).rejects.toMatchObject({ code: 'retirement_conflict' })
+ expect(mocks.txQuery).toHaveBeenCalledTimes(4)
+ expect(String(mocks.txQuery.mock.calls[3]?.[0])).toContain('lifecycle_version = $8')
+ })
+
+ it('rejects an actor with the wrong typed identity field before opening a transaction', async () => {
+ const { retireDesktopUser } = await import('../src/services/directory/users.js')
+
+ await expect(
+ retireDesktopUser(
+ { kind: 'control_admin', desktopUserId: ADMIN_ID } as never,
+ USER_ID,
+ 'invalid actor',
+ 'idem-invalid-actor',
+ null
+ )
+ ).rejects.toMatchObject({ code: 'invalid_input' })
+ expect(mocks.withTransaction).not.toHaveBeenCalled()
+ })
+})
diff --git a/control-api/test/services.gfsDesktopOperatorLinkService.test.ts b/control-api/test/services.gfsDesktopOperatorLinkService.test.ts
index 89e24bcde..f31a30dba 100644
--- a/control-api/test/services.gfsDesktopOperatorLinkService.test.ts
+++ b/control-api/test/services.gfsDesktopOperatorLinkService.test.ts
@@ -176,7 +176,7 @@ describe('GfsDesktopOperatorLinkService', () => {
service.retireParentInTransaction({ query: txQuery } as DbClient, {
kind: 'desktop_user',
parentId: DESKTOP_USER_ID,
- operatorSub: OPERATOR_ID,
+ actor: { kind: 'control_admin', controlAdminId: OPERATOR_ID },
reason: 'account_retired',
requestId: 'request-2',
})
@@ -186,6 +186,7 @@ describe('GfsDesktopOperatorLinkService', () => {
expect.anything(),
expect.objectContaining({
operatorSub: OPERATOR_ID,
+ operatorKind: 'control_admin',
requestId: 'request-2',
changes: expect.arrayContaining([
expect.objectContaining({
@@ -200,7 +201,65 @@ describe('GfsDesktopOperatorLinkService', () => {
expect(appendPermissionEvents.mock.invocationCallOrder[0]).toBeLessThan(
txQuery.mock.invocationCallOrder[1]!
)
- expect(txQuery.mock.calls[1]?.[0]).toContain('row_version = $4')
+ expect(txQuery.mock.calls[1]?.[0]).toContain('row_version = $7')
+ })
+
+ it('records a platform-user actor in separate typed revocation columns', 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,
+ actor: { kind: 'platform_user', desktopUserId: OTHER_DESKTOP_USER_ID },
+ reason: 'manager_retired_account',
+ requestId: 'request-3',
+ operationId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ })
+ ).resolves.toBe(true)
+
+ expect(appendPermissionEvents).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ operatorSub: OTHER_DESKTOP_USER_ID,
+ operatorKind: 'platform_user',
+ operationId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ changes: expect.arrayContaining([
+ expect.objectContaining({
+ detailRef: expect.stringContaining(`actor_desktop_user_id:${OTHER_DESKTOP_USER_ID}`),
+ }),
+ expect.objectContaining({
+ detailRef: expect.stringContaining('event:parent.retired'),
+ }),
+ ]),
+ })
+ )
+ const revokeUpdate = String(txQuery.mock.calls[1]?.[0])
+ expect(revokeUpdate).toContain('revoked_by_control_admin_id = $4::uuid')
+ expect(revokeUpdate).toContain('revoked_by_desktop_user_id = $5::uuid')
+ expect(txQuery.mock.calls[1]?.[1]).toEqual([
+ DESKTOP_USER_ID,
+ 'platform_user',
+ null,
+ null,
+ OTHER_DESKTOP_USER_ID,
+ 'manager_retired_account',
+ 1,
+ ])
})
it.each([
@@ -255,6 +314,24 @@ describe('GfsDesktopOperatorLinkService', () => {
expect(appendPermissionEvents).not.toHaveBeenCalled()
})
+ it('refuses to create a new operator generation for a retired Desktop user', async () => {
+ txQuery.mockResolvedValueOnce({
+ rows: [{ id: DESKTOP_USER_ID, lifecycle_state: 'retired' }],
+ rowCount: 1,
+ })
+
+ await expect(
+ service.link({
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ operatorSub: OPERATOR_ID,
+ source: 'initial_setup',
+ })
+ ).rejects.toMatchObject({ code: 'desktop_user_retired' })
+ expect(txQuery).toHaveBeenCalledTimes(1)
+ expect(appendPermissionEvents).not.toHaveBeenCalled()
+ })
+
it.each([
{ rows: [], code: 'control_admin_not_found' },
{ rows: [{ id: CONTROL_ADMIN_ID, status: 'disabled' }], code: 'control_admin_inactive' },
@@ -340,6 +417,17 @@ describe('GfsDesktopOperatorLinkService', () => {
await expect(service.resolveActiveLink(DESKTOP_USER_ID)).resolves.toBeNull()
})
+ it('exposes an explicit lifecycle guard so a revoked link cannot fall back to a retired user session', async () => {
+ readQuery
+ .mockResolvedValueOnce({ rows: [{ lifecycle_state: 'retired' }], rowCount: 1 })
+ .mockResolvedValueOnce({ rows: [{ lifecycle_state: 'active' }], rowCount: 1 })
+
+ await expect(service.isDesktopUserActive(DESKTOP_USER_ID)).resolves.toBe(false)
+ await expect(service.isDesktopUserActive(DESKTOP_USER_ID)).resolves.toBe(true)
+ expect(String(readQuery.mock.calls[0]?.[0])).toContain('FROM users')
+ expect(String(readQuery.mock.calls[0]?.[0])).toContain('lifecycle_state')
+ })
+
it.each([
{
label: 'missing admin',
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.ts
index 86a98c812..84d7ace10 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,7 +1,12 @@
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'
+import {
+ type GfsOperatorLifecycleEvent,
+ type GfsResourceRow,
+ expect,
+ test,
+} from './helpers/gfsDesktopOperatorParityFixtures'
async function expectToast(page: Page, message: string): Promise<void> {
await expect(page.getByRole('status', { name: message, exact: true })).toBeVisible({
@@ -73,6 +78,62 @@ async function selectOrdinarySubject(page: Page, ordinaryEmail: string): Promise
await listbox.getByRole('option').filter({ hasText: ordinaryEmail }).click()
}
+function lifecycleDetailFields(detailRef: string | null): Record<string, string> {
+ if (!detailRef) throw new Error('GFS operator lifecycle audit is missing detail_ref')
+ const fields: Record<string, string> = {}
+ for (const field of detailRef.split(';')) {
+ const [key, ...value] = field.split(':')
+ if (!key || value.length === 0) {
+ throw new Error(`malformed GFS operator lifecycle detail_ref: ${detailRef}`)
+ }
+ if (Object.hasOwn(fields, key)) {
+ throw new Error(`duplicate GFS operator lifecycle detail field: ${key}`)
+ }
+ fields[key] = value.join(':')
+ }
+ return fields
+}
+
+function expectLifecycleAudit(
+ event: GfsOperatorLifecycleEvent,
+ link: { desktopUserId: string; controlAdminId: string; source: string },
+ expected: {
+ action: 'permission_grant' | 'permission_revoke'
+ status: 'linked' | 'unlinked'
+ lifecycle: 'link.created' | 'link.revoked' | 'link.reactivated'
+ generation: number
+ predecessorId?: string
+ reason?: string
+ }
+): void {
+ expect(event).toMatchObject({
+ action: expected.action,
+ outcome: 'committed',
+ operatorSub: link.controlAdminId,
+ targetRef: `gfs_desktop_operator_link:${link.desktopUserId}:${link.controlAdminId}`,
+ sourceAuditRef: `gfs_desktop_operator_link_source:${link.source}`,
+ status: expected.status,
+ })
+ const detail = lifecycleDetailFields(event.detailRef)
+ expect(detail).toMatchObject({
+ event: expected.lifecycle,
+ desktop_user_id: link.desktopUserId,
+ control_admin_id: link.controlAdminId,
+ source: link.source,
+ generation: String(expected.generation),
+ })
+ if (expected.predecessorId === undefined) {
+ expect(detail.predecessor_id).toBeUndefined()
+ } else {
+ expect(detail.predecessor_id).toBe(expected.predecessorId)
+ }
+ if (expected.reason === undefined) {
+ expect(detail.reason).toBeUndefined()
+ } else {
+ expect(detail.reason).toBe(expected.reason)
+ }
+}
+
test.describe.serial('GFS Desktop linked-operator parity', () => {
test('@gfs-operator/setup-linked-operator setup creates the exact link before visible Desktop login', async ({
operatorJourney,
@@ -89,6 +150,46 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
operatorJourney.operatorLink = operatorJourney.readOperatorLink()
expect(operatorJourney.operatorLink).not.toBeNull()
expect(operatorJourney.operatorLink?.controlAdminId).toBe(setup.controlAdminId)
+ await expect
+ .poll(() => operatorJourney.countActiveLinks(), {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(1)
+ await expect
+ .poll(() => operatorJourney.readLinkHistory().length, {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(1)
+ const [initialGeneration] = operatorJourney.assertGenerationChain({
+ activeCount: 1,
+ revokedCount: 0,
+ })
+ expect(initialGeneration).toMatchObject({
+ generation: 1,
+ predecessorId: null,
+ state: 'active',
+ desktopUserId: operatorJourney.operatorLink!.desktopUserId,
+ controlAdminId: setup.controlAdminId,
+ source: 'initial_setup',
+ createdByControlAdminId: setup.controlAdminId,
+ rowVersion: 1,
+ })
+ await expect
+ .poll(() => operatorJourney.readLinkLifecycleEvents().length, {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(1)
+ const [createdEvent] = operatorJourney.readLinkLifecycleEvents()
+ expect(createdEvent).toBeDefined()
+ expectLifecycleAudit(createdEvent!, operatorJourney.operatorLink!, {
+ action: 'permission_grant',
+ status: 'linked',
+ lifecycle: 'link.created',
+ generation: 1,
+ })
operatorJourney.createOrdinaryUserFixture()
const rootResourceId = operatorJourney.readRootResourceId()
@@ -426,7 +527,57 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
await expect(controlPage.getByTestId(`gfs-operator-link-${link.controlAdminId}`)).toHaveText(
'Revoked'
)
- await expect.poll(() => operatorJourney.operatorLinkCount()).toBe(0)
+ await expect
+ .poll(() => operatorJourney.countActiveLinks(), {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(0)
+ await expect
+ .poll(() => operatorJourney.readLinkHistory().length, {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(1)
+ const [firstTombstone] = operatorJourney.assertGenerationChain({
+ activeCount: 0,
+ revokedCount: 1,
+ })
+ expect(firstTombstone).toMatchObject({
+ generation: 1,
+ predecessorId: null,
+ state: 'revoked',
+ desktopUserId: link.desktopUserId,
+ controlAdminId: link.controlAdminId,
+ source: 'initial_setup',
+ createdByControlAdminId: link.controlAdminId,
+ revokedByType: 'control_admin',
+ revokedById: link.controlAdminId,
+ revokedByControlAdminId: link.controlAdminId,
+ revokedByDesktopUserId: null,
+ revocationReason: 'control_ui_revoke',
+ })
+ expect(firstTombstone?.revokedAt).toEqual(expect.any(String))
+ await expect
+ .poll(() => operatorJourney.readLinkLifecycleEvents().length, {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(2)
+ const firstRevokeEvents = operatorJourney
+ .readLinkLifecycleEvents()
+ .filter(event => lifecycleDetailFields(event.detailRef).event === 'link.revoked')
+ expect(firstRevokeEvents).toHaveLength(1)
+ expectLifecycleAudit(firstRevokeEvents[0]!, link, {
+ action: 'permission_revoke',
+ status: 'unlinked',
+ lifecycle: 'link.revoked',
+ generation: 1,
+ reason: 'control_ui_revoke',
+ })
+ expect(lifecycleDetailFields(firstRevokeEvents[0]!.detailRef).lineage_id).toBe(
+ firstTombstone!.lineageId
+ )
operatorJourney.deniedAuditFloor = operatorJourney.auditFloor()
// Keep the user-visible direct-access dialog open across the Control UI
@@ -475,6 +626,51 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
await expect(controlPage.getByTestId(`gfs-operator-link-${link.controlAdminId}`)).toHaveText(
'Active'
)
+ await expect
+ .poll(() => operatorJourney.countActiveLinks(), {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(1)
+ await expect
+ .poll(() => operatorJourney.readLinkHistory().length, {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(2)
+ const [revokedPredecessor, successor] = operatorJourney.assertGenerationChain({
+ activeCount: 1,
+ revokedCount: 1,
+ })
+ expect(successor).toMatchObject({
+ generation: revokedPredecessor!.generation + 1,
+ predecessorId: revokedPredecessor!.id,
+ lineageId: revokedPredecessor!.lineageId,
+ state: 'active',
+ desktopUserId: link.desktopUserId,
+ controlAdminId: link.controlAdminId,
+ source: 'initial_setup',
+ createdByControlAdminId: link.controlAdminId,
+ rowVersion: 1,
+ })
+ await expect
+ .poll(() => operatorJourney.readLinkLifecycleEvents().length, {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(3)
+ const reactivationEvents = operatorJourney
+ .readLinkLifecycleEvents()
+ .filter(event => lifecycleDetailFields(event.detailRef).event === 'link.reactivated')
+ expect(reactivationEvents).toHaveLength(1)
+ expectLifecycleAudit(reactivationEvents[0]!, link, {
+ action: 'permission_grant',
+ status: 'linked',
+ lifecycle: 'link.reactivated',
+ generation: successor!.generation,
+ predecessorId: revokedPredecessor!.id,
+ reason: 'control_ui_reactivate',
+ })
// Retry is the user-visible next Desktop request. It cannot restore a
// client capability; the reactivated server link must return the root.
@@ -511,7 +707,61 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
await expect(controlPage.getByTestId(`gfs-operator-link-${link.controlAdminId}`)).toHaveText(
'Revoked'
)
- await expect.poll(() => operatorJourney.operatorLinkCount()).toBe(0)
+ await expect
+ .poll(() => operatorJourney.countActiveLinks(), {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(0)
+ await expect
+ .poll(() => operatorJourney.readLinkHistory().length, {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(2)
+ const [firstRevokedGeneration, secondTombstone] = operatorJourney.assertGenerationChain({
+ activeCount: 0,
+ revokedCount: 2,
+ })
+ expect(firstRevokedGeneration).toMatchObject({
+ generation: 1,
+ predecessorId: null,
+ state: 'revoked',
+ })
+ expect(secondTombstone).toMatchObject({
+ generation: firstRevokedGeneration!.generation + 1,
+ predecessorId: firstRevokedGeneration!.id,
+ lineageId: firstRevokedGeneration!.lineageId,
+ state: 'revoked',
+ desktopUserId: link.desktopUserId,
+ controlAdminId: link.controlAdminId,
+ source: 'initial_setup',
+ createdByControlAdminId: link.controlAdminId,
+ revokedByType: 'control_admin',
+ revokedById: link.controlAdminId,
+ revokedByControlAdminId: link.controlAdminId,
+ revokedByDesktopUserId: null,
+ revocationReason: 'control_ui_revoke',
+ })
+ expect(secondTombstone?.revokedAt).toEqual(expect.any(String))
+ await expect
+ .poll(() => operatorJourney.readLinkLifecycleEvents().length, {
+ timeout: 30_000,
+ intervals: [250, 500, 1_000],
+ })
+ .toBe(4)
+ const secondRevokeEvents = operatorJourney
+ .readLinkLifecycleEvents()
+ .filter(event => lifecycleDetailFields(event.detailRef).event === 'link.revoked')
+ expect(secondRevokeEvents).toHaveLength(2)
+ expectLifecycleAudit(secondRevokeEvents[1]!, link, {
+ action: 'permission_revoke',
+ status: 'unlinked',
+ lifecycle: 'link.revoked',
+ generation: secondTombstone!.generation,
+ predecessorId: firstRevokedGeneration!.id,
+ reason: 'control_ui_revoke',
+ })
})
test('@gfs-operator/audit-correlation successful and denied Desktop requests preserve exact actor and request IDs', async ({
@@ -589,13 +839,53 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
expect(
deniedRows.filter(row => row.requestId && row.op === 'create' && row.mutationOutcome)
).toHaveLength(0)
- const lifecycle = operatorJourney.readUnlinkLifecycleEvent()
- expect(lifecycle).toMatchObject({
- operatorSub: link.controlAdminId,
- targetRef: `gfs_desktop_operator_link:${link.desktopUserId}:${link.controlAdminId}`,
+ const lifecycleEvents = operatorJourney.readLinkLifecycleEvents()
+ expect(lifecycleEvents).toHaveLength(4)
+ expect(new Set(lifecycleEvents.map(event => event.eventId)).size).toBe(4)
+ const [firstGeneration, secondGeneration] = operatorJourney.assertGenerationChain({
+ activeCount: 0,
+ revokedCount: 2,
+ })
+ const [createdEvent, firstRevokeEvent, reactivatedEvent, secondRevokeEvent] = lifecycleEvents
+ expect(createdEvent).toBeDefined()
+ expect(firstRevokeEvent).toBeDefined()
+ expect(reactivatedEvent).toBeDefined()
+ expect(secondRevokeEvent).toBeDefined()
+
+ expectLifecycleAudit(createdEvent!, link, {
+ action: 'permission_grant',
+ status: 'linked',
+ lifecycle: 'link.created',
+ generation: 1,
})
- expect(lifecycle?.detailRef).toContain(`desktop_user_id:${link.desktopUserId}`)
- expect(lifecycle?.detailRef).toContain(`control_admin_id:${link.controlAdminId}`)
- expect(lifecycle?.detailRef).toContain('source:initial_setup')
+ expectLifecycleAudit(firstRevokeEvent!, link, {
+ action: 'permission_revoke',
+ status: 'unlinked',
+ lifecycle: 'link.revoked',
+ generation: 1,
+ reason: 'control_ui_revoke',
+ })
+ expectLifecycleAudit(reactivatedEvent!, link, {
+ action: 'permission_grant',
+ status: 'linked',
+ lifecycle: 'link.reactivated',
+ generation: 2,
+ predecessorId: firstGeneration!.id,
+ reason: 'control_ui_reactivate',
+ })
+ expectLifecycleAudit(secondRevokeEvent!, link, {
+ action: 'permission_revoke',
+ status: 'unlinked',
+ lifecycle: 'link.revoked',
+ generation: 2,
+ predecessorId: firstGeneration!.id,
+ reason: 'control_ui_revoke',
+ })
+
+ const reactivationDetail = lifecycleDetailFields(reactivatedEvent!.detailRef)
+ const secondRevokeDetail = lifecycleDetailFields(secondRevokeEvent!.detailRef)
+ expect(secondGeneration!.predecessorId).toBe(firstGeneration!.id)
+ expect(reactivationDetail.predecessor_id).toBe(firstGeneration!.id)
+ expect(secondRevokeDetail.predecessor_id).toBe(firstGeneration!.id)
})
})
diff --git a/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts b/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts
index a50072d6f..27ec85e3c 100644
--- a/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts
+++ b/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts
@@ -25,6 +25,38 @@ export interface GfsOperatorScenarioResult {
title: string
}
+/**
+ * A persisted generation is deliberately more detailed than the status shown
+ * in Control UI. The E2E reads this evidence after a visible lifecycle action;
+ * it never uses it to manufacture a link or advance the browser journey.
+ */
+export interface GfsOperatorLinkGeneration {
+ id: string
+ lineageId: string
+ generation: number
+ predecessorId: string | null
+ state: 'active' | 'revoked'
+ desktopUserId: string
+ controlAdminId: string
+ source: string
+ createdByControlAdminId: string
+ rowVersion: number
+ revokedAt: string | null
+ revokedByType: 'control_admin' | 'platform_user' | null
+ revokedById: string | null
+ revokedByControlAdminId: string | null
+ revokedByDesktopUserId: string | null
+ revocationReason: string | null
+}
+
+export interface GfsOperatorGenerationChainExpectation {
+ desktopUserId: string
+ controlAdminId: string
+ source: string
+ activeCount: number
+ revokedCount: number
+}
+
export interface GfsOperatorContractVerdict {
ok: boolean
errors: string[]
@@ -100,6 +132,122 @@ export function scenarioIdFromTitle(title: string): GfsOperatorScenarioId | null
return matches.length === 1 ? (matches[0] ?? null) : null
}
+/**
+ * Verifies the immutable operator-link lineage independently of UI rendering.
+ * The caller supplies rows ordered by generation so a non-contiguous or
+ * reordered history is a failure rather than being normalized away.
+ */
+export function assertGenerationChain(
+ history: readonly GfsOperatorLinkGeneration[],
+ expected: GfsOperatorGenerationChainExpectation
+): void {
+ const prefix = '[GFS-OPERATOR-E2E] generation history invariant failed:'
+ const fail = (message: string): never => {
+ throw new Error(`${prefix} ${message}`)
+ }
+ const requireCount = (name: string, value: number): void => {
+ if (!Number.isSafeInteger(value) || value < 0) {
+ fail(`${name} must be a non-negative integer`)
+ }
+ }
+
+ requireCount('activeCount', expected.activeCount)
+ requireCount('revokedCount', expected.revokedCount)
+ if (history.length !== expected.activeCount + expected.revokedCount) {
+ fail(
+ `expected ${expected.activeCount} active and ${expected.revokedCount} revoked generations; received ${history.length} rows`
+ )
+ }
+ if (history.length === 0) fail('history must contain at least one generation')
+
+ const first = history[0]!
+ const activeRows: GfsOperatorLinkGeneration[] = []
+ const revokedRows: GfsOperatorLinkGeneration[] = []
+
+ for (const [index, row] of history.entries()) {
+ const expectedGeneration = index + 1
+ if (row.generation !== expectedGeneration) {
+ fail(
+ `expected generation ${expectedGeneration} at index ${index}, received ${row.generation}`
+ )
+ }
+ if (
+ row.desktopUserId !== expected.desktopUserId ||
+ row.controlAdminId !== expected.controlAdminId
+ ) {
+ fail(
+ `generation ${row.generation} does not preserve the exact Desktop-user/Control-Admin pair`
+ )
+ }
+ if (row.source !== expected.source) {
+ fail(`generation ${row.generation} changed source from ${expected.source} to ${row.source}`)
+ }
+ if (row.lineageId !== first.lineageId) {
+ fail(`generation ${row.generation} does not preserve lineage ${first.lineageId}`)
+ }
+ if (!Number.isSafeInteger(row.rowVersion) || row.rowVersion < 1) {
+ fail(`generation ${row.generation} has an invalid row version`)
+ }
+ if (index === 0) {
+ if (row.predecessorId !== null) fail('generation 1 must not have a predecessor')
+ } else {
+ const predecessor = history[index - 1]
+ if (!predecessor || row.predecessorId !== predecessor.id) {
+ fail(`generation ${row.generation} must point to generation ${expectedGeneration - 1}`)
+ }
+ }
+
+ if (row.state === 'active') {
+ activeRows.push(row)
+ if (
+ row.revokedAt !== null ||
+ row.revokedByType !== null ||
+ row.revokedById !== null ||
+ row.revokedByControlAdminId !== null ||
+ row.revokedByDesktopUserId !== null ||
+ row.revocationReason !== null
+ ) {
+ fail(`active generation ${row.generation} contains revocation evidence`)
+ }
+ continue
+ }
+
+ if (row.state !== 'revoked') fail(`generation ${row.generation} has invalid state ${row.state}`)
+ revokedRows.push(row)
+ if (!row.revokedAt || !row.revocationReason) {
+ fail(`revoked generation ${row.generation} is missing timestamp or reason`)
+ }
+ if (row.revokedByType === 'control_admin') {
+ if (
+ !row.revokedById ||
+ row.revokedById !== row.revokedByControlAdminId ||
+ row.revokedByDesktopUserId !== null
+ ) {
+ fail(`control-admin revocation actor is malformed for generation ${row.generation}`)
+ }
+ continue
+ }
+ if (row.revokedByType === 'platform_user') {
+ if (
+ row.revokedById !== null ||
+ row.revokedByControlAdminId !== null ||
+ !row.revokedByDesktopUserId
+ ) {
+ fail(`platform-user revocation actor is malformed for generation ${row.generation}`)
+ }
+ continue
+ }
+ fail(`revoked generation ${row.generation} has no typed revocation actor`)
+ }
+
+ if (activeRows.length !== expected.activeCount) {
+ fail(`expected ${expected.activeCount} active generations, received ${activeRows.length}`)
+ }
+ if (revokedRows.length !== expected.revokedCount) {
+ fail(`expected ${expected.revokedCount} revoked generations, received ${revokedRows.length}`)
+ }
+}
+
export function evaluateGfsOperatorScenarioResults(
results: readonly GfsOperatorScenarioResult[],
runtimeEvidencePresent: boolean
diff --git a/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts b/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts
index 6a367b5f4..cd7678136 100644
--- a/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts
+++ b/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts
@@ -23,6 +23,9 @@ import {
import { cleanupGfsFixture } from '../../../../tests/e2e/gfsResourceFixtures'
import {
GFS_OPERATOR_SETUP_PATH,
+ type GfsOperatorGenerationChainExpectation,
+ type GfsOperatorLinkGeneration,
+ assertGenerationChain as assertGenerationChainContract,
requireGfsOperatorRunId,
} from '../gfsDesktopOperatorParityContract'
import { openResourcesNavItem } from '../navigationHelpers'
@@ -92,6 +95,132 @@ export interface GfsAuditRow {
gfsUri: string | null
}
+export interface GfsOperatorLifecycleEvent {
+ eventId: string
+ action: 'permission_grant' | 'permission_revoke'
+ outcome: string
+ operatorSub: string | null
+ targetRef: string
+ sourceAuditRef: string | null
+ status: string | null
+ detailRef: string | null
+ requestId: string | null
+ operationId: string | null
+}
+
+function asRecord(value: unknown, label: string): Record<string, unknown> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error(`[GFS-OPERATOR-E2E] ${label} must be a JSON object`)
+ }
+ return value as Record<string, unknown>
+}
+
+function requiredString(record: Record<string, unknown>, field: string, label: string): string {
+ const value = record[field]
+ if (typeof value !== 'string' || !value.trim()) {
+ throw new Error(`[GFS-OPERATOR-E2E] ${label}.${field} must be a non-empty string`)
+ }
+ return value
+}
+
+function nullableString(
+ record: Record<string, unknown>,
+ field: string,
+ label: string
+): string | null {
+ const value = record[field]
+ if (value === null) return null
+ if (typeof value !== 'string') {
+ throw new Error(`[GFS-OPERATOR-E2E] ${label}.${field} must be a string or null`)
+ }
+ return value
+}
+
+function requiredUuid(record: Record<string, unknown>, field: string, label: string): string {
+ const value = requiredString(record, field, label)
+ if (!UUID_RE.test(value)) {
+ throw new Error(`[GFS-OPERATOR-E2E] ${label}.${field} must be a UUID`)
+ }
+ return value
+}
+
+function nullableUuid(
+ record: Record<string, unknown>,
+ field: string,
+ label: string
+): string | null {
+ const value = nullableString(record, field, label)
+ if (value !== null && !UUID_RE.test(value)) {
+ throw new Error(`[GFS-OPERATOR-E2E] ${label}.${field} must be a UUID or null`)
+ }
+ return value
+}
+
+function positiveInteger(record: Record<string, unknown>, field: string, label: string): number {
+ const raw = record[field]
+ const value = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : Number.NaN
+ if (!Number.isSafeInteger(value) || value < 1) {
+ throw new Error(`[GFS-OPERATOR-E2E] ${label}.${field} must be a positive integer`)
+ }
+ return value
+}
+
+function parseLinkGeneration(value: unknown): GfsOperatorLinkGeneration {
+ const row = asRecord(value, 'operator-link history')
+ const state = requiredString(row, 'state', 'operator-link history')
+ if (state !== 'active' && state !== 'revoked') {
+ throw new Error(`[GFS-OPERATOR-E2E] operator-link history.state is unsupported: ${state}`)
+ }
+ const revokedByType = nullableString(row, 'revokedByType', 'operator-link history')
+ if (
+ revokedByType !== null &&
+ revokedByType !== 'control_admin' &&
+ revokedByType !== 'platform_user'
+ ) {
+ throw new Error(
+ `[GFS-OPERATOR-E2E] operator-link history.revokedByType is unsupported: ${revokedByType}`
+ )
+ }
+ return {
+ id: requiredUuid(row, 'id', 'operator-link history'),
+ lineageId: requiredUuid(row, 'lineageId', 'operator-link history'),
+ generation: positiveInteger(row, 'generation', 'operator-link history'),
+ predecessorId: nullableUuid(row, 'predecessorId', 'operator-link history'),
+ state,
+ desktopUserId: requiredUuid(row, 'desktopUserId', 'operator-link history'),
+ controlAdminId: requiredUuid(row, 'controlAdminId', 'operator-link history'),
+ source: requiredString(row, 'source', 'operator-link history'),
+ createdByControlAdminId: requiredUuid(row, 'createdByControlAdminId', 'operator-link history'),
+ rowVersion: positiveInteger(row, 'rowVersion', 'operator-link history'),
+ revokedAt: nullableString(row, 'revokedAt', 'operator-link history'),
+ revokedByType,
+ revokedById: nullableUuid(row, 'revokedById', 'operator-link history'),
+ revokedByControlAdminId: nullableUuid(row, 'revokedByControlAdminId', 'operator-link history'),
+ revokedByDesktopUserId: nullableUuid(row, 'revokedByDesktopUserId', 'operator-link history'),
+ revocationReason: nullableString(row, 'revocationReason', 'operator-link history'),
+ }
+}
+
+function parseLifecycleEvent(value: unknown): GfsOperatorLifecycleEvent {
+ const row = asRecord(value, 'operator-link lifecycle event')
+ const action = requiredString(row, 'action', 'operator-link lifecycle event')
+ if (action !== 'permission_grant' && action !== 'permission_revoke') {
+ throw new Error(`[GFS-OPERATOR-E2E] unsupported lifecycle action: ${action}`)
+ }
+ return {
+ eventId: requiredUuid(row, 'eventId', 'operator-link lifecycle event'),
+ action,
+ outcome: requiredString(row, 'outcome', 'operator-link lifecycle event'),
+ operatorSub: nullableString(row, 'operatorSub', 'operator-link lifecycle event'),
+ targetRef: requiredString(row, 'targetRef', 'operator-link lifecycle event'),
+ sourceAuditRef: nullableString(row, 'sourceAuditRef', 'operator-link lifecycle event'),
+ status: nullableString(row, 'status', 'operator-link lifecycle event'),
+ detailRef: nullableString(row, 'detailRef', 'operator-link lifecycle event'),
+ requestId: nullableString(row, 'requestId', 'operator-link lifecycle event'),
+ operationId: nullableUuid(row, 'operationId', 'operator-link lifecycle event'),
+ }
+}
+
export class GfsDesktopOperatorJourney {
readonly runId = requireGfsOperatorRunId()
readonly runTag = createHash('sha256').update(this.runId).digest('hex').slice(0, 10)
@@ -282,6 +411,8 @@ export class GfsDesktopOperatorJourney {
WHERE control_admin_id IN (
SELECT id FROM control_admin_users WHERE lower(email) = lower(${sqlLiteral(this.operatorEmail)})
)
+ AND state = 'active'
+ ORDER BY generation DESC
LIMIT 1;
`)
)
@@ -293,17 +424,78 @@ export class GfsDesktopOperatorJourney {
return { desktopUserId, controlAdminId, source }
}
- operatorLinkCount(): number {
- if (!this.operatorLink) throw new Error('operator link is not initialized')
- return Number(
- firstDataLine(
- runControlPostgresSql(`
- SELECT count(*)::text FROM gfs_desktop_operator_links
- WHERE user_id = ${sqlLiteral(this.operatorLink?.desktopUserId ?? '')}::uuid
- AND control_admin_id = ${sqlLiteral(this.operatorLink?.controlAdminId ?? '')}::uuid;
- `)
- )
+ /** Counts current authority only; revoked generations remain readable history. */
+ countActiveLinks(): number {
+ const link = this.requireOperatorLink()
+ const value = firstDataLine(
+ runControlPostgresSql(`
+ SELECT count(*)::text
+ FROM gfs_desktop_operator_links
+ WHERE user_id = ${sqlLiteral(link.desktopUserId)}::uuid
+ AND control_admin_id = ${sqlLiteral(link.controlAdminId)}::uuid
+ AND state = 'active';
+ `)
)
+ const count = Number(value)
+ if (!Number.isSafeInteger(count) || count < 0) {
+ throw new Error(`[GFS-OPERATOR-E2E] invalid active operator-link count: ${value}`)
+ }
+ return count
+ }
+
+ /**
+ * Read-only proof for the immutable lineage after a visible lifecycle action.
+ * This is intentionally separate from countActiveLinks() so retained
+ * tombstones cannot be mistaken for present authority.
+ */
+ readLinkHistory(): GfsOperatorLinkGeneration[] {
+ const link = this.requireOperatorLink()
+ const output = runControlPostgresSql(`
+ SELECT jsonb_build_object(
+ 'id', id::text,
+ 'lineageId', lineage_id::text,
+ 'generation', generation,
+ 'predecessorId', predecessor_id::text,
+ 'state', state,
+ 'desktopUserId', user_id::text,
+ 'controlAdminId', control_admin_id::text,
+ 'source', source,
+ 'createdByControlAdminId', created_by::text,
+ 'rowVersion', row_version,
+ 'revokedAt', revoked_at::text,
+ 'revokedByType', revoked_by_type,
+ 'revokedById', revoked_by_id::text,
+ 'revokedByControlAdminId', revoked_by_control_admin_id::text,
+ 'revokedByDesktopUserId', revoked_by_desktop_user_id::text,
+ 'revocationReason', revocation_reason
+ )::text
+ FROM gfs_desktop_operator_links
+ WHERE user_id = ${sqlLiteral(link.desktopUserId)}::uuid
+ AND control_admin_id = ${sqlLiteral(link.controlAdminId)}::uuid
+ ORDER BY generation ASC, id ASC;
+ `)
+ return output
+ .split('\n')
+ .map(line => line.trim())
+ .filter(line => line.startsWith('{') && line.endsWith('}'))
+ .map(line => parseLinkGeneration(JSON.parse(line) as unknown))
+ }
+
+ assertGenerationChain(
+ expected: Omit<
+ GfsOperatorGenerationChainExpectation,
+ 'desktopUserId' | 'controlAdminId' | 'source'
+ >
+ ): GfsOperatorLinkGeneration[] {
+ const link = this.requireOperatorLink()
+ const history = this.readLinkHistory()
+ assertGenerationChainContract(history, {
+ desktopUserId: link.desktopUserId,
+ controlAdminId: link.controlAdminId,
+ source: link.source,
+ ...expected,
+ })
+ return history
}
operatorSubjectGrantCount(): number {
@@ -518,24 +710,35 @@ export class GfsDesktopOperatorJourney {
.map(line => JSON.parse(line) as GfsAuditRow)
}
- readUnlinkLifecycleEvent(): { operatorSub: string; targetRef: string; detailRef: string } | null {
- if (!this.operatorLink) return null
- const targetRef = `gfs_desktop_operator_link:${this.operatorLink.desktopUserId}:${this.operatorLink.controlAdminId}`
- const row = firstDataLine(
- runControlPostgresSql(`
- SELECT operator_sub, target_ref, payload_metadata->>'detail_ref'
- FROM administrative_events
- WHERE action = 'permission_revoke'
- AND target_type = 'permission'
- AND target_ref = ${sqlLiteral(targetRef)}
- AND payload_metadata->>'status' = 'unlinked'
- ORDER BY occurred_at DESC
- LIMIT 1;
- `)
- )
- if (!row) return null
- const [operatorSub, persistedTargetRef, detailRef] = splitSqlRow(row)
- return { operatorSub, targetRef: persistedTargetRef, detailRef }
+ /** Read-only governed evidence for the exact pair, ordered by occurrence. */
+ readLinkLifecycleEvents(): GfsOperatorLifecycleEvent[] {
+ const link = this.requireOperatorLink()
+ const targetRef = `gfs_desktop_operator_link:${link.desktopUserId}:${link.controlAdminId}`
+ const sourceAuditRef = `gfs_desktop_operator_link_source:${link.source}`
+ const output = runControlPostgresSql(`
+ SELECT jsonb_build_object(
+ 'eventId', event_id::text,
+ 'action', action,
+ 'outcome', outcome,
+ 'operatorSub', operator_sub,
+ 'targetRef', target_ref,
+ 'sourceAuditRef', source_audit_ref,
+ 'status', payload_metadata->>'status',
+ 'detailRef', payload_metadata->>'detail_ref',
+ 'requestId', request_id,
+ 'operationId', operation_id::text
+ )::text
+ FROM administrative_events
+ WHERE target_type = 'permission'
+ AND target_ref = ${sqlLiteral(targetRef)}
+ AND source_audit_ref = ${sqlLiteral(sourceAuditRef)}
+ ORDER BY occurred_at ASC, event_id ASC;
+ `)
+ return output
+ .split('\n')
+ .map(line => line.trim())
+ .filter(line => line.startsWith('{') && line.endsWith('}'))
+ .map(line => parseLifecycleEvent(JSON.parse(line) as unknown))
}
async loginControlUi(): Promise<Page> {
@@ -652,6 +855,11 @@ export class GfsDesktopOperatorJourney {
if (!this.controlPage) throw new Error('Control UI page has not been initialized')
return this.controlPage
}
+
+ private requireOperatorLink(): OperatorLinkRow {
+ if (!this.operatorLink) throw new Error('operator link is not initialized')
+ return this.operatorLink
+ }
}
type GfsDesktopOperatorTestFixtures = {
diff --git a/desktop-app/test/gfsDesktopOperatorParityFixtures.test.ts b/desktop-app/test/gfsDesktopOperatorParityFixtures.test.ts
new file mode 100644
index 000000000..25b8f8207
--- /dev/null
+++ b/desktop-app/test/gfsDesktopOperatorParityFixtures.test.ts
@@ -0,0 +1,171 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { GfsOperatorLinkGeneration } from './e2e-playwright/gfsDesktopOperatorParityContract'
+import { GfsDesktopOperatorJourney } from './e2e-playwright/helpers/gfsDesktopOperatorParityFixtures'
+
+const runControlPostgresSqlMock = vi.hoisted(() => vi.fn())
+const cleanupGfsFixtureMock = vi.hoisted(() => vi.fn())
+
+vi.mock('../../tests/e2e/gfsFixtureCore', () => ({
+ UUID_RE: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
+ firstDataLine: (output: string) =>
+ output
+ .split('\n')
+ .map(line => line.trim())
+ .find(line => line.length > 0 && !/^\(\d+ rows?\)$/.test(line)) ?? '',
+ kubectlOut: vi.fn(),
+ runControlPostgresSql: runControlPostgresSqlMock,
+ splitSqlRow: (row: string) => row.split('|').map(value => value.trim()),
+ sqlLiteral: (value: string) => `'${value.replace(/'/g, "''")}'`,
+}))
+
+vi.mock('../../tests/e2e/gfsResourceFixtures', () => ({
+ cleanupGfsFixture: cleanupGfsFixtureMock,
+}))
+
+const DESKTOP_USER_ID = '5a50453e-04d1-4403-8473-23013eaa56c7'
+const CONTROL_ADMIN_ID = 'ef72208d-783a-4574-9181-440a6764fa27'
+const LINEAGE_ID = 'd4d2c593-6932-488e-844c-c5852b910783'
+const FIRST_GENERATION_ID = '11111111-1111-4111-8111-111111111111'
+const SECOND_GENERATION_ID = '22222222-2222-4222-8222-222222222222'
+const environment = {
+ E2E_GFS_OPERATOR_RUN_ID: 'fixture-contract',
+ CONTROL_UI_BASE_URL: 'http://127.0.0.1:45101',
+ CONTROL_API_BASE_URL: 'http://127.0.0.1:45102',
+ EXTERNAL_REST_API_BASE_URL: 'http://127.0.0.1:45103',
+ RPC_PROXY_BASE_URL: 'http://127.0.0.1:45104',
+}
+const originalEnvironment = new Map<string, string | undefined>()
+
+function generation(overrides: Partial<GfsOperatorLinkGeneration> = {}): GfsOperatorLinkGeneration {
+ return {
+ id: FIRST_GENERATION_ID,
+ lineageId: LINEAGE_ID,
+ generation: 1,
+ predecessorId: null,
+ state: 'revoked',
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ source: 'initial_setup',
+ createdByControlAdminId: CONTROL_ADMIN_ID,
+ rowVersion: 2,
+ revokedAt: '2026-08-11T09:00:00.000Z',
+ revokedByType: 'control_admin',
+ revokedById: CONTROL_ADMIN_ID,
+ revokedByControlAdminId: CONTROL_ADMIN_ID,
+ revokedByDesktopUserId: null,
+ revocationReason: 'control_ui_revoke',
+ ...overrides,
+ }
+}
+
+function createJourney(): GfsDesktopOperatorJourney {
+ const journey = new GfsDesktopOperatorJourney(
+ {} as never,
+ { project: { outputDir: '/private/tmp/gfs-operator-fixture-contract' } } as never
+ )
+ journey.operatorLink = {
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ source: 'initial_setup',
+ }
+ return journey
+}
+
+describe('GFS Desktop operator generation evidence fixture', () => {
+ beforeEach(() => {
+ for (const [key, value] of Object.entries(environment)) {
+ originalEnvironment.set(key, process.env[key])
+ process.env[key] = value
+ }
+ runControlPostgresSqlMock.mockReset()
+ cleanupGfsFixtureMock.mockReset()
+ })
+
+ afterEach(() => {
+ for (const key of Object.keys(environment)) {
+ const original = originalEnvironment.get(key)
+ if (original === undefined) delete process.env[key]
+ else process.env[key] = original
+ }
+ originalEnvironment.clear()
+ })
+
+ it('counts active authority separately from retained revoked history', () => {
+ runControlPostgresSqlMock.mockReturnValue('0\n')
+
+ expect(createJourney().countActiveLinks()).toBe(0)
+
+ const sql = String(runControlPostgresSqlMock.mock.calls[0]?.[0])
+ expect(sql).toContain("AND state = 'active'")
+ expect(sql).toMatch(/^\s*SELECT/m)
+ expect(sql).not.toMatch(/\b(?:INSERT|UPDATE|DELETE)\b/i)
+ })
+
+ it('reads immutable history in generation order and validates the active successor', () => {
+ const first = generation()
+ const successor = generation({
+ id: SECOND_GENERATION_ID,
+ generation: 2,
+ predecessorId: FIRST_GENERATION_ID,
+ state: 'active',
+ rowVersion: 1,
+ revokedAt: null,
+ revokedByType: null,
+ revokedById: null,
+ revokedByControlAdminId: null,
+ revocationReason: null,
+ })
+ runControlPostgresSqlMock.mockReturnValue(
+ `\n${JSON.stringify(first)}\n${JSON.stringify(successor)}\n`
+ )
+
+ expect(
+ createJourney().assertGenerationChain({
+ activeCount: 1,
+ revokedCount: 1,
+ })
+ ).toEqual([first, successor])
+
+ const sql = String(runControlPostgresSqlMock.mock.calls[0]?.[0])
+ expect(sql).toContain('ORDER BY generation ASC, id ASC')
+ expect(sql).toContain("'predecessorId', predecessor_id::text")
+ expect(sql).toContain("'revokedByControlAdminId', revoked_by_control_admin_id::text")
+ expect(sql).toMatch(/^\s*SELECT/m)
+ expect(sql).not.toMatch(/\b(?:INSERT|UPDATE|DELETE)\b/i)
+ })
+
+ it('reads each governed lifecycle event for the exact pair and source without collapsing retries', () => {
+ const createdEvent = {
+ eventId: '33333333-3333-4333-8333-333333333333',
+ action: 'permission_grant',
+ outcome: 'committed',
+ operatorSub: CONTROL_ADMIN_ID,
+ targetRef: `gfs_desktop_operator_link:${DESKTOP_USER_ID}:${CONTROL_ADMIN_ID}`,
+ sourceAuditRef: 'gfs_desktop_operator_link_source:initial_setup',
+ status: 'linked',
+ detailRef: `event:link.created;desktop_user_id:${DESKTOP_USER_ID};control_admin_id:${CONTROL_ADMIN_ID};source:initial_setup;lineage_id:${LINEAGE_ID};generation:1`,
+ requestId: 'request-1',
+ operationId: null,
+ }
+ const revokedEvent = {
+ ...createdEvent,
+ eventId: '44444444-4444-4444-8444-444444444444',
+ action: 'permission_revoke',
+ status: 'unlinked',
+ detailRef: `event:link.revoked;desktop_user_id:${DESKTOP_USER_ID};control_admin_id:${CONTROL_ADMIN_ID};source:initial_setup;lineage_id:${LINEAGE_ID};generation:1;reason:control_ui_revoke`,
+ requestId: 'request-2',
+ }
+ runControlPostgresSqlMock.mockReturnValue(
+ `\n${JSON.stringify(createdEvent)}\n${JSON.stringify(revokedEvent)}\n`
+ )
+
+ expect(createJourney().readLinkLifecycleEvents()).toEqual([createdEvent, revokedEvent])
+
+ const sql = String(runControlPostgresSqlMock.mock.calls[0]?.[0])
+ expect(sql).toContain(`target_ref = '${createdEvent.targetRef}'`)
+ expect(sql).toContain(`source_audit_ref = '${createdEvent.sourceAuditRef}'`)
+ expect(sql).toContain('ORDER BY occurred_at ASC, event_id ASC')
+ expect(sql).toMatch(/^\s*SELECT/m)
+ expect(sql).not.toMatch(/\b(?:INSERT|UPDATE|DELETE)\b/i)
+ })
+})
diff --git a/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts b/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts
index dffbadda5..f808c4c38 100644
--- a/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts
+++ b/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts
@@ -4,7 +4,9 @@ import os from 'node:os'
import path from 'node:path'
import {
GFS_OPERATOR_REQUIRED_SCENARIOS,
+ type GfsOperatorLinkGeneration,
type GfsOperatorScenarioResult,
+ assertGenerationChain,
evaluateGfsOperatorScenarioResults,
gfsOperatorEvidenceDirectory,
requireGfsOperatorRunId,
@@ -13,9 +15,53 @@ import {
} from './e2e-playwright/gfsDesktopOperatorParityContract'
const evidenceRoots: string[] = []
+const DESKTOP_USER_ID = '5a50453e-04d1-4403-8473-23013eaa56c7'
+const CONTROL_ADMIN_ID = 'ef72208d-783a-4574-9181-440a6764fa27'
+const LINEAGE_ID = 'd4d2c593-6932-488e-844c-c5852b910783'
+const FIRST_GENERATION_ID = '11111111-1111-4111-8111-111111111111'
+const SECOND_GENERATION_ID = '22222222-2222-4222-8222-222222222222'
+
+function activeGeneration(
+ overrides: Partial<GfsOperatorLinkGeneration> = {}
+): GfsOperatorLinkGeneration {
+ return {
+ id: FIRST_GENERATION_ID,
+ lineageId: LINEAGE_ID,
+ generation: 1,
+ predecessorId: null,
+ state: 'active',
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ source: 'initial_setup',
+ createdByControlAdminId: CONTROL_ADMIN_ID,
+ rowVersion: 1,
+ revokedAt: null,
+ revokedByType: null,
+ revokedById: null,
+ revokedByControlAdminId: null,
+ revokedByDesktopUserId: null,
+ revocationReason: null,
+ ...overrides,
+ }
+}
+
+function controlAdminTombstone(
+ overrides: Partial<GfsOperatorLinkGeneration> = {}
+): GfsOperatorLinkGeneration {
+ return activeGeneration({
+ state: 'revoked',
+ rowVersion: 2,
+ revokedAt: '2026-08-11T09:00:00.000Z',
+ revokedByType: 'control_admin',
+ revokedById: CONTROL_ADMIN_ID,
+ revokedByControlAdminId: CONTROL_ADMIN_ID,
+ revocationReason: 'control_ui_revoke',
+ ...overrides,
+ })
+}
afterEach(() => {
- for (const root of evidenceRoots.splice(0)) fs.rmSync(root, { recursive: true, force: true })
+ for (const root of evidenceRoots.splice(0)) fs.rmSync(root, { recursive: true })
delete process.env.E2E_GFS_OPERATOR_EVIDENCE_DIR
})
@@ -108,4 +154,93 @@ describe('GFS Desktop operator Playwright gate', () => {
expect(verdict.ok).toBe(false)
expect(verdict.errors).toContain('runtime evidence is missing')
})
+
+ it('keeps active authority separate from retained revoked generations across a full lifecycle', () => {
+ const firstTombstone = controlAdminTombstone()
+ assertGenerationChain([firstTombstone], {
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ source: 'initial_setup',
+ activeCount: 0,
+ revokedCount: 1,
+ })
+
+ const successor = activeGeneration({
+ id: SECOND_GENERATION_ID,
+ generation: 2,
+ predecessorId: FIRST_GENERATION_ID,
+ })
+ assertGenerationChain([firstTombstone, successor], {
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ source: 'initial_setup',
+ activeCount: 1,
+ revokedCount: 1,
+ })
+
+ const secondTombstone = controlAdminTombstone({
+ id: SECOND_GENERATION_ID,
+ generation: 2,
+ predecessorId: FIRST_GENERATION_ID,
+ rowVersion: 2,
+ })
+ assertGenerationChain([firstTombstone, secondTombstone], {
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ source: 'initial_setup',
+ activeCount: 0,
+ revokedCount: 2,
+ })
+ })
+
+ it('rejects malformed predecessor, source, active-state, and revocation-actor evidence', () => {
+ const expected = {
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ source: 'initial_setup',
+ activeCount: 0,
+ revokedCount: 2,
+ }
+ const firstTombstone = controlAdminTombstone()
+ const secondTombstone = controlAdminTombstone({
+ id: SECOND_GENERATION_ID,
+ generation: 2,
+ predecessorId: FIRST_GENERATION_ID,
+ })
+
+ expect(() =>
+ assertGenerationChain([firstTombstone, { ...secondTombstone, predecessorId: null }], expected)
+ ).toThrow('must point to generation 1')
+ expect(() =>
+ assertGenerationChain(
+ [firstTombstone, { ...secondTombstone, source: 'migrated_source' }],
+ expected
+ )
+ ).toThrow('changed source')
+ expect(() =>
+ assertGenerationChain(
+ [
+ firstTombstone,
+ {
+ ...secondTombstone,
+ state: 'active',
+ revokedAt: '2026-08-11T09:05:00.000Z',
+ },
+ ],
+ { ...expected, activeCount: 1, revokedCount: 1 }
+ )
+ ).toThrow('active generation 2 contains revocation evidence')
+ expect(() =>
+ assertGenerationChain(
+ [
+ firstTombstone,
+ {
+ ...secondTombstone,
+ revokedById: DESKTOP_USER_ID,
+ },
+ ],
+ expected
+ )
+ ).toThrow('control-admin revocation actor is malformed')
+ })
})
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 1951f661c..fe07b4a3e 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -305,7 +305,6 @@ 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
-<<<<<<< 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
diff --git a/external-rest-api/src/controlApiClient.ts b/external-rest-api/src/controlApiClient.ts
index eb7a087a0..38efea234 100644
--- a/external-rest-api/src/controlApiClient.ts
+++ b/external-rest-api/src/controlApiClient.ts
@@ -2,15 +2,42 @@ import { config } from './config.js'
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
+// Response headers are an API contract only where a caller can safely act on
+// them. In particular, never relay Set-Cookie, server identity, CORS, or
+// arbitrary proxy headers from the internal control-api boundary.
+const FORWARDABLE_RESPONSE_HEADERS = [
+ 'retry-after',
+ 'x-ratelimit-limit',
+ 'x-ratelimit-remaining',
+ 'x-ratelimit-reset',
+ 'x-request-id',
+] as const
+
export class ControlApiError extends Error {
status: number
body: unknown
- constructor(message: string, status: number, body: unknown) {
+ headers: Record<string, string>
+ constructor(
+ message: string,
+ status: number,
+ body: unknown,
+ headers: Record<string, string> = {}
+ ) {
super(message)
this.name = 'ControlApiError'
this.status = status
this.body = body
+ this.headers = headers
+ }
+}
+
+function forwardableResponseHeaders(response: Response): Record<string, string> {
+ const headers: Record<string, string> = {}
+ for (const name of FORWARDABLE_RESPONSE_HEADERS) {
+ const value = response.headers.get(name)
+ if (value) headers[name] = value
}
+ return headers
}
function buildUrl(path: string, query?: Record<string, string | undefined>): string {
@@ -90,7 +117,8 @@ export async function controlApiRequestWithStatus<T>(
throw new ControlApiError(
`Control API ${method} ${path} returned non-JSON body (status=${response.status})`,
502,
- { error: 'Upstream returned non-JSON body', status: response.status }
+ { error: 'Upstream returned non-JSON body', status: response.status },
+ forwardableResponseHeaders(response)
)
}
@@ -102,7 +130,8 @@ export async function controlApiRequestWithStatus<T>(
throw new ControlApiError(
`Control API ${method} ${path} failed (${response.status}): ${errorMessage}`,
response.status,
- parsed
+ parsed,
+ forwardableResponseHeaders(response)
)
}
@@ -155,7 +184,8 @@ export async function controlApiBinaryRequestWithStatus(
throw new ControlApiError(
`Control API ${method} ${path} failed (${response.status})`,
response.status,
- parsed
+ parsed,
+ forwardableResponseHeaders(response)
)
}
@@ -211,7 +241,8 @@ export async function controlApiStreamRequest(
throw new ControlApiError(
`Control API ${method} ${path} failed (${response.status})`,
response.status,
- parsed
+ parsed,
+ forwardableResponseHeaders(response)
)
}
return response
diff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.ts
index 29a97c12c..c1f1fac27 100644
--- a/external-rest-api/src/routes/gfs.ts
+++ b/external-rest-api/src/routes/gfs.ts
@@ -2,6 +2,7 @@ import { Router } from 'express'
import type { NextFunction, Response } from 'express'
import type { Request } from 'express'
import { randomUUID } from 'node:crypto'
+import { isIP } from 'node:net'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { ControlApiError, controlApiRequest, controlApiStreamRequest } from '../controlApiClient.js'
@@ -23,6 +24,13 @@ import { type AuthedRequest, extractAuthToken, requireAuth } from '../middleware
// client (a wedged gfsc looks identical to an internal bug).
const PROPAGATED = new Set([400, 401, 403, 404, 409, 410, 412, 422, 429, 500, 502, 503, 504])
const STREAM_HEADERS = ['content-type', 'content-length', 'content-disposition']
+const CONTROL_API_ERROR_HEADERS = [
+ 'retry-after',
+ 'x-ratelimit-limit',
+ 'x-ratelimit-remaining',
+ 'x-ratelimit-reset',
+ 'x-request-id',
+] as const
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
type GfsAuthedRequest = AuthedRequest & { gfsRequestId?: string }
@@ -42,9 +50,21 @@ function attachGfsRequestId(req: Request, res: Response, next: NextFunction): vo
}
function withGfsRequestId(req: GfsAuthedRequest, options: GfsRequestOptions): GfsRequestOptions {
+ // The control-api is behind profile-control-funnel, which appends its own
+ // peer to X-Forwarded-For. Preserve the external-rest API's proxy-attested
+ // client address as the first value so the control-api's pre-resolution
+ // limiter can enforce its approved per-source-IP bucket. This overwrites
+ // any caller-supplied value; only req.ip (after this service's trust-proxy
+ // policy) is propagated across the authenticated service boundary.
+ const clientIp = req.ip?.trim()
+ const forwardedClientIp = clientIp && isIP(clientIp) !== 0 ? clientIp : undefined
return {
...options,
- extraHeaders: { ...options.extraHeaders, 'x-request-id': req.gfsRequestId! },
+ extraHeaders: {
+ ...options.extraHeaders,
+ 'x-request-id': req.gfsRequestId!,
+ ...(forwardedClientIp ? { 'x-forwarded-for': forwardedClientIp } : {}),
+ },
}
}
@@ -59,6 +79,13 @@ function gfsControlApiRequest<T>(
function forwardControlApiError(error: unknown, res: Response, next: NextFunction): void {
if (error instanceof ControlApiError && PROPAGATED.has(error.status)) {
+ // The internal client has already filtered this map. Keep the allowlist at
+ // this last hop too so a hand-constructed/mocked ControlApiError cannot
+ // accidentally turn arbitrary internal response headers into public ones.
+ for (const name of CONTROL_API_ERROR_HEADERS) {
+ const value = error.headers?.[name]
+ if (value) res.setHeader(name, value)
+ }
const body =
error.body && typeof error.body === 'object' ? error.body : { error: String(error.message) }
res.status(error.status).json(body)
diff --git a/external-rest-api/test/controlApiClient.test.ts b/external-rest-api/test/controlApiClient.test.ts
new file mode 100644
index 000000000..07d8625b2
--- /dev/null
+++ b/external-rest-api/test/controlApiClient.test.ts
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ ControlApiError,
+ controlApiBinaryRequestWithStatus,
+ controlApiRequestWithStatus,
+ controlApiStreamRequest,
+} from '../src/controlApiClient.js'
+
+const ALLOWED_HEADERS = {
+ 'retry-after': '17',
+ 'x-ratelimit-limit': '30',
+ 'x-ratelimit-remaining': '0',
+ 'x-ratelimit-reset': '1776000000',
+ 'x-request-id': '11111111-2222-4333-8444-555555555555',
+}
+
+function rateLimitedResponse() {
+ return new Response(JSON.stringify({ error: 'Too Many Requests' }), {
+ status: 429,
+ headers: {
+ ...ALLOWED_HEADERS,
+ 'set-cookie': 'internal-session=must-not-leak',
+ server: 'control-api-internal',
+ 'x-internal-debug': 'must-not-leak',
+ },
+ })
+}
+
+async function captureError(work: () => Promise<unknown>): Promise<ControlApiError> {
+ try {
+ await work()
+ } catch (error) {
+ expect(error).toBeInstanceOf(ControlApiError)
+ return error as ControlApiError
+ }
+ throw new Error('expected control-api request to reject')
+}
+
+describe('controlApiClient error headers', () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it.each([
+ ['JSON request', () => controlApiRequestWithStatus('GET', '/external/gfs/resources')],
+ [
+ 'binary request',
+ () => controlApiBinaryRequestWithStatus('GET', '/external/gfs/proxy/resource-id'),
+ ],
+ ['stream request', () => controlApiStreamRequest('GET', '/external/gfs/proxy/resource-id')],
+ ] as const)('%s preserves only the public error-header allowlist', async (_name, work) => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(rateLimitedResponse()))
+
+ const error = await captureError(work)
+
+ expect(error.status).toBe(429)
+ expect(error.headers).toEqual(ALLOWED_HEADERS)
+ expect(error.headers).not.toHaveProperty('set-cookie')
+ expect(error.headers).not.toHaveProperty('server')
+ expect(error.headers).not.toHaveProperty('x-internal-debug')
+ })
+})
diff --git a/external-rest-api/test/routes.gfs.test.ts b/external-rest-api/test/routes.gfs.test.ts
index 3c739b454..07213816b 100644
--- a/external-rest-api/test/routes.gfs.test.ts
+++ b/external-rest-api/test/routes.gfs.test.ts
@@ -8,7 +8,8 @@ const { ControlApiError, clientMock } = vi.hoisted(() => {
constructor(
message: string,
public status: number,
- public body: unknown
+ public body: unknown,
+ public headers: Record<string, string> = {}
) {
super(message)
}
@@ -62,7 +63,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('POST', '/external/gfs/token', {
userSessionToken: 'sess-xyz',
body: { scopes: ['gfs.read'] },
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
expect(res.headers['x-request-id']).toBe(REQUEST_ID)
})
@@ -84,7 +85,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('PUT', '/external/gfs/grants', {
userSessionToken: 'sess-xyz',
body,
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
})
@@ -102,10 +103,60 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/resources', {
userSessionToken: 'sess-xyz',
query: { drive: 'main', limit: '25', cursor: 'cursor-1' },
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
})
+ it('forwards the proxy-attested client IP for the control-api GFS rate boundary', async () => {
+ clientMock.controlApiRequest.mockResolvedValue({
+ ok: true,
+ data: { items: [], nextCursor: null },
+ })
+ const app = buildApp()
+ app.set('trust proxy', 1)
+
+ await request(app)
+ .get('/me/gfs/resources')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-request-id', REQUEST_ID)
+ .set('x-forwarded-for', '198.51.100.42')
+ .expect(200)
+
+ expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/resources', {
+ userSessionToken: 'sess-xyz',
+ query: { drive: undefined, limit: undefined, cursor: undefined },
+ extraHeaders: {
+ 'x-request-id': REQUEST_ID,
+ 'x-forwarded-for': '198.51.100.42',
+ },
+ })
+ })
+
+ it('does not forward a caller-supplied XFF value when the hop is untrusted', async () => {
+ clientMock.controlApiRequest.mockResolvedValue({
+ ok: true,
+ data: { items: [], nextCursor: null },
+ })
+ const app = buildApp()
+ // The production app trusts exactly its configured proxy hop. This test
+ // exercises the fail-closed behavior when that trust is absent: the
+ // incoming XFF must not become the attestation sent to control-api.
+ app.set('trust proxy', false)
+
+ await request(app)
+ .get('/me/gfs/resources')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-request-id', REQUEST_ID)
+ .set('x-forwarded-for', '203.0.113.99')
+ .expect(200)
+
+ const call = clientMock.controlApiRequest.mock.calls.at(-1)
+ const forwarded = (call?.[2] as { extraHeaders?: Record<string, string> } | undefined)
+ ?.extraHeaders?.['x-forwarded-for']
+ expect(forwarded).toBeDefined()
+ expect(forwarded).not.toBe('203.0.113.99')
+ })
+
it('propagates a control-api no-escalation 403 verbatim', async () => {
clientMock.controlApiRequest.mockRejectedValue(
new ControlApiError('escalation', 403, { error: 'escalation_rejected' })
@@ -164,7 +215,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
{
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
})
@@ -204,7 +255,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
body: { newName: 'renamed.md', ifMatch: 1 },
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(
@@ -215,7 +266,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
body: { name: 'docs', kind: 'directory' },
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(
@@ -226,7 +277,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
body: { content: 'hello', ifMatch: 2 },
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(
@@ -237,7 +288,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
body: { ifMatch: 3 },
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
})
@@ -274,7 +325,7 @@ describe('GET /me/gfs/grants (delegation list passthrough)', () => {
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/grants', {
userSessionToken: 'sess-xyz',
query: { drive: 'main', resourceId: '11111111-1111-1111-1111-111111111111' },
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
})
@@ -289,18 +340,40 @@ describe('GET /me/gfs/grants (delegation list passthrough)', () => {
expect(res.body).toEqual({ error: 'manage_acl_required' })
})
- it('propagates the delegation-plane 429 with retryAfterSeconds intact', async () => {
+ it('forwards only the allowlisted rate-limit and request headers on a control-api 429', async () => {
clientMock.controlApiRequest.mockRejectedValue(
- new ControlApiError('rate limited', 429, {
- error: 'Too Many Requests',
- retryAfterSeconds: 17,
- })
+ new ControlApiError(
+ 'rate limited',
+ 429,
+ {
+ error: 'Too Many Requests',
+ retryAfterSeconds: 17,
+ },
+ {
+ 'retry-after': '17',
+ 'x-ratelimit-limit': '30',
+ 'x-ratelimit-remaining': '0',
+ 'x-ratelimit-reset': '1776000000',
+ 'x-request-id': REQUEST_ID,
+ 'set-cookie': 'internal-session=never-forward',
+ server: 'control-api-internal',
+ 'x-internal-debug': 'never-forward',
+ }
+ )
)
const res = await request(buildApp())
.get('/me/gfs/grants?drive=main&resourceId=11111111-1111-1111-1111-111111111111')
.set('authorization', 'Bearer sess-xyz')
expect(res.status).toBe(429)
expect(res.body).toEqual({ error: 'Too Many Requests', retryAfterSeconds: 17 })
+ expect(res.headers['retry-after']).toBe('17')
+ expect(res.headers['x-ratelimit-limit']).toBe('30')
+ expect(res.headers['x-ratelimit-remaining']).toBe('0')
+ expect(res.headers['x-ratelimit-reset']).toBe('1776000000')
+ expect(res.headers['x-request-id']).toBe(REQUEST_ID)
+ expect(res.headers['set-cookie']).toBeUndefined()
+ expect(res.headers.server).toBeUndefined()
+ expect(res.headers['x-internal-debug']).toBeUndefined()
})
})
@@ -329,7 +402,7 @@ describe('GET /me/gfs/shares (delegation list passthrough)', () => {
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/shares', {
userSessionToken: 'sess-xyz',
query: { drive: 'main', resourceId: '11111111-1111-1111-1111-111111111111' },
- extraHeaders: { 'x-request-id': REQUEST_ID },
+ extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
clientMock.controlApiRequest.mockClear()
diff --git a/gfs-controller/src/authz/storeProbe.test.ts b/gfs-controller/src/authz/storeProbe.test.ts
index c00f76b54..079e174d9 100644
--- a/gfs-controller/src/authz/storeProbe.test.ts
+++ b/gfs-controller/src/authz/storeProbe.test.ts
@@ -1,9 +1,5 @@
import { describe, expect, it } from "vitest";
-import {
- createPermissionStoreProbe,
- type PingPool,
- type ProbeClient,
-} from "./storeProbe.js";
+import { type PingPool, type ProbeClient, createPermissionStoreProbe } from "./storeProbe.js";
/**
* Issue #775: the readiness store check must detect a rotated database
@@ -67,8 +63,10 @@ interface FakeClientBehavior {
canDeleteManifests?: boolean;
canInsertResources?: boolean;
canUpdateResources?: boolean;
- auditSchemaReady?: boolean;
- auditConstraintsReady?: boolean;
+ auditDecisionEvidenceSchemaReady?: boolean;
+ auditDecisionEvidenceConstraintsReady?: boolean;
+ auditActorCorrelationColumnsReady?: boolean;
+ auditActorCorrelationConstraintReady?: boolean;
canMutateResources?: boolean;
canMutateGrants?: boolean;
canMutateShares?: boolean;
@@ -116,8 +114,14 @@ function fakeClientFactory(behavior: FakeClientBehavior): {
can_delete_manifests: behavior.canDeleteManifests !== false,
can_insert_resources: behavior.canInsertResources !== false,
can_update_resources: behavior.canUpdateResources !== false,
- audit_schema_ready: behavior.auditSchemaReady !== false,
- audit_constraints_ready: behavior.auditConstraintsReady !== false,
+ audit_decision_evidence_schema_ready:
+ behavior.auditDecisionEvidenceSchemaReady !== false,
+ audit_decision_evidence_constraints_ready:
+ behavior.auditDecisionEvidenceConstraintsReady !== false,
+ audit_actor_correlation_columns_ready:
+ behavior.auditActorCorrelationColumnsReady !== false,
+ audit_actor_correlation_constraint_ready:
+ behavior.auditActorCorrelationConstraintReady !== false,
can_mutate_resources: behavior.canMutateResources === true,
can_mutate_grants: behavior.canMutateGrants === true,
can_mutate_shares: behavior.canMutateShares === true,
@@ -222,19 +226,21 @@ describe("createPermissionStoreProbe", () => {
["manifest mutation", { canMutateManifests: true }],
["non-append audit mutation", { canMutateAudit: true }],
["audit sequence update", { canUpdateAuditSequence: true }],
- ] satisfies Array<[string, FakeClientBehavior]>)
- ("rejects a reader granted forbidden %s privileges", async (_privilege, behavior) => {
- const { factory } = fakeClientFactory(behavior);
- const probe = createPermissionStoreProbe({
- pool: fakePool(),
- connectionString: DSN,
- intervalMs: INTERVAL,
- storageRole: "reader",
- clientFactory: factory,
- now: () => 0,
- });
- await expect(probe()).rejects.toThrow(/reader has forbidden GFS mutation privileges.*0069/s);
- });
+ ] satisfies Array<[string, FakeClientBehavior]>)(
+ "rejects a reader granted forbidden %s privileges",
+ async (_privilege, behavior) => {
+ const { factory } = fakeClientFactory(behavior);
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "reader",
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).rejects.toThrow(/reader has forbidden GFS mutation privileges.*0069/s);
+ }
+ );
it("does not apply reader-only negative privilege checks to the writer", async () => {
const { factory } = fakeClientFactory({
@@ -252,15 +258,15 @@ describe("createPermissionStoreProbe", () => {
await expect(probe()).resolves.toBeUndefined();
});
- it.each(["reader", "writer"] as const)(
- "rejects a %s when migration 0092 audit actor-correlation columns are missing",
- async (storageRole) => {
- const { factory } = fakeClientFactory({ auditSchemaReady: false });
+ it.each(["actor_on_behalf_of", "desktop_user_id", "authority_source"] as const)(
+ "rejects readiness before 0092 when the required %s audit column is absent or drifted",
+ async _column => {
+ const { factory } = fakeClientFactory({ auditActorCorrelationColumnsReady: false });
const probe = createPermissionStoreProbe({
pool: fakePool(),
connectionString: DSN,
intervalMs: INTERVAL,
- storageRole,
+ storageRole: "reader",
clientFactory: factory,
now: () => 0,
});
@@ -270,8 +276,8 @@ describe("createPermissionStoreProbe", () => {
it.each(["reader", "writer"] as const)(
"rejects a %s when migration 0092 audit actor-correlation constraints are missing or unvalidated",
- async (storageRole) => {
- const { factory } = fakeClientFactory({ auditConstraintsReady: false });
+ async storageRole => {
+ const { factory } = fakeClientFactory({ auditActorCorrelationConstraintReady: false });
const probe = createPermissionStoreProbe({
pool: fakePool(),
connectionString: DSN,
@@ -290,19 +296,21 @@ describe("createPermissionStoreProbe", () => {
["manifest DELETE", { canDeleteManifests: false }],
["resource INSERT", { canInsertResources: false }],
["resource UPDATE", { canUpdateResources: false }],
- ] satisfies Array<[string, FakeClientBehavior]>)
- ("rejects a writer missing only %s", async (_privilege, behavior) => {
- const { factory } = fakeClientFactory(behavior);
- const probe = createPermissionStoreProbe({
- pool: fakePool(),
- connectionString: DSN,
- intervalMs: INTERVAL,
- storageRole: "writer",
- clientFactory: factory,
- now: () => 0,
- });
- await expect(probe()).rejects.toThrow(/writer lacks.*0068/s);
- });
+ ] satisfies Array<[string, FakeClientBehavior]>)(
+ "rejects a writer missing only %s",
+ async (_privilege, behavior) => {
+ const { factory } = fakeClientFactory(behavior);
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "writer",
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).rejects.toThrow(/writer lacks.*0068/s);
+ }
+ );
it("pins the coherence canary SQL to both least-privilege grants", async () => {
// Regression guard: gutting COHERENCE_SQL (e.g. SELECT true AS can_read...)
@@ -344,6 +352,13 @@ describe("createPermissionStoreProbe", () => {
expect(sql).toContain("gfs_audit_record_type_fields_valid");
expect(sql).toContain("gfs_audit_actor_correlation_valid");
expect(sql).toContain("convalidated");
+ expect(sql).toContain("pg_get_constraintdef");
+ expect(sql).toContain("actor_on_behalf_ofISNULL");
+ expect(sql).toContain("actor_on_behalf_ofISNOTNULL");
+ expect(sql).toContain("authority_source=''user-session''");
+ expect(sql).toContain("authority_source=''linked-admin''");
+ expect(sql).toContain("desktop_user_idISNULL");
+ expect(sql).toContain("NOT attnotnull");
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.ts
index 2fc30067c..6a1771b7b 100644
--- a/gfs-controller/src/authz/storeProbe.ts
+++ b/gfs-controller/src/authz/storeProbe.ts
@@ -89,15 +89,28 @@ 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(*) = 8 " +
- "AND bool_and(attname <> 'desktop_user_id' OR atttypid = 'uuid'::regtype) " +
- "AND bool_and(attname = 'desktop_user_id' OR atttypid = 'text'::regtype) " +
+ "(SELECT count(*) = 5 " +
+ "AND bool_and(attname = 'record_type' 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['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";
+ "AND attname = ANY (ARRAY['record_type', 'matched_subject', 'authorization_source', 'cached_authorization_source', 'mutation_outcome'])) AS audit_decision_evidence_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 contype = 'c' AND convalidated) AS audit_decision_evidence_constraints_ready, " +
+ "(SELECT count(*) = 3 " +
+ "AND bool_and((attname = 'actor_on_behalf_of' AND atttypid = 'text'::regtype AND NOT attnotnull) " +
+ "OR (attname = 'desktop_user_id' AND atttypid = 'uuid'::regtype AND NOT attnotnull) " +
+ "OR (attname = 'authority_source' AND atttypid = 'text'::regtype AND NOT attnotnull)) " +
+ "FROM pg_attribute WHERE attrelid = 'gfs_audit'::regclass AND attnum > 0 AND NOT attisdropped " +
+ "AND attname = ANY (ARRAY['actor_on_behalf_of', 'desktop_user_id', 'authority_source'])) AS audit_actor_correlation_columns_ready, " +
+ "EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = 'gfs_audit'::regclass " +
+ "AND conname = 'gfs_audit_actor_correlation_valid' AND contype = 'c' AND convalidated " +
+ "AND regexp_replace(pg_get_constraintdef(oid), '\\s+', '', 'g') LIKE '%desktop_user_idISNULL%' " +
+ "AND regexp_replace(pg_get_constraintdef(oid), '\\s+', '', 'g') LIKE '%authority_sourceISNULL%' " +
+ "AND regexp_replace(pg_get_constraintdef(oid), '\\s+', '', 'g') LIKE '%authority_source=''user-session''%' " +
+ "AND regexp_replace(pg_get_constraintdef(oid), '\\s+', '', 'g') LIKE '%authority_source=''linked-admin''%' " +
+ "AND regexp_replace(pg_get_constraintdef(oid), '\\s+', '', 'g') LIKE '%actor_on_behalf_ofISNULL%' " +
+ "AND regexp_replace(pg_get_constraintdef(oid), '\\s+', '', 'g') LIKE '%actor_on_behalf_ofISNOTNULL%') AS audit_actor_correlation_constraint_ready";
// The reader is deliberately read-only except for append-only audit records.
// Positive checks alone are insufficient: a stale/manual grant would keep the
@@ -223,7 +236,19 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi
"are missing (control-api migration 0068 not applied?)"
);
}
- if (row?.audit_schema_ready !== true || row?.audit_constraints_ready !== true) {
+ if (
+ row?.audit_decision_evidence_schema_ready !== true ||
+ row?.audit_decision_evidence_constraints_ready !== true
+ ) {
+ throw new Error(
+ "permission store coherence check failed: GFS audit decision-evidence schema is missing " +
+ "(control-api migration 0073 not applied?)"
+ );
+ }
+ if (
+ row?.audit_actor_correlation_columns_ready !== true ||
+ row?.audit_actor_correlation_constraint_ready !== true
+ ) {
throw new Error(
"permission store coherence check failed: GFS audit actor-correlation schema is missing " +
"(control-api migration 0092 not applied?)"
@@ -262,7 +287,7 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi
} finally {
// Best-effort close of the ephemeral client; a close error must not mask
// the probe verdict, but it is logged loudly (never swallowed silently).
- await client.end().catch((err) => {
+ await client.end().catch(err => {
console.error(`[gfsc] store-probe client close error: ${errMsg(err)}`);
});
}