Skip to content

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

TypeScript

fix(gfs): close lifecycle and external boundary regressions

Alfredo Lopezfcbe8288f366
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index bfa0d0a98..4909e8d74 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.452",
+ "version": "0.1.453",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.452",
+ "version": "0.1.453",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 1459f79eb..8b1d19751 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.452",
+ "version": "0.1.453",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index 7fe310e2c..c2cddcdc0 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -132,6 +132,7 @@ type Config = {
approvalRlRefreshPerMin: number
approvalRlExternalPerMin: number
approvalRlExternalEdgePerMin: number
+ approvalRlExternalClientIpPerMin: number
oauthBrokerRlPerMin: number
adminPublicTokenRlPerMin: number
// External Desktop GFS is a separate authority plane. The process-local
@@ -358,6 +359,23 @@ function parseRegistryConnectionMode(): 'managed' | 'self-hosted' {
throw new Error(`REGISTRY_CONNECTION_MODE must be 'managed' or 'self-hosted' (got '${raw}')`)
}
+// External routes intentionally have three independent dimensions: the
+// operation/user budget is the narrowest, the session edge budget is wider,
+// and the source-IP backstop is widest so a shared NAT cannot become a
+// platform-wide choke point. Reject an incoherent deployment at boot instead
+// of silently running with a different security/capacity contract.
+const externalRateLimitConfig = (() => {
+ const operation = positiveIntegerFromEnv('APPROVAL_RL_EXTERNAL_PER_MIN', 60)
+ const session = positiveIntegerFromEnv('APPROVAL_RL_EXTERNAL_EDGE_PER_MIN', 120)
+ const clientIp = positiveIntegerFromEnv('APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN', 1200)
+ if (!(operation <= session && session < clientIp)) {
+ throw new Error(
+ 'APPROVAL_RL_EXTERNAL_PER_MIN must be <= APPROVAL_RL_EXTERNAL_EDGE_PER_MIN < APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN'
+ )
+ }
+ return { operation, session, clientIp }
+})()
+
function failClosedBooleanFromEnv(name: string): boolean {
const raw = process.env[name]
if (raw === undefined || raw === '' || raw === 'false') return false
@@ -743,8 +761,13 @@ export const config: Config = {
),
approvalRlRequestPerMin: Number(process.env.APPROVAL_RL_REQUEST_PER_MIN || 120),
approvalRlRefreshPerMin: Number(process.env.APPROVAL_RL_REFRESH_PER_MIN || 20),
- approvalRlExternalPerMin: Number(process.env.APPROVAL_RL_EXTERNAL_PER_MIN || 60),
- approvalRlExternalEdgePerMin: Number(process.env.APPROVAL_RL_EXTERNAL_EDGE_PER_MIN || 120),
+ approvalRlExternalPerMin: externalRateLimitConfig.operation,
+ approvalRlExternalEdgePerMin: externalRateLimitConfig.session,
+ // The source-IP backstop is intentionally wider than the per-session edge
+ // bucket. A shared NAT must not turn a 120/min fairness budget into a
+ // platform-wide ceiling; token/session fairness remains independently
+ // bounded by approvalRlExternalEdgePerMin.
+ approvalRlExternalClientIpPerMin: externalRateLimitConfig.clientIp,
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
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index b5a7890da..4d5199213 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -2965,7 +2965,21 @@ async function applyControlAdminSessionVersionDefaultSchema(db: DbClient): Promi
SET session_version = 1
WHERE session_version IS NULL OR session_version < 1;
ALTER TABLE control_admin_users
- ALTER COLUMN session_version SET DEFAULT 1;
+ ALTER COLUMN session_version SET DEFAULT 1,
+ ALTER COLUMN session_version SET NOT NULL;
+ DO $$
+ BEGIN
+ IF NOT EXISTS (
+ SELECT 1
+ FROM pg_constraint
+ WHERE conrelid = 'control_admin_users'::regclass
+ AND conname = 'control_admin_session_version_positive'
+ ) THEN
+ ALTER TABLE control_admin_users
+ ADD CONSTRAINT control_admin_session_version_positive
+ CHECK (session_version >= 1);
+ END IF;
+ END $$;
`)
}
diff --git a/control-api/src/middleware/externalClientIdentity.ts b/control-api/src/middleware/externalClientIdentity.ts
index 48ca78ec5..618494058 100644
--- a/control-api/src/middleware/externalClientIdentity.ts
+++ b/control-api/src/middleware/externalClientIdentity.ts
@@ -1,5 +1,5 @@
-import type { Request } from 'express'
-import { ipKeyGenerator } from 'express-rate-limit'
+import type { Request, RequestHandler } from 'express'
+import { ipKeyGenerator, rateLimit } from 'express-rate-limit'
import { createHash } from 'node:crypto'
import { isIP } from 'node:net'
@@ -18,11 +18,57 @@ export function externalClientIp(req: Request): string {
return fallback && isIP(fallback) !== 0 ? fallback : '__unknown_peer__'
}
-/** Stable per-client key for express-rate-limit's pre-auth edge buckets. */
-export function externalClientRateLimitKey(req: Request): string {
+/** Stable source-IP key for express-rate-limit's pre-auth edge bucket. */
+export function externalClientIpRateLimitKey(req: Request): string {
+ const ipKey = ipKeyGenerator(externalClientIp(req))
+ return `external-client-ip:${ipKey}`
+}
+
+/**
+ * Stable per-session key for the second pre-auth edge bucket.
+ *
+ * The session token is deliberately only an additional dimension: it must not
+ * replace the source-IP bucket because it is unverified at this boundary and
+ * can be rotated by a caller. Both buckets are applied by the external route
+ * families, so token rotation cannot evade the IP ceiling.
+ */
+export function externalClientSessionRateLimitKey(req: Request): string {
const ipKey = ipKeyGenerator(externalClientIp(req))
const sessionToken = req.header('x-user-session-token')?.trim()
- if (!sessionToken) return `external-client-ip:${ipKey}`
+ if (!sessionToken) return `external-client-session:${ipKey}:anonymous`
const sessionKey = createHash('sha256').update(sessionToken).digest('hex').slice(0, 24)
- return `external-client-ip:${ipKey}:session:${sessionKey}`
+ return `external-client-session:${ipKey}:${sessionKey}`
+}
+
+/** Backwards-compatible name for callers/tests of the session dimension. */
+export function externalClientRateLimitKey(req: Request): string {
+ return externalClientSessionRateLimitKey(req)
+}
+
+/**
+ * Compose independent source-IP and IP+session pre-auth gates. Keeping both
+ * dimensions explicit prevents an unverified token rotation from evading the
+ * source-IP ceiling while preserving per-session fairness after the IP gate.
+ */
+export function createExternalClientRateLimiters(
+ bucketType: string,
+ ipMaxPerMinute: number,
+ sessionMaxPerMinute = ipMaxPerMinute
+): [RequestHandler, RequestHandler] {
+ const commonOptions = {
+ windowMs: 60_000,
+ standardHeaders: 'draft-7' as const,
+ legacyHeaders: false,
+ }
+ const sourceIp = rateLimit({
+ ...commonOptions,
+ limit: ipMaxPerMinute,
+ keyGenerator: req => `external-edge:${bucketType}:${externalClientIpRateLimitKey(req)}`,
+ })
+ const session = rateLimit({
+ ...commonOptions,
+ limit: sessionMaxPerMinute,
+ keyGenerator: req => `external-edge:${bucketType}:${externalClientSessionRateLimitKey(req)}`,
+ })
+ return [sourceIp, session]
}
diff --git a/control-api/src/routes/external/decisions.routes.ts b/control-api/src/routes/external/decisions.routes.ts
index 65e17de47..4b51b539b 100644
--- a/control-api/src/routes/external/decisions.routes.ts
+++ b/control-api/src/routes/external/decisions.routes.ts
@@ -1,8 +1,7 @@
import { NextFunction, Request, Response, Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { requireApprovalDecisionAccess } from '../../middleware/approvalDecisionAccess.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import { requireValidExternalSessionToken } from '../../middleware/externalSessionAuth.js'
import type { ExternalAuthedRequest } from '../../middleware/externalSessionAuth.js'
import { mcpHostHttpMetrics } from '../../middleware/mcpHostHttpMetrics.js'
@@ -45,17 +44,15 @@ function userAgent(req: Request): string | null {
export function createExternalUserApprovalDecisionsRouter(): Router {
const router = Router()
- const externalApprovalEdgeRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
+ const externalApprovalEdgeRateLimits = createExternalClientRateLimiters(
+ 'workflow-approvals',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
router.get(
'/external/workflow-approvals/pending',
- externalApprovalEdgeRateLimit,
+ ...externalApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_user_approval_requests_pending'),
requireValidExternalSessionToken,
rateLimitMiddleware({
@@ -93,7 +90,7 @@ export function createExternalUserApprovalDecisionsRouter(): Router {
router.post(
'/external/workflow-approvals/:id/decide',
- externalApprovalEdgeRateLimit,
+ ...externalApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_user_approval_requests_decide'),
requireValidExternalSessionToken,
requireValidApprovalIdParam,
diff --git a/control-api/src/routes/external/directory.ts b/control-api/src/routes/external/directory.ts
index 1160726e4..1837bf81b 100644
--- a/control-api/src/routes/external/directory.ts
+++ b/control-api/src/routes/external/directory.ts
@@ -1,7 +1,6 @@
import { Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import {
requireExternalTeamParamMatch,
requireValidExternalSessionToken,
@@ -10,14 +9,16 @@ import { searchDirectory } from '../../services/directory/index.js'
export function createExternalDirectoryRouter(): Router {
const router = Router()
- const externalDirectoryRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
- router.use('/external/directory', externalDirectoryRateLimit, requireValidExternalSessionToken)
+ const externalDirectoryRateLimits = createExternalClientRateLimiters(
+ 'directory',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
+ router.use(
+ '/external/directory',
+ ...externalDirectoryRateLimits,
+ requireValidExternalSessionToken
+ )
router.get(
'/external/directory/search',
diff --git a/control-api/src/routes/external/invitations.ts b/control-api/src/routes/external/invitations.ts
index e989045ff..fe150f0e1 100644
--- a/control-api/src/routes/external/invitations.ts
+++ b/control-api/src/routes/external/invitations.ts
@@ -1,8 +1,7 @@
import { Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { randomBytes } from 'node:crypto'
import { config } from '../../config.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
rejectBodyUserTeamMismatch,
@@ -35,16 +34,14 @@ function invitationLookupIpKey(req: {
export function createExternalInvitationsRouter(): Router {
const router = Router()
- const externalInvitationsEdgeRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
+ const externalInvitationsEdgeRateLimits = createExternalClientRateLimiters(
+ 'invitations',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
// Keep one edge limiter at the common prefix so every invitation endpoint,
// including Desktop authorization, is covered once.
- router.use('/external/invitations', externalInvitationsEdgeRateLimit)
+ router.use('/external/invitations', ...externalInvitationsEdgeRateLimits)
router.get(
'/external/invitations/token/:token',
rateLimitMiddleware({
diff --git a/control-api/src/routes/external/members.ts b/control-api/src/routes/external/members.ts
index 2b56e0285..e312426ad 100644
--- a/control-api/src/routes/external/members.ts
+++ b/control-api/src/routes/external/members.ts
@@ -1,7 +1,6 @@
import { Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -29,14 +28,12 @@ function currentUserId(req: ExternalAuthedRequest): string | null {
export function createExternalMembersRouter(): Router {
const router = Router()
- const externalMembersRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
- router.use('/external/members', externalMembersRateLimit, requireValidExternalSessionToken)
+ const externalMembersRateLimits = createExternalClientRateLimiters(
+ 'members',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
+ router.use('/external/members', ...externalMembersRateLimits, requireValidExternalSessionToken)
router.get(
'/external/members/manageable-teams',
diff --git a/control-api/src/routes/external/notifications.routes.ts b/control-api/src/routes/external/notifications.routes.ts
index 029ec289b..ae30dc9bb 100644
--- a/control-api/src/routes/external/notifications.routes.ts
+++ b/control-api/src/routes/external/notifications.routes.ts
@@ -1,8 +1,7 @@
import { Request, Response, Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -93,17 +92,15 @@ function setStreamHeaders(res: Response): void {
export function createExternalNotificationsRouter(): Router {
const router = Router()
- const externalNotificationsEdgeRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
+ const externalNotificationsEdgeRateLimits = createExternalClientRateLimiters(
+ 'notifications',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
router.get(
'/external/notifications/stream',
- externalNotificationsEdgeRateLimit,
+ ...externalNotificationsEdgeRateLimits,
mcpHostHttpMetrics('external_notifications_stream'),
requireValidExternalSessionToken,
rateLimitMiddleware({
@@ -336,7 +333,7 @@ export function createExternalNotificationsRouter(): Router {
router.post(
'/external/notifications/:id/ack',
- externalNotificationsEdgeRateLimit,
+ ...externalNotificationsEdgeRateLimits,
mcpHostHttpMetrics('external_notification_ack'),
requireValidExternalSessionToken,
rateLimitMiddleware({
@@ -369,7 +366,7 @@ export function createExternalNotificationsRouter(): Router {
router.get(
'/external/me/notification-preferences',
- externalNotificationsEdgeRateLimit,
+ ...externalNotificationsEdgeRateLimits,
mcpHostHttpMetrics('external_notification_preferences_get'),
requireValidExternalSessionToken,
asyncHandler(async (req: Request, res: Response) => {
@@ -385,7 +382,7 @@ export function createExternalNotificationsRouter(): Router {
router.put(
'/external/me/notification-preferences',
- externalNotificationsEdgeRateLimit,
+ ...externalNotificationsEdgeRateLimits,
mcpHostHttpMetrics('external_notification_preferences_put'),
requireValidExternalSessionToken,
asyncHandler(async (req: Request, res: Response) => {
diff --git a/control-api/src/routes/external/oauthGrants.ts b/control-api/src/routes/external/oauthGrants.ts
index 0fbd21ebd..c3ae753cc 100644
--- a/control-api/src/routes/external/oauthGrants.ts
+++ b/control-api/src/routes/external/oauthGrants.ts
@@ -1,8 +1,7 @@
import { Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { pool } from '../../db.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -24,19 +23,17 @@ function dbClient() {
*/
export function createExternalOauthGrantsRouter(): Router {
const router = Router()
- const externalOauthGrantsRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
+ const externalOauthGrantsRateLimits = createExternalClientRateLimiters(
+ 'oauth-grants',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
// GET /external/oauth/grants
// Returns all grants for the authenticated user.
router.get(
'/external/oauth/grants',
- externalOauthGrantsRateLimit,
+ ...externalOauthGrantsRateLimits,
requireValidExternalSessionToken,
(req: ExternalAuthedRequest, res, next) => {
void (async () => {
@@ -62,7 +59,7 @@ export function createExternalOauthGrantsRouter(): Router {
// row existed (no information leak).
router.delete(
'/external/oauth/grants/:recipeNamespace/:recipeName/:oauthClientId',
- externalOauthGrantsRateLimit,
+ ...externalOauthGrantsRateLimits,
requireValidExternalSessionToken,
(req: ExternalAuthedRequest, res, next) => {
void (async () => {
diff --git a/control-api/src/routes/external/sharedFilesystems.ts b/control-api/src/routes/external/sharedFilesystems.ts
index 4ffa398bb..4cc14a25b 100644
--- a/control-api/src/routes/external/sharedFilesystems.ts
+++ b/control-api/src/routes/external/sharedFilesystems.ts
@@ -1,9 +1,8 @@
import { Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import type { K8sGateway } from '../../k8s.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -183,19 +182,17 @@ function curatedSfsMessage(phase: string | null | undefined): string | null {
export function createExternalSharedFilesystemsRouter(gateway: K8sGateway): Router {
const router = Router()
- const externalSharedFilesystemsRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
+ const externalSharedFilesystemsRateLimits = createExternalClientRateLimiters(
+ 'shared-filesystems',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
const sfsNs = config.sharedFilesystemsNamespace
const ctxNs = config.contextsNamespace
router.use(
'/external/contexts/:contextId/shared-filesystems',
- externalSharedFilesystemsRateLimit,
+ ...externalSharedFilesystemsRateLimits,
requireValidExternalSessionToken
)
diff --git a/control-api/src/routes/external/teams.ts b/control-api/src/routes/external/teams.ts
index d543d35cd..1e2cc03e8 100644
--- a/control-api/src/routes/external/teams.ts
+++ b/control-api/src/routes/external/teams.ts
@@ -1,8 +1,7 @@
import { Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import type { K8sGateway } from '../../k8s.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import type { ExternalAuthedRequest } from '../../middleware/externalSessionAuth.js'
import {
rejectBodyUserTeamMismatch,
@@ -42,14 +41,12 @@ function sendInvitationServiceError(
export function createExternalTeamsRouter(gateway: K8sGateway): Router {
const router = Router()
- const externalTeamsRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
- router.use('/external/teams', externalTeamsRateLimit, requireValidExternalSessionToken)
+ const externalTeamsRateLimits = createExternalClientRateLimiters(
+ 'teams',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
+ router.use('/external/teams', ...externalTeamsRateLimits, requireValidExternalSessionToken)
router.get(
'/external/teams/:teamId/users/:userId/current',
diff --git a/control-api/src/routes/external/users.ts b/control-api/src/routes/external/users.ts
index b752950de..8be8d9540 100644
--- a/control-api/src/routes/external/users.ts
+++ b/control-api/src/routes/external/users.ts
@@ -1,8 +1,7 @@
import { Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import type { K8sGateway } from '../../k8s.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
rejectBodyUserTeamMismatch,
@@ -77,14 +76,12 @@ async function mapWithConcurrencyLimit<T, R>(
export function createExternalUsersRouter(gateway: K8sGateway): Router {
const router = Router()
- const externalUsersRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
- router.use('/external/users', externalUsersRateLimit, requireValidExternalSessionToken)
+ const externalUsersRateLimits = createExternalClientRateLimiters(
+ 'users',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
+ router.use('/external/users', ...externalUsersRateLimits, requireValidExternalSessionToken)
router.get(
'/external/users/:userId/teams',
diff --git a/control-api/src/routes/external/workflow-approval-mediums.routes.ts b/control-api/src/routes/external/workflow-approval-mediums.routes.ts
index 9e84831da..71910912c 100644
--- a/control-api/src/routes/external/workflow-approval-mediums.routes.ts
+++ b/control-api/src/routes/external/workflow-approval-mediums.routes.ts
@@ -1,8 +1,7 @@
import { Router } from 'express'
-import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import type { K8sGateway } from '../../k8s.js'
-import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
+import { createExternalClientRateLimiters } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -73,17 +72,15 @@ function displayNameFromBody(body: unknown): string | null {
export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway): Router {
const router = Router()
- const externalWorkflowApprovalEdgeRateLimit = rateLimit({
- windowMs: 60_000,
- limit: config.approvalRlExternalEdgePerMin,
- standardHeaders: 'draft-7',
- legacyHeaders: false,
- keyGenerator: externalClientRateLimitKey,
- })
+ const externalWorkflowApprovalEdgeRateLimits = createExternalClientRateLimiters(
+ 'workflow-approval-mediums',
+ config.approvalRlExternalClientIpPerMin,
+ config.approvalRlExternalEdgePerMin
+ )
router.post(
'/external/workflow-approval-mediums/challenges',
- externalWorkflowApprovalEdgeRateLimit,
+ ...externalWorkflowApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_workflow_approval_medium_challenge'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -171,7 +168,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.post(
'/external/workflow-approval-mediums/link-sessions',
- externalWorkflowApprovalEdgeRateLimit,
+ ...externalWorkflowApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_workflow_approval_medium_link_session'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -261,7 +258,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.post(
'/external/workflow-approval-mediums/challenges/:id/confirm',
- externalWorkflowApprovalEdgeRateLimit,
+ ...externalWorkflowApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_workflow_approval_medium_confirm'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -307,7 +304,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.get(
'/external/workflow-approval-mediums',
- externalWorkflowApprovalEdgeRateLimit,
+ ...externalWorkflowApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_workflow_approval_medium_list'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -341,7 +338,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.get(
'/external/workflow-approval-mediums/targets',
- externalWorkflowApprovalEdgeRateLimit,
+ ...externalWorkflowApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_workflow_approval_medium_targets'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -376,7 +373,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.put(
'/external/workflow-approval-mediums/:id/preference',
- externalWorkflowApprovalEdgeRateLimit,
+ ...externalWorkflowApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_workflow_approval_medium_preference'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -401,7 +398,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.patch(
'/external/workflow-approval-mediums/:id/display-name',
- externalWorkflowApprovalEdgeRateLimit,
+ ...externalWorkflowApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_workflow_approval_medium_display_name'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -439,7 +436,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.delete(
'/external/workflow-approval-mediums/:id',
- externalWorkflowApprovalEdgeRateLimit,
+ ...externalWorkflowApprovalEdgeRateLimits,
mcpHostHttpMetrics('external_workflow_approval_medium_delete'),
requireValidExternalSessionToken,
(req, res, next) => {
diff --git a/control-api/src/services/adminAuthService.ts b/control-api/src/services/adminAuthService.ts
index 5f51538ae..3d94b0a32 100644
--- a/control-api/src/services/adminAuthService.ts
+++ b/control-api/src/services/adminAuthService.ts
@@ -562,6 +562,22 @@ export async function deleteControlAdmin(
LIMIT 1`,
[actorAdminId]
)
+
+ // Serialize retirement against a concurrent delete/disable. The lifecycle
+ // transition is active -> disabled; a replay must be a stable not-found
+ // result and must not revoke another generation or append duplicate audit.
+ const targetResult = await db.query(
+ `SELECT id, username, email, status
+ FROM control_admin_users
+ WHERE id = $1
+ FOR UPDATE`,
+ [adminId]
+ )
+ const target = targetResult.rows[0] as
+ | { id: string; username: string; email: string | null; status: 'active' | 'disabled' }
+ | undefined
+ if (!target || target.status !== 'active') return { error: 'not_found' as const }
+
await gfsDesktopOperatorLinkService.retireParentInTransaction(db, {
kind: 'control_admin',
parentId: adminId,
@@ -572,6 +588,7 @@ export async function deleteControlAdmin(
`UPDATE control_admin_users
SET status = 'disabled', session_version = session_version + 1, updated_at = NOW()
WHERE id = $1
+ AND status = 'active'
RETURNING id, username, email`,
[adminId]
)
diff --git a/control-api/src/services/directory/agentAccess.ts b/control-api/src/services/directory/agentAccess.ts
index d8ffd2c48..b0ad0bc7c 100644
--- a/control-api/src/services/directory/agentAccess.ts
+++ b/control-api/src/services/directory/agentAccess.ts
@@ -83,8 +83,10 @@ export async function setAgentUsers(agentName: string, userIds: string[], operat
export async function getUserAgents(userId: string, db: Pick<DbClient, 'query'> = pool) {
const result = await db.query(
`SELECT agent_name
- FROM user_agents
- WHERE user_id = $1
+ FROM user_agents ua
+ JOIN users u ON u.id = ua.user_id
+ WHERE ua.user_id = $1
+ AND u.lifecycle_state = 'active'
ORDER BY agent_name ASC`,
[userId]
)
@@ -104,6 +106,7 @@ export async function listUsersByAgent(agentName: string) {
JOIN users u ON u.id = ua.user_id
LEFT JOIN profiles p ON p.user_id = u.id
WHERE ua.agent_name = $1
+ AND u.lifecycle_state = 'active'
ORDER BY u.email ASC`,
[resolvedAgentName]
)
diff --git a/control-api/src/services/directory/contextAccess.ts b/control-api/src/services/directory/contextAccess.ts
index 635b3cdbb..69ca7ae5d 100644
--- a/control-api/src/services/directory/contextAccess.ts
+++ b/control-api/src/services/directory/contextAccess.ts
@@ -41,8 +41,10 @@ export async function setUserContexts(userId: string, contextIds: string[], oper
export async function getUserContexts(userId: string) {
const result = await pool.query(
`SELECT context_id
- FROM user_contexts
- WHERE user_id = $1
+ FROM user_contexts uc
+ JOIN users u ON u.id = uc.user_id
+ WHERE uc.user_id = $1
+ AND u.lifecycle_state = 'active'
ORDER BY context_id ASC`,
[userId]
)
@@ -62,6 +64,7 @@ export async function listUsersByContext(contextId: string) {
JOIN users u ON u.id = uc.user_id
LEFT JOIN profiles p ON p.user_id = u.id
WHERE uc.context_id = $1
+ AND u.lifecycle_state = 'active'
ORDER BY u.email ASC`,
[resolvedContextId]
)
diff --git a/control-api/src/services/directory/login.ts b/control-api/src/services/directory/login.ts
index 3f6df5bb8..afbe4ac08 100644
--- a/control-api/src/services/directory/login.ts
+++ b/control-api/src/services/directory/login.ts
@@ -21,6 +21,7 @@ async function findFirstActiveMembership(
`SELECT tm.team_id, tm.role, t.name AS team_name
FROM team_members tm
JOIN teams t ON t.id = tm.team_id
+ JOIN users member_user ON member_user.id = tm.user_id
LEFT JOIN LATERAL (
SELECT MAX(i.accepted_at) AS accepted_at
FROM invitations i
@@ -32,6 +33,7 @@ async function findFirstActiveMembership(
) accepted_invitation ON TRUE
WHERE tm.user_id = $1
AND tm.status = 'active'
+ AND member_user.lifecycle_state = 'active'
ORDER BY
CASE WHEN accepted_invitation.accepted_at IS NULL THEN 1 ELSE 0 END,
accepted_invitation.accepted_at DESC NULLS LAST,
diff --git a/control-api/src/services/directory/membership.ts b/control-api/src/services/directory/membership.ts
index 39c8cc476..181fc5443 100644
--- a/control-api/src/services/directory/membership.ts
+++ b/control-api/src/services/directory/membership.ts
@@ -398,9 +398,11 @@ export async function findMembership(userId: string, teamId: string) {
`SELECT tm.team_id, tm.role, t.name AS team_name
FROM team_members tm
JOIN teams t ON t.id = tm.team_id
+ JOIN users u ON u.id = tm.user_id
WHERE tm.user_id = $1
AND tm.team_id = $2
AND tm.status = 'active'
+ AND u.lifecycle_state = 'active'
LIMIT 1`,
[userId, teamId]
)
@@ -419,6 +421,7 @@ export async function getMe(userId: string, teamId: string) {
LEFT JOIN teams t ON t.id = tm.team_id
LEFT JOIN profiles p ON p.user_id = u.id
WHERE u.id = $1
+ AND u.lifecycle_state = 'active'
LIMIT 1`,
[userId, teamId]
)
@@ -481,6 +484,7 @@ export async function listMembers(teamId: string) {
JOIN users u ON u.id = tm.user_id
WHERE tm.team_id = $1
AND tm.status = 'active'
+ AND u.lifecycle_state = 'active'
ORDER BY u.email ASC`,
[teamId]
)
@@ -491,9 +495,11 @@ export async function findMemberRole(teamId: string, userId: string) {
const result = await pool.query(
`SELECT role
FROM team_members
+ JOIN users u ON u.id = team_members.user_id
WHERE team_id = $1
AND user_id = $2
AND status = 'active'
+ AND u.lifecycle_state = 'active'
LIMIT 1`,
[teamId, userId]
)
@@ -843,6 +849,7 @@ export async function requestProfilePasswordReset(email: string): Promise<{ requ
`SELECT id, email, name
FROM users
WHERE email = $1
+ AND lifecycle_state = 'active'
LIMIT 1`,
[normalizedEmail]
)
@@ -1404,6 +1411,7 @@ export async function searchDirectory(teamId: string, q: string) {
LEFT JOIN profiles p ON p.user_id = u.id
WHERE tm.team_id = $1
AND tm.status = 'active'
+ AND u.lifecycle_state = 'active'
AND (
u.email ILIKE $2
OR COALESCE(u.name, '') ILIKE $2
@@ -1421,9 +1429,11 @@ export async function listManageableTeamsForUser(userId: string) {
`SELECT t.id, t.name, tm.role
FROM team_members tm
JOIN teams t ON t.id = tm.team_id
+ JOIN users u ON u.id = tm.user_id
WHERE tm.user_id = $1
AND tm.status = 'active'
AND tm.role IN ('admin', 'inviter')
+ AND u.lifecycle_state = 'active'
ORDER BY t.name ASC`,
[userId.trim()]
)
@@ -1441,12 +1451,14 @@ export async function listManagedMembersForUser(userId: string, targetUserId?: s
const result = normalizedTargetUserId
? await pool.query(
`WITH managed_teams AS (
- SELECT tm.team_id, tm.role AS manager_role, t.name AS team_name
+ SELECT tm.team_id, tm.role AS manager_role, t.name AS team_name
FROM team_members tm
JOIN teams t ON t.id = tm.team_id
+ JOIN users manager ON manager.id = tm.user_id
WHERE tm.user_id = $1
AND tm.status = 'active'
AND tm.role IN ('admin', 'inviter')
+ AND manager.lifecycle_state = 'active'
),
eligible_target AS (
SELECT 1
@@ -1487,6 +1499,7 @@ export async function listManagedMembersForUser(userId: string, targetUserId?: s
LEFT JOIN managed_teams mt ON mt.team_id = target_tm.team_id
LEFT JOIN profiles p ON p.user_id = u.id
WHERE u.id::text = $2
+ AND u.lifecycle_state = 'active'
AND EXISTS (SELECT 1 FROM eligible_target)
GROUP BY u.id, u.email, u.name, u.picture, p.display_name
ORDER BY COALESCE(p.display_name, u.name, u.email) ASC`,
@@ -1497,9 +1510,11 @@ export async function listManagedMembersForUser(userId: string, targetUserId?: s
SELECT tm.team_id, tm.role AS manager_role, t.name AS team_name
FROM team_members tm
JOIN teams t ON t.id = tm.team_id
+ JOIN users manager ON manager.id = tm.user_id
WHERE tm.user_id = $1
AND tm.status = 'active'
AND tm.role IN ('admin', 'inviter')
+ AND manager.lifecycle_state = 'active'
),
visible_users AS (
SELECT DISTINCT target_tm.user_id
@@ -1507,6 +1522,8 @@ export async function listManagedMembersForUser(userId: string, targetUserId?: s
JOIN team_members target_tm
ON target_tm.team_id = mt.team_id
AND target_tm.status = 'active'
+ JOIN users visible ON visible.id = target_tm.user_id
+ AND visible.lifecycle_state = 'active'
)
SELECT u.id,
u.email,
@@ -1581,10 +1598,12 @@ async function getManagerRolesForTeams(
if (teamIds.length === 0) return new Map()
const result = await pool.query(
`SELECT team_id, role
- FROM team_members
+ FROM team_members tm
+ JOIN users u ON u.id = tm.user_id
WHERE user_id = $1
AND team_id = ANY($2::uuid[])
- AND status = 'active'`,
+ AND status = 'active'
+ AND u.lifecycle_state = 'active'`,
[managerUserId.trim(), teamIds]
)
return new Map(
@@ -1617,11 +1636,13 @@ export async function listManagedPendingInvitationsForUser(managerUserId: string
const normalizedManagerUserId = managerUserId.trim()
const result = await pool.query(
`WITH managed_teams AS (
- SELECT tm.team_id, tm.role AS manager_role
+ SELECT tm.team_id, tm.role AS manager_role
FROM team_members tm
+ JOIN users manager ON manager.id = tm.user_id
WHERE tm.user_id = $1
AND tm.status = 'active'
AND tm.role IN ('admin', 'inviter')
+ AND manager.lifecycle_state = 'active'
)
SELECT DISTINCT i.id, i.team_id, i.invitee_name, i.email, i.role, i.token, i.status, i.purpose, i.created_at, i.expires_at,
i.accepted_at, i.accepted_user_id,
@@ -1675,10 +1696,12 @@ export async function createManagedInvitationForUser(
`SELECT tm.team_id, tm.role, t.name AS team_name
FROM team_members tm
JOIN teams t ON t.id = tm.team_id
+ JOIN users manager ON manager.id = tm.user_id
WHERE tm.user_id = $1
AND tm.team_id = ANY($2::uuid[])
AND tm.status = 'active'
- AND tm.role IN ('admin', 'inviter')`,
+ AND tm.role IN ('admin', 'inviter')
+ AND manager.lifecycle_state = 'active'`,
[managerUserId.trim(), assignments.map(assignment => assignment.teamId)]
)
const managerRoles = new Map(
@@ -1792,9 +1815,11 @@ export async function deleteManagedUserForUser(
const teamsResult = await pool.query(
`SELECT team_id
- FROM team_members
+ FROM team_members tm
+ JOIN users target ON target.id = tm.user_id
WHERE user_id = $1
- AND status = 'active'`,
+ AND status = 'active'
+ AND target.lifecycle_state = 'active'`,
[normalizedTargetUserId]
)
const teamIds = (teamsResult.rows as Array<{ team_id: string }>).map(row => row.team_id)
diff --git a/control-api/src/services/directory/teams.ts b/control-api/src/services/directory/teams.ts
index f2a9d3a1e..9996698f7 100644
--- a/control-api/src/services/directory/teams.ts
+++ b/control-api/src/services/directory/teams.ts
@@ -7,8 +7,10 @@ export async function listTeams(userId: string, currentTeamId: string) {
`SELECT t.id, t.name, tm.role
FROM team_members tm
JOIN teams t ON t.id = tm.team_id
+ JOIN users u ON u.id = tm.user_id
WHERE tm.user_id = $1
AND tm.status = 'active'
+ AND u.lifecycle_state = 'active'
ORDER BY t.created_at ASC`,
[userId]
)
@@ -23,9 +25,10 @@ export async function listAllTeams() {
const result = await pool.query(
`SELECT t.id,
t.name,
- COUNT(CASE WHEN tm.status = 'active' THEN 1 END) AS member_count
+ COUNT(CASE WHEN tm.status = 'active' AND u.lifecycle_state = 'active' THEN 1 END) AS member_count
FROM teams t
LEFT JOIN team_members tm ON tm.team_id = t.id
+ LEFT JOIN users u ON u.id = tm.user_id
GROUP BY t.id, t.name
ORDER BY t.name ASC`
)
@@ -57,9 +60,11 @@ export async function getCurrentTeam(
`SELECT t.id, t.name, tm.role
FROM teams t
JOIN team_members tm ON tm.team_id = t.id
+ JOIN users u ON u.id = tm.user_id
WHERE tm.user_id = $1
AND tm.team_id = $2
AND tm.status = 'active'
+ AND u.lifecycle_state = 'active'
LIMIT 1`,
[userId, teamId]
)
diff --git a/control-api/src/services/directory/workflowGrants.ts b/control-api/src/services/directory/workflowGrants.ts
index 7689416d8..8884f0e5a 100644
--- a/control-api/src/services/directory/workflowGrants.ts
+++ b/control-api/src/services/directory/workflowGrants.ts
@@ -52,7 +52,9 @@ export async function listWorkflowGrants(
FROM user_workflow_triggers uwt
JOIN users u ON u.id = uwt.user_id
LEFT JOIN profiles p ON p.user_id = u.id
- WHERE uwt.recipe_namespace = $1 AND uwt.recipe_name = $2
+ WHERE uwt.recipe_namespace = $1
+ AND uwt.recipe_name = $2
+ AND u.lifecycle_state = 'active'
ORDER BY u.email ASC`,
[ns, name]
)
diff --git a/control-api/src/services/gfsDesktopOperatorLinkService.ts b/control-api/src/services/gfsDesktopOperatorLinkService.ts
index c6fd65b5b..0ae200c91 100644
--- a/control-api/src/services/gfsDesktopOperatorLinkService.ts
+++ b/control-api/src/services/gfsDesktopOperatorLinkService.ts
@@ -806,46 +806,59 @@ export class GfsDesktopOperatorLinkService {
const rows = await db.query(
`SELECT id::text AS id, lineage_id::text AS lineage_id, generation,
predecessor_id::text AS predecessor_id, state, row_version,
+ revoked_at, revocation_reason,
user_id::text AS user_id, control_admin_id::text AS control_admin_id,
source, created_at
FROM gfs_desktop_operator_links
- WHERE ${column} = $1::uuid AND state = 'active'
+ WHERE ${column} = $1::uuid
+ ORDER BY generation DESC
LIMIT 1 FOR UPDATE`,
[parentId]
)
if (rows.rows.length === 0) return false
const link = mapStoredLink(rows.rows[0])
+ const parentRetiredChange = {
+ action: 'revoke' as const,
+ resourceClass: `gfs_desktop_operator_${input.kind}`,
+ resourceRef: `${input.kind}:${parentId}`,
+ subject:
+ input.kind === 'desktop_user'
+ ? { kind: 'user' as const, id: parentId }
+ : {
+ kind: 'service' as const,
+ id: `control_admin:${parentId}`,
+ principalKind: 'operator' as const,
+ },
+ 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}`,
+ `actor_type:${actor.kind}`,
+ actor.kind === 'control_admin'
+ ? `actor_control_admin_id:${actor.controlAdminId}`
+ : `actor_desktop_user_id:${actor.desktopUserId}`,
+ `reason:${reason}`,
+ ].join(';'),
+ }
await this.dependencies.appendPermissionEvents(db, {
operatorSub,
operatorKind: actor.kind,
requestId: input.requestId,
operationId: input.operationId,
- changes: [
- lifecycleChange('revoke', link, reason, 'link.revoked', actor),
- {
- action: 'revoke',
- resourceClass: `gfs_desktop_operator_${input.kind}`,
- resourceRef: `${input.kind}:${parentId}`,
- subject:
- input.kind === 'desktop_user'
- ? { kind: 'user', id: parentId }
- : { kind: 'service', id: `control_admin:${parentId}`, principalKind: 'operator' },
- sourceAuditRef: `gfs_desktop_operator_link_source:${link.source}`,
- status: 'retired',
- detailRef: [
- 'event:parent.retired',
- `desktop_user_id:${link.desktopUserId}`,
- `control_admin_id:${link.controlAdminId}`,
- `source:${link.source}`,
- `actor_type:${actor.kind}`,
- actor.kind === 'control_admin'
- ? `actor_control_admin_id:${actor.controlAdminId}`
- : `actor_desktop_user_id:${actor.desktopUserId}`,
- `reason:${reason}`,
- ].join(';'),
- },
- ],
+ changes:
+ link.state === 'revoked'
+ ? [parentRetiredChange]
+ : [lifecycleChange('revoke', link, reason, 'link.revoked', actor), parentRetiredChange],
})
+
+ // A prior Control UI revoke already created the immutable tombstone. The
+ // parent can still be retired afterwards; preserve that history and emit
+ // only the missing parent.retired evidence without creating a generation.
+ if (link.state === 'revoked') return true
+
const updated = await db.query(
`UPDATE gfs_desktop_operator_links
SET state = 'revoked',
diff --git a/control-api/test/config.approvalRateLimit.test.ts b/control-api/test/config.approvalRateLimit.test.ts
index 5003eb222..da37c216a 100644
--- a/control-api/test/config.approvalRateLimit.test.ts
+++ b/control-api/test/config.approvalRateLimit.test.ts
@@ -1,6 +1,11 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-const RATE_LIMIT_KEYS = ['APPROVAL_RL_REQUEST_PER_MIN'] as const
+const RATE_LIMIT_KEYS = [
+ 'APPROVAL_RL_REQUEST_PER_MIN',
+ 'APPROVAL_RL_EXTERNAL_PER_MIN',
+ 'APPROVAL_RL_EXTERNAL_EDGE_PER_MIN',
+ 'APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN',
+] as const
async function loadConfigWith(
overrides: Partial<Record<(typeof RATE_LIMIT_KEYS)[number], string>>
@@ -42,4 +47,44 @@ describe('control-api approval rate limit config', () => {
expect(config.approvalRlRequestPerMin).toBe(30)
})
+
+ it('keeps the external client IP backstop wider than the session edge bucket', async () => {
+ const config = await loadConfigWith({})
+
+ expect(config.approvalRlExternalEdgePerMin).toBe(120)
+ expect(config.approvalRlExternalClientIpPerMin).toBe(1200)
+ expect(config.approvalRlExternalClientIpPerMin).toBeGreaterThan(
+ config.approvalRlExternalEdgePerMin
+ )
+ })
+
+ it('rejects malformed external rate-limit configuration at startup', async () => {
+ await expect(loadConfigWith({ APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: '0' })).rejects.toThrow(
+ 'APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN must be a positive integer'
+ )
+ })
+
+ it('rejects an incoherent external limiter hierarchy at startup', async () => {
+ await expect(
+ loadConfigWith({
+ APPROVAL_RL_EXTERNAL_PER_MIN: '60',
+ APPROVAL_RL_EXTERNAL_EDGE_PER_MIN: '1200',
+ APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: '120',
+ })
+ ).rejects.toThrow(
+ 'APPROVAL_RL_EXTERNAL_PER_MIN must be <= APPROVAL_RL_EXTERNAL_EDGE_PER_MIN < APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN'
+ )
+ })
+
+ it('rejects an operation budget wider than the session budget', async () => {
+ await expect(
+ loadConfigWith({
+ APPROVAL_RL_EXTERNAL_PER_MIN: '121',
+ APPROVAL_RL_EXTERNAL_EDGE_PER_MIN: '120',
+ APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: '1200',
+ })
+ ).rejects.toThrow(
+ 'APPROVAL_RL_EXTERNAL_PER_MIN must be <= APPROVAL_RL_EXTERNAL_EDGE_PER_MIN < APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN'
+ )
+ })
})
diff --git a/control-api/test/db.controlAdminSessionVersionDefaultMigration.test.ts b/control-api/test/db.controlAdminSessionVersionDefaultMigration.test.ts
index 0c8a807c9..76368b8ea 100644
--- a/control-api/test/db.controlAdminSessionVersionDefaultMigration.test.ts
+++ b/control-api/test/db.controlAdminSessionVersionDefaultMigration.test.ts
@@ -27,5 +27,8 @@ describe('0096_control_admin_session_version_default migration', () => {
expect(sql).toContain('SET session_version = 1')
expect(sql).toContain('ALTER COLUMN session_version SET DEFAULT 1')
+ expect(sql).toContain('ALTER COLUMN session_version SET NOT NULL')
+ expect(sql).toContain('control_admin_session_version_positive')
+ expect(sql).toContain('CHECK (session_version >= 1)')
})
})
diff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.ts
index 7b3dd31df..bb1d46864 100644
--- a/control-api/test/db.realPostgresMigration.integration.test.ts
+++ b/control-api/test/db.realPostgresMigration.integration.test.ts
@@ -191,6 +191,56 @@ describeRealPostgres('control-api real Postgres migrations', () => {
expect(secondVersions.rows.map(row => row.version)).toContain(
'0095_gfs_lifecycle_authority_projection'
)
+ expect(secondVersions.rows.map(row => row.version)).toContain(
+ '0096_control_admin_session_version_default'
+ )
+
+ const sessionVersionContract = await dbPool.query<{
+ column_default: string | null
+ is_nullable: string
+ constraint_validated: boolean
+ }>(
+ `SELECT column_default,
+ is_nullable,
+ EXISTS (
+ SELECT 1
+ FROM pg_constraint
+ WHERE conrelid = 'control_admin_users'::regclass
+ AND conname = 'control_admin_session_version_positive'
+ AND convalidated
+ ) AS constraint_validated
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'control_admin_users'
+ AND column_name = 'session_version'`
+ )
+ expect(sessionVersionContract.rows).toEqual([
+ {
+ column_default: '1',
+ is_nullable: 'NO',
+ constraint_validated: true,
+ },
+ ])
+
+ const contractAdminId = randomUUID()
+ await dbPool.query(
+ `INSERT INTO control_admin_users (id, username, password_hash)
+ VALUES ($1, $2, 'migration-test-hash')`,
+ [contractAdminId, `migration-contract-${contractAdminId}`]
+ )
+ const defaultEpoch = await dbPool.query<{ session_version: number }>(
+ `SELECT session_version FROM control_admin_users WHERE id = $1`,
+ [contractAdminId]
+ )
+ expect(defaultEpoch.rows).toEqual([{ session_version: 1 }])
+ await expect(
+ dbPool.query(
+ `INSERT INTO control_admin_users (id, username, password_hash, session_version)
+ VALUES ($1, $2, 'migration-test-hash', 0)`,
+ [randomUUID(), `migration-invalid-${randomUUID()}`]
+ )
+ ).rejects.toThrow(/session_version|control_admin_session_version_positive/)
+ await dbPool.query(`DELETE FROM control_admin_users WHERE id = $1`, [contractAdminId])
await dbPool.query(`
DELETE FROM schema_migrations
diff --git a/control-api/test/middleware.externalClientIdentity.test.ts b/control-api/test/middleware.externalClientIdentity.test.ts
index 1ad37e9f6..c3a427f9d 100644
--- a/control-api/test/middleware.externalClientIdentity.test.ts
+++ b/control-api/test/middleware.externalClientIdentity.test.ts
@@ -1,8 +1,16 @@
import { describe, expect, it } from 'vitest'
+import express from 'express'
import { ipKeyGenerator } from 'express-rate-limit'
+import { readFileSync } from 'node:fs'
+import { dirname, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import supertest from 'supertest'
import {
+ createExternalClientRateLimiters,
externalClientIp,
+ externalClientIpRateLimitKey,
externalClientRateLimitKey,
+ externalClientSessionRateLimitKey,
} from '../src/middleware/externalClientIdentity.js'
function request(headers: Record<string, string>, ip = '10.0.0.9') {
@@ -16,10 +24,38 @@ function request(headers: Record<string, string>, ip = '10.0.0.9') {
}
describe('external client rate-limit identity', () => {
+ it('installs both independent gates on every non-GFS external family', () => {
+ const routesDir = resolve(dirname(fileURLToPath(import.meta.url)), '../src/routes/external')
+ const families = [
+ 'directory.ts',
+ 'members.ts',
+ 'teams.ts',
+ 'users.ts',
+ 'invitations.ts',
+ 'oauthGrants.ts',
+ 'sharedFilesystems.ts',
+ 'decisions.routes.ts',
+ 'notifications.routes.ts',
+ 'workflow-approval-mediums.routes.ts',
+ ]
+
+ for (const family of families) {
+ const source = readFileSync(resolve(routesDir, family), 'utf8')
+ expect(source, family).toContain('createExternalClientRateLimiters')
+ expect(source, family).toContain('config.approvalRlExternalClientIpPerMin')
+ expect(source, family).toContain('config.approvalRlExternalEdgePerMin')
+ expect(source, family).toMatch(/\.\.\.[A-Za-z]+RateLimits/)
+ expect(source, family).toContain('requireValidExternalSessionToken')
+ }
+ })
+
it('uses the authenticated external-rest identity before the funnel address', () => {
const req = request({ 'x-external-client-ip': '203.0.113.41' })
expect(externalClientIp(req)).toBe('203.0.113.41')
- expect(externalClientRateLimitKey(req)).toBe('external-client-ip:203.0.113.41')
+ expect(externalClientIpRateLimitKey(req)).toBe('external-client-ip:203.0.113.41')
+ expect(externalClientSessionRateLimitKey(req)).toBe(
+ 'external-client-session:203.0.113.41:anonymous'
+ )
})
it('rejects malformed asserted identity and falls back to the proxy-aware request IP', () => {
@@ -30,14 +66,86 @@ describe('external client rate-limit identity', () => {
it('uses express-rate-limit IPv6 masking so address rotation cannot evade the bucket', () => {
const ipv6 = '2001:db8:abcd:1234:5678:9abc:def0:1234'
const req = request({ 'x-external-client-ip': ipv6 })
- expect(externalClientRateLimitKey(req)).toBe(`external-client-ip:${ipKeyGenerator(ipv6)}`)
- expect(externalClientRateLimitKey(req)).not.toContain(ipv6)
+ expect(externalClientIpRateLimitKey(req)).toBe(`external-client-ip:${ipKeyGenerator(ipv6)}`)
+ expect(externalClientIpRateLimitKey(req)).not.toContain(ipv6)
+ expect(externalClientSessionRateLimitKey(req)).toBe(
+ `external-client-session:${ipKeyGenerator(ipv6)}:anonymous`
+ )
})
it('separates authenticated sessions sharing one external address without exposing the token', () => {
const first = request({ 'x-user-session-token': 'session-one' })
const second = request({ 'x-user-session-token': 'session-two' })
- expect(externalClientRateLimitKey(first)).not.toBe(externalClientRateLimitKey(second))
- expect(externalClientRateLimitKey(first)).not.toContain('session-one')
+ expect(externalClientSessionRateLimitKey(first)).not.toBe(
+ externalClientSessionRateLimitKey(second)
+ )
+ expect(externalClientSessionRateLimitKey(first)).not.toContain('session-one')
+ expect(externalClientIpRateLimitKey(first)).toBe(externalClientIpRateLimitKey(second))
+ })
+
+ it('keeps the source-IP ceiling stable while unverified session tokens rotate', () => {
+ const first = request({ 'x-user-session-token': 'session-one' })
+ const rotated = request({ 'x-user-session-token': 'rotated-session' })
+ expect(externalClientIpRateLimitKey(first)).toBe(externalClientIpRateLimitKey(rotated))
+ expect(externalClientSessionRateLimitKey(first)).not.toBe(
+ externalClientSessionRateLimitKey(rotated)
+ )
+ // The legacy export is intentionally the session dimension, not the IP
+ // ceiling; route factories install both gates together.
+ expect(externalClientRateLimitKey(first)).toBe(externalClientSessionRateLimitKey(first))
+ })
+
+ it('enforces the shared source-IP ceiling across rotated session tokens', async () => {
+ const app = express()
+ const [sourceIpLimiter, sessionLimiter] = createExternalClientRateLimiters('identity-test', 2)
+ app.use('/external/identity-test', sourceIpLimiter, sessionLimiter, (_req, res) => {
+ res.sendStatus(204)
+ })
+
+ for (const token of ['session-one', 'session-two']) {
+ await supertest(app)
+ .get('/external/identity-test')
+ .set('x-external-client-ip', '203.0.113.41')
+ .set('x-user-session-token', token)
+ .expect(204)
+ }
+ await supertest(app)
+ .get('/external/identity-test')
+ .set('x-external-client-ip', '203.0.113.41')
+ .set('x-user-session-token', 'session-three')
+ .expect(429)
+ })
+
+ it('keeps the source-IP ceiling wider than the per-session fairness bucket', async () => {
+ const app = express()
+ const [sourceIpLimiter, sessionLimiter] = createExternalClientRateLimiters(
+ 'identity-width-test',
+ 3,
+ 2
+ )
+ app.use('/external/identity-width-test', sourceIpLimiter, sessionLimiter, (_req, res) => {
+ res.sendStatus(204)
+ })
+
+ await supertest(app)
+ .get('/external/identity-width-test')
+ .set('x-external-client-ip', '203.0.113.42')
+ .set('x-user-session-token', 'same-session')
+ .expect(204)
+ await supertest(app)
+ .get('/external/identity-width-test')
+ .set('x-external-client-ip', '203.0.113.42')
+ .set('x-user-session-token', 'same-session')
+ .expect(204)
+ await supertest(app)
+ .get('/external/identity-width-test')
+ .set('x-external-client-ip', '203.0.113.42')
+ .set('x-user-session-token', 'rotated-session')
+ .expect(204)
+ await supertest(app)
+ .get('/external/identity-width-test')
+ .set('x-external-client-ip', '203.0.113.42')
+ .set('x-user-session-token', 'third-session')
+ .expect(429)
})
})
diff --git a/control-api/test/services.adminAuthDelete.test.ts b/control-api/test/services.adminAuthDelete.test.ts
new file mode 100644
index 000000000..18d7387ae
--- /dev/null
+++ b/control-api/test/services.adminAuthDelete.test.ts
@@ -0,0 +1,118 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const state = vi.hoisted(() => ({
+ targetStatus: 'active' as 'active' | 'disabled',
+ queries: [] as string[],
+}))
+
+const linkService = vi.hoisted(() => ({
+ retireParentInTransaction: vi.fn(),
+}))
+
+const eventService = vi.hoisted(() => ({
+ appendInTransaction: vi.fn(),
+}))
+
+const db = vi.hoisted(() => ({
+ withTransaction: vi.fn(),
+ pool: { query: vi.fn() },
+}))
+
+vi.mock('../src/config.js', () => ({
+ config: { adminJwtIssuer: 'test-issuer', adminJwtAudience: 'test-audience' },
+}))
+vi.mock('../src/db.js', () => db)
+vi.mock('../src/observability/logger.js', () => ({ rootLogger: { warn: vi.fn() } }))
+vi.mock('../src/services/gfsDesktopOperatorLinkService.js', () => ({
+ gfsDesktopOperatorLinkService: linkService,
+}))
+vi.mock('../src/services/tracing/adminOperationContext.js', () => ({
+ currentAdministrativeRequestContext: vi.fn(() => null),
+}))
+vi.mock('../src/services/tracing/administrativeEvents.js', () => ({
+ AdministrativeEventService: class {
+ appendInTransaction = eventService.appendInTransaction
+ },
+}))
+vi.mock('../src/services/tracing/controlApiLocalAdministrativeBindingResolver.js', () => ({
+ CONTROL_API_LOCAL_ADMINISTRATIVE_PRINCIPAL_V1: { kind: 'control_api_local' },
+}))
+vi.mock('../src/services/tracing/environment.js', () => ({
+ canonicalTracingEnvironment: vi.fn(() => 'test'),
+}))
+
+function queryResult(text: string) {
+ state.queries.push(text)
+ if (text.includes('FOR UPDATE') && text.includes('status')) {
+ return {
+ rows:
+ state.targetStatus === 'active'
+ ? [
+ {
+ id: 'target-admin',
+ username: 'target',
+ email: '[email protected]',
+ status: 'active',
+ },
+ ]
+ : [
+ {
+ id: 'target-admin',
+ username: 'target',
+ email: '[email protected]',
+ status: 'disabled',
+ },
+ ],
+ rowCount: 1,
+ }
+ }
+ if (text.includes('SELECT id, username, email')) {
+ return {
+ rows: [{ id: 'actor-admin', username: 'actor', email: '[email protected]' }],
+ rowCount: 1,
+ }
+ }
+ if (text.includes('UPDATE control_admin_users')) {
+ if (state.targetStatus === 'disabled') return { rows: [], rowCount: 0 }
+ state.targetStatus = 'disabled'
+ return {
+ rows: [{ id: 'target-admin', username: 'target', email: '[email protected]' }],
+ rowCount: 1,
+ }
+ }
+ if (text.includes('INSERT INTO control_admin_deletion_audit')) {
+ return { rows: [{ id: 'audit-1' }], rowCount: 1 }
+ }
+ throw new Error(`unexpected query in test: ${text}`)
+}
+
+describe('deleteControlAdmin lifecycle transition', () => {
+ beforeEach(() => {
+ state.targetStatus = 'active'
+ state.queries = []
+ db.withTransaction.mockImplementation(
+ async (callback: (tx: { query: typeof queryResult }) => unknown) =>
+ callback({ query: async (text: string) => queryResult(text) })
+ )
+ linkService.retireParentInTransaction.mockReset().mockResolvedValue(true)
+ eventService.appendInTransaction.mockReset().mockResolvedValue(undefined)
+ })
+
+ it('makes repeated retirement idempotent and emits one lifecycle side effect', async () => {
+ const { deleteControlAdmin } = await import('../src/services/adminAuthService.js')
+
+ await expect(deleteControlAdmin('actor-admin', 'target-admin')).resolves.toEqual({
+ deleted: true,
+ })
+ await expect(deleteControlAdmin('actor-admin', 'target-admin')).resolves.toEqual({
+ error: 'not_found',
+ })
+
+ expect(state.queries.filter(query => query.includes('FOR UPDATE'))).toHaveLength(2)
+ expect(
+ state.queries.some(query => query.includes("WHERE id = $1\n AND status = 'active'"))
+ ).toBe(true)
+ expect(linkService.retireParentInTransaction).toHaveBeenCalledOnce()
+ expect(eventService.appendInTransaction).toHaveBeenCalledOnce()
+ })
+})
diff --git a/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts b/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts
index 7ea2e4b33..995cae0e0 100644
--- a/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts
+++ b/control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts
@@ -3,6 +3,7 @@ import { randomBytes, randomUUID } from 'node:crypto'
import { Pool } from 'pg'
import { initDb, pool } from '../src/db.js'
import { retireDesktopUser } from '../src/services/directory/users.js'
+import { gfsDesktopOperatorLinkService } from '../src/services/gfsDesktopOperatorLinkService.js'
const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
const describeRealPostgres = adminUrl ? describe : describe.skip
@@ -174,4 +175,73 @@ describeRealPostgres('retireDesktopUser on real PostgreSQL', () => {
},
])
})
+
+ it('retires a user after the Control UI already revoked the link without changing the tombstone', async () => {
+ const userId = await seedDesktopUser('revoked-before-retire')
+ const linkId = randomUUID()
+ const lineageId = randomUUID()
+ await testPool.query(
+ `INSERT INTO gfs_desktop_operator_links
+ (id, lineage_id, generation, user_id, control_admin_id, state, source, created_by, row_version)
+ VALUES ($1::uuid, $2::uuid, 1, $3::uuid, $4::uuid,
+ 'active', 'initial_setup', $4::uuid, 1)`,
+ [linkId, lineageId, userId, actorId]
+ )
+
+ const revoked = await gfsDesktopOperatorLinkService.unlink({
+ desktopUserId: userId,
+ controlAdminId: actorId,
+ operatorSub: actorId,
+ rowVersion: 1,
+ reason: 'control_ui_revoke_before_retire',
+ requestId: 'real-pg-revoke-before-retire',
+ })
+ expect(revoked.unlinked).toBe(true)
+
+ const result = await retireDesktopUser(
+ { kind: 'control_admin', controlAdminId: actorId },
+ userId,
+ 'retire after prior operator revoke',
+ 'real-pg-revoke-before-retire-v1',
+ 'retirement-after-revoke-request-v1'
+ )
+ expect(result).toMatchObject({ id: userId, outcome: 'retired', lifecycleVersion: 2 })
+
+ const [user, link] = await Promise.all([
+ testPool.query(
+ `SELECT lifecycle_state, lifecycle_version, retirement_operation_id::text AS retirement_operation_id
+ FROM users WHERE id = $1::uuid`,
+ [userId]
+ ),
+ testPool.query(
+ `SELECT id::text AS id, lineage_id::text AS lineage_id, generation, state, row_version
+ FROM gfs_desktop_operator_links WHERE user_id = $1::uuid`,
+ [userId]
+ ),
+ ])
+ expect(user.rows).toEqual([
+ {
+ lifecycle_state: 'retired',
+ lifecycle_version: '2',
+ retirement_operation_id: expect.any(String),
+ },
+ ])
+ expect(link.rows).toEqual([
+ { id: linkId, lineage_id: lineageId, generation: 1, state: 'revoked', row_version: '2' },
+ ])
+
+ const events = await testPool.query(
+ `SELECT action, target_ref, payload_metadata->>'detail_ref' AS detail_ref
+ FROM administrative_events
+ WHERE operation_id = $1::uuid
+ ORDER BY ingest_sequence ASC`,
+ [user.rows[0].retirement_operation_id]
+ )
+ expect(events.rows).toHaveLength(1)
+ expect(events.rows[0]).toMatchObject({
+ action: 'permission_revoke',
+ target_ref: `desktop_user:${userId}`,
+ })
+ expect(events.rows[0].detail_ref).toContain('event:parent.retired')
+ })
})
diff --git a/control-api/test/services.directory.userRetirement.test.ts b/control-api/test/services.directory.userRetirement.test.ts
index aea7e7aae..6a64d6b35 100644
--- a/control-api/test/services.directory.userRetirement.test.ts
+++ b/control-api/test/services.directory.userRetirement.test.ts
@@ -251,25 +251,32 @@ describe('retireDesktopUser', () => {
expect(String(mocks.txQuery.mock.calls[6]?.[0])).toContain("outcome = 'deleted'")
})
- it('fails closed for retained tombstone history with no active generation', async () => {
+ it('retires a user after the Control UI already revoked the operator 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)
+ .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,
- 'tombstone cannot be retired twice',
+ 'retire after operator revoke',
'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(
+ ).resolves.toMatchObject({
+ id: USER_ID,
+ outcome: 'retired',
+ operationId: OPERATION_ID,
+ lifecycleVersion: 2,
+ replayed: false,
+ })
+ expect(mocks.txQuery.mock.calls.map(([sql]) => String(sql))).toEqual(
expect.arrayContaining([expect.stringContaining("lifecycle_state = 'retired'")])
)
})
diff --git a/control-api/test/services.gfsDesktopOperatorLinkService.test.ts b/control-api/test/services.gfsDesktopOperatorLinkService.test.ts
index d0e7c2dd0..778a17e25 100644
--- a/control-api/test/services.gfsDesktopOperatorLinkService.test.ts
+++ b/control-api/test/services.gfsDesktopOperatorLinkService.test.ts
@@ -266,6 +266,45 @@ describe('GfsDesktopOperatorLinkService', () => {
])
})
+ it('retains an existing tombstone and emits only parent retirement evidence', async () => {
+ txQuery.mockResolvedValueOnce({
+ rows: [
+ {
+ ...storedLink(),
+ id: '88888888-8888-4888-8888-888888888888',
+ lineage_id: '99999999-9999-4999-8999-999999999999',
+ generation: 1,
+ state: 'revoked',
+ row_version: 2,
+ revoked_at: new Date('2026-08-10T12:05:00.000Z'),
+ revocation_reason: 'control_ui_revoke',
+ },
+ ],
+ rowCount: 1,
+ })
+
+ await expect(
+ service.retireParentInTransaction({ query: txQuery } as DbClient, {
+ kind: 'desktop_user',
+ parentId: DESKTOP_USER_ID,
+ actor: { kind: 'control_admin', controlAdminId: OPERATOR_ID },
+ reason: 'account_retired_after_revoke',
+ requestId: 'request-tombstone',
+ })
+ ).resolves.toBe(true)
+
+ expect(appendPermissionEvents).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ changes: [
+ expect.objectContaining({ detailRef: expect.stringContaining('event:parent.retired') }),
+ ],
+ })
+ )
+ expect(txQuery).toHaveBeenCalledOnce()
+ expect(String(txQuery.mock.calls[0]?.[0])).toContain('ORDER BY generation DESC')
+ })
+
it.each([
{
label: 'Desktop user',
diff --git a/control-ui/components/ControlAdminsPanel/index.tsx b/control-ui/components/ControlAdminsPanel/index.tsx
index 4de5cab01..5a2c3c3cd 100644
--- a/control-ui/components/ControlAdminsPanel/index.tsx
+++ b/control-ui/components/ControlAdminsPanel/index.tsx
@@ -104,8 +104,13 @@ export function ControlAdminsPanel({
}, [invitations, normalizedSearch])
const filteredAdmins = useMemo(() => {
- if (!normalizedSearch) return admins
- return admins.filter(admin =>
+ // Disabled admins are retained for audit/lifecycle history, but they are
+ // not part of the operational admin list. Keeping them here would make a
+ // refresh re-expose Delete, member-access, and GFS-reactivation actions
+ // that the server correctly refuses after retirement.
+ const operationalAdmins = admins.filter(admin => admin.status !== 'disabled')
+ if (!normalizedSearch) return operationalAdmins
+ return operationalAdmins.filter(admin =>
[admin.username, admin.email, admin.status]
.filter((value): value is string => typeof value === 'string')
.some(value => value.toLowerCase().includes(normalizedSearch))
diff --git a/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx b/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx
index 6517cea67..6a4792304 100644
--- a/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx
+++ b/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx
@@ -161,6 +161,34 @@ describe('ControlAdminsPanel GFS operator link lifecycle', () => {
expect(await screen.findByTestId('gfs-operator-link-admin-2')).toHaveTextContent('Not linked')
})
+ it('keeps disabled admin tombstones out of the operational action list after refresh', async () => {
+ vi.mocked(getControlAdmins).mockResolvedValueOnce({
+ admins: [
+ {
+ id: 'disabled-admin',
+ username: 'retired-admin',
+ email: '[email protected]',
+ memberId: LINK.desktopUserId,
+ status: 'disabled',
+ gfsOperatorLink: { ...LINK, controlAdminId: 'disabled-admin', status: 'revoked' },
+ gfsOperatorLinkStatus: 'revoked',
+ lastLoginAt: null,
+ createdAt: '2026-08-10T11:00:00.000Z',
+ },
+ ],
+ invitations: [],
+ })
+
+ render(<ControlAdminsPanel />)
+ await waitFor(() => expect(getControlAdmins).toHaveBeenCalled())
+ expect(screen.queryByText('retired-admin')).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', {
+ name: /Reactivate Desktop GFS operator access for retired-admin/,
+ })
+ ).not.toBeInTheDocument()
+ })
+
it('reactivates a retained revoked generation through the visible Control UI action', async () => {
vi.mocked(getControlAdmins).mockResolvedValueOnce({
admins: [
diff --git a/desktop-app/ui/src/components/GfsImagePreview/index.tsx b/desktop-app/ui/src/components/GfsImagePreview/index.tsx
index 813d5bffa..57e0b9d1c 100644
--- a/desktop-app/ui/src/components/GfsImagePreview/index.tsx
+++ b/desktop-app/ui/src/components/GfsImagePreview/index.tsx
@@ -11,6 +11,7 @@ export function GfsImagePreview({
gfsUri,
mimeType,
onClose,
+ onDownloadError,
}: GfsImagePreviewProps) {
const titleId = useId()
const closeButtonRef = useRef<HTMLButtonElement | null>(null)
@@ -40,6 +41,7 @@ export function GfsImagePreview({
setPreviewUrl(objectUrl)
} catch (error) {
if (!active) return
+ onDownloadError?.(error)
setPreviewError(error instanceof Error ? error.message : 'Could not load the image preview')
}
}
@@ -49,7 +51,7 @@ export function GfsImagePreview({
active = false
if (objectUrl) URL.revokeObjectURL(objectUrl)
}
- }, [byteLength, gfsUri, mimeType])
+ }, [byteLength, gfsUri, mimeType, onDownloadError])
return createPortal(
<div
diff --git a/desktop-app/ui/src/components/GfsImagePreview/types.ts b/desktop-app/ui/src/components/GfsImagePreview/types.ts
index 6e5ed9d51..bac51aef6 100644
--- a/desktop-app/ui/src/components/GfsImagePreview/types.ts
+++ b/desktop-app/ui/src/components/GfsImagePreview/types.ts
@@ -4,4 +4,5 @@ export type GfsImagePreviewProps = {
gfsUri: string
mimeType: string
onClose: () => void
+ onDownloadError?: (error: unknown) => void
}
diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx
index 4d9ec9ea3..e27c37b60 100644
--- a/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx
+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx
@@ -61,6 +61,7 @@ export function GfsMarkdownPreview({
fileName,
gfsUri,
onClose,
+ onDownloadError,
}: GfsMarkdownPreviewProps) {
const titleId = useId()
const closeButtonRef = useRef<HTMLButtonElement | null>(null)
@@ -89,6 +90,7 @@ export function GfsMarkdownPreview({
if (active) setSource(markdown)
} catch (error) {
if (!active) return
+ onDownloadError?.(error)
setPreviewError(
error instanceof Error ? error.message : 'Could not load the Markdown preview'
)
@@ -99,7 +101,7 @@ export function GfsMarkdownPreview({
return () => {
active = false
}
- }, [byteLength, gfsUri])
+ }, [byteLength, gfsUri, onDownloadError])
return createPortal(
<div
diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/types.ts b/desktop-app/ui/src/components/GfsMarkdownPreview/types.ts
index 42fd56af5..a35970ca1 100644
--- a/desktop-app/ui/src/components/GfsMarkdownPreview/types.ts
+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/types.ts
@@ -3,4 +3,5 @@ export type GfsMarkdownPreviewProps = {
fileName: string
gfsUri: string
onClose: () => void
+ onDownloadError?: (error: unknown) => void
}
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
index 9be8f5680..2464f1850 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
@@ -210,8 +210,9 @@ describe('useGfsBrowserController', () => {
['403 Forbidden: escalation_rejected', false],
['403 Forbidden: foreign_agent_forbidden', false],
['403 Forbidden: operator_link_inactive', true],
+ ['401 Unauthorized', true],
] as const)(
- 'distinguishes per-operation 403s from session authority (%s)',
+ 'distinguishes resource policy verdicts from session authority (%s)',
(message, expected) => {
expect(isGfsSessionAuthorityFailure(message, 'operation')).toBe(expected)
}
@@ -460,11 +461,26 @@ describe('useGfsBrowserController', () => {
expect(screen.getByTestId('current').textContent).toBe('none')
})
- it('clears cached operator state after a 403 and retries only through fresh server discovery', async () => {
+ it('downgrades a revoked operator link to ordinary user scope through fresh discovery', async () => {
const rootResourceId = '11111111-1111-1111-1111-111111111111'
- let active = true
+ const ordinaryResource = {
+ resourceId: '33333333-3333-4333-8333-333333333333',
+ rid: '33333333333343338333333333333333',
+ gfsUri: 'gfs://main/33333333333343338333333333333333',
+ name: 'Shared report.md',
+ kind: 'file' as const,
+ path: '/Shared report.md',
+ version: 1,
+ bytes: 12,
+ permissions: ['read'],
+ }
+ let state: 'operator' | 'revoking' | 'ordinary' = 'operator'
const listAccessible = vi.fn(async () => {
- if (!active) throw new Error('403 operator_link_inactive')
+ if (state === 'revoking') {
+ state = 'ordinary'
+ throw new Error('403 operator_link_inactive')
+ }
+ if (state === 'ordinary') return { items: [ordinaryResource], nextCursor: null }
return { items: [], nextCursor: null, rootResourceId, view: 'operator' as const }
})
Object.defineProperty(window, 'clerum', {
@@ -487,19 +503,51 @@ describe('useGfsBrowserController', () => {
render(<Probe />, { wrapper: Harness })
await waitFor(() => expect(screen.getByTestId('operator-root').textContent).toBe('yes'))
- active = false
+ state = 'revoking'
await act(async () => {
screen.getByRole('button', { name: 'reset browser' }).click()
})
- await waitFor(() => expect(screen.getByTestId('access-state').textContent).toBe('revoked'))
+ await waitFor(() => expect(screen.getByTestId('access-state').textContent).toBe('active'))
+ await waitFor(() => expect(screen.getByTestId('view').textContent).toBe('shared'))
expect(screen.getByTestId('current').textContent).toBe('none')
- expect(screen.getByTestId('accessible-count').textContent).toBe('0')
+ await waitFor(() => expect(screen.getByTestId('accessible-count').textContent).toBe('1'))
+ expect(screen.getByTestId('operator-root').textContent).toBe('no')
+ expect(listAccessible).toHaveBeenCalledTimes(3)
+ })
- active = true
- await act(async () => {
- screen.getByRole('button', { name: 'retry access' }).click()
+ it('fails closed after a second lifecycle denial instead of retrying forever', async () => {
+ const rootResourceId = '11111111-1111-1111-1111-111111111111'
+ let deny = false
+ const listAccessible = vi.fn(async () => {
+ if (deny) throw new Error('403 operator_link_inactive')
+ return { items: [], nextCursor: null, rootResourceId, view: 'operator' as const }
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible,
+ resolve: vi.fn(),
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances: vi.fn(async () => ({
+ held: ['read'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ })),
+ },
+ },
})
+
+ render(<Probe />, { wrapper: Harness })
await waitFor(() => expect(screen.getByTestId('operator-root').textContent).toBe('yes'))
+
+ deny = true
+ await act(async () => {
+ screen.getByRole('button', { name: 'reset browser' }).click()
+ })
+
+ await waitFor(() => expect(screen.getByTestId('access-state').textContent).toBe('revoked'))
expect(listAccessible).toHaveBeenCalledTimes(3)
})
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index 5ab683d21..e9e37bd62 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -149,6 +149,11 @@ export function isGfsSessionAuthorityFailure(
)
}
+/** A revoked operator link downgrades an active Desktop session to user scope. */
+export function isGfsOperatorLinkRevocation(message: string): boolean {
+ return message.toLowerCase().includes('operator_link_inactive')
+}
+
/** Stable user-facing state for root/folder read failures crossing Electron IPC. */
export function describeGfsBrowserFailure(message: string): GfsBrowserFailure {
if (isUninitializedDriveError(message)) {
@@ -209,6 +214,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
// capability decision: a later server-backed request is the only way out.
const [accessState, setAccessState] = useState<GfsBrowserAccessState>('active')
const previousSessionScopeRef = useRef<string | null>(null)
+ const operatorViewRef = useRef(false)
+ const operatorRecoveryAttemptedRef = useRef(false)
const current = crumbs.length ? crumbs[crumbs.length - 1] : null
const currentIsDirectory = current?.kind === 'directory'
@@ -230,6 +237,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
setCrumbs([])
setOpenError(null)
setAccessState('active')
+ operatorViewRef.current = false
+ operatorRecoveryAttemptedRef.current = false
void queryClient.removeQueries({ queryKey: [...desktopQueryKeys.gfsRoot, previous] })
}
}, [queryClient, sessionScope])
@@ -265,6 +274,21 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
() => (operatorRootResourceId ? rootCrumb(operatorRootResourceId) : null),
[operatorRootResourceId]
)
+
+ useEffect(() => {
+ if (view === 'operator') {
+ const wasOperator = operatorViewRef.current
+ operatorViewRef.current = true
+ // A successful operator discovery starts a fresh recovery cycle. Do not
+ // reset the guard on every render while stale operator data is still
+ // visible after a failed discovery; the next lifecycle denial must then
+ // fail closed instead of retrying indefinitely.
+ if (!wasOperator && firstAccessiblePage) operatorRecoveryAttemptedRef.current = false
+ } else if (view === 'shared' && accessState === 'active' && firstAccessiblePage) {
+ operatorViewRef.current = false
+ operatorRecoveryAttemptedRef.current = false
+ }
+ }, [accessState, firstAccessiblePage, view])
const rootContractError =
firstAccessiblePage?.view === 'operator' && !operatorRoot
? 'operator_root_missing: operator view did not include a valid rootResourceId'
@@ -360,8 +384,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
enabled:
Boolean(sessionScope) && Boolean(current) && grantsListEnabled && accessState === 'active',
})
- const revokeAccess = useCallback(() => {
- setAccessState('revoked')
+ const clearGfsState = useCallback(() => {
setCrumbs([])
setOpenError(null)
// Remove every GFS response for this Desktop session. In particular, never
@@ -369,17 +392,37 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
// revocation response.
queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
}, [queryClient])
+ const revokeAccess = useCallback(() => {
+ setAccessState('revoked')
+ clearGfsState()
+ }, [clearGfsState])
+ const downgradeToOrdinaryUser = useCallback(() => {
+ // A link revoke removes only operator authority. The authenticated Desktop
+ // user remains eligible for explicitly shared GFS resources, so clear the
+ // operator cache and let fresh discovery resolve the user view.
+ setAccessState('active')
+ clearGfsState()
+ }, [clearGfsState])
+ const handleAuthorityFailure = useCallback(
+ (message: string, surface: 'discovery' | 'operation' = 'operation'): boolean => {
+ if (!isGfsSessionAuthorityFailure(message, surface)) return false
+ if (isGfsOperatorLinkRevocation(message) && !operatorRecoveryAttemptedRef.current) {
+ operatorRecoveryAttemptedRef.current = true
+ downgradeToOrdinaryUser()
+ } else revokeAccess()
+ return true
+ },
+ [downgradeToOrdinaryUser, revokeAccess]
+ )
const retryAccess = useCallback(() => {
// This does not restore a local capability. It only permits the normal
// discovery request to run again, so an explicit server-side reactivation
// remains the sole authority that can restore the operator root.
setAccessState('active')
}, [])
- // Root discovery is a session/authority boundary. A children request is a
- // per-resource read: a generic 401/403 there can mean that one shared
- // folder was revoked while the rest of the session remains valid. Only
- // explicit lifecycle codes may revoke from that surface; do not collapse
- // the entire browser state for a resource-scoped policy denial.
+ // Root discovery is a session/authority boundary. A resource-scoped 403 is
+ // a policy verdict and must remain local, while a 401 still means the
+ // authenticated session is no longer accepted and revokes session state.
const queryAuthorizationError = [
accessibleQuery.error
? { message: toMessage(accessibleQuery.error), surface: 'discovery' as const }
@@ -387,14 +430,37 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
childrenQuery.error
? { message: toMessage(childrenQuery.error), surface: 'operation' as const }
: null,
+ affordancesQuery.error
+ ? { message: toMessage(affordancesQuery.error), surface: 'operation' as const }
+ : null,
+ grantsQuery.error
+ ? { message: toMessage(grantsQuery.error), surface: 'operation' as const }
+ : null,
+ sharesQuery.error
+ ? { message: toMessage(sharesQuery.error), surface: 'operation' as const }
+ : null,
]
.filter(
(entry): entry is { message: string; surface: 'discovery' | 'operation' } => entry !== null
)
.find(entry => isGfsSessionAuthorityFailure(entry.message, entry.surface))
useEffect(() => {
- if (queryAuthorizationError && accessState !== 'revoked') revokeAccess()
- }, [accessState, queryAuthorizationError, revokeAccess])
+ if (!queryAuthorizationError || accessState === 'revoked') return
+ const genericOperatorDiscoveryFailure =
+ queryAuthorizationError.surface === 'discovery' &&
+ operatorViewRef.current &&
+ !/(^|\D)401(\D|$)/.test(queryAuthorizationError.message.toLowerCase())
+ if (
+ (genericOperatorDiscoveryFailure ||
+ isGfsOperatorLinkRevocation(queryAuthorizationError.message)) &&
+ !operatorRecoveryAttemptedRef.current
+ ) {
+ operatorRecoveryAttemptedRef.current = true
+ downgradeToOrdinaryUser()
+ return
+ }
+ revokeAccess()
+ }, [accessState, downgradeToOrdinaryUser, queryAuthorizationError, revokeAccess])
const refreshShares = useCallback(async () => {
const resourceId = current?.resourceId
if (!resourceId) return
@@ -546,14 +612,13 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
// Opening a URI is an operation on one resource. A generic 403 may be
// a per-resource policy decision; only typed lifecycle failures or a
// bare 401 invalidate the session-wide authority state.
- if (isGfsSessionAuthorityFailure(message, 'operation')) revokeAccess()
- else setOpenError(message)
+ if (!handleAuthorityFailure(message, 'operation')) setOpenError(message)
return false
} finally {
setResolving(false)
}
},
- [operatorRoot, revokeAccess]
+ [handleAuthorityFailure, operatorRoot]
)
const openChild = useCallback((child: GfsBrowserChild) => {
@@ -659,6 +724,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
goToCrumb,
reset,
revokeAccess,
+ downgradeToOrdinaryUser,
+ handleAuthorityFailure,
retryAccess,
refreshAffordances,
grant,
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 447cf59b6..b70d583c8 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -1,4 +1,11 @@
-import { type DragEvent as ReactDragEvent, useEffect, useMemo, useRef, useState } from 'react'
+import {
+ type DragEvent as ReactDragEvent,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react'
import { useQuery } from '@tanstack/react-query'
import { Button, EmptyState, IconButton, StatusBanner, TextInput } from '@components/Common'
import { GfsImagePreview } from '@components/GfsImagePreview'
@@ -16,7 +23,6 @@ import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import {
type GfsBrowserFailure,
describeGfsBrowserFailure,
- isGfsSessionAuthorityFailure,
useGfsBrowserController,
} from '@hooks/domain/useGfsBrowserController'
import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'
@@ -143,6 +149,15 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
const uploadInputRef = useRef<HTMLInputElement | null>(null)
const replaceInputRef = useRef<HTMLInputElement | null>(null)
const ctrl = useGfsBrowserController({ grantsListEnabled: manageOpen })
+ const handlePreviewDownloadError = useCallback(
+ (error: unknown) => {
+ ctrl.handleAuthorityFailure(
+ error instanceof Error ? error.message : String(error),
+ 'operation'
+ )
+ },
+ [ctrl.handleAuthorityFailure]
+ )
const {
current,
crumbs,
@@ -258,8 +273,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
const surfaceContentMutationError = (mutationError: unknown) => {
const raw = mutationError instanceof Error ? mutationError.message : String(mutationError)
const failure = describeGfsBrowserFailure(raw)
- if (isGfsSessionAuthorityFailure(raw, 'operation')) {
- ctrl.revokeAccess()
+ if (ctrl.handleAuthorityFailure(raw, 'operation')) {
setMutationFailure(failure)
pushToast?.(failure.message, 'error')
return
@@ -312,7 +326,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
// forced false for files by the panel.
const failClosedOnAuthorizationError = (error: unknown): never => {
const message = error instanceof Error ? error.message : String(error)
- if (isGfsSessionAuthorityFailure(message, 'operation')) ctrl.revokeAccess()
+ ctrl.handleAuthorityFailure(message, 'operation')
throw error
}
const handleGrant = async (subjectKeys: string[], bits: string[], inherit: boolean) => {
@@ -334,7 +348,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
await ctrl.revokeGrant(grantId)
pushToast?.(`Access revoked for ${label}`, 'success')
} catch (revokeError) {
- if (isGfsSessionAuthorityFailure(String(revokeError), 'operation')) ctrl.revokeAccess()
+ ctrl.handleAuthorityFailure(String(revokeError), 'operation')
pushToast?.(describeGfsGrantError(revokeError).message, 'error')
}
}
@@ -357,7 +371,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
await ctrl.revokeShare(shareId)
pushToast?.(`Shared access revoked for ${label}`, 'success')
} catch (revokeError) {
- if (isGfsSessionAuthorityFailure(String(revokeError), 'operation')) ctrl.revokeAccess()
+ ctrl.handleAuthorityFailure(String(revokeError), 'operation')
pushToast?.(describeGfsGrantError(revokeError).message, 'error')
}
}
@@ -372,8 +386,12 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
anchor.click()
setTimeout(() => URL.revokeObjectURL(url), 10_000)
pushToast?.(`Downloaded ${name}`, 'success')
- } catch (uploadError) {
- pushToast?.(uploadError instanceof Error ? uploadError.message : String(uploadError), 'error')
+ } catch (downloadError) {
+ ctrl.handleAuthorityFailure(String(downloadError), 'operation')
+ pushToast?.(
+ downloadError instanceof Error ? downloadError.message : String(downloadError),
+ 'error'
+ )
}
}
@@ -1264,6 +1282,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
gfsUri={filePreview.gfsUri}
mimeType={filePreview.mimeType}
onClose={() => setFilePreview(null)}
+ onDownloadError={handlePreviewDownloadError}
/>
) : null}
@@ -1273,6 +1292,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
fileName={filePreview.name}
gfsUri={filePreview.gfsUri}
onClose={() => setFilePreview(null)}
+ onDownloadError={handlePreviewDownloadError}
/>
) : null}
</section>
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index a0782edd0..ff6951133 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -6,7 +6,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testi
import { GFS_FILE_UPLOAD_MAX_BYTES } from '@constants/gfsFileUpload'
import { GFS_IMAGE_PREVIEW_MAX_BYTES } from '@constants/gfsImagePreview'
import { GFS_MARKDOWN_PREVIEW_MAX_BYTES } from '@constants/gfsMarkdownPreview'
-import type { GfsCrumb } from '@hooks/domain/useGfsBrowserController'
+import { type GfsCrumb, isGfsSessionAuthorityFailure } from '@hooks/domain/useGfsBrowserController'
import type { Tone } from '@/uiTypes'
import { FilesPage } from '../FilesPage'
@@ -20,6 +20,7 @@ vi.mock('@hooks/domain/useGfsBrowserController', async importOriginal => ({
}))
function baseController() {
+ const revokeAccess = vi.fn()
return {
current: null,
crumbs: [],
@@ -69,7 +70,14 @@ function baseController() {
deleteResource: vi.fn(),
mutating: false,
reset: vi.fn(),
- revokeAccess: vi.fn(),
+ revokeAccess,
+ handleAuthorityFailure: vi.fn(
+ (message: string, surface: 'discovery' | 'operation' = 'operation') => {
+ const handled = isGfsSessionAuthorityFailure(message, surface)
+ if (handled) revokeAccess()
+ return handled
+ }
+ ),
retryAccess: vi.fn(),
refreshAffordances: vi.fn(),
}
@@ -296,6 +304,50 @@ describe('FilesPage', () => {
}
)
+ it('keeps the session and mutation controls after a resource-scoped 403', async () => {
+ const rootResourceId = '11111111-1111-1111-1111-111111111111'
+ const createFolder = vi.fn(async () => {
+ throw new Error('403 Forbidden: manage_acl_required')
+ })
+ const revokeAccess = vi.fn()
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ view: 'operator',
+ isOperatorRoot: true,
+ current: {
+ resourceId: rootResourceId,
+ gfsUri: 'gfs://main/11111111111111111111111111111111',
+ name: 'Global File System',
+ kind: 'directory',
+ version: 0,
+ bytes: 0,
+ isDriveRoot: true,
+ },
+ affordances: {
+ held: ['read', 'write', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read', 'write', 'manage_acl'],
+ canCreateShare: true,
+ },
+ createFolder,
+ revokeAccess,
+ })
+
+ renderFilesPage(pushToast)
+ fireEvent.click(screen.getByTestId('gfs-create-folder-action'))
+ const form = screen.getByRole('form', { name: 'Create folder' })
+ fireEvent.change(screen.getByLabelText('Folder name'), { target: { value: 'Denied' } })
+ fireEvent.click(form.querySelector('button[type="submit"]')!)
+
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith('403 Forbidden: manage_acl_required', 'error')
+ )
+ expect(revokeAccess).not.toHaveBeenCalled()
+ expect(screen.getByRole('form', { name: 'Create folder' })).toBeTruthy()
+ expect(screen.getByTestId('gfs-manage-access-action')).toBeTruthy()
+ })
+
it.each([
['unauthorized', '403 Forbidden: operator_link_inactive', 'File access is not authorized'],
['upstream', '502 Bad Gateway: gfsc_unreachable', 'Global File System is unavailable'],
@@ -1391,6 +1443,52 @@ describe('FilesPage', () => {
expect(revokeObjectURL).toHaveBeenCalledWith('blob:gfs-download')
})
+ it('revokes browser authority when a download reports a session failure', async () => {
+ const download = vi.fn(async () => {
+ throw new Error('401 Unauthorized')
+ })
+ const revokeAccess = vi.fn()
+ const pushToast = vi.fn()
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { download } },
+ })
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ revokeAccess,
+ handleAuthorityFailure: vi.fn(
+ (message: string, surface: 'discovery' | 'operation' = 'operation') => {
+ const handled = isGfsSessionAuthorityFailure(message, surface)
+ if (handled) revokeAccess()
+ return handled
+ }
+ ),
+ accessibleResources: [
+ {
+ resourceId: 'file-1',
+ rid: 'file-1',
+ gfsUri: 'gfs://main/file-1',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'report.pdf',
+ kind: 'file',
+ path: '/report.pdf',
+ version: 0,
+ bytes: 3,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: false,
+ },
+ ],
+ })
+
+ renderFilesPage(pushToast)
+ fireEvent.click(screen.getByRole('button', { name: 'Download report.pdf' }))
+
+ await waitFor(() => expect(revokeAccess).toHaveBeenCalledOnce())
+ expect(pushToast).toHaveBeenCalledWith('401 Unauthorized', 'error')
+ })
+
it('previews an image file in a closable modal without downloading it to disk', async () => {
const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
const createObjectURL = vi.fn(() => 'blob:gfs-image-preview')
diff --git a/docs/architecture/gfs-desktop-operator-parity.md b/docs/architecture/gfs-desktop-operator-parity.md
index d1e8f65d8..742f93812 100644
--- a/docs/architecture/gfs-desktop-operator-parity.md
+++ b/docs/architecture/gfs-desktop-operator-parity.md
@@ -64,22 +64,47 @@ header coherence are tracked as independent global follow-ups:
- [Issue #352](https://github.com/evenfire-ai/evenfire/issues/352)
- [Issue #353](https://github.com/evenfire-ai/evenfire/issues/353)
+The non-GFS external directory, team, member, invitation, workflow, decision,
+notification, and OAuth route families also retain two independent edge gates:
+the source-IP backstop is 1,200/min and the per-session fairness bucket is
+120/min; authenticated operation buckets remain at 60/min where the route
+defines them. The enforced hierarchy is `60 <= 120 < 1,200`. The IP gate is intentionally first, so rotating or malformed session
+tokens cannot evade the source-IP ceiling, while a shared NAT is not limited to
+the narrower per-session budget. These gates do not change the GFS
+read/mutation budgets above.
+
## Migration sequence
-| Migration | Responsibility |
-| --- | --- |
-| `0091_gfs_desktop_operator_links` | Explicit `initial_setup` Desktop/Admin relationship. |
-| `0092_gfs_audit_actor_correlation` | Desktop actor, effective admin, source, and request correlation. |
-| `0093_gfs_desktop_operator_link_generations` | Immutable generations, lineage, tombstones, CAS, and restrictive parent FKs. |
-| `0094_desktop_user_retirement_lifecycle` | Active/retired Desktop lifecycle, typed retirement actors, and idempotent outcomes. |
-| `0095_gfs_lifecycle_authority_projection` | GFSC lifecycle projection, readiness checks, and least-privilege reads. |
-| `0096_control_admin_session_version_default` | Safe session-generation defaults for existing Control Admin rows. |
+| Migration | Responsibility |
+| -------------------------------------------- | ----------------------------------------------------------------------------------- |
+| `0091_gfs_desktop_operator_links` | Explicit `initial_setup` Desktop/Admin relationship. |
+| `0092_gfs_audit_actor_correlation` | Desktop actor, effective admin, source, and request correlation. |
+| `0093_gfs_desktop_operator_link_generations` | Immutable generations, lineage, tombstones, CAS, and restrictive parent FKs. |
+| `0094_desktop_user_retirement_lifecycle` | Active/retired Desktop lifecycle, typed retirement actors, and idempotent outcomes. |
+| `0095_gfs_lifecycle_authority_projection` | GFSC lifecycle projection, readiness checks, and least-privilege reads. |
+| `0096_control_admin_session_version_default` | Safe session-generation defaults for existing Control Admin rows. |
The deployment pre-gate applies migrations in order, reconciles the runtime
roles and ACL manifest, verifies readiness, and only then exposes consumers.
Rollback disables new issuance and mutations; it does not down-migrate or
delete retained lifecycle evidence.
+## Rollout and compatibility contract
+
+The first deployment of generation-aware authority deliberately invalidates
+older external session tokens that do not carry `authGeneration`. Operators
+must expect an ordinary sign-in again after the rollout; this is a bounded
+security migration, not a legacy-token grace path. Deploy the Control API
+token producer only after the GFSC lifecycle projection and readiness gate are
+green, so a mixed fleet cannot issue claims an older data-plane verifier would
+silently ignore.
+
+The external member-retirement endpoint now requires a non-empty `reason` and
+an `Idempotency-Key`. First-party Profile UI callers send both values. Clients
+using the external API directly must adopt this contract before upgrading; the
+server does not synthesize an idempotency key because doing so would make a
+retry non-deterministic and could duplicate a retirement side effect.
+
## Validation surface
- Unit and integration suites cover setup, authority resolution, lifecycle
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index deae760e7..8e512a40f 100644
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.75",
+ "version": "0.1.76",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.75",
+ "version": "0.1.76",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 2b5f2fb80..604223d6d 100644
--- a/external-rest-api/package.json
+++ b/external-rest-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.75",
+ "version": "0.1.76",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index 76a00b2e0..b971ac89a 100644
--- a/external-rest-api/src/releaseManifest.ts
+++ b/external-rest-api/src/releaseManifest.ts
@@ -8,7 +8,7 @@ export type ReleaseManifest = {
export const releaseManifest: ReleaseManifest = {
releaseId: 'v0.7.0',
- externalRestApiVersion: '0.1.75',
+ externalRestApiVersion: '0.1.76',
rpcProxyVersion: '0.1.64',
desktopVersion: '0.7.0',
minimumDesktopVersion: '0.1.252',
diff --git a/external-rest-api/src/routes/contextSharedFilesystems.ts b/external-rest-api/src/routes/contextSharedFilesystems.ts
index 4788a7a11..894df2f5e 100644
--- a/external-rest-api/src/routes/contextSharedFilesystems.ts
+++ b/external-rest-api/src/routes/contextSharedFilesystems.ts
@@ -111,6 +111,10 @@ export function createContextSharedFilesystemsRouter(): Router {
// shared filesystem object must never be downloaded just to suppress
// its body at the public Express boundary.
if (req.method === 'HEAD') {
+ // Fetch normally exposes a null body for HEAD, but cancel an unusual
+ // non-null stream explicitly so a custom upstream cannot retain a
+ // connection after the metadata response is complete.
+ if (upstreamRes.body) void upstreamRes.body.cancel().catch(() => undefined)
res.end()
return
}
diff --git a/external-rest-api/test/routes.contextSharedFilesystems.test.ts b/external-rest-api/test/routes.contextSharedFilesystems.test.ts
index ded516b37..1d8dd0fb4 100644
--- a/external-rest-api/test/routes.contextSharedFilesystems.test.ts
+++ b/external-rest-api/test/routes.contextSharedFilesystems.test.ts
@@ -150,13 +150,14 @@ describe('Method gating', () => {
const getReader = vi.fn(() => {
throw new Error('HEAD body must not be read')
})
+ const cancel = vi.fn(() => Promise.reject(new Error('upstream disconnect')))
controlApiClientMock.controlApiStreamRequest.mockResolvedValue({
status: 200,
headers: new Headers({
'content-type': 'application/octet-stream',
'content-length': '1234',
}),
- body: { getReader },
+ body: { getReader, cancel },
} as unknown as Response)
const res = await request(buildApp())
@@ -166,6 +167,7 @@ describe('Method gating', () => {
expect(res.status).toBe(200)
expect(res.headers['content-length']).toBe('1234')
expect(getReader).not.toHaveBeenCalled()
+ expect(cancel).toHaveBeenCalledOnce()
expect(controlApiClientMock.controlApiStreamRequest).toHaveBeenCalledWith(
'HEAD',
'/external/contexts/ctx-a/shared-filesystems/team-mission/proxy/files?download=1',
diff --git a/gfs-controller/src/authz/storeProbe.test.ts b/gfs-controller/src/authz/storeProbe.test.ts
index ecd0d46e2..9f464f0e0 100644
--- a/gfs-controller/src/authz/storeProbe.test.ts
+++ b/gfs-controller/src/authz/storeProbe.test.ts
@@ -69,6 +69,7 @@ interface FakeClientBehavior {
auditActorCorrelationConstraintReady?: boolean;
authorityUsersColumnsReady?: boolean;
authorityAdminColumnsReady?: boolean;
+ authorityAdminSessionEpochReady?: boolean;
authorityLinksColumnsReady?: boolean;
authorityUsersPrivilegesReady?: boolean;
authorityAdminPrivilegesReady?: boolean;
@@ -130,6 +131,7 @@ function fakeClientFactory(behavior: FakeClientBehavior): {
behavior.auditActorCorrelationConstraintReady !== false,
authority_users_columns_ready: behavior.authorityUsersColumnsReady !== false,
authority_admin_columns_ready: behavior.authorityAdminColumnsReady !== false,
+ authority_admin_session_epoch_ready: behavior.authorityAdminSessionEpochReady !== false,
authority_links_columns_ready: behavior.authorityLinksColumnsReady !== false,
authority_users_privileges_ready: behavior.authorityUsersPrivilegesReady !== false,
authority_admin_privileges_ready: behavior.authorityAdminPrivilegesReady !== false,
@@ -231,6 +233,19 @@ describe("createPermissionStoreProbe", () => {
expect(probeClient.lastSql()).toContain("gfs_audit_record_type_fields_valid");
});
+ it("rejects readiness when migration 0096 default or backfill is incomplete", async () => {
+ const { factory } = fakeClientFactory({ authorityAdminSessionEpochReady: false });
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "reader",
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).rejects.toThrow(/0095\/0096/);
+ });
+
it.each([
["resource mutation", { canMutateResources: true }],
["grant mutation", { canMutateGrants: true }],
@@ -396,6 +411,7 @@ describe("createPermissionStoreProbe", () => {
expect(sql).toContain("NOT attnotnull");
expect(sql).toContain("authority_users_columns_ready");
expect(sql).toContain("authority_admin_columns_ready");
+ expect(sql).toContain("authority_admin_session_epoch_ready");
expect(sql).toContain("authority_links_columns_ready");
expect(sql).toContain("authority_users_privileges_ready");
expect(sql).toContain("authority_admin_privileges_ready");
diff --git a/gfs-controller/src/authz/storeProbe.ts b/gfs-controller/src/authz/storeProbe.ts
index 591f9b4df..d003229e5 100644
--- a/gfs-controller/src/authz/storeProbe.ts
+++ b/gfs-controller/src/authz/storeProbe.ts
@@ -30,7 +30,6 @@ export interface PingPool {
release(err?: Error): void;
}>;
}
-
/** Minimal ephemeral-client surface (structurally satisfied by pg.Client). */
export interface ProbeClient {
connect(): Promise<void>;
@@ -123,6 +122,21 @@ const AUTHORITY_PROJECTION_SQL =
"(attname = 'session_version' AND atttypid = 'int4'::regtype)) " +
"FROM pg_attribute WHERE attrelid = 'control_admin_users'::regclass AND attnum > 0 AND NOT attisdropped " +
"AND attname = ANY (ARRAY['id','status','session_version'])) AS authority_admin_columns_ready" +
+ ", (SELECT count(*) = 1 " +
+ "AND EXISTS (SELECT 1 FROM pg_attrdef defs JOIN pg_attribute attrs " +
+ "ON attrs.attrelid = defs.adrelid AND attrs.attnum = defs.adnum " +
+ "WHERE defs.adrelid = 'control_admin_users'::regclass " +
+ "AND attrs.attname = 'session_version' " +
+ "AND attrs.attnotnull " +
+ "AND pg_get_expr(defs.adbin, defs.adrelid) IN ('1', '1::integer')) " +
+ "AND NOT EXISTS (SELECT 1 FROM control_admin_users WHERE session_version < 1) " +
+ "AND EXISTS (SELECT 1 FROM pg_constraint " +
+ "WHERE conrelid = 'control_admin_users'::regclass " +
+ "AND conname = 'control_admin_session_version_positive' " +
+ "AND contype = 'c' AND convalidated) " +
+ "FROM pg_attribute WHERE attrelid = 'control_admin_users'::regclass " +
+ "AND attname = 'session_version' AND attnum > 0 AND NOT attisdropped) " +
+ 'AS authority_admin_session_epoch_ready' +
", (SELECT count(*) = 7 AND bool_and((attname = 'id' AND atttypid = 'uuid'::regtype) OR " +
"(attname = 'lineage_id' AND atttypid = 'uuid'::regtype) OR " +
"(attname = 'generation' AND atttypid = 'int4'::regtype) OR " +
@@ -296,6 +310,7 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi
if (
row?.authority_users_columns_ready !== true ||
row?.authority_admin_columns_ready !== true ||
+ row?.authority_admin_session_epoch_ready !== true ||
row?.authority_links_columns_ready !== true ||
row?.authority_users_privileges_ready !== true ||
row?.authority_admin_privileges_ready !== true ||
@@ -303,7 +318,7 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi
) {
throw new Error(
"permission store coherence check failed: GFS lifecycle authority projection is missing " +
- "(control-api migration 0095 not applied?)"
+ "(control-api migration 0095/0096 not applied?)"
);
}
if (
diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.json
index ee191a51d..85e7d27fe 100644
--- a/profile-ui/package-lock.json
+++ b/profile-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.122",
+ "version": "0.1.123",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-profile-ui",
- "version": "0.1.122",
+ "version": "0.1.123",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
"next": "16.2.11",
diff --git a/profile-ui/package.json b/profile-ui/package.json
index 3a220df6b..ca7d3d5e9 100644
--- a/profile-ui/package.json
+++ b/profile-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.122",
+ "version": "0.1.123",
"private": true,
"scripts": {
"dev": "next dev",
diff --git a/profile-ui/test/memberApi.test.ts b/profile-ui/test/memberApi.test.ts
index ea1d3563e..a3707a844 100644
--- a/profile-ui/test/memberApi.test.ts
+++ b/profile-ui/test/memberApi.test.ts
@@ -35,3 +35,33 @@ test('deleteManagedUser sends the governed retirement contract', async () => {
globalThis.fetch = previousFetch
}
})
+
+test('deleteManagedUser default caller path supplies generated idempotency and correlation values', async () => {
+ const previousFetch = globalThis.fetch
+ let request: { url: string; init?: RequestInit } | undefined
+ globalThis.fetch = (async (input, init) => {
+ request = { url: String(input), init }
+ return new Response(JSON.stringify({ deleted: true, id: USER_ID }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ }) as typeof fetch
+ try {
+ await deleteManagedUser(USER_ID)
+ assert.ok(request)
+ const headers = new Headers(request.init?.headers)
+ assert.match(
+ headers.get('Idempotency-Key') || '',
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+ )
+ assert.match(
+ headers.get('x-correlation-id') || '',
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+ )
+ assert.deepEqual(JSON.parse(String(request.init?.body)), {
+ reason: 'profile_ui_user_retirement',
+ })
+ } finally {
+ globalThis.fetch = previousFetch
+ }
+})