Skip to content

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

TypeScript

fix(gfs): fence retired bearer authority by generation

Alfredo Lopez1b8e6ee926ee
diff --git a/control-api/src/auth/gfsToken.ts b/control-api/src/auth/gfsToken.ts
index 24bdb6d18..d7625a3d3 100644
--- a/control-api/src/auth/gfsToken.ts
+++ b/control-api/src/auth/gfsToken.ts
@@ -46,6 +46,8 @@ export interface GfsTokenClaims extends jwt.JwtPayload {
drive: string
scopes: GfsScope[]
pathBindings: GfsPathBinding[]
+ /** Current users.lifecycle_version or control-admin session_version. */
+ authGeneration?: number
brokeredAuthority?: GfsBrokeredAuthority
principalType?: 'user' | 'control-admin'
}
@@ -54,6 +56,9 @@ export interface GfsBrokeredAuthority {
desktopUserId: string
controlAdminId: string
authoritySource: 'linked-admin'
+ linkLineageId?: string
+ linkGeneration?: number
+ desktopUserGeneration?: number
}
/**
@@ -89,6 +94,7 @@ export function signGfsToken(input: {
drive: string
scopes: readonly GfsScope[]
pathBindings?: readonly GfsPathBinding[]
+ authGeneration?: number
brokeredAuthority?: GfsBrokeredAuthority
principalType?: 'user' | 'control-admin'
}): { token: string; expiresInSeconds: number } {
@@ -97,6 +103,7 @@ export function signGfsToken(input: {
drive: input.drive,
scopes: [...input.scopes],
pathBindings: input.pathBindings ? input.pathBindings.map(b => ({ ...b })) : [],
+ ...(input.authGeneration === undefined ? {} : { authGeneration: input.authGeneration }),
...(input.brokeredAuthority ? { brokeredAuthority: { ...input.brokeredAuthority } } : {}),
...(input.principalType ? { principalType: input.principalType } : {}),
}
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index 971e662e3..bf1841a4c 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -2923,6 +2923,36 @@ async function applyDesktopUserRetirementLifecycleSchema(db: DbClient): Promise<
`)
}
+/**
+ * Expose only the authoritative lifecycle/link projection needed by gfsc.
+ * The data-plane resolver must be able to deny a stale bearer directly, but it
+ * must not gain write access to identity or relationship tables.
+ */
+async function applyGfsLifecycleAuthorityProjectionSchema(db: DbClient): Promise<void> {
+ await db.query(`
+ -- Generation zero was the pre-lifecycle default. Normalize existing admins
+ -- before gfsc begins treating session_version as an authorization epoch.
+ UPDATE control_admin_users
+ SET session_version = 1
+ WHERE session_version IS NULL OR session_version < 1;
+
+ REVOKE INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER
+ ON users, control_admin_users, gfs_desktop_operator_links
+ FROM gfs_controller, gfs_controller_reader;
+
+ GRANT SELECT (id, lifecycle_state, lifecycle_version)
+ ON users TO gfs_controller, gfs_controller_reader;
+ GRANT SELECT (id, status, session_version)
+ ON control_admin_users TO gfs_controller, gfs_controller_reader;
+ GRANT SELECT (id, lineage_id, generation, user_id, control_admin_id, state, source)
+ ON gfs_desktop_operator_links TO gfs_controller, gfs_controller_reader;
+
+ REVOKE INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER
+ ON users, control_admin_users, gfs_desktop_operator_links
+ FROM PUBLIC;
+ `)
+}
+
// Exported (read-only) so the migration-order invariant test can assert the
// array is monotonic by version-string. Applied strictly in array order and
// tracked by full version-string in `schema_migrations`, so a non-monotonic
@@ -5801,6 +5831,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0094_desktop_user_retirement_lifecycle',
apply: applyDesktopUserRetirementLifecycleSchema,
},
+ {
+ version: '0095_gfs_lifecycle_authority_projection',
+ apply: applyGfsLifecycleAuthorityProjectionSchema,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/src/gfs/externalAuthority.ts b/control-api/src/gfs/externalAuthority.ts
index d7fbdd79e..ac6563e22 100644
--- a/control-api/src/gfs/externalAuthority.ts
+++ b/control-api/src/gfs/externalAuthority.ts
@@ -10,6 +10,7 @@ export type ExternalGfsUserAuthority = {
kind: 'user-session'
desktopUserId: string
tokenSubject: string
+ authGeneration?: number
}
export type ExternalGfsLinkedAdminAuthority = {
@@ -18,6 +19,11 @@ export type ExternalGfsLinkedAdminAuthority = {
controlAdminId: string
tokenSubject: string
authoritySource: 'linked-admin'
+ authGeneration?: number
+ linkLineageId: string
+ linkGeneration: number
+ desktopUserGeneration: number
+ controlAdminGeneration: number
}
export type ExternalGfsAuthority = ExternalGfsUserAuthority | ExternalGfsLinkedAdminAuthority
@@ -53,8 +59,13 @@ const defaultDesktopUserLifecycleGuard =
? (id: string) => gfsDesktopOperatorLinkService.isDesktopUserActive(id)
: undefined
-function userAuthority(desktopUserId: string): ExternalGfsUserAuthority {
- return { kind: 'user-session', desktopUserId, tokenSubject: desktopUserId }
+function userAuthority(desktopUserId: string, authGeneration?: number): ExternalGfsUserAuthority {
+ return {
+ kind: 'user-session',
+ desktopUserId,
+ tokenSubject: desktopUserId,
+ ...(authGeneration === undefined ? {} : { authGeneration }),
+ }
}
async function assertDesktopUserActive(
@@ -110,7 +121,14 @@ export async function resolveExternalGfsAuthority(
}
if (!link) return userAuthority(desktopUserId)
- if (link.desktopUserId !== desktopUserId || link.source !== 'initial_setup') {
+ if (
+ link.desktopUserId !== desktopUserId ||
+ link.source !== 'initial_setup' ||
+ !link.lineageId ||
+ link.generation === undefined ||
+ link.desktopUserGeneration === undefined ||
+ link.controlAdminGeneration === undefined
+ ) {
throw new ExternalGfsAuthorityError(403, 'gfs_operator_link_invalid')
}
return {
@@ -119,6 +137,11 @@ export async function resolveExternalGfsAuthority(
controlAdminId: link.controlAdminId,
tokenSubject: link.controlAdminId,
authoritySource: 'linked-admin',
+ authGeneration: link.controlAdminGeneration,
+ linkLineageId: link.lineageId,
+ linkGeneration: link.generation,
+ desktopUserGeneration: link.desktopUserGeneration,
+ controlAdminGeneration: link.controlAdminGeneration,
}
}
@@ -138,8 +161,13 @@ export async function attachExternalGfsAuthority(
return
}
try {
- ;(req as RequestWithExternalGfsAuthority).gfsAuthority =
- await resolveExternalGfsAuthority(desktopUserId)
+ const authority = await resolveExternalGfsAuthority(desktopUserId)
+ if (authority.kind === 'user-session') {
+ const generation = (req as Request & { externalAuth?: { authGeneration?: number } })
+ .externalAuth?.authGeneration
+ if (generation !== undefined) authority.authGeneration = generation
+ }
+ ;(req as RequestWithExternalGfsAuthority).gfsAuthority = authority
next()
} catch (error) {
if (error instanceof ExternalGfsAuthorityError) {
diff --git a/control-api/src/middleware/externalSessionAuth.ts b/control-api/src/middleware/externalSessionAuth.ts
index 814ebddce..9f1096712 100644
--- a/control-api/src/middleware/externalSessionAuth.ts
+++ b/control-api/src/middleware/externalSessionAuth.ts
@@ -1,4 +1,5 @@
import { NextFunction, Request, Response } from 'express'
+import { pool } from '../db.js'
import { AuthClaims, TeamRole } from '../profileTypes.js'
import { verifyExternalSessionToken } from '../utils/auth/externalSessionAuthToken.js'
@@ -6,6 +7,37 @@ export type ExternalAuthedRequest = Request & {
externalAuth?: AuthClaims
}
+/**
+ * The session JWT is only a signed locator. The user row remains authoritative
+ * for lifecycle and generation, so retirement takes effect before the token's
+ * nominal expiry. A missing row and an inactive row intentionally share the
+ * same denial to avoid user enumeration.
+ */
+export async function isCurrentExternalSession(claims: AuthClaims): Promise<boolean> {
+ const result = await pool.query(
+ `SELECT lifecycle_state, lifecycle_version
+ FROM users
+ WHERE id = $1
+ LIMIT 1`,
+ [claims.userId]
+ )
+ const row = result.rows[0] as
+ | { lifecycle_state?: unknown; lifecycle_version?: unknown }
+ | undefined
+ if (row?.lifecycle_state !== 'active') return false
+ // Real verifier output always contains the explicit legacy marker (0). The
+ // undefined branch is only for isolated route doubles that inject the old
+ // structural shape without bypassing production verification.
+ if (claims.authGeneration === undefined) return true
+ return Number(row.lifecycle_version) === claims.authGeneration
+}
+
+export async function assertCurrentExternalSession(claims: AuthClaims): Promise<void> {
+ if (!(await isCurrentExternalSession(claims))) {
+ throw new Error('external session is inactive or stale')
+ }
+}
+
function extractUserSessionToken(req: Request): string {
return String(req.header('x-user-session-token') || '').trim()
}
@@ -14,21 +46,42 @@ export function requireValidExternalSessionToken(
req: ExternalAuthedRequest,
res: Response,
next: NextFunction
-): void {
- const token = extractUserSessionToken(req)
- if (!token || token.length > 4096) {
- res.status(401).json({ error: 'Unauthorized' })
- return
- }
+): Promise<void> {
+ return requireValidExternalSessionTokenAsync(req, res, next)
+}
- const claims = verifyExternalSessionToken(token)
- if (!claims) {
- res.status(401).json({ error: 'Unauthorized' })
- return
- }
+async function requireValidExternalSessionTokenAsync(
+ req: ExternalAuthedRequest,
+ res: Response,
+ next: NextFunction
+): Promise<void> {
+ try {
+ const token = extractUserSessionToken(req)
+ if (!token || token.length > 4096) {
+ res.status(401).json({ error: 'Unauthorized' })
+ return
+ }
- req.externalAuth = claims
- next()
+ const claims = verifyExternalSessionToken(token)
+ if (!claims) {
+ res.status(401).json({ error: 'Unauthorized' })
+ return
+ }
+
+ // Real verifier output always carries authGeneration (0 marks a legacy
+ // token). Test doubles that inject the pre-generation structural shape are
+ // intentionally left to their own route fixture; they never reach this
+ // branch in production because the verifier rejects that shape.
+ if (claims.authGeneration !== undefined && !(await isCurrentExternalSession(claims))) {
+ res.status(401).json({ error: 'Unauthorized' })
+ return
+ }
+
+ req.externalAuth = claims
+ next()
+ } catch (error) {
+ next(error)
+ }
}
export function requireExternalUserParamMatch(paramName = 'userId') {
diff --git a/control-api/src/profileTypes.ts b/control-api/src/profileTypes.ts
index 88e95b76f..604663ecd 100644
--- a/control-api/src/profileTypes.ts
+++ b/control-api/src/profileTypes.ts
@@ -44,6 +44,8 @@ export type AuthClaims = {
email: string
teamId: string | null
role: TeamRole
+ /** Authoritative users.lifecycle_version captured when the session was issued. */
+ authGeneration?: number
exp: number
}
diff --git a/control-api/src/routes/external/auth.ts b/control-api/src/routes/external/auth.ts
index 391dadf05..eb633acf5 100644
--- a/control-api/src/routes/external/auth.ts
+++ b/control-api/src/routes/external/auth.ts
@@ -1,6 +1,7 @@
import { Router } from 'express'
import { pool } from '../../db.js'
import type { K8sGateway } from '../../k8s.js'
+import { isCurrentExternalSession } from '../../middleware/externalSessionAuth.js'
import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'
import { AuthClaims, RpcScope, TEAM_ROLES } from '../../profileTypes.js'
import {
@@ -39,12 +40,16 @@ export function createExternalAuthRouter(gateway: K8sGateway): Router {
name: google.name,
picture: google.picture,
})
+ if ('error' in login) {
+ return res.status(401).json({ error: 'Unauthorized' })
+ }
const role = login.membership.role
const token = signExternalSessionToken({
userId: login.user.id,
email: google.email,
teamId: login.membership.team_id || null,
role,
+ authGeneration: login.authGeneration,
})
return res.status(200).json({
token,
@@ -79,6 +84,9 @@ export function createExternalAuthRouter(gateway: K8sGateway): Router {
return res.status(401).json({ error: 'Unauthorized' })
}
if ('error' in login) {
+ if (login.error === 'user_retired') {
+ return res.status(401).json({ error: 'Unauthorized' })
+ }
if (login.error === 'password_not_set') {
return res.status(409).json({ error: 'password_not_set' })
}
@@ -91,6 +99,7 @@ export function createExternalAuthRouter(gateway: K8sGateway): Router {
email: login.user.email,
teamId: login.membership.team_id || null,
role,
+ authGeneration: login.authGeneration,
})
return res.status(200).json({
token,
@@ -140,6 +149,9 @@ export function createExternalAuthRouter(gateway: K8sGateway): Router {
if (!token || token.length > 4096) return res.status(401).json({ error: 'Unauthorized' })
const claims = verifyExternalSessionToken(token)
if (!claims) return res.status(401).json({ error: 'Unauthorized' })
+ if (!(await isCurrentExternalSession(claims))) {
+ return res.status(401).json({ error: 'Unauthorized' })
+ }
return res.status(200).json({ claims })
} catch (error) {
return next(error)
@@ -158,11 +170,12 @@ export function createExternalAuthRouter(gateway: K8sGateway): Router {
return res.status(400).json({ error: 'invalid payload' })
}
const membership = await pool.query(
- `SELECT 1
+ `SELECT u.lifecycle_version
FROM users u
JOIN team_members tm ON tm.user_id = u.id
WHERE u.id = $1
AND LOWER(u.email) = LOWER($2)
+ AND u.lifecycle_state = 'active'
AND tm.team_id = $3
AND tm.role = $4
AND tm.status = 'active'
@@ -172,7 +185,13 @@ export function createExternalAuthRouter(gateway: K8sGateway): Router {
if ((membership.rowCount ?? 0) === 0) {
return res.status(403).json({ error: 'membership_not_found' })
}
- const token = signExternalSessionToken({ userId, email, teamId, role })
+ const authGeneration = Number(
+ (membership.rows[0] as { lifecycle_version?: unknown }).lifecycle_version
+ )
+ if (!Number.isSafeInteger(authGeneration) || authGeneration < 1) {
+ return res.status(403).json({ error: 'membership_not_found' })
+ }
+ const token = signExternalSessionToken({ userId, email, teamId, role, authGeneration })
return res.status(200).json({ token })
} catch (error) {
return next(error)
@@ -186,6 +205,9 @@ export function createExternalAuthRouter(gateway: K8sGateway): Router {
return res.status(401).json({ error: 'Unauthorized' })
const claims = verifyExternalSessionToken(sessionToken)
if (!claims) return res.status(401).json({ error: 'Unauthorized' })
+ if (!(await isCurrentExternalSession(claims))) {
+ return res.status(401).json({ error: 'Unauthorized' })
+ }
const requestedScopes = normalizeRequestedScopes(req.body?.scopes)
const hostRefs = normalizeRequestedHostRefs(req.body?.hostRefs)
if (hostRefs.length === 0) {
diff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.ts
index d64d9a4c7..13ad81a20 100644
--- a/control-api/src/routes/external/gfs.ts
+++ b/control-api/src/routes/external/gfs.ts
@@ -410,6 +410,7 @@ export function createExternalGfsRouter(): Router {
drive,
scopes,
pathBindings: [],
+ ...(claims.authGeneration === undefined ? {} : { authGeneration: claims.authGeneration }),
principalType: 'user',
})
res.status(200).json({ token, expiresInSeconds })
@@ -778,6 +779,7 @@ async function proxyReadToGfsc(
subject: authority.tokenSubject,
drive,
scopes: [GFS_READ_SCOPE],
+ ...(authority.authGeneration === undefined ? {} : { authGeneration: authority.authGeneration }),
principalType: authority.kind === 'linked-admin' ? 'control-admin' : 'user',
...(authority.kind === 'linked-admin'
? {
@@ -785,6 +787,9 @@ async function proxyReadToGfsc(
desktopUserId: authority.desktopUserId,
controlAdminId: authority.controlAdminId,
authoritySource: authority.authoritySource,
+ linkLineageId: authority.linkLineageId,
+ linkGeneration: authority.linkGeneration,
+ desktopUserGeneration: authority.desktopUserGeneration,
},
}
: {}),
@@ -875,6 +880,7 @@ async function proxyMutationToGfsc(
subject: authority.tokenSubject,
drive,
scopes: [scope],
+ ...(authority.authGeneration === undefined ? {} : { authGeneration: authority.authGeneration }),
principalType: authority.kind === 'linked-admin' ? 'control-admin' : 'user',
...(authority.kind === 'linked-admin'
? {
@@ -882,6 +888,9 @@ async function proxyMutationToGfsc(
desktopUserId: authority.desktopUserId,
controlAdminId: authority.controlAdminId,
authoritySource: authority.authoritySource,
+ linkLineageId: authority.linkLineageId,
+ linkGeneration: authority.linkGeneration,
+ desktopUserGeneration: authority.desktopUserGeneration,
},
}
: {}),
diff --git a/control-api/src/routes/external/invitations.ts b/control-api/src/routes/external/invitations.ts
index 078b41cf0..f4c38e2d6 100644
--- a/control-api/src/routes/external/invitations.ts
+++ b/control-api/src/routes/external/invitations.ts
@@ -116,6 +116,9 @@ export function createExternalInvitationsRouter(): Router {
if (result.error === 'expired') {
return res.status(410).json({ error: 'expired' })
}
+ if (result.error === 'user_retired') {
+ return res.status(401).json({ error: 'Unauthorized' })
+ }
return res.status(400).json({ error: 'invalid_password' })
}
@@ -123,12 +126,21 @@ export function createExternalInvitationsRouter(): Router {
if (!userId) {
return res.status(409).json({ error: 'invitation_not_ready' })
}
+ const authGeneration = Number(result.data.authGeneration)
+ if (
+ result.data.lifecycleState !== 'active' ||
+ !Number.isSafeInteger(authGeneration) ||
+ authGeneration < 1
+ ) {
+ return res.status(409).json({ error: 'invitation_not_ready' })
+ }
const sessionToken = signExternalSessionToken({
userId,
email: result.data.email,
teamId: result.data.teamId || null,
role: result.data.role,
+ authGeneration,
})
return res.status(200).json({
@@ -174,6 +186,9 @@ export function createExternalInvitationsRouter(): Router {
if (result.error === 'expired') {
return res.status(410).json({ error: 'expired' })
}
+ if (result.error === 'user_retired') {
+ return res.status(401).json({ error: 'Unauthorized' })
+ }
return res.status(400).json({ error: 'invalid_password' })
}
return res.status(200).json(result.data)
@@ -266,14 +281,26 @@ export function createExternalInvitationsRouter(): Router {
if (result.error === 'expired') {
return res.status(410).json({ error: 'expired' })
}
+ if (result.error === 'user_retired') {
+ return res.status(401).json({ error: 'Unauthorized' })
+ }
return res.status(400).json({ error: 'not_pending' })
}
+ const authGeneration = Number(result.data.authGeneration)
+ if (
+ result.data.lifecycleState !== 'active' ||
+ !Number.isSafeInteger(authGeneration) ||
+ authGeneration < 1
+ ) {
+ return res.status(409).json({ error: 'invitation_not_ready' })
+ }
const sessionToken = signExternalSessionToken({
userId: result.data.userId,
email: result.data.email,
teamId: result.data.teamId || null,
role: result.data.role,
+ authGeneration,
})
return res.status(200).json({
diff --git a/control-api/src/routes/external/workflows/read.routes.ts b/control-api/src/routes/external/workflows/read.routes.ts
index d1db02f53..dbf5ac52e 100644
--- a/control-api/src/routes/external/workflows/read.routes.ts
+++ b/control-api/src/routes/external/workflows/read.routes.ts
@@ -20,7 +20,7 @@ export function createExternalWorkflowReadRoutes(gateway: K8sGateway): Router {
router.get(
BASE,
asyncHandler(async (req: Request, res: Response) => {
- const caller = requireExternalWorkflowCaller(req, res)
+ const caller = await requireExternalWorkflowCaller(req, res)
if (!caller) return
const recipes = await getAuthorizedRecipeResources(caller, gateway)
@@ -31,7 +31,7 @@ export function createExternalWorkflowReadRoutes(gateway: K8sGateway): Router {
router.get(
`${BASE}/:ns/:name`,
asyncHandler(async (req: Request, res: Response) => {
- const caller = requireExternalWorkflowCaller(req, res)
+ const caller = await requireExternalWorkflowCaller(req, res)
if (!caller) return
const { ns, name } = req.params
@@ -60,7 +60,7 @@ export function createExternalWorkflowReadRoutes(gateway: K8sGateway): Router {
router.get(
`${BASE}/:ns/:name/health`,
asyncHandler(async (req: Request, res: Response) => {
- const caller = requireExternalWorkflowCaller(req, res)
+ const caller = await requireExternalWorkflowCaller(req, res)
if (!caller) return
const { ns, name } = req.params
diff --git a/control-api/src/routes/external/workflows/runs.routes.ts b/control-api/src/routes/external/workflows/runs.routes.ts
index 3af47998e..2f72d68f7 100644
--- a/control-api/src/routes/external/workflows/runs.routes.ts
+++ b/control-api/src/routes/external/workflows/runs.routes.ts
@@ -48,7 +48,7 @@ export function createExternalWorkflowRunsRoutes(gateway: K8sGateway): Router {
router.get(
`${BASE}/:ns/:name/runs`,
asyncHandler(async (req: Request, res: Response) => {
- const caller = requireExternalWorkflowCaller(req, res)
+ const caller = await requireExternalWorkflowCaller(req, res)
if (!caller) return
const { ns, name } = req.params
@@ -70,7 +70,7 @@ export function createExternalWorkflowRunsRoutes(gateway: K8sGateway): Router {
router.get(
`${BASE}/:ns/:name/runs/:runId/artifacts`,
asyncHandler(async (req: Request, res: Response) => {
- const caller = requireExternalWorkflowCaller(req, res)
+ const caller = await requireExternalWorkflowCaller(req, res)
if (!caller) return
try {
@@ -91,7 +91,7 @@ export function createExternalWorkflowRunsRoutes(gateway: K8sGateway): Router {
router.get(
`${BASE}/:ns/:name/runs/:runId/artifacts/:artifactName/download`,
asyncHandler(async (req: Request, res: Response) => {
- const caller = requireExternalWorkflowCaller(req, res)
+ const caller = await requireExternalWorkflowCaller(req, res)
if (!caller) return
try {
diff --git a/control-api/src/routes/external/workflows/trigger.routes.ts b/control-api/src/routes/external/workflows/trigger.routes.ts
index 75a952583..e93b17fd5 100644
--- a/control-api/src/routes/external/workflows/trigger.routes.ts
+++ b/control-api/src/routes/external/workflows/trigger.routes.ts
@@ -23,7 +23,7 @@ export function createExternalWorkflowTriggerRoutes(gateway: K8sGateway): Router
`${BASE}/:ns/:name/trigger`,
workflowTriggerRateLimit(),
asyncHandler(async (req: Request, res: Response) => {
- const caller = requireExternalWorkflowCaller(req, res)
+ const caller = await requireExternalWorkflowCaller(req, res)
if (!caller) return
const { ns, name } = req.params
diff --git a/control-api/src/routes/gfs/proxy.ts b/control-api/src/routes/gfs/proxy.ts
index d4bd6888c..53db78953 100644
--- a/control-api/src/routes/gfs/proxy.ts
+++ b/control-api/src/routes/gfs/proxy.ts
@@ -35,6 +35,15 @@ export function registerGfsProxyRoute(router: Router): void {
res.status(401).json({ error: 'unauthorized' })
return
}
+ const authGeneration = req.adminAuth?.sessionVersion
+ if (
+ typeof authGeneration !== 'number' ||
+ !Number.isSafeInteger(authGeneration) ||
+ authGeneration < 1
+ ) {
+ res.status(401).json({ error: 'unauthorized' })
+ return
+ }
const scope =
req.method === 'GET' || req.method === 'HEAD'
@@ -56,6 +65,7 @@ export function registerGfsProxyRoute(router: Router): void {
subject,
drive: DEFAULT_DRIVE,
scopes: [scope],
+ authGeneration,
principalType: 'control-admin',
})
const headers: Record<string, string> = {}
diff --git a/control-api/src/routes/gfs/token.ts b/control-api/src/routes/gfs/token.ts
index 65f5a9559..2fe8b1189 100644
--- a/control-api/src/routes/gfs/token.ts
+++ b/control-api/src/routes/gfs/token.ts
@@ -48,6 +48,15 @@ export function registerGfsTokenRoute(router: Router): void {
res.status(401).json({ error: 'unauthorized' })
return
}
+ const authGeneration = req.adminAuth?.sessionVersion
+ if (
+ typeof authGeneration !== 'number' ||
+ !Number.isSafeInteger(authGeneration) ||
+ authGeneration < 1
+ ) {
+ res.status(401).json({ error: 'unauthorized' })
+ return
+ }
const body = (req.body ?? {}) as { drive?: unknown; scopes?: unknown }
const drive =
typeof body.drive === 'string' && body.drive.length > 0 ? body.drive : GFS_DEFAULT_DRIVE
@@ -61,6 +70,7 @@ export function registerGfsTokenRoute(router: Router): void {
drive,
scopes,
pathBindings: [],
+ authGeneration,
principalType: 'control-admin',
})
res.status(200).json({ token, expiresInSeconds })
diff --git a/control-api/src/routes/workflows/shared/auth.ts b/control-api/src/routes/workflows/shared/auth.ts
index 1ddce023e..252506e06 100644
--- a/control-api/src/routes/workflows/shared/auth.ts
+++ b/control-api/src/routes/workflows/shared/auth.ts
@@ -1,4 +1,5 @@
import { Request, Response } from 'express'
+import { isCurrentExternalSession } from '../../../middleware/externalSessionAuth.js'
import { isAdminTokenRevoked } from '../../../services/adminAuthService.js'
import type { WorkflowCaller } from '../../../services/workflows/types.js'
import { verifyAdminToken } from '../../../utils/auth/adminAuthToken.js'
@@ -7,8 +8,8 @@ import {
type McpHostControlScope,
verifyMcpHostControlJwt,
} from '../../../utils/auth/mcpHostJwtToken.js'
-import { extractBearerToken } from '../../../utils/extractBearerToken.js'
import { CONTROL_UI_ADMIN_SESSION_COOKIE, readCookie } from '../../../utils/auth/sessionCookies.js'
+import { extractBearerToken } from '../../../utils/extractBearerToken.js'
function getUserSessionToken(req: Request): string {
return String(req.header('x-user-session-token') || '').trim()
@@ -40,15 +41,22 @@ export async function requireAdminWorkflowCaller(
return { kind: 'admin-ui', userId: adminClaims.sub }
}
-export function requireExternalWorkflowCaller(
+export async function requireExternalWorkflowCaller(
req: Request,
res: Response
-): Extract<WorkflowCaller, { kind: 'user-session' }> | null {
+): Promise<Extract<WorkflowCaller, { kind: 'user-session' }> | null> {
const userSessionToken = getUserSessionToken(req)
if (!userSessionToken || userSessionToken.length > 4096) return unauthorized(res)
const claims = verifyExternalSessionToken(userSessionToken)
if (!claims) return unauthorized(res)
+ // The cryptographic verifier always supplies authGeneration in production.
+ // Isolated route fixtures may inject the historic structural shape without
+ // a generation field; those fixtures remain focused on workflow policy, not
+ // the session lifecycle gate itself.
+ if (claims.authGeneration !== undefined && !(await isCurrentExternalSession(claims))) {
+ return unauthorized(res)
+ }
return { kind: 'user-session', claims }
}
diff --git a/control-api/src/services/directory/login.ts b/control-api/src/services/directory/login.ts
index 07ab944cd..3f6df5bb8 100644
--- a/control-api/src/services/directory/login.ts
+++ b/control-api/src/services/directory/login.ts
@@ -132,18 +132,24 @@ function teamlessMemberMembership(): MembershipRow {
export async function googleLoginData(input: { email: string; name?: string; picture?: string }) {
return withTransaction(async db => {
const existing = await db.query(
- `SELECT id, email, name, picture
+ `SELECT id, email, name, picture, lifecycle_state, lifecycle_version
FROM users
WHERE email = $1`,
[input.email]
)
const isNewUser = (existing.rowCount ?? 0) === 0
+ if (
+ !isNewUser &&
+ (existing.rows[0] as { lifecycle_state?: unknown }).lifecycle_state !== 'active'
+ ) {
+ return { error: 'user_retired' as const }
+ }
const userResult = isNewUser
? await db.query(
`INSERT INTO users(email, name, picture)
VALUES($1, $2, $3)
- RETURNING id, email, name, picture`,
+ RETURNING id, email, name, picture, lifecycle_version`,
[input.email, input.name || null, input.picture || null]
)
: await db.query(
@@ -152,7 +158,7 @@ export async function googleLoginData(input: { email: string; name?: string; pic
picture = COALESCE($3, picture),
updated_at = NOW()
WHERE email = $1
- RETURNING id, email, name, picture`,
+ RETURNING id, email, name, picture, lifecycle_version`,
[input.email, input.name || null, input.picture || null]
)
@@ -161,6 +167,7 @@ export async function googleLoginData(input: { email: string; name?: string; pic
email: string
name: string | null
picture: string | null
+ lifecycle_version: number | string | null
}
await db.query(
@@ -181,6 +188,7 @@ export async function googleLoginData(input: { email: string; name?: string; pic
return {
isNewUser,
+ authGeneration: Number(user.lifecycle_version || 0),
user,
membership: ((membership.rows[0] as MembershipRow | undefined) ||
teamlessMemberMembership()) as MembershipRow,
@@ -191,7 +199,7 @@ export async function googleLoginData(input: { email: string; name?: string; pic
export async function passwordLoginData(input: { email: string; password: string }) {
return withTransaction(async db => {
const result = await db.query(
- `SELECT id, email, name, picture, password_hash
+ `SELECT id, email, name, picture, password_hash, lifecycle_state, lifecycle_version
FROM users
WHERE email = $1
LIMIT 1`,
@@ -207,6 +215,11 @@ export async function passwordLoginData(input: { email: string; password: string
name: string | null
picture: string | null
password_hash: string | null
+ lifecycle_state?: string | null
+ lifecycle_version?: number | string | null
+ }
+ if (user.lifecycle_state !== 'active') {
+ return { error: 'user_retired' as const }
}
if (!user.password_hash) {
return { error: 'password_not_set' as const }
@@ -226,6 +239,7 @@ export async function passwordLoginData(input: { email: string; password: string
if ((membership.rowCount ?? 0) === 0) {
return {
+ authGeneration: Number(user.lifecycle_version || 0),
user: {
id: user.id,
email: user.email,
@@ -237,6 +251,7 @@ export async function passwordLoginData(input: { email: string; password: string
}
return {
+ authGeneration: Number(user.lifecycle_version || 0),
user: {
id: user.id,
email: user.email,
@@ -259,6 +274,7 @@ export async function verifyUserPassword(input: {
FROM users
WHERE id = $1
AND email = $2
+ AND lifecycle_state = 'active'
LIMIT 1`,
[input.userId.trim(), input.email.trim().toLowerCase()]
)
diff --git a/control-api/src/services/directory/membership.ts b/control-api/src/services/directory/membership.ts
index 742634aca..39c8cc476 100644
--- a/control-api/src/services/directory/membership.ts
+++ b/control-api/src/services/directory/membership.ts
@@ -51,6 +51,8 @@ type InvitationUserRow = {
name: string | null
picture: string | null
password_hash: string | null
+ lifecycle_state?: 'active' | 'retired' | string | null
+ lifecycle_version?: number | string | null
}
type InvitationWithTeams = {
@@ -168,7 +170,7 @@ async function ensureInvitationUser(
const normalizedEmail = email.trim().toLowerCase()
const normalizedInviteeName = String(inviteeName || '').trim() || null
const existing = await db.query(
- `SELECT id, email, name, picture, password_hash
+ `SELECT id, email, name, picture, password_hash, lifecycle_state, lifecycle_version
FROM users
WHERE email = $1
LIMIT 1`,
@@ -184,7 +186,7 @@ async function ensureInvitationUser(
ON CONFLICT (email) DO UPDATE
SET name = COALESCE(users.name, EXCLUDED.name),
updated_at = NOW()
- RETURNING id, email, name, picture, password_hash`,
+ RETURNING id, email, name, picture, password_hash, lifecycle_state, lifecycle_version`,
[normalizedEmail, normalizedInviteeName]
)
).rows[0] as InvitationUserRow
@@ -195,7 +197,7 @@ async function ensureInvitationUser(
SET name = $2,
updated_at = NOW()
WHERE id = $1
- RETURNING id, email, name, picture, password_hash`,
+ RETURNING id, email, name, picture, password_hash, lifecycle_state, lifecycle_version`,
[user.id, normalizedInviteeName]
)
).rows[0] as InvitationUserRow
@@ -220,6 +222,10 @@ async function ensureInvitationUser(
return user
}
+function invitationUserIsRetired(user: InvitationUserRow): boolean {
+ return user.lifecycle_state === 'retired'
+}
+
function normalizeInvitationTeamAssignments(
assignments: readonly InvitationTeamAssignment[] | null | undefined
): InvitationTeamAssignment[] {
@@ -358,6 +364,8 @@ function invitationResponse(
acceptedAt: string | null
userId: string | null
passwordPending: boolean
+ authGeneration: number | null
+ lifecycleState: string | null
} {
const primaryTeam = teams[0] || null
return {
@@ -377,6 +385,11 @@ function invitationResponse(
acceptedAt: invitation.accepted_at ? invitation.accepted_at.toISOString() : null,
userId: invitation.accepted_user_id || user?.id || null,
passwordPending: !user?.password_hash,
+ authGeneration:
+ user?.lifecycle_version === undefined || user.lifecycle_version === null
+ ? null
+ : Number(user.lifecycle_version),
+ lifecycleState: user?.lifecycle_state ?? null,
}
}
@@ -1015,7 +1028,7 @@ export async function getInvitationByToken(token: string) {
const user = invitation.accepted_user_id
? ((
await pool.query(
- `SELECT id, email, name, picture, password_hash
+ `SELECT id, email, name, picture, password_hash, lifecycle_state, lifecycle_version
FROM users
WHERE id = $1
LIMIT 1`,
@@ -1024,7 +1037,7 @@ export async function getInvitationByToken(token: string) {
).rows[0] as InvitationUserRow | undefined) || null
: ((
await pool.query(
- `SELECT id, email, name, picture, password_hash
+ `SELECT id, email, name, picture, password_hash, lifecycle_state, lifecycle_version
FROM users
WHERE email = $1
LIMIT 1`,
@@ -1079,6 +1092,7 @@ export async function setInvitationPasswordForUser(
}
const user = await ensureInvitationUser(db, invitation.email, invitation.invitee_name)
+ if (invitationUserIsRetired(user)) return { error: 'user_retired' as const }
if (user.id !== trimmedUserId) {
return { error: 'forbidden' as const }
}
@@ -1088,7 +1102,8 @@ export async function setInvitationPasswordForUser(
SET password_hash = $2,
password_set_at = NOW(),
updated_at = NOW()
- WHERE id = $1`,
+ WHERE id = $1
+ AND lifecycle_state = 'active'`,
[user.id, passwordHash]
)
if (invitation.purpose === 'password_reset' && invitation.status === 'pending') {
@@ -1164,13 +1179,15 @@ export async function setInvitationPasswordForEmail(
}
const user = await ensureInvitationUser(db, invitation.email, invitation.invitee_name)
+ if (invitationUserIsRetired(user)) return { error: 'user_retired' as const }
const passwordHash = await bcrypt.hash(trimmedPassword, 12)
await db.query(
`UPDATE users
SET password_hash = $2,
password_set_at = NOW(),
updated_at = NOW()
- WHERE id = $1`,
+ WHERE id = $1
+ AND lifecycle_state = 'active'`,
[user.id, passwordHash]
)
if (invitation.purpose === 'password_reset' && invitation.status === 'pending') {
@@ -1229,6 +1246,7 @@ export async function acceptInvitation(
}
const user = await ensureInvitationUser(db, invitation.email, invitation.invitee_name)
+ if (invitationUserIsRetired(user)) return { error: 'user_retired' as const }
if (user.id !== userId) {
return { error: 'forbidden' as const }
}
@@ -1284,6 +1302,7 @@ export async function acceptInvitationForEmail(email: string, token: string, inv
}
const user = await ensureInvitationUser(db, invitation.email, invitation.invitee_name)
+ if (invitationUserIsRetired(user)) return { error: 'user_retired' as const }
if (invitation.status === 'pending' && invitation.purpose !== 'password_reset') {
await applyInvitationMemberships(db, invitation, user.id)
@@ -1337,6 +1356,7 @@ export async function acceptInvitationById(email: string, invitationId: string)
}
const user = await ensureInvitationUser(db, invitation.email, invitation.invitee_name)
+ if (invitationUserIsRetired(user)) return { error: 'user_retired' as const }
if (invitation.status === 'pending' && invitation.purpose !== 'password_reset') {
await applyInvitationMemberships(db, invitation, user.id)
diff --git a/control-api/src/services/gfsDesktopOperatorLinkService.ts b/control-api/src/services/gfsDesktopOperatorLinkService.ts
index 2a5c47d28..c6fd65b5b 100644
--- a/control-api/src/services/gfsDesktopOperatorLinkService.ts
+++ b/control-api/src/services/gfsDesktopOperatorLinkService.ts
@@ -16,6 +16,9 @@ export type GfsDesktopOperatorLink = {
desktopUserId: string
controlAdminId: string
source: GfsDesktopOperatorLinkSource
+ /** Current parent generations read from the same authoritative snapshot. */
+ desktopUserGeneration?: number
+ controlAdminGeneration?: number
state?: 'active' | 'revoked'
rowVersion?: number
createdAt: Date
@@ -146,6 +149,9 @@ type StoredLinkRow = {
control_admin_id: unknown
source: unknown
created_at: unknown
+ desktop_user_lifecycle_state?: unknown
+ desktop_user_lifecycle_version?: unknown
+ control_admin_session_version?: unknown
}
function requireRowVersion(value: unknown): number {
@@ -161,6 +167,19 @@ function requireRowVersion(value: unknown): number {
return normalized
}
+function requireGeneration(value: unknown): number {
+ const normalized =
+ typeof value === 'number'
+ ? value
+ : typeof value === 'string' && /^\d+$/.test(value.trim())
+ ? Number(value)
+ : Number.NaN
+ if (!Number.isSafeInteger(normalized) || normalized < 0) {
+ throw new GfsDesktopOperatorLinkError('malformed_link', 'parent generation is malformed')
+ }
+ return normalized
+}
+
function requireReason(value: unknown): string {
const reason = String(value || '').trim()
if (!reason || reason.length > 512) {
@@ -174,8 +193,11 @@ function requireReason(value: unknown): string {
type ResolvedLinkRow = StoredLinkRow & {
desktop_user_exists?: unknown
+ desktop_user_lifecycle_state?: unknown
+ desktop_user_lifecycle_version?: unknown
control_admin_exists?: unknown
control_admin_status?: unknown
+ control_admin_session_version?: unknown
}
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
@@ -289,6 +311,16 @@ function mapStoredLink(row: unknown): GfsDesktopOperatorLink {
'operator-link revocation timestamp is malformed'
)
}
+ const desktopUserGeneration =
+ stored.desktop_user_lifecycle_version === undefined ||
+ stored.desktop_user_lifecycle_version === null
+ ? undefined
+ : requireGeneration(stored.desktop_user_lifecycle_version)
+ const controlAdminGeneration =
+ stored.control_admin_session_version === undefined ||
+ stored.control_admin_session_version === null
+ ? undefined
+ : requireGeneration(stored.control_admin_session_version)
return {
...(id ? { id } : {}),
...(lineageId ? { lineageId } : {}),
@@ -297,6 +329,8 @@ function mapStoredLink(row: unknown): GfsDesktopOperatorLink {
desktopUserId,
controlAdminId,
source: stored.source,
+ ...(desktopUserGeneration === undefined ? {} : { desktopUserGeneration }),
+ ...(controlAdminGeneration === undefined ? {} : { controlAdminGeneration }),
...(state === undefined ? {} : { state }),
...(rowVersion === undefined ? {} : { rowVersion }),
createdAt,
@@ -359,6 +393,12 @@ function mapActiveResolvedLink(
'operator link references a missing Desktop user'
)
}
+ if (row.desktop_user_lifecycle_state !== 'active') {
+ throw new GfsDesktopOperatorLinkError(
+ 'desktop_user_retired',
+ 'linked Desktop user is not active'
+ )
+ }
if (row.control_admin_exists !== true) {
throw new GfsDesktopOperatorLinkError(
'control_admin_not_found',
@@ -847,8 +887,11 @@ export class GfsDesktopOperatorLinkService {
links.source,
links.created_at,
users.id IS NOT NULL AS desktop_user_exists,
+ users.lifecycle_state AS desktop_user_lifecycle_state,
+ users.lifecycle_version AS desktop_user_lifecycle_version,
admins.id IS NOT NULL AS control_admin_exists,
- admins.status AS control_admin_status
+ admins.status AS control_admin_status,
+ admins.session_version AS control_admin_session_version
FROM gfs_desktop_operator_links links
LEFT JOIN users ON users.id = links.user_id
LEFT JOIN control_admin_users admins ON admins.id = links.control_admin_id
@@ -922,8 +965,11 @@ export class GfsDesktopOperatorLinkService {
links.source,
links.created_at,
users.id IS NOT NULL AS desktop_user_exists,
+ users.lifecycle_state AS desktop_user_lifecycle_state,
+ users.lifecycle_version AS desktop_user_lifecycle_version,
admins.id IS NOT NULL AS control_admin_exists,
- admins.status AS control_admin_status
+ admins.status AS control_admin_status,
+ admins.session_version AS control_admin_session_version
FROM gfs_desktop_operator_links links
LEFT JOIN users ON users.id = links.user_id
LEFT JOIN control_admin_users admins ON admins.id = links.control_admin_id
diff --git a/control-api/src/utils/auth/externalSessionAuthToken.ts b/control-api/src/utils/auth/externalSessionAuthToken.ts
index 7c2300cc2..3dc5aee6f 100644
--- a/control-api/src/utils/auth/externalSessionAuthToken.ts
+++ b/control-api/src/utils/auth/externalSessionAuthToken.ts
@@ -13,12 +13,22 @@ export function signExternalSessionToken(
claims: Omit<AuthClaims, 'exp'>,
ttlSeconds = 60 * 60 * 12
): string {
- return jwt.sign(claims, config.sessionJwtPrivateKey, {
- algorithm: 'RS256',
- expiresIn: ttlSeconds,
- issuer: config.jwtIssuer,
- audience: config.jwtAudience,
- })
+ return jwt.sign(
+ {
+ ...claims,
+ // A zero generation is an explicit legacy marker. Current issuers pass
+ // the user's lifecycle_version; consumers reject the marker when the
+ // authoritative row is checked, so an old token cannot survive a retire.
+ authGeneration: typeof claims.authGeneration === 'number' ? claims.authGeneration : 0,
+ },
+ config.sessionJwtPrivateKey,
+ {
+ algorithm: 'RS256',
+ expiresIn: ttlSeconds,
+ issuer: config.jwtIssuer,
+ audience: config.jwtAudience,
+ }
+ )
}
export function verifyExternalSessionToken(token: string): AuthClaims | null {
@@ -30,12 +40,15 @@ export function verifyExternalSessionToken(token: string): AuthClaims | null {
}) as jwt.JwtPayload & Omit<AuthClaims, 'exp'>
const teamId = payload?.teamId
+ const authGeneration = payload?.authGeneration
if (
typeof payload?.userId !== 'string' ||
typeof payload?.email !== 'string' ||
(teamId !== null && typeof teamId !== 'string') ||
typeof payload?.role !== 'string' ||
- typeof payload?.exp !== 'number'
+ typeof payload?.exp !== 'number' ||
+ !Number.isSafeInteger(authGeneration) ||
+ Number(authGeneration) < 0
) {
return null
}
@@ -48,6 +61,7 @@ export function verifyExternalSessionToken(token: string): AuthClaims | null {
email: payload.email,
teamId,
role: payload.role as AuthClaims['role'],
+ authGeneration: Number(authGeneration),
exp: payload.exp,
}
} catch {
diff --git a/control-api/test/app.test.ts b/control-api/test/app.test.ts
index 31c15842b..9cdbd82c8 100644
--- a/control-api/test/app.test.ts
+++ b/control-api/test/app.test.ts
@@ -178,7 +178,10 @@ describe('app router wiring', () => {
.send(payload)
.expect(401)
- vi.spyOn(pool, 'query').mockResolvedValueOnce({ rows: [{}], rowCount: 1 })
+ vi.spyOn(pool, 'query').mockResolvedValueOnce({
+ rows: [{ lifecycle_state: 'active', lifecycle_version: 1 }],
+ rowCount: 1,
+ })
const res = await request(app)
.post('/api/v1/external/auth/session-token')
diff --git a/control-api/test/db.gfsLifecycleAuthorityProjectionMigration.test.ts b/control-api/test/db.gfsLifecycleAuthorityProjectionMigration.test.ts
new file mode 100644
index 000000000..ac9d218d0
--- /dev/null
+++ b/control-api/test/db.gfsLifecycleAuthorityProjectionMigration.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('pg', () => ({
+ Pool: vi.fn(function MockPool() {
+ return { connect: vi.fn(), query: vi.fn() }
+ }),
+}))
+
+describe('0095_gfs_lifecycle_authority_projection migration', () => {
+ it('follows the retirement lifecycle migration and grants only the resolver projection', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const versions = CONTROL_API_MIGRATIONS.map(migration => migration.version)
+ expect(versions.indexOf('0095_gfs_lifecycle_authority_projection')).toBeGreaterThan(
+ versions.indexOf('0094_desktop_user_retirement_lifecycle')
+ )
+
+ const migration = CONTROL_API_MIGRATIONS.find(
+ candidate => candidate.version === '0095_gfs_lifecycle_authority_projection'
+ )
+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })
+ await migration!.apply({ query })
+ const sql = String(query.mock.calls[0]?.[0])
+
+ expect(sql).toContain('GRANT SELECT (id, lifecycle_state, lifecycle_version)')
+ expect(sql).toContain('GRANT SELECT (id, status, session_version)')
+ expect(sql).toContain(
+ 'GRANT SELECT (id, lineage_id, generation, user_id, control_admin_id, state, source)'
+ )
+ expect(sql).toContain('REVOKE INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER')
+ expect(sql).toContain('gfs_controller, gfs_controller_reader')
+ expect(sql).toContain('FROM PUBLIC')
+ })
+})
diff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.ts
index 6af125649..7b3dd31df 100644
--- a/control-api/test/db.realPostgresMigration.integration.test.ts
+++ b/control-api/test/db.realPostgresMigration.integration.test.ts
@@ -188,6 +188,9 @@ describeRealPostgres('control-api real Postgres migrations', () => {
expect(secondVersions.rows.map(row => row.version)).toContain(
'0094_desktop_user_retirement_lifecycle'
)
+ expect(secondVersions.rows.map(row => row.version)).toContain(
+ '0095_gfs_lifecycle_authority_projection'
+ )
await dbPool.query(`
DELETE FROM schema_migrations
diff --git a/control-api/test/deploy.gfsProvisioning.test.ts b/control-api/test/deploy.gfsProvisioning.test.ts
index 587291b33..d58cdefe9 100644
--- a/control-api/test/deploy.gfsProvisioning.test.ts
+++ b/control-api/test/deploy.gfsProvisioning.test.ts
@@ -107,7 +107,11 @@ describe('deploy/scripts/provision-gfs-db.sh', () => {
expect(script).toContain(
"has_column_privilege(:'role_name', 'team_members', 'status', 'SELECT')"
)
- expect(script).toContain("column_name NOT IN ('id', 'status')")
+ expect(script).toContain("column_name NOT IN ('id', 'status', 'session_version')")
+ expect(script).toContain("column_name NOT IN ('id', 'lifecycle_state', 'lifecycle_version')")
+ expect(script).toContain(
+ "column_name NOT IN ('id', 'lineage_id', 'generation', 'user_id', 'control_admin_id', 'state', 'source')"
+ )
expect(script).toContain("column_name NOT IN ('team_id', 'user_id', 'status')")
expect(script).toContain("'INSERT,UPDATE,REFERENCES'")
expect(script).toContain("'DELETE,TRUNCATE,TRIGGER'")
diff --git a/control-api/test/gfs.externalAuthority.test.ts b/control-api/test/gfs.externalAuthority.test.ts
index 6e7660e45..2702aff96 100644
--- a/control-api/test/gfs.externalAuthority.test.ts
+++ b/control-api/test/gfs.externalAuthority.test.ts
@@ -30,6 +30,10 @@ const LINK = {
desktopUserId: DESKTOP_USER_ID,
controlAdminId: CONTROL_ADMIN_ID,
source: 'initial_setup' as const,
+ lineageId: '33333333-3333-4333-8333-333333333333',
+ generation: 1,
+ desktopUserGeneration: 1,
+ controlAdminGeneration: 1,
createdAt: new Date('2026-08-10T00:00:00.000Z'),
}
@@ -89,6 +93,11 @@ describe('resolveExternalGfsAuthority', () => {
controlAdminId: CONTROL_ADMIN_ID,
tokenSubject: CONTROL_ADMIN_ID,
authoritySource: 'linked-admin',
+ authGeneration: 1,
+ linkLineageId: LINK.lineageId,
+ linkGeneration: 1,
+ desktopUserGeneration: 1,
+ controlAdminGeneration: 1,
})
})
diff --git a/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts b/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts
new file mode 100644
index 000000000..3362f36bb
--- /dev/null
+++ b/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+
+const poolQuery = vi.hoisted(() => vi.fn())
+const verifyToken = vi.hoisted(() => vi.fn())
+
+vi.mock('../src/db.js', () => ({
+ pool: { query: (...args: unknown[]) => poolQuery(...args) },
+}))
+vi.mock('../src/utils/auth/externalSessionAuthToken.js', () => ({
+ verifyExternalSessionToken: (...args: unknown[]) => verifyToken(...args),
+}))
+
+const claims = {
+ userId: '11111111-1111-4111-8111-111111111111',
+ email: '[email protected]',
+ teamId: null,
+ role: 'member' as const,
+ authGeneration: 4,
+ exp: Math.floor(Date.now() / 1000) + 3600,
+}
+
+function app() {
+ const server = express()
+ server.get(
+ '/protected',
+ async (req, res, next) => {
+ const { requireValidExternalSessionToken } =
+ await import('../src/middleware/externalSessionAuth.js')
+ await requireValidExternalSessionToken(req as never, res, next)
+ },
+ (_req, res) => res.status(200).json({ ok: true })
+ )
+ return server
+}
+
+describe('external session lifecycle gate', () => {
+ it('accepts an active session whose generation matches the user row', async () => {
+ verifyToken.mockReturnValueOnce(claims)
+ poolQuery.mockResolvedValueOnce({
+ rows: [{ lifecycle_state: 'active', lifecycle_version: 4 }],
+ rowCount: 1,
+ })
+ const response = await request(app()).get('/protected').set('x-user-session-token', 'session')
+ expect(response.status).toBe(200)
+ })
+
+ it.each([
+ [{ lifecycle_state: 'retired', lifecycle_version: 5 }],
+ [{ lifecycle_state: 'active', lifecycle_version: 5 }],
+ [[]],
+ ])('denies retired, stale, or missing authoritative rows', async row => {
+ verifyToken.mockReturnValueOnce(claims)
+ poolQuery.mockResolvedValueOnce({ rows: row, rowCount: row.length })
+ const response = await request(app()).get('/protected').set('x-user-session-token', 'session')
+ expect(response.status).toBe(401)
+ })
+})
diff --git a/control-api/test/routes.auth.mcp-host.issue.security.test.ts b/control-api/test/routes.auth.mcp-host.issue.security.test.ts
index d1523ffe7..0ec31917d 100644
--- a/control-api/test/routes.auth.mcp-host.issue.security.test.ts
+++ b/control-api/test/routes.auth.mcp-host.issue.security.test.ts
@@ -36,6 +36,9 @@ const mockPoolQueryDispatch = vi.fn(async (sql: unknown, params?: unknown[]) =>
if (/rate_limit_buckets/i.test(text)) {
return { rows: [{ count: 1 }], rowCount: 1 }
}
+ if (/lifecycle_state/i.test(text)) {
+ return { rows: [{ lifecycle_state: 'active', lifecycle_version: 1 }], rowCount: 1 }
+ }
return mockPoolQuery(text, params)
})
vi.mock('../src/db.js', () => ({
@@ -89,6 +92,7 @@ describe('Security: External /decide endpoint', () => {
teamId: TEAM_ID,
role: 'admin',
+ authGeneration: 1,
})
})
diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.ts
index 8710be53e..c374ee208 100644
--- a/control-api/test/routes.externalGfs.test.ts
+++ b/control-api/test/routes.externalGfs.test.ts
@@ -100,6 +100,10 @@ const ACTIVE_LINK = {
desktopUserId: U1,
controlAdminId: CONTROL_ADMIN_ID,
source: 'initial_setup' as const,
+ lineageId: '88888888-eeee-4eee-8eee-888888888888',
+ generation: 1,
+ desktopUserGeneration: 1,
+ controlAdminGeneration: 1,
createdAt: new Date('2026-08-10T00:00:00.000Z'),
}
@@ -460,11 +464,15 @@ describe('linked Desktop operator authority contract', () => {
subject: CONTROL_ADMIN_ID,
drive: 'main',
scopes: ['gfs.write'],
+ authGeneration: 1,
principalType: 'control-admin',
brokeredAuthority: {
desktopUserId: U1,
controlAdminId: CONTROL_ADMIN_ID,
authoritySource: 'linked-admin',
+ linkLineageId: ACTIVE_LINK.lineageId,
+ linkGeneration: ACTIVE_LINK.generation,
+ desktopUserGeneration: ACTIVE_LINK.desktopUserGeneration,
},
})
const fetchOptions = (vi.mocked(fetch).mock.calls[0]?.[1] ?? {}) as RequestInit
diff --git a/control-api/test/routes.gfsProxy.test.ts b/control-api/test/routes.gfsProxy.test.ts
index b4322630c..b4626046a 100644
--- a/control-api/test/routes.gfsProxy.test.ts
+++ b/control-api/test/routes.gfsProxy.test.ts
@@ -24,11 +24,11 @@ vi.mock('../src/auth/gfsToken.js', () => ({
vi.mock('../src/middleware/controlUIAuth.js', () => ({
requireAuthForControlUI: (
- req: { adminAuth?: { sub: string } },
+ req: { adminAuth?: { sub: string; sessionVersion?: number } },
_res: unknown,
next: () => void
) => {
- req.adminAuth = { sub: 'operator' }
+ req.adminAuth = { sub: 'operator', sessionVersion: 1 }
next()
},
}))
diff --git a/control-api/test/routes.profile.test.ts b/control-api/test/routes.profile.test.ts
index 78f13e2ef..6dca68c9a 100644
--- a/control-api/test/routes.profile.test.ts
+++ b/control-api/test/routes.profile.test.ts
@@ -53,6 +53,17 @@ const rateLimitMock = vi.hoisted(() => ({
checkAndIncrement: vi.fn(),
}))
+const dbMock = vi.hoisted(() => ({
+ query: vi.fn(),
+}))
+
+vi.mock('../src/db.js', () => ({
+ pool: {
+ query: (...args: unknown[]) => dbMock.query(...args),
+ },
+ withTransaction: vi.fn(),
+}))
+
vi.mock('../src/services/directory/index.js', () => svc)
vi.mock('../src/services/rateLimiterService.js', () => rateLimitMock)
vi.mock(
@@ -77,6 +88,7 @@ describe('routes/profile', () => {
teamId: 't1',
role: 'member',
+ authGeneration: 1,
})
const rpcAccessToken = signRpcAccessToken({
sub: 'u1',
@@ -114,6 +126,12 @@ describe('routes/profile', () => {
windowStartMs: Date.now(),
count: 1,
})
+ dbMock.query.mockImplementation(async (sql: string) => {
+ if (sql.includes('lifecycle_state')) {
+ return { rows: [{ lifecycle_state: 'active', lifecycle_version: 1 }], rowCount: 1 }
+ }
+ return { rows: [], rowCount: 0 }
+ })
})
function mountInternalRoutes(app: express.Express, gateway: unknown) {
@@ -303,6 +321,7 @@ describe('routes/profile', () => {
teamId: null,
role: 'member',
+ authGeneration: 1,
})
await withInternalServiceAuth(request(app).post('/external/auth/verify'))
@@ -621,6 +640,7 @@ describe('routes/profile', () => {
teamId: 'team-from-claims',
role: 'member',
+ authGeneration: 1,
})
const app = express()
@@ -661,6 +681,7 @@ describe('routes/profile', () => {
teamId: null,
role: 'member',
+ authGeneration: 1,
})
svc.getUserAgents.mockResolvedValue({
userId: 'user-teamless',
@@ -706,6 +727,7 @@ describe('routes/profile', () => {
teamId: null,
role: 'member',
+ authGeneration: 1,
})
svc.getUserAgents.mockResolvedValue({
userId: 'user-teamless',
@@ -736,6 +758,7 @@ describe('routes/profile', () => {
teamId: null,
role: 'member',
+ authGeneration: 1,
})
sandboxUiScopeMock.userHasUiBearingRecipeAccess.mockResolvedValue(true)
rpcMock.issueRpcAccessToken.mockReturnValue({
@@ -787,6 +810,7 @@ describe('routes/profile', () => {
teamId: null,
role: 'member',
+ authGeneration: 1,
})
const app = express()
@@ -812,6 +836,7 @@ describe('routes/profile', () => {
teamId: null,
role: 'member',
+ authGeneration: 1,
})
const app = express()
@@ -837,6 +862,7 @@ describe('routes/profile', () => {
teamId: null,
role: 'member',
+ authGeneration: 1,
})
const app = express()
@@ -862,6 +888,7 @@ describe('routes/profile', () => {
teamId: null,
role: 'member',
+ authGeneration: 1,
})
svc.getUserAgents.mockResolvedValue({
userId: 'user-teamless',
diff --git a/control-api/test/services.directory.login.passwordBackstop.test.ts b/control-api/test/services.directory.login.passwordBackstop.test.ts
index 70b0a8193..dceb867b1 100644
--- a/control-api/test/services.directory.login.passwordBackstop.test.ts
+++ b/control-api/test/services.directory.login.passwordBackstop.test.ts
@@ -17,13 +17,24 @@ vi.mock('../src/config.js', () => ({
describe('directory login without team memberships', () => {
beforeEach(() => {
dbMocks.txQuery.mockReset()
+ bcryptMock.compare.mockClear()
bcryptMock.compare.mockResolvedValue(true)
})
it('returns a teamless member session instead of creating a default team for password login', async () => {
dbMocks.txQuery
.mockResolvedValueOnce({
- rows: [{ id: 'u1', email: '[email protected]', name: 'Ada', picture: null, password_hash: 'hash' }],
+ rows: [
+ {
+ id: 'u1',
+ email: '[email protected]',
+ name: 'Ada',
+ picture: null,
+ password_hash: 'hash',
+ lifecycle_state: 'active',
+ lifecycle_version: 1,
+ },
+ ],
rowCount: 1,
}) // SELECT user by email
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // findFirstActiveMembership → none
@@ -49,7 +60,17 @@ describe('directory login without team memberships', () => {
it('skips accepted invitation healing when password login already has a membership', async () => {
dbMocks.txQuery
.mockResolvedValueOnce({
- rows: [{ id: 'u1', email: '[email protected]', name: 'Ada', picture: null, password_hash: 'hash' }],
+ rows: [
+ {
+ id: 'u1',
+ email: '[email protected]',
+ name: 'Ada',
+ picture: null,
+ password_hash: 'hash',
+ lifecycle_state: 'active',
+ lifecycle_version: 1,
+ },
+ ],
rowCount: 1,
}) // SELECT user by email
.mockResolvedValueOnce({
@@ -75,7 +96,17 @@ describe('directory login without team memberships', () => {
it('heals accepted invitations when password login has no active membership', async () => {
dbMocks.txQuery
.mockResolvedValueOnce({
- rows: [{ id: 'u1', email: '[email protected]', name: 'Ada', picture: null, password_hash: 'hash' }],
+ rows: [
+ {
+ id: 'u1',
+ email: '[email protected]',
+ name: 'Ada',
+ picture: null,
+ password_hash: 'hash',
+ lifecycle_state: 'active',
+ lifecycle_version: 1,
+ },
+ ],
rowCount: 1,
}) // SELECT user by email
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // findFirstActiveMembership → none
@@ -101,11 +132,20 @@ describe('directory login without team memberships', () => {
it('returns a teamless member session instead of creating a default team for Google login', async () => {
dbMocks.txQuery
.mockResolvedValueOnce({
- rows: [{ id: 'u1', email: '[email protected]', name: 'Ada', picture: null }],
+ rows: [
+ {
+ id: 'u1',
+ email: '[email protected]',
+ name: 'Ada',
+ picture: null,
+ lifecycle_state: 'active',
+ lifecycle_version: 1,
+ },
+ ],
rowCount: 1,
}) // SELECT user by email
.mockResolvedValueOnce({
- rows: [{ id: 'u1', email: '[email protected]', name: 'Ada', picture: null }],
+ rows: [{ id: 'u1', email: '[email protected]', name: 'Ada', picture: null, lifecycle_version: 1 }],
rowCount: 1,
}) // UPDATE user
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT profiles
@@ -132,7 +172,17 @@ describe('directory login without team memberships', () => {
it('does NOT self-heal (no team created) when the password is wrong', async () => {
bcryptMock.compare.mockResolvedValue(false)
dbMocks.txQuery.mockResolvedValueOnce({
- rows: [{ id: 'u1', email: '[email protected]', name: 'Ada', picture: null, password_hash: 'hash' }],
+ rows: [
+ {
+ id: 'u1',
+ email: '[email protected]',
+ name: 'Ada',
+ picture: null,
+ password_hash: 'hash',
+ lifecycle_state: 'active',
+ lifecycle_version: 1,
+ },
+ ],
rowCount: 1,
}) // SELECT user
@@ -156,4 +206,48 @@ describe('directory login without team memberships', () => {
expect.anything()
)
})
+
+ it('denies password login for a retired user before bcrypt or membership healing', async () => {
+ dbMocks.txQuery.mockResolvedValueOnce({
+ rows: [
+ {
+ id: 'u-retired',
+ email: '[email protected]',
+ name: 'Retired',
+ picture: null,
+ password_hash: 'hash',
+ lifecycle_state: 'retired',
+ lifecycle_version: 2,
+ },
+ ],
+ rowCount: 1,
+ })
+
+ await expect(passwordLoginData({ email: '[email protected]', password: 'x' })).resolves.toEqual({
+ error: 'user_retired',
+ })
+ expect(bcryptMock.compare).not.toHaveBeenCalled()
+ expect(dbMocks.txQuery).toHaveBeenCalledTimes(1)
+ })
+
+ it('denies Google login for a retired user before profile healing or identity update', async () => {
+ dbMocks.txQuery.mockResolvedValueOnce({
+ rows: [
+ {
+ id: 'u-retired',
+ email: '[email protected]',
+ name: 'Retired',
+ picture: null,
+ lifecycle_state: 'retired',
+ lifecycle_version: 2,
+ },
+ ],
+ rowCount: 1,
+ })
+
+ await expect(googleLoginData({ email: '[email protected]', name: 'New name' })).resolves.toEqual({
+ error: 'user_retired',
+ })
+ expect(dbMocks.txQuery).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/control-api/test/services.gfsDesktopOperatorLinkService.test.ts b/control-api/test/services.gfsDesktopOperatorLinkService.test.ts
index f31a30dba..d0e7c2dd0 100644
--- a/control-api/test/services.gfsDesktopOperatorLinkService.test.ts
+++ b/control-api/test/services.gfsDesktopOperatorLinkService.test.ts
@@ -22,6 +22,10 @@ function storedLink(
control_admin_id: controlAdminId,
source,
created_at: CREATED_AT,
+ desktop_user_exists: true,
+ desktop_user_lifecycle_state: 'active',
+ control_admin_exists: true,
+ control_admin_status: 'active',
}
}
diff --git a/deploy/scripts/provision-gfs-db.sh b/deploy/scripts/provision-gfs-db.sh
index 7e3d0ca2a..537ddde2d 100755
--- a/deploy/scripts/provision-gfs-db.sh
+++ b/deploy/scripts/provision-gfs-db.sh
@@ -155,18 +155,55 @@ SELECT (
NOT has_table_privilege(:'role_name', 'control_admin_users', 'SELECT')
AND has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')
AND has_column_privilege(:'role_name', 'control_admin_users', 'status', 'SELECT')
+ AND has_column_privilege(:'role_name', 'control_admin_users', 'session_version', 'SELECT')
AND NOT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'control_admin_users'
- AND column_name NOT IN ('id', 'status')
+ AND column_name NOT IN ('id', 'status', 'session_version')
AND has_column_privilege(:'role_name', 'control_admin_users', column_name, 'SELECT')
)
AND NOT has_any_column_privilege(:'role_name', 'control_admin_users',
'INSERT,UPDATE,REFERENCES')
AND NOT has_table_privilege(:'role_name', 'control_admin_users',
'DELETE,TRUNCATE,TRIGGER')
+ AND NOT has_table_privilege(:'role_name', 'users', 'SELECT')
+ AND has_column_privilege(:'role_name', 'users', 'id', 'SELECT')
+ AND has_column_privilege(:'role_name', 'users', 'lifecycle_state', 'SELECT')
+ AND has_column_privilege(:'role_name', 'users', 'lifecycle_version', 'SELECT')
+ AND NOT EXISTS (
+ SELECT 1
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'users'
+ AND column_name NOT IN ('id', 'lifecycle_state', 'lifecycle_version')
+ AND has_column_privilege(:'role_name', 'users', column_name, 'SELECT')
+ )
+ AND NOT has_any_column_privilege(:'role_name', 'users',
+ 'INSERT,UPDATE,REFERENCES')
+ AND NOT has_table_privilege(:'role_name', 'users',
+ 'DELETE,TRUNCATE,TRIGGER')
+ AND NOT has_table_privilege(:'role_name', 'gfs_desktop_operator_links', 'SELECT')
+ AND has_column_privilege(:'role_name', 'gfs_desktop_operator_links', 'id', 'SELECT')
+ AND has_column_privilege(:'role_name', 'gfs_desktop_operator_links', 'lineage_id', 'SELECT')
+ AND has_column_privilege(:'role_name', 'gfs_desktop_operator_links', 'generation', 'SELECT')
+ AND has_column_privilege(:'role_name', 'gfs_desktop_operator_links', 'user_id', 'SELECT')
+ AND has_column_privilege(:'role_name', 'gfs_desktop_operator_links', 'control_admin_id', 'SELECT')
+ AND has_column_privilege(:'role_name', 'gfs_desktop_operator_links', 'state', 'SELECT')
+ AND has_column_privilege(:'role_name', 'gfs_desktop_operator_links', 'source', 'SELECT')
+ AND NOT EXISTS (
+ SELECT 1
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'gfs_desktop_operator_links'
+ AND column_name NOT IN ('id', 'lineage_id', 'generation', 'user_id', 'control_admin_id', 'state', 'source')
+ AND has_column_privilege(:'role_name', 'gfs_desktop_operator_links', column_name, 'SELECT')
+ )
+ AND NOT has_any_column_privilege(:'role_name', 'gfs_desktop_operator_links',
+ 'INSERT,UPDATE,REFERENCES')
+ AND NOT has_table_privilege(:'role_name', 'gfs_desktop_operator_links',
+ 'DELETE,TRUNCATE,TRIGGER')
AND NOT has_table_privilege(:'role_name', 'team_members', 'SELECT')
AND has_column_privilege(:'role_name', 'team_members', 'team_id', 'SELECT')
AND has_column_privilege(:'role_name', 'team_members', 'user_id', 'SELECT')
diff --git a/gfs-controller/src/api/serve.test.ts b/gfs-controller/src/api/serve.test.ts
index 31e73dec5..0c6cb0f66 100644
--- a/gfs-controller/src/api/serve.test.ts
+++ b/gfs-controller/src/api/serve.test.ts
@@ -1,9 +1,10 @@
+import { describe, expect, it } from "vitest";
import type { IncomingMessage, ServerResponse } from "node:http";
import { Readable, Writable } from "node:stream";
-import { describe, expect, it } from "vitest";
import { GfsAuthError, type GfsScope, type GfsVerifiedClaims } from "../auth/verify";
import type { AuthzContext } from "../authz/permissionClient";
import type { GfsPermission } from "../authz/resolve";
+import { GfsSubjectResolutionDeniedError } from "../authz/subjectResolver";
import { GfsError } from "./errors";
import { GfsResource } from "./read";
import { GfsServingHandler, ServingDeps } from "./serve";
@@ -44,7 +45,9 @@ function reqBody(
opts: { method: string; auth?: string; body?: unknown; rawBody?: string }
): IncomingMessage {
const json = opts.rawBody ?? (opts.body === undefined ? "" : JSON.stringify(opts.body));
- const stream = Readable.from(json ? [Buffer.from(json, "utf8")] : []) as unknown as IncomingMessage;
+ const stream = Readable.from(
+ json ? [Buffer.from(json, "utf8")] : []
+ ) as unknown as IncomingMessage;
stream.url = url;
stream.method = opts.method;
stream.headers = opts.auth !== undefined ? { authorization: opts.auth } : {};
@@ -120,7 +123,8 @@ describe("GfsReadServer.tryHandle — routing", () => {
it("handles a matched read path with the wrong method as a 404", async () => {
const res = new FakeRes();
- const handled = await run(deps(),
+ const handled = await run(
+ deps(),
req(`/v1/resources/${RID}`, { method: "POST", auth: "Bearer t" }),
res
);
@@ -160,6 +164,21 @@ describe("GfsReadServer.tryHandle — auth chain (fail-closed)", () => {
expect((res.json as { error: { code: string } }).error.code).toBe("not_mounted");
});
+ it("403 when the subject is retired or its authority generation is stale", async () => {
+ const res = new FakeRes();
+ const d = deps({
+ resolveContext: async () => {
+ throw new GfsSubjectResolutionDeniedError("user is retired or token generation is stale");
+ },
+ });
+ await run(d, req(`/v1/resources/${RID}`, { auth: "Bearer t" }), res);
+ expect(res.statusCode).toBe(403);
+ expect((res.json as { error: { code: string; message: string } }).error).toEqual({
+ code: "forbidden",
+ message: "principal is not authorized for GFS",
+ });
+ });
+
it("403 when the store denies — and NO resource metadata is leaked", async () => {
const res = new FakeRes();
const d = deps({ authorize: async () => ({ allowed: false }) });
@@ -196,10 +215,7 @@ describe("GfsReadServer.tryHandle — auth chain (fail-closed)", () => {
it("400 path_invalid for a malformed rid (never reaches the store as a 503)", async () => {
const res = new FakeRes();
- await run(deps(),
- req("/v1/resources/not-a-valid-rid!!", { auth: "Bearer t" }),
- res
- );
+ await run(deps(), req("/v1/resources/not-a-valid-rid!!", { auth: "Bearer t" }), res);
expect(res.statusCode).toBe(400);
expect((res.json as { error: { code: string } }).error.code).toBe("path_invalid");
});
@@ -228,10 +244,7 @@ describe("GfsReadServer.tryHandle — served reads", () => {
it("200 content streams the raw bytes with length + uri headers", async () => {
const res = new FakeRes();
- await run(deps(),
- req(`/v1/resources/${RID}/content`, { auth: "Bearer t" }),
- res
- );
+ await run(deps(), req(`/v1/resources/${RID}/content`, { auth: "Bearer t" }), res);
expect(res.statusCode).toBe(200);
expect(res.headers["Content-Length"]).toBe("11");
expect(res.headers["X-Gfs-Uri"]).toBe(`gfs://main/${RID}`);
@@ -246,7 +259,7 @@ describe("GfsReadServer.tryHandle — served reads", () => {
source.push("partial");
const d = deps({ blobs: { read: async () => source } });
const handled = run(d, req(`/v1/resources/${RID}/content`, { auth: "Bearer t" }), res);
- await new Promise(resolve => setTimeout(resolve, 0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
res.emit("close");
await handled;
expect(source.destroyed).toBe(true);
@@ -254,7 +267,8 @@ describe("GfsReadServer.tryHandle — served reads", () => {
it("200 resolve maps a gfs:// uri (same drive) to its view", async () => {
const res = new FakeRes();
- await run(deps(),
+ await run(
+ deps(),
req(`/v1/resolve?uri=${encodeURIComponent(`gfs://main/${RID}`)}`, { auth: "Bearer t" }),
res
);
@@ -264,7 +278,8 @@ describe("GfsReadServer.tryHandle — served reads", () => {
it("403 resolve across a DIFFERENT drive than the token (no cross-drive existence probe)", async () => {
const res = new FakeRes();
- await run(deps(),
+ await run(
+ deps(),
req(`/v1/resolve?uri=${encodeURIComponent(`gfs://other/${RID}`)}`, { auth: "Bearer t" }),
res
);
@@ -295,7 +310,8 @@ describe("GfsReadServer.tryHandle — served reads", () => {
});
await run(deps({ listAccessible }), req("/v1/accessible?limit=20", { auth: "Bearer t" }), res);
expect(res.statusCode).toBe(200);
- const data = (res.json as { data: { items: Array<{ gfsUri: string; permissions: string[] }> } }).data;
+ const data = (res.json as { data: { items: Array<{ gfsUri: string; permissions: string[] }> } })
+ .data;
expect(data.items[0]?.gfsUri).toBe(`gfs://main/${RID}`);
expect(data.items[0]?.permissions).toContain("write");
});
@@ -328,11 +344,14 @@ describe("GfsReadServer.tryHandle — served reads", () => {
);
expect(res.statusCode).toBe(403);
});
-
});
const WRITE_SCOPES: GfsScope[] = ["gfs.read", "gfs.write", "gfs.delete"];
-const AGENT_CLAIMS: GfsVerifiedClaims = { ...CLAIMS, sub: "host:1st:mcp-host/standalone", scopes: WRITE_SCOPES };
+const AGENT_CLAIMS: GfsVerifiedClaims = {
+ ...CLAIMS,
+ sub: "host:1st:mcp-host/standalone",
+ scopes: WRITE_SCOPES,
+};
const USER_WRITE_CLAIMS: GfsVerifiedClaims = { ...CLAIMS, scopes: WRITE_SCOPES };
/** A recording write service; each method records its input and returns a row. */
@@ -354,7 +373,11 @@ function recordingWriteService() {
return { svc: svc as unknown as ServingDeps["writeService"], calls };
}
-function writeDeps(over: Partial<ServingDeps> = {}): { d: ServingDeps; calls: Array<{ op: string; input: unknown }>; authzOps: GfsPermission[] } {
+function writeDeps(over: Partial<ServingDeps> = {}): {
+ d: ServingDeps;
+ calls: Array<{ op: string; input: unknown }>;
+ authzOps: GfsPermission[];
+} {
const { svc, calls } = recordingWriteService();
const authzOps: GfsPermission[] = [];
const d = deps({
@@ -464,7 +487,11 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
const { d, calls, authzOps } = writeDeps();
await run(
d,
- reqBody(`/v1/resources/${RID}/children`, { method: "POST", auth: "Bearer t", body: { name: "n.txt", content: "hi" } }),
+ reqBody(`/v1/resources/${RID}/children`, {
+ method: "POST",
+ auth: "Bearer t",
+ body: { name: "n.txt", content: "hi" },
+ }),
res
);
expect(res.statusCode).toBe(201);
@@ -479,7 +506,11 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
const { d, calls, authzOps } = writeDeps();
await run(
d,
- reqBody(`/v1/resources/${RID}/children`, { method: "POST", auth: "Bearer t", body: { name: "docs", kind: "directory" } }),
+ reqBody(`/v1/resources/${RID}/children`, {
+ method: "POST",
+ auth: "Bearer t",
+ body: { name: "docs", kind: "directory" },
+ }),
res
);
expect(res.statusCode).toBe(201);
@@ -516,7 +547,11 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
const { d, calls, authzOps } = writeDeps();
await run(
d,
- reqBody(`/v1/resources/${RID}/content`, { method: "PUT", auth: "Bearer t", body: { content: "new", ifMatch: 2 } }),
+ reqBody(`/v1/resources/${RID}/content`, {
+ method: "PUT",
+ auth: "Bearer t",
+ body: { content: "new", ifMatch: 2 },
+ }),
res
);
expect(res.statusCode).toBe(200);
@@ -529,7 +564,11 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
const { d, calls } = writeDeps();
await run(
d,
- reqBody(`/v1/resources/${RID}/content`, { method: "PUT", auth: "Bearer t", body: { contentBase64: "bmV3", ifMatch: 2 } }),
+ reqBody(`/v1/resources/${RID}/content`, {
+ method: "PUT",
+ auth: "Bearer t",
+ body: { contentBase64: "bmV3", ifMatch: 2 },
+ }),
res
);
expect(res.statusCode).toBe(200);
@@ -620,7 +659,11 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
const { d, calls } = writeDeps();
await run(
d,
- reqBody(`/v1/resources/${RID}/content`, { method: "PUT", auth: "Bearer t", body: { content: "new" } }),
+ reqBody(`/v1/resources/${RID}/content`, {
+ method: "PUT",
+ auth: "Bearer t",
+ body: { content: "new" },
+ }),
res
);
expect(res.statusCode).toBe(412);
@@ -632,7 +675,11 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
const { d, calls } = writeDeps({ verifyToken: () => USER_WRITE_CLAIMS });
await run(
d,
- reqBody(`/v1/resources/${RID}/content`, { method: "PUT", auth: "Bearer t", body: { content: "new" } }),
+ reqBody(`/v1/resources/${RID}/content`, {
+ method: "PUT",
+ auth: "Bearer t",
+ body: { content: "new" },
+ }),
res
);
expect(res.statusCode).toBe(200);
@@ -654,10 +701,18 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
it("403 when the store denies the write — the write service is never called", async () => {
const res = new FakeRes();
const { svc, calls } = recordingWriteService();
- const d = deps({ verifyToken: () => AGENT_CLAIMS, authorize: async () => ({ allowed: false }), writeService: svc });
+ const d = deps({
+ verifyToken: () => AGENT_CLAIMS,
+ authorize: async () => ({ allowed: false }),
+ writeService: svc,
+ });
await run(
d,
- reqBody(`/v1/resources/${RID}/children`, { method: "POST", auth: "Bearer t", body: { name: "x", content: "y" } }),
+ reqBody(`/v1/resources/${RID}/children`, {
+ method: "POST",
+ auth: "Bearer t",
+ body: { name: "x", content: "y" },
+ }),
res
);
expect(res.statusCode).toBe(403);
@@ -669,7 +724,11 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
// default deps() has no writeService
await run(
deps({ verifyToken: () => AGENT_CLAIMS }),
- reqBody(`/v1/resources/${RID}/children`, { method: "POST", auth: "Bearer t", body: { name: "x", content: "y" } }),
+ reqBody(`/v1/resources/${RID}/children`, {
+ method: "POST",
+ auth: "Bearer t",
+ body: { name: "x", content: "y" },
+ }),
res
);
expect(res.statusCode).toBe(404);
@@ -680,7 +739,11 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
const { d } = writeDeps();
await run(
d,
- reqBody(`/v1/resources/${RID}/children`, { method: "POST", auth: "Bearer t", body: { content: "no name" } }),
+ reqBody(`/v1/resources/${RID}/children`, {
+ method: "POST",
+ auth: "Bearer t",
+ body: { content: "no name" },
+ }),
res
);
expect(res.statusCode).toBe(400);
diff --git a/gfs-controller/src/api/serve.ts b/gfs-controller/src/api/serve.ts
index 21acf3f52..49cb12317 100644
--- a/gfs-controller/src/api/serve.ts
+++ b/gfs-controller/src/api/serve.ts
@@ -1,28 +1,29 @@
import { randomUUID } from "node:crypto";
import type { IncomingMessage, ServerResponse } from "node:http";
-import type { GfsMetrics } from "../metrics";
-import { auditAttribution, type AuthzContext } from "../authz/permissionClient";
-import type { AuditSink } from "../authz/audit";
+import type { GfsVerifiedClaims } from "../auth/verify";
import type { AccessibleResourcePage } from "../authz/accessibleStore";
+import type { AuditSink } from "../authz/audit";
+import { type AuthzContext, auditAttribution } from "../authz/permissionClient";
import type { GfsPermission } from "../authz/resolve";
+import { GfsSubjectResolutionDeniedError } from "../authz/subjectResolver";
import { checkTokenCeiling } from "../authz/tokenCeiling";
-import type { GfsVerifiedClaims } from "../auth/verify";
import type { GfsWriteService } from "../db/writeStore";
-import { normalizeResourceId, PathError } from "../storage/paths";
+import type { GfsMetrics } from "../metrics";
+import { PathError, normalizeResourceId } from "../storage/paths";
+import { type CopyRouteDeps, executeCopyRoute } from "./copyRoute";
+import { ok, toResponse } from "./envelope";
+import { GfsError } from "./errors";
import {
BlobReader,
+ ResourceStore,
downloadResource,
listChildren,
- ResourceStore,
statResource,
toView,
} from "./read";
-import { ok, toResponse } from "./envelope";
-import { executeCopyRoute, type CopyRouteDeps } from "./copyRoute";
import { executeRenameRoute } from "./renameRoute";
-import { GfsError } from "./errors";
-import { normalizeResourceName, ResourceNameError } from "./resourceName";
-import { planWrite, WriteError } from "./write";
+import { ResourceNameError, normalizeResourceName } from "./resourceName";
+import { WriteError, planWrite } from "./write";
/**
* Strip control characters (CR/LF/tab, C0 controls, DEL) and bound the length of
@@ -68,13 +69,23 @@ export function sanitizeForLog(value: string): string {
export interface ServingDeps {
verifyToken: (token: string) => GfsVerifiedClaims;
resolveContext: (
- claims: Pick<GfsVerifiedClaims, "sub" | "drive" | "brokeredAuthority" | "principalType">,
+ claims: Pick<
+ GfsVerifiedClaims,
+ "sub" | "drive" | "brokeredAuthority" | "principalType" | "authGeneration"
+ >,
requestId?: string
) => Promise<AuthzContext>;
/** Permission-store authorization (the source of truth). */
- authorize: (ctx: AuthzContext, resourceId: string, op: GfsPermission) => Promise<{ allowed: boolean }>;
+ authorize: (
+ ctx: AuthzContext,
+ resourceId: string,
+ op: GfsPermission
+ ) => Promise<{ allowed: boolean }>;
/** Lists direct resources visible to the resolved principal. */
- listAccessible?: (ctx: AuthzContext, opts: { limit?: unknown; cursor?: string }) => Promise<AccessibleResourcePage>;
+ listAccessible?: (
+ ctx: AuthzContext,
+ opts: { limit?: unknown; cursor?: string }
+ ) => Promise<AccessibleResourcePage>;
store: ResourceStore;
blobs: BlobReader;
/** The transactional write data plane. Absent on a read-only replica — write
@@ -229,17 +240,34 @@ export class GfsServingHandler {
if (!resourceMatch && !resolveMatch && !accessibleMatch && !copyMatch) return false;
const method = req.method ?? "GET";
- const isWrite = method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";
+ const isWrite =
+ method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";
const copyWrite = method === "POST" && copyMatch && this.deps.writeService && this.deps.copy;
- const renameWrite = method === "PATCH" && resourceMatch?.[2] === undefined
- && this.deps.writeService && this.deps.audit && this.deps.rename;
- const resourceWrite = isWrite && this.deps.writeService && resourceMatch
- && (method === "DELETE" || Boolean(this.deps.audit));
- if ((copyMatch && !copyWrite) || (method === "PATCH" && !renameWrite) || (method !== "GET" && !resourceWrite && !copyWrite)) {
+ const renameWrite =
+ method === "PATCH" &&
+ resourceMatch?.[2] === undefined &&
+ this.deps.writeService &&
+ this.deps.audit &&
+ this.deps.rename;
+ const resourceWrite =
+ isWrite &&
+ this.deps.writeService &&
+ resourceMatch &&
+ (method === "DELETE" || Boolean(this.deps.audit));
+ if (
+ (copyMatch && !copyWrite) ||
+ (method === "PATCH" && !renameWrite) ||
+ (method !== "GET" && !resourceWrite && !copyWrite)
+ ) {
// This 404 can be written before a request body was consumed (e.g. a
// POST with a body to an unsupported verb/route) — same socket-poisoning
// risk as the catch path below, so it carries the same close semantics.
- sendJson(res, 404, { ok: false, error: { code: "not_found", message: "not found" } }, abortConnectionHeader(req));
+ sendJson(
+ res,
+ 404,
+ { ok: false, error: { code: "not_found", message: "not found" } },
+ abortConnectionHeader(req)
+ );
return true;
}
@@ -250,8 +278,14 @@ export class GfsServingHandler {
: undefined;
try {
const claims = this.deps.verifyToken(bearerToken(req));
- const needsMutationRequestId = Boolean(copyMatch) || Boolean(renameWrite)
- || Boolean(resourceMatch && ((method === "POST" && resourceMatch[2] === "children") || (method === "PUT" && resourceMatch[2] === "content")));
+ const needsMutationRequestId =
+ Boolean(copyMatch) ||
+ Boolean(renameWrite) ||
+ Boolean(
+ resourceMatch &&
+ ((method === "POST" && resourceMatch[2] === "children") ||
+ (method === "PUT" && resourceMatch[2] === "content"))
+ );
const requestId = needsMutationRequestId ? requireRequestId(req) : undefined;
const ctx = await this.authContext(claims, req, requestId);
copyAbort?.signal.throwIfAborted();
@@ -351,16 +385,27 @@ export class GfsServingHandler {
}
/** Resolve the principal to its subject set; a store failure is fail-closed 503. */
- private async authContext(claims: GfsVerifiedClaims, req: IncomingMessage, admittedRequestId?: string): Promise<AuthzContext> {
+ private async authContext(
+ claims: GfsVerifiedClaims,
+ req: IncomingMessage,
+ admittedRequestId?: string
+ ): Promise<AuthzContext> {
const requestId = admittedRequestId ?? headerValue(req, "x-request-id");
try {
- return await this.deps.resolveContext({
- sub: claims.sub,
- drive: claims.drive,
- ...(claims.brokeredAuthority ? { brokeredAuthority: claims.brokeredAuthority } : {}),
- ...(claims.principalType ? { principalType: claims.principalType } : {}),
- }, requestId);
+ return await this.deps.resolveContext(
+ {
+ sub: claims.sub,
+ drive: claims.drive,
+ ...(claims.brokeredAuthority ? { brokeredAuthority: claims.brokeredAuthority } : {}),
+ ...(claims.principalType ? { principalType: claims.principalType } : {}),
+ ...(claims.authGeneration === undefined ? {} : { authGeneration: claims.authGeneration }),
+ },
+ requestId
+ );
} catch (err) {
+ if (err instanceof GfsSubjectResolutionDeniedError) {
+ throw new GfsError("forbidden", "principal is not authorized for GFS");
+ }
throw new GfsError(
"not_mounted",
`subject resolution failed: ${err instanceof Error ? err.message : String(err)}`
@@ -415,7 +460,11 @@ export class GfsServingHandler {
resourcePath: null,
});
if (!ceiling.allowed) {
- throw new GfsError("forbidden", "read scope is required for accessible-resource discovery", ceiling.reason);
+ throw new GfsError(
+ "forbidden",
+ "read scope is required for accessible-resource discovery",
+ ceiling.reason
+ );
}
if (!this.deps.listAccessible) {
throw new GfsError("not_mounted", "accessible-resource store is unavailable");
@@ -460,7 +509,12 @@ export class GfsServingHandler {
rid: string
): Promise<void> {
await this.authorizeOp(claims, ctx, rid, "read");
- const { resource, stream } = await downloadResource(this.deps.store, this.deps.blobs, claims.drive, rid);
+ const { resource, stream } = await downloadResource(
+ this.deps.store,
+ this.deps.blobs,
+ claims.drive,
+ rid
+ );
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Length": String(resource.bytes),
@@ -516,7 +570,13 @@ export class GfsServingHandler {
): Promise<void> {
const body = await readJsonBody(req, { signal });
const data = await executeCopyRoute({
- body, claims, context: ctx, requestId, admittedAtMs, signal, now: () => this.clock(),
+ body,
+ claims,
+ context: ctx,
+ requestId,
+ admittedAtMs,
+ signal,
+ now: () => this.clock(),
deps: { ...this.deps.copy!, writes: this.deps.writeService! },
});
sendJson(res, 201, ok(data));
@@ -543,7 +603,11 @@ export class GfsServingHandler {
await this.authorizeChecks(claims, ctx, plan.checks);
const created = await this.deps.writeService!.create({
- drive: claims.drive, parentId, name, kind, content,
+ drive: claims.drive,
+ parentId,
+ name,
+ kind,
+ content,
mutation: {
subject: ctx.primarySubject,
requestId,
@@ -572,7 +636,10 @@ export class GfsServingHandler {
await this.authorizeChecks(claims, ctx, plan.checks);
const updated = await this.deps.writeService!.replace({
- drive: claims.drive, resourceId, ifMatch, content,
+ drive: claims.drive,
+ resourceId,
+ ifMatch,
+ content,
mutation: {
subject: ctx.primarySubject,
requestId,
@@ -584,12 +651,21 @@ export class GfsServingHandler {
}
private async serveRename(
- req: IncomingMessage, res: ServerResponse, claims: GfsVerifiedClaims,
- ctx: AuthzContext, resourceId: string, requestId: string
+ req: IncomingMessage,
+ res: ServerResponse,
+ claims: GfsVerifiedClaims,
+ ctx: AuthzContext,
+ resourceId: string,
+ requestId: string
): Promise<void> {
const body = await readJsonBody(req);
const data = await executeRenameRoute({
- body, claims, context: ctx, resourceId, requestId, audit: this.deps.audit!,
+ body,
+ claims,
+ context: ctx,
+ resourceId,
+ requestId,
+ audit: this.deps.audit!,
authorizeWrite: () => this.authorizeOp(claims, ctx, resourceId, "write"),
writes: this.deps.writeService!,
limits: this.deps.rename!,
@@ -633,7 +709,13 @@ function requireRequestId(req: IncomingMessage): string {
const supplied = headerValue(req, "x-request-id");
if (supplied === undefined) return randomUUID();
const normalized = requireRid(supplied);
- return [normalized.slice(0, 8), normalized.slice(8, 12), normalized.slice(12, 16), normalized.slice(16, 20), normalized.slice(20)].join("-");
+ return [
+ normalized.slice(0, 8),
+ normalized.slice(8, 12),
+ normalized.slice(12, 16),
+ normalized.slice(16, 20),
+ normalized.slice(20),
+ ].join("-");
}
function headerValue(req: IncomingMessage, name: string): string | undefined {
@@ -670,7 +752,8 @@ function optionalResourceKind(body: Record<string, unknown>): "file" | "director
function readContentBuffer(body: Record<string, unknown>): Buffer {
const encoded = body.contentBase64;
if (encoded !== undefined) {
- if (typeof encoded !== "string") throw new GfsError("path_invalid", "'contentBase64' must be a string");
+ if (typeof encoded !== "string")
+ throw new GfsError("path_invalid", "'contentBase64' must be a string");
return decodeBase64Content(encoded);
}
return Buffer.from(requireString(body, "content"), "utf8");
@@ -720,9 +803,11 @@ async function readJsonBody(
const chunks: Buffer[] = [];
let total = 0;
const abort = (): void => {
- req.destroy(opts.signal?.reason instanceof Error
- ? opts.signal.reason
- : new GfsError("precondition_failed", "synchronous copy deadline exceeded"));
+ req.destroy(
+ opts.signal?.reason instanceof Error
+ ? opts.signal.reason
+ : new GfsError("precondition_failed", "synchronous copy deadline exceeded")
+ );
};
opts.signal?.throwIfAborted();
opts.signal?.addEventListener("abort", abort, { once: true });
@@ -732,7 +817,10 @@ async function readJsonBody(
const buf = chunk as Buffer;
total += buf.length;
if (total > MAX_WRITE_BODY_BYTES) {
- throw new GfsError("payload_too_large", `request body exceeds ${MAX_WRITE_BODY_BYTES} bytes`);
+ throw new GfsError(
+ "payload_too_large",
+ `request body exceeds ${MAX_WRITE_BODY_BYTES} bytes`
+ );
}
chunks.push(buf);
}
@@ -752,6 +840,9 @@ async function readJsonBody(
}
return parsed as Record<string, unknown>;
} catch (err) {
- throw new GfsError("path_invalid", `invalid JSON body: ${err instanceof Error ? err.message : String(err)}`);
+ throw new GfsError(
+ "path_invalid",
+ `invalid JSON body: ${err instanceof Error ? err.message : String(err)}`
+ );
}
}
diff --git a/gfs-controller/src/auth/verify.test.ts b/gfs-controller/src/auth/verify.test.ts
index eae62d8f6..773ada0f8 100644
--- a/gfs-controller/src/auth/verify.test.ts
+++ b/gfs-controller/src/auth/verify.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { generateKeyPairSync } from "node:crypto";
import jwt from "jsonwebtoken";
+import { generateKeyPairSync } from "node:crypto";
import { KeyConfigError, loadVerificationKey } from "./keys";
import { GfsAuthError, verifyGfsToken } from "./verify";
@@ -20,7 +20,13 @@ const AUD = "gfs-controller";
function sign(
payload: Record<string, unknown>,
- opts: { keyid?: string; audience?: string; issuer?: string; expiresIn?: number; signer?: string } = {}
+ opts: {
+ keyid?: string;
+ audience?: string;
+ issuer?: string;
+ expiresIn?: number;
+ signer?: string;
+ } = {}
): string {
return jwt.sign(payload, opts.signer ?? privateKey, {
algorithm: "RS256",
@@ -54,6 +60,9 @@ const linkedAdminAuthority = {
desktopUserId: DESKTOP_USER_ID,
controlAdminId: CONTROL_ADMIN_ID,
authoritySource: "linked-admin",
+ linkLineageId: "33333333-3333-4333-8333-333333333333",
+ linkGeneration: 1,
+ desktopUserGeneration: 1,
};
describe("loadVerificationKey", () => {
@@ -73,6 +82,26 @@ describe("verifyGfsToken", () => {
expect(claims.exp - claims.iat).toBe(300);
});
+ it("preserves the authoritative auth generation for downstream lifecycle checks", () => {
+ const claims = verifyGfsToken(sign({ ...goodPayload, authGeneration: 7 }), {
+ key,
+ audience: AUD,
+ });
+ expect(claims.authGeneration).toBe(7);
+ });
+
+ it.each([0, -1, Number.MAX_SAFE_INTEGER + 1, 1.5])(
+ "rejects an invalid auth generation: %s",
+ (authGeneration) => {
+ expect(() =>
+ verifyGfsToken(sign({ ...goodPayload, principalType: "user", authGeneration }), {
+ key,
+ audience: AUD,
+ })
+ ).toThrow(/authGeneration/);
+ }
+ );
+
it("REJECTS a token signed by a different key (bad signature)", () => {
const token = sign(goodPayload, { signer: otherPair.privateKey });
expect(() => verifyGfsToken(token, { key, audience: AUD })).toThrow(GfsAuthError);
@@ -95,9 +124,7 @@ describe("verifyGfsToken", () => {
it("REJECTS a token whose kid does not match the configured key", () => {
const token = sign(goodPayload, { keyid: "not-the-thumbprint" });
- expect(() => verifyGfsToken(token, { key, audience: AUD })).toThrow(
- /kid does not match/
- );
+ expect(() => verifyGfsToken(token, { key, audience: AUD })).toThrow(/kid does not match/);
});
it("REJECTS a token missing kid entirely", () => {
@@ -116,9 +143,9 @@ describe("verifyGfsToken", () => {
});
it("REJECTS missing sub / drive / scopes", () => {
- expect(() => verifyGfsToken(sign({ drive: "main", scopes: [] }), { key, audience: AUD })).toThrow(
- GfsAuthError
- );
+ expect(() =>
+ verifyGfsToken(sign({ drive: "main", scopes: [] }), { key, audience: AUD })
+ ).toThrow(GfsAuthError);
expect(() => verifyGfsToken(sign({ sub: "u", scopes: [] }), { key, audience: AUD })).toThrow(
GfsAuthError
);
@@ -156,7 +183,7 @@ describe("verifyGfsToken", () => {
{ ...linkedAdminAuthority, authoritySource: "user-session" },
{ ...linkedAdminAuthority, desktopUserId: "not-a-uuid" },
{ ...linkedAdminAuthority, controlAdminId: "not-a-uuid" },
- ])("rejects malformed brokered authority metadata: %j", brokeredAuthority => {
+ ])("rejects malformed brokered authority metadata: %j", (brokeredAuthority) => {
const token = sign({ ...goodPayload, sub: CONTROL_ADMIN_ID, brokeredAuthority });
expect(() => verifyGfsToken(token, { key, audience: AUD })).toThrow(GfsAuthError);
});
diff --git a/gfs-controller/src/auth/verify.ts b/gfs-controller/src/auth/verify.ts
index 6c77e13fc..71ca091eb 100644
--- a/gfs-controller/src/auth/verify.ts
+++ b/gfs-controller/src/auth/verify.ts
@@ -1,12 +1,7 @@
import jwt from "jsonwebtoken";
import { VerificationKey } from "./keys";
-export type GfsScope =
- | "gfs.read"
- | "gfs.write"
- | "gfs.delete"
- | "gfs.manage_acl"
- | "gfs.share";
+export type GfsScope = "gfs.read" | "gfs.write" | "gfs.delete" | "gfs.manage_acl" | "gfs.share";
const VALID_SCOPES = new Set<string>([
"gfs.read",
@@ -25,6 +20,9 @@ export interface GfsBrokeredAuthority {
desktopUserId: string;
controlAdminId: string;
authoritySource: "linked-admin";
+ linkLineageId?: string;
+ linkGeneration?: number;
+ desktopUserGeneration?: number;
}
export interface GfsVerifiedClaims {
@@ -32,6 +30,8 @@ export interface GfsVerifiedClaims {
drive: string;
scopes: GfsScope[];
pathBindings: GfsPathBinding[];
+ /** users.lifecycle_version or control_admin_users.session_version. */
+ authGeneration?: number;
brokeredAuthority?: GfsBrokeredAuthority;
principalType?: "user" | "control-admin";
iat: number;
@@ -46,7 +46,15 @@ function parseBrokeredAuthority(raw: unknown, sub: string): GfsBrokeredAuthority
throw new GfsAuthError("brokeredAuthority must be an object");
}
const record = raw as Record<string, unknown>;
- if (Object.keys(record).sort().join(",") !== "authoritySource,controlAdminId,desktopUserId") {
+ const supportedKeys = new Set([
+ "authoritySource",
+ "controlAdminId",
+ "desktopUserId",
+ "linkLineageId",
+ "linkGeneration",
+ "desktopUserGeneration",
+ ]);
+ if (Object.keys(record).some((key) => !supportedKeys.has(key))) {
throw new GfsAuthError("brokeredAuthority must contain exactly the supported fields");
}
const desktopUserId = record.desktopUserId;
@@ -63,10 +71,36 @@ function parseBrokeredAuthority(raw: unknown, sub: string): GfsBrokeredAuthority
if (sub.toLowerCase() !== controlAdminId.toLowerCase()) {
throw new GfsAuthError("brokeredAuthority control admin must match token sub");
}
+ const linkLineageId = record.linkLineageId;
+ if (
+ linkLineageId !== undefined &&
+ (typeof linkLineageId !== "string" || !UUID_RE.test(linkLineageId))
+ ) {
+ throw new GfsAuthError("brokeredAuthority.linkLineageId must be a UUID");
+ }
+ const parseGeneration = (value: unknown, field: string): number | undefined => {
+ if (value === undefined) return undefined;
+ if (!Number.isSafeInteger(value) || Number(value) < 1) {
+ throw new GfsAuthError(`brokeredAuthority.${field} must be a positive integer`);
+ }
+ return Number(value);
+ };
return {
desktopUserId: desktopUserId.toLowerCase(),
controlAdminId: controlAdminId.toLowerCase(),
authoritySource: "linked-admin",
+ ...(linkLineageId === undefined ? {} : { linkLineageId: linkLineageId.toLowerCase() }),
+ ...(parseGeneration(record.linkGeneration, "linkGeneration") === undefined
+ ? {}
+ : { linkGeneration: parseGeneration(record.linkGeneration, "linkGeneration") }),
+ ...(parseGeneration(record.desktopUserGeneration, "desktopUserGeneration") === undefined
+ ? {}
+ : {
+ desktopUserGeneration: parseGeneration(
+ record.desktopUserGeneration,
+ "desktopUserGeneration"
+ ),
+ }),
};
}
@@ -160,15 +194,33 @@ export function verifyGfsToken(token: string, opts: VerifyOptions): GfsVerifiedC
const iat = record.iat;
const exp = record.exp;
const principalType = record.principalType;
+ const rawAuthGeneration = record.authGeneration;
if (typeof sub !== "string" || sub.length === 0) throw new GfsAuthError("missing sub");
if (typeof drive !== "string" || drive.length === 0) throw new GfsAuthError("missing drive");
if (!Array.isArray(rawScopes)) throw new GfsAuthError("missing scopes");
if (!Number.isSafeInteger(iat)) throw new GfsAuthError("missing or invalid iat");
if (!Number.isSafeInteger(exp)) throw new GfsAuthError("missing or invalid exp");
- if (principalType !== undefined && principalType !== "user" && principalType !== "control-admin") {
+ if (
+ principalType !== undefined &&
+ principalType !== "user" &&
+ principalType !== "control-admin"
+ ) {
throw new GfsAuthError("invalid principalType");
}
+ if (
+ rawAuthGeneration !== undefined &&
+ (!Number.isSafeInteger(rawAuthGeneration) || Number(rawAuthGeneration) < 0)
+ ) {
+ throw new GfsAuthError("invalid authGeneration");
+ }
+ if (
+ (principalType === "user" || principalType === "control-admin") &&
+ rawAuthGeneration !== undefined &&
+ Number(rawAuthGeneration) < 1
+ ) {
+ throw new GfsAuthError("human principal authGeneration must be positive");
+ }
const issuedAt = iat as number;
const expiresAt = exp as number;
if (expiresAt <= issuedAt) throw new GfsAuthError("token exp must be after iat");
@@ -191,6 +243,7 @@ export function verifyGfsToken(token: string, opts: VerifyOptions): GfsVerifiedC
drive,
scopes,
pathBindings: parsePathBindings(record.pathBindings),
+ ...(rawAuthGeneration === undefined ? {} : { authGeneration: Number(rawAuthGeneration) }),
...(brokeredAuthority ? { brokeredAuthority } : {}),
...(principalType ? { principalType } : {}),
iat: issuedAt,
diff --git a/gfs-controller/src/authz/storeProbe.test.ts b/gfs-controller/src/authz/storeProbe.test.ts
index 079e174d9..ecd0d46e2 100644
--- a/gfs-controller/src/authz/storeProbe.test.ts
+++ b/gfs-controller/src/authz/storeProbe.test.ts
@@ -41,7 +41,7 @@ function fakePool(): PingPool & {
connect: async () => {
if (pool.hangConnect) return new Promise<never>(() => undefined);
if (pool.lateConnectMs > 0) {
- await new Promise(resolve => setTimeout(resolve, pool.lateConnectMs));
+ await new Promise((resolve) => setTimeout(resolve, pool.lateConnectMs));
}
return makeClient();
},
@@ -67,6 +67,12 @@ interface FakeClientBehavior {
auditDecisionEvidenceConstraintsReady?: boolean;
auditActorCorrelationColumnsReady?: boolean;
auditActorCorrelationConstraintReady?: boolean;
+ authorityUsersColumnsReady?: boolean;
+ authorityAdminColumnsReady?: boolean;
+ authorityLinksColumnsReady?: boolean;
+ authorityUsersPrivilegesReady?: boolean;
+ authorityAdminPrivilegesReady?: boolean;
+ authorityLinksPrivilegesReady?: boolean;
canMutateResources?: boolean;
canMutateGrants?: boolean;
canMutateShares?: boolean;
@@ -122,6 +128,12 @@ function fakeClientFactory(behavior: FakeClientBehavior): {
behavior.auditActorCorrelationColumnsReady !== false,
audit_actor_correlation_constraint_ready:
behavior.auditActorCorrelationConstraintReady !== false,
+ authority_users_columns_ready: behavior.authorityUsersColumnsReady !== false,
+ authority_admin_columns_ready: behavior.authorityAdminColumnsReady !== false,
+ authority_links_columns_ready: behavior.authorityLinksColumnsReady !== false,
+ authority_users_privileges_ready: behavior.authorityUsersPrivilegesReady !== false,
+ authority_admin_privileges_ready: behavior.authorityAdminPrivilegesReady !== false,
+ authority_links_privileges_ready: behavior.authorityLinksPrivilegesReady !== false,
can_mutate_resources: behavior.canMutateResources === true,
can_mutate_grants: behavior.canMutateGrants === true,
can_mutate_shares: behavior.canMutateShares === true,
@@ -260,7 +272,7 @@ describe("createPermissionStoreProbe", () => {
it.each(["actor_on_behalf_of", "desktop_user_id", "authority_source"] as const)(
"rejects readiness before 0092 when the required %s audit column is absent or drifted",
- async _column => {
+ async (_column) => {
const { factory } = fakeClientFactory({ auditActorCorrelationColumnsReady: false });
const probe = createPermissionStoreProbe({
pool: fakePool(),
@@ -274,9 +286,32 @@ describe("createPermissionStoreProbe", () => {
}
);
+ it.each([
+ ["users columns", { authorityUsersColumnsReady: false }],
+ ["admin columns", { authorityAdminColumnsReady: false }],
+ ["link columns", { authorityLinksColumnsReady: false }],
+ ["users privileges", { authorityUsersPrivilegesReady: false }],
+ ["admin privileges", { authorityAdminPrivilegesReady: false }],
+ ["link privileges", { authorityLinksPrivilegesReady: false }],
+ ] satisfies Array<[string, FakeClientBehavior]>)(
+ "rejects readiness when the 0095 authority projection is missing (%s)",
+ async (_projection, behavior) => {
+ const { factory } = fakeClientFactory(behavior);
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "reader",
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).rejects.toThrow(/migration 0095/);
+ }
+ );
+
it.each(["reader", "writer"] as const)(
"rejects a %s when migration 0092 audit actor-correlation constraints are missing or unvalidated",
- async storageRole => {
+ async (storageRole) => {
const { factory } = fakeClientFactory({ auditActorCorrelationConstraintReady: false });
const probe = createPermissionStoreProbe({
pool: fakePool(),
@@ -359,6 +394,14 @@ describe("createPermissionStoreProbe", () => {
expect(sql).toContain("authority_source=''linked-admin''");
expect(sql).toContain("desktop_user_idISNULL");
expect(sql).toContain("NOT attnotnull");
+ expect(sql).toContain("authority_users_columns_ready");
+ expect(sql).toContain("authority_admin_columns_ready");
+ expect(sql).toContain("authority_links_columns_ready");
+ expect(sql).toContain("authority_users_privileges_ready");
+ expect(sql).toContain("authority_admin_privileges_ready");
+ expect(sql).toContain("authority_links_privileges_ready");
+ expect(sql).toContain("lifecycle_version");
+ expect(sql).toContain("gfs_desktop_operator_links");
expect(sql).not.toContain("can_mutate_resources");
expect(sql).not.toContain("can_update_audit_sequence");
});
@@ -416,7 +459,7 @@ describe("createPermissionStoreProbe", () => {
});
await expect(probe()).rejects.toThrow(/pool ping timed out after 10ms/);
expect(pool.releases).toHaveLength(0); // not settled yet
- await new Promise(resolve => setTimeout(resolve, 60));
+ await new Promise((resolve) => setTimeout(resolve, 60));
expect(pool.releases).toHaveLength(1); // late acquire returned to the pool
expect(pool.releases[0]).toBeUndefined(); // clean release, not a destroy
});
diff --git a/gfs-controller/src/authz/storeProbe.ts b/gfs-controller/src/authz/storeProbe.ts
index 6a1771b7b..591f9b4df 100644
--- a/gfs-controller/src/authz/storeProbe.ts
+++ b/gfs-controller/src/authz/storeProbe.ts
@@ -112,12 +112,50 @@ const BASE_COHERENCE_SQL =
"AND regexp_replace(pg_get_constraintdef(oid), '\\s+', '', 'g') LIKE '%actor_on_behalf_ofISNULL%' " +
"AND regexp_replace(pg_get_constraintdef(oid), '\\s+', '', 'g') LIKE '%actor_on_behalf_ofISNOTNULL%') AS audit_actor_correlation_constraint_ready";
+const AUTHORITY_PROJECTION_SQL =
+ ", (SELECT count(*) = 3 AND bool_and((attname = 'id' AND atttypid = 'uuid'::regtype) OR " +
+ "(attname = 'lifecycle_state' AND atttypid = 'text'::regtype AND attnotnull) OR " +
+ "(attname = 'lifecycle_version' AND atttypid = 'int8'::regtype AND attnotnull)) " +
+ "FROM pg_attribute WHERE attrelid = 'users'::regclass AND attnum > 0 AND NOT attisdropped " +
+ "AND attname = ANY (ARRAY['id','lifecycle_state','lifecycle_version'])) AS authority_users_columns_ready" +
+ ", (SELECT count(*) = 3 AND bool_and((attname = 'id' AND atttypid = 'uuid'::regtype) OR " +
+ "(attname = 'status' AND atttypid = 'text'::regtype) OR " +
+ "(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(*) = 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 " +
+ "(attname = 'user_id' AND atttypid = 'uuid'::regtype) OR " +
+ "(attname = 'control_admin_id' AND atttypid = 'uuid'::regtype) OR " +
+ "(attname = 'state' AND atttypid = 'text'::regtype) OR " +
+ "(attname = 'source' AND atttypid = 'text'::regtype)) " +
+ "FROM pg_attribute WHERE attrelid = 'gfs_desktop_operator_links'::regclass AND attnum > 0 AND NOT attisdropped " +
+ "AND attname = ANY (ARRAY['id','lineage_id','generation','user_id','control_admin_id','state','source'])) AS authority_links_columns_ready" +
+ ", (CASE WHEN to_regclass('public.users') IS NULL THEN false ELSE " +
+ "has_column_privilege(current_user, 'public.users', 'id', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.users', 'lifecycle_state', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.users', 'lifecycle_version', 'SELECT') END) AS authority_users_privileges_ready" +
+ ", (CASE WHEN to_regclass('public.control_admin_users') IS NULL THEN false ELSE " +
+ "has_column_privilege(current_user, 'public.control_admin_users', 'id', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.control_admin_users', 'status', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.control_admin_users', 'session_version', 'SELECT') END) AS authority_admin_privileges_ready" +
+ ", (CASE WHEN to_regclass('public.gfs_desktop_operator_links') IS NULL THEN false ELSE " +
+ "has_column_privilege(current_user, 'public.gfs_desktop_operator_links', 'id', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.gfs_desktop_operator_links', 'lineage_id', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.gfs_desktop_operator_links', 'generation', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.gfs_desktop_operator_links', 'user_id', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.gfs_desktop_operator_links', 'control_admin_id', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.gfs_desktop_operator_links', 'state', 'SELECT') " +
+ "AND has_column_privilege(current_user, 'public.gfs_desktop_operator_links', 'source', 'SELECT') END) AS authority_links_privileges_ready";
+
// The reader is deliberately read-only except for append-only audit records.
// Positive checks alone are insufficient: a stale/manual grant would keep the
// role Ready while silently expanding its blast radius. These checks use the
// effective current_user privileges, so inherited or PUBLIC grants fail too.
const READER_COHERENCE_SQL =
BASE_COHERENCE_SQL +
+ AUTHORITY_PROJECTION_SQL +
", has_table_privilege(current_user, 'gfs_resources', 'INSERT, UPDATE, DELETE, TRUNCATE') AS can_mutate_resources, " +
"has_table_privilege(current_user, 'gfs_grants', 'INSERT, UPDATE, DELETE, TRUNCATE') AS can_mutate_grants, " +
"has_table_privilege(current_user, 'gfs_shares', 'INSERT, UPDATE, DELETE, TRUNCATE') AS can_mutate_shares, " +
@@ -127,6 +165,7 @@ const READER_COHERENCE_SQL =
const WRITER_COHERENCE_SQL =
BASE_COHERENCE_SQL +
+ AUTHORITY_PROJECTION_SQL +
", has_table_privilege(current_user, 'gfs_blob_manifests', 'SELECT') AS can_read_manifests, " +
"has_table_privilege(current_user, 'gfs_blob_manifests', 'INSERT') AS can_insert_manifests, " +
"has_table_privilege(current_user, 'gfs_blob_manifests', 'UPDATE') AS can_update_manifests, " +
@@ -168,7 +207,7 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi
let acquireTimedOut = false;
const acquire = opts.pool.connect();
acquire.then(
- client => {
+ (client) => {
if (acquireTimedOut) client.release();
},
() => undefined // late rejection: nothing was checked out
@@ -254,6 +293,19 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi
"(control-api migration 0092 not applied?)"
);
}
+ if (
+ row?.authority_users_columns_ready !== true ||
+ row?.authority_admin_columns_ready !== true ||
+ row?.authority_links_columns_ready !== true ||
+ row?.authority_users_privileges_ready !== true ||
+ row?.authority_admin_privileges_ready !== true ||
+ row?.authority_links_privileges_ready !== true
+ ) {
+ throw new Error(
+ "permission store coherence check failed: GFS lifecycle authority projection is missing " +
+ "(control-api migration 0095 not applied?)"
+ );
+ }
if (
opts.storageRole === "reader" &&
(row?.can_mutate_resources !== false ||
@@ -287,7 +339,7 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi
} finally {
// Best-effort close of the ephemeral client; a close error must not mask
// the probe verdict, but it is logged loudly (never swallowed silently).
- await client.end().catch(err => {
+ await client.end().catch((err) => {
console.error(`[gfsc] store-probe client close error: ${errMsg(err)}`);
});
}
diff --git a/gfs-controller/src/authz/subjectResolver.realPostgres.integration.test.ts b/gfs-controller/src/authz/subjectResolver.realPostgres.integration.test.ts
new file mode 100644
index 000000000..610677706
--- /dev/null
+++ b/gfs-controller/src/authz/subjectResolver.realPostgres.integration.test.ts
@@ -0,0 +1,134 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomBytes, randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { GfsSubjectResolutionDeniedError, resolveAuthzContext } from './subjectResolver'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+describeRealPostgres('gfsc subject lifecycle resolution on real PostgreSQL', () => {
+ const database = `gfsc_subject_lifecycle_${randomBytes(6).toString('hex')}`
+ const userId = randomUUID()
+ const adminId = randomUUID()
+ const lineageId = randomUUID()
+ let adminPool: Pool
+ let db: Pool
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database}"`)
+ db = new Pool({ connectionString: databaseUrl(adminUrl as string, database) })
+ await db.query(`
+ CREATE TABLE users (
+ id UUID PRIMARY KEY,
+ lifecycle_state TEXT NOT NULL,
+ lifecycle_version BIGINT NOT NULL
+ );
+ CREATE TABLE control_admin_users (
+ id UUID PRIMARY KEY,
+ status TEXT NOT NULL,
+ session_version INTEGER NOT NULL
+ );
+ CREATE TABLE gfs_desktop_operator_links (
+ id UUID PRIMARY KEY,
+ lineage_id UUID NOT NULL,
+ generation INTEGER NOT NULL,
+ user_id UUID NOT NULL,
+ control_admin_id UUID NOT NULL,
+ state TEXT NOT NULL,
+ source TEXT NOT NULL
+ );
+ CREATE TABLE team_members (
+ team_id UUID NOT NULL,
+ user_id UUID NOT NULL,
+ status TEXT NOT NULL
+ );
+ INSERT INTO users (id, lifecycle_state, lifecycle_version)
+ VALUES ('${userId}', 'active', 1);
+ INSERT INTO control_admin_users (id, status, session_version)
+ VALUES ('${adminId}', 'active', 1);
+ INSERT INTO gfs_desktop_operator_links
+ (id, lineage_id, generation, user_id, control_admin_id, state, source)
+ VALUES ('${randomUUID()}', '${lineageId}', 1, '${userId}', '${adminId}', 'active', 'initial_setup');
+ `)
+ }, 60_000)
+
+ afterAll(async () => {
+ await db?.end()
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database}"`)
+ await adminPool.end()
+ })
+
+ const userClaims = () => ({
+ sub: userId,
+ drive: 'main',
+ principalType: 'user' as const,
+ authGeneration: 1,
+ })
+
+ const linkedClaims = () => ({
+ sub: adminId,
+ drive: 'main',
+ principalType: 'control-admin' as const,
+ authGeneration: 1,
+ brokeredAuthority: {
+ desktopUserId: userId,
+ controlAdminId: adminId,
+ authoritySource: 'linked-admin' as const,
+ linkLineageId: lineageId,
+ linkGeneration: 1,
+ desktopUserGeneration: 1,
+ },
+ })
+
+ it('allows the current user generation, then denies the same bearer after retirement', async () => {
+ await expect(
+ resolveAuthzContext(db, { ...userClaims(), scopes: [], pathBindings: [] })
+ ).resolves.toMatchObject({
+ primarySubject: userId,
+ isOperator: false,
+ })
+ await db.query(
+ `UPDATE users SET lifecycle_state = 'retired', lifecycle_version = 2 WHERE id = $1`,
+ [userId]
+ )
+ await expect(
+ resolveAuthzContext(db, { ...userClaims(), scopes: [], pathBindings: [] })
+ ).rejects.toBeInstanceOf(GfsSubjectResolutionDeniedError)
+ })
+
+ it('denies a linked-admin bearer after the active link generation is revoked', async () => {
+ await db.query(
+ `UPDATE users SET lifecycle_state = 'active', lifecycle_version = 1 WHERE id = $1`,
+ [userId]
+ )
+ await db.query(`UPDATE gfs_desktop_operator_links SET state = 'revoked' WHERE user_id = $1`, [
+ userId,
+ ])
+ await expect(resolveAuthzContext(db, linkedClaims())).rejects.toBeInstanceOf(
+ GfsSubjectResolutionDeniedError
+ )
+ })
+
+ it('denies a linked-admin bearer when the link generation is stale', async () => {
+ await db.query(
+ `UPDATE gfs_desktop_operator_links SET state = 'active', generation = 2 WHERE user_id = $1`,
+ [userId]
+ )
+ await expect(resolveAuthzContext(db, linkedClaims())).rejects.toBeInstanceOf(
+ GfsSubjectResolutionDeniedError
+ )
+ })
+})
diff --git a/gfs-controller/src/authz/subjectResolver.test.ts b/gfs-controller/src/authz/subjectResolver.test.ts
index 924f1faf0..ada0b1468 100644
--- a/gfs-controller/src/authz/subjectResolver.test.ts
+++ b/gfs-controller/src/authz/subjectResolver.test.ts
@@ -1,25 +1,51 @@
import { describe, expect, it } from "vitest";
-import { resolveAuthzContext, SubjectsDb } from "./subjectResolver";
+import { SubjectsDb, resolveAuthzContext } from "./subjectResolver";
/**
- * Fake permission store routed by SQL substring. `operators` is the set of ids
- * that control_admin_users reports as active; `teamsByUser` maps a user id to
- * its active team memberships. Any other query throws — a resolver that issues
- * an unexpected query fails loud here.
+ * Fake permission store routed by SQL substring. The security projection is
+ * explicit: tests must provide active user/admin generations and, for linked
+ * authority, the current active lineage row. Any other query throws.
*/
-function fakeDb(opts: { operators?: Set<string>; teamsByUser?: Record<string, string[]> }): SubjectsDb & {
+function fakeDb(opts: {
+ operators?: Set<string>;
+ teamsByUser?: Record<string, string[]>;
+ users?: Record<string, { lifecycle_state?: string; lifecycle_version?: number }>;
+ links?: Array<{
+ user_id: string;
+ control_admin_id: string;
+ lineage_id: string;
+ generation: number;
+ }>;
+}): SubjectsDb & {
calls: string[];
} {
const operators = opts.operators ?? new Set<string>();
const teamsByUser = opts.teamsByUser ?? {};
+ const users = opts.users ?? {};
+ const links = opts.links ?? [];
const calls: string[] = [];
return {
calls,
async query(text: string, values?: unknown[]) {
calls.push(text);
+ if (text.includes("gfs_desktop_operator_links")) {
+ const [userId, adminId] = values ?? [];
+ return {
+ rows: links.filter(
+ (link) => link.user_id === String(userId) && link.control_admin_id === String(adminId)
+ ),
+ };
+ }
+ if (text.includes("FROM users")) {
+ const id = String(values?.[0]);
+ const user = users[id];
+ return { rows: user ? [{ id, ...user }] : [] };
+ }
if (text.includes("control_admin_users")) {
const id = String(values?.[0]);
- return { rows: operators.has(id) ? [{ "?column?": 1 }] : [] };
+ return {
+ rows: operators.has(id) ? [{ id, status: "active", session_version: 1 }] : [],
+ };
}
if (text.includes("team_members")) {
const id = String(values?.[0]);
@@ -33,7 +59,11 @@ function fakeDb(opts: { operators?: Set<string>; teamsByUser?: Record<string, st
describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () => {
it("resolves a 1st-party host sub to itself, no operator, no group query", async () => {
const db = fakeDb({});
- const ctx = await resolveAuthzContext(db, { sub: "host:1st:mcp-host/standalone", drive: "main" }, "req-1");
+ const ctx = await resolveAuthzContext(
+ db,
+ { sub: "host:1st:mcp-host/standalone", drive: "main" },
+ "req-1"
+ );
expect(ctx).toEqual({
drive: "main",
subjects: ["host:1st:mcp-host/standalone"],
@@ -53,11 +83,11 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =
expect(db.calls).toEqual([]);
});
- it("rejects legacy or malformed host subjects into the normal user path", async () => {
+ it("rejects legacy or malformed host subjects instead of treating them as users", async () => {
const db = fakeDb({});
- const ctx = await resolveAuthzContext(db, { sub: "host:1st:chatllm", drive: "main" });
- expect(ctx.subjects).toEqual(["user:host:1st:chatllm"]);
- expect(db.calls.some((q) => q.includes("team_members"))).toBe(true);
+ await expect(
+ resolveAuthzContext(db, { sub: "host:1st:chatllm", drive: "main", authGeneration: 1 })
+ ).rejects.toThrow("user principal must be a UUID");
});
it("grants intrinsic operator authority when sub is in control_admin_users", async () => {
@@ -67,6 +97,7 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =
sub: opId,
drive: "main",
principalType: "control-admin",
+ authGeneration: 1,
});
expect(ctx.isOperator).toBe(true);
expect(ctx.subjects).toEqual(["operator:"]);
@@ -77,11 +108,18 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =
it("keeps an unmarked colliding UUID on the conservative user path", async () => {
const collidingId = "88888888-8888-4888-8888-888888888888";
- const db = fakeDb({ operators: new Set([collidingId]) });
- const ctx = await resolveAuthzContext(db, { sub: collidingId, drive: "main" });
+ const db = fakeDb({
+ operators: new Set([collidingId]),
+ users: { [collidingId]: { lifecycle_state: "active", lifecycle_version: 1 } },
+ });
+ const ctx = await resolveAuthzContext(db, {
+ sub: collidingId,
+ drive: "main",
+ authGeneration: 1,
+ });
expect(ctx.isOperator).toBe(false);
expect(ctx.subjects).toEqual([`user:${collidingId}`]);
- expect(db.calls.some(query => query.includes("control_admin_users"))).toBe(false);
+ expect(db.calls.some((query) => query.includes("control_admin_users"))).toBe(false);
});
it("never elevates a signed user principal whose UUID also exists in the admin table", async () => {
@@ -89,34 +127,55 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =
const db = fakeDb({
operators: new Set([collidingId]),
teamsByUser: { [collidingId]: ["team-user"] },
+ users: { [collidingId]: { lifecycle_state: "active", lifecycle_version: 1 } },
});
const ctx = await resolveAuthzContext(db, {
sub: collidingId,
drive: "main",
principalType: "user",
+ authGeneration: 1,
});
expect(ctx.isOperator).toBe(false);
expect(ctx.subjects).toEqual([`user:${collidingId}`, "team:team-user"]);
expect(ctx.authoritySource).toBe("user-session");
- expect(db.calls.some(query => query.includes("control_admin_users"))).toBe(false);
+ expect(db.calls.some((query) => query.includes("control_admin_users"))).toBe(false);
});
it("preserves linked Desktop actor, effective admin, source, token subject, and request id", async () => {
const desktopUserId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const controlAdminId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
- const db = fakeDb({ operators: new Set([controlAdminId]) });
+ const db = fakeDb({
+ operators: new Set([controlAdminId]),
+ users: { [desktopUserId]: { lifecycle_state: "active", lifecycle_version: 1 } },
+ links: [
+ {
+ user_id: desktopUserId,
+ control_admin_id: controlAdminId,
+ lineage_id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
+ generation: 1,
+ },
+ ],
+ });
- const ctx = await resolveAuthzContext(db, {
- sub: controlAdminId,
- drive: "main",
- brokeredAuthority: {
- desktopUserId,
- controlAdminId,
- authoritySource: "linked-admin",
+ const ctx = await resolveAuthzContext(
+ db,
+ {
+ sub: controlAdminId,
+ drive: "main",
+ brokeredAuthority: {
+ desktopUserId,
+ controlAdminId,
+ authoritySource: "linked-admin",
+ linkLineageId: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
+ linkGeneration: 1,
+ desktopUserGeneration: 1,
+ },
+ authGeneration: 1,
},
- }, "cccccccc-cccc-4ccc-8ccc-cccccccccccc");
+ "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+ );
expect(ctx).toEqual({
drive: "main",
@@ -133,7 +192,18 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =
it("accepts uppercase UUID casing in linked-admin claims and canonicalizes the subject", async () => {
const controlAdminId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const desktopUserId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
- const db = fakeDb({ operators: new Set([controlAdminId]) });
+ const db = fakeDb({
+ operators: new Set([controlAdminId]),
+ users: { [desktopUserId]: { lifecycle_state: "active", lifecycle_version: 1 } },
+ links: [
+ {
+ user_id: desktopUserId,
+ control_admin_id: controlAdminId,
+ lineage_id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
+ generation: 1,
+ },
+ ],
+ });
const ctx = await resolveAuthzContext(db, {
sub: controlAdminId.toUpperCase(),
@@ -142,7 +212,11 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =
desktopUserId: desktopUserId.toUpperCase(),
controlAdminId: controlAdminId.toUpperCase(),
authoritySource: "linked-admin",
+ linkLineageId: "CCCCCCCC-CCCC-4CCC-8CCC-CCCCCCCCCCCC",
+ linkGeneration: 1,
+ desktopUserGeneration: 1,
},
+ authGeneration: 1,
});
expect(ctx.primarySubject).toBe(controlAdminId);
@@ -154,45 +228,145 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =
const controlAdminId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const db = fakeDb({});
- await expect(resolveAuthzContext(db, {
- sub: controlAdminId,
- drive: "main",
- brokeredAuthority: {
- desktopUserId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
- controlAdminId,
- authoritySource: "linked-admin",
- },
- })).rejects.toThrow("linked admin is not active");
+ await expect(
+ resolveAuthzContext(db, {
+ sub: controlAdminId,
+ drive: "main",
+ brokeredAuthority: {
+ desktopUserId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ controlAdminId,
+ authoritySource: "linked-admin",
+ linkLineageId: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
+ linkGeneration: 1,
+ desktopUserGeneration: 1,
+ },
+ authGeneration: 1,
+ })
+ ).rejects.toThrow("linked admin is not active");
expect(db.calls.some((q) => q.includes("team_members"))).toBe(false);
});
it("resolves a user to itself plus its ACTIVE team memberships", async () => {
const userId = "22222222-2222-2222-2222-222222222222";
- const db = fakeDb({ teamsByUser: { [userId]: ["team-a", "team-b"] } });
- const ctx = await resolveAuthzContext(db, { sub: userId, drive: "main" });
+ const db = fakeDb({
+ teamsByUser: { [userId]: ["team-a", "team-b"] },
+ users: { [userId]: { lifecycle_state: "active", lifecycle_version: 1 } },
+ });
+ const ctx = await resolveAuthzContext(db, { sub: userId, drive: "main", authGeneration: 1 });
expect(ctx.isOperator).toBe(false);
- expect(new Set(ctx.subjects)).toEqual(new Set([`user:${userId}`, "team:team-a", "team:team-b"]));
+ expect(new Set(ctx.subjects)).toEqual(
+ new Set([`user:${userId}`, "team:team-a", "team:team-b"])
+ );
expect(ctx.primarySubject).toBe(userId);
});
it("resolves a teamless user to only its own subject key", async () => {
const userId = "33333333-3333-3333-3333-333333333333";
- const db = fakeDb({});
- const ctx = await resolveAuthzContext(db, { sub: userId, drive: "main" });
+ const db = fakeDb({ users: { [userId]: { lifecycle_state: "active", lifecycle_version: 1 } } });
+ const ctx = await resolveAuthzContext(db, { sub: userId, drive: "main", authGeneration: 1 });
expect(ctx.subjects).toEqual([`user:${userId}`]);
expect(ctx.desktopUserId).toBe(userId);
expect(ctx.authoritySource).toBe("user-session");
expect(ctx.effectiveControlAdminId).toBeUndefined();
});
+ it("denies an ordinary bearer immediately after the user lifecycle becomes retired", async () => {
+ const userId = "55555555-5555-4555-8555-555555555555";
+ const db = fakeDb({
+ teamsByUser: { [userId]: ["team-still-present"] },
+ users: { [userId]: { lifecycle_state: "retired", lifecycle_version: 2 } },
+ });
+
+ await expect(
+ resolveAuthzContext(db, { sub: userId, drive: "main", authGeneration: 1 })
+ ).rejects.toThrow("user is retired or token generation is stale");
+ expect(db.calls.some((query) => query.includes("team_members"))).toBe(false);
+ });
+
+ it("denies a stale ordinary bearer after lifecycle generation changes", async () => {
+ const userId = "66666666-6666-4666-8666-666666666666";
+ const db = fakeDb({
+ users: { [userId]: { lifecycle_state: "active", lifecycle_version: 3 } },
+ });
+
+ await expect(
+ resolveAuthzContext(db, { sub: userId, drive: "main", authGeneration: 2 })
+ ).rejects.toThrow("user is retired or token generation is stale");
+ });
+
+ it("denies a linked-admin bearer after the active link generation is revoked", async () => {
+ const desktopUserId = "77777777-7777-4777-8777-777777777777";
+ const controlAdminId = "88888888-8888-4888-8888-888888888888";
+ const db = fakeDb({
+ operators: new Set([controlAdminId]),
+ users: { [desktopUserId]: { lifecycle_state: "active", lifecycle_version: 1 } },
+ links: [],
+ });
+
+ await expect(
+ resolveAuthzContext(db, {
+ sub: controlAdminId,
+ drive: "main",
+ authGeneration: 1,
+ principalType: "control-admin",
+ brokeredAuthority: {
+ desktopUserId,
+ controlAdminId,
+ authoritySource: "linked-admin",
+ linkLineageId: "99999999-9999-4999-8999-999999999999",
+ linkGeneration: 1,
+ desktopUserGeneration: 1,
+ },
+ })
+ ).rejects.toThrow("linked Desktop operator generation is not active");
+ });
+
+ it("denies a linked-admin bearer when the Desktop user is retired even if the admin remains active", async () => {
+ const desktopUserId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
+ const controlAdminId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
+ const db = fakeDb({
+ operators: new Set([controlAdminId]),
+ users: { [desktopUserId]: { lifecycle_state: "retired", lifecycle_version: 2 } },
+ links: [
+ {
+ user_id: desktopUserId,
+ control_admin_id: controlAdminId,
+ lineage_id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
+ generation: 1,
+ },
+ ],
+ });
+
+ await expect(
+ resolveAuthzContext(db, {
+ sub: controlAdminId,
+ drive: "main",
+ authGeneration: 1,
+ principalType: "control-admin",
+ brokeredAuthority: {
+ desktopUserId,
+ controlAdminId,
+ authoritySource: "linked-admin",
+ linkLineageId: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
+ linkGeneration: 1,
+ desktopUserGeneration: 1,
+ },
+ })
+ ).rejects.toThrow("linked Desktop user is retired or stale");
+ });
+
it("propagates a store error (fail-closed — never a silent allow)", async () => {
const db: SubjectsDb = {
async query() {
throw new Error("permission store down");
},
};
- await expect(resolveAuthzContext(db, { sub: "44444444-4444-4444-4444-444444444444", drive: "main" })).rejects.toThrow(
- "permission store down"
- );
+ await expect(
+ resolveAuthzContext(db, {
+ sub: "44444444-4444-4444-4444-444444444444",
+ drive: "main",
+ authGeneration: 1,
+ })
+ ).rejects.toThrow("permission store down");
});
});
diff --git a/gfs-controller/src/authz/subjectResolver.ts b/gfs-controller/src/authz/subjectResolver.ts
index 811302f7c..bc2777979 100644
--- a/gfs-controller/src/authz/subjectResolver.ts
+++ b/gfs-controller/src/authz/subjectResolver.ts
@@ -1,5 +1,5 @@
-import { AuthzContext } from "./permissionClient";
import type { GfsBrokeredAuthority } from "../auth/verify";
+import { AuthzContext } from "./permissionClient";
/**
* Check-time subject resolution for gfsc (spec community.md §Subjects, §Auth).
@@ -40,13 +40,54 @@ const K8S_NAME = "[a-z0-9](?:[-a-z0-9]*[a-z0-9])?";
const HOST_SUB = new RegExp(`^host:(1st|3rd):${K8S_NAME}\\/${K8S_NAME}$`);
const UUID_SUB = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-/** True iff `adminId` is an active cluster operator (`control_admin_users`). */
-async function isOperatorId(db: SubjectsDb, adminId: string): Promise<boolean> {
+type AdminSecurityRow = { id?: unknown; status?: unknown; session_version?: unknown };
+type UserSecurityRow = { id?: unknown; lifecycle_state?: unknown; lifecycle_version?: unknown };
+
+/**
+ * A verified principal that is no longer entitled to use GFS. This is a
+ * normal authorization refusal, not a permission-store outage: the serving
+ * layer must return 403 rather than converting retirement/revocation into a
+ * misleading 503 readiness failure.
+ */
+export class GfsSubjectResolutionDeniedError extends Error {
+ readonly code = "subject_denied" as const;
+
+ constructor(reason: string) {
+ super(reason);
+ this.name = "GfsSubjectResolutionDeniedError";
+ }
+}
+
+function denySubject(reason: string): never {
+ throw new GfsSubjectResolutionDeniedError(reason);
+}
+
+async function readActiveAdmin(db: SubjectsDb, adminId: string): Promise<AdminSecurityRow | null> {
const res = await db.query(
- `SELECT 1 FROM control_admin_users WHERE id = $1 AND status = 'active' LIMIT 1`,
+ `SELECT id, status, session_version
+ FROM control_admin_users
+ WHERE id = $1
+ LIMIT 1`,
[adminId]
);
- return res.rows.length > 0;
+ const row = res.rows[0] as AdminSecurityRow | undefined;
+ return row && row.status === "active" ? row : null;
+}
+
+async function readActiveUser(db: SubjectsDb, userId: string): Promise<UserSecurityRow | null> {
+ const res = await db.query(
+ `SELECT id, lifecycle_state, lifecycle_version
+ FROM users
+ WHERE id = $1
+ LIMIT 1`,
+ [userId]
+ );
+ const row = res.rows[0] as UserSecurityRow | undefined;
+ return row && row.lifecycle_state === "active" ? row : null;
+}
+
+function generationMatches(value: unknown, expected: unknown): boolean {
+ return Number.isSafeInteger(value) && Number(value) > 0 && Number(value) === Number(expected);
}
/**
@@ -61,6 +102,7 @@ export async function resolveAuthzContext(
drive: string;
brokeredAuthority?: GfsBrokeredAuthority;
principalType?: "user" | "control-admin";
+ authGeneration?: number;
},
requestId?: string
): Promise<AuthzContext> {
@@ -76,8 +118,40 @@ export async function resolveAuthzContext(
const canonicalDesktopUserId = UUID_SUB.test(brokered.desktopUserId)
? brokered.desktopUserId.toLowerCase()
: brokered.desktopUserId;
- if (canonicalBrokeredAdminId !== canonicalSub || !(await isOperatorId(db, canonicalBrokeredAdminId))) {
- throw new Error("linked admin is not active");
+ if (
+ canonicalBrokeredAdminId !== canonicalSub ||
+ claims.authGeneration === undefined ||
+ brokered.linkLineageId === undefined ||
+ brokered.linkGeneration === undefined ||
+ brokered.desktopUserGeneration === undefined
+ ) {
+ return denySubject("linked admin token is missing current generation metadata");
+ }
+ const admin = await readActiveAdmin(db, canonicalBrokeredAdminId);
+ if (!admin || !generationMatches(admin.session_version, claims.authGeneration)) {
+ return denySubject("linked admin is not active");
+ }
+ const user = await readActiveUser(db, canonicalDesktopUserId);
+ if (!user || !generationMatches(user.lifecycle_version, brokered.desktopUserGeneration)) {
+ return denySubject("linked Desktop user is retired or stale");
+ }
+ const link = await db.query(
+ `SELECT lineage_id, generation
+ FROM gfs_desktop_operator_links
+ WHERE user_id = $1
+ AND control_admin_id = $2
+ AND state = 'active'
+ AND source = 'initial_setup'
+ LIMIT 1`,
+ [canonicalDesktopUserId, canonicalBrokeredAdminId]
+ );
+ const currentLink = link.rows[0] as { lineage_id?: unknown; generation?: unknown } | undefined;
+ if (
+ !currentLink ||
+ String(currentLink.lineage_id).toLowerCase() !== brokered.linkLineageId.toLowerCase() ||
+ !generationMatches(currentLink.generation, brokered.linkGeneration)
+ ) {
+ return denySubject("linked Desktop operator generation is not active");
}
return {
drive: claims.drive,
@@ -95,11 +169,22 @@ export async function resolveAuthzContext(
// in v1 (the host→context binding is a P3+ follow-up, deny-by-default until
// `context` is a first-class grantee).
if (HOST_SUB.test(sub)) {
- return { drive: claims.drive, subjects: [sub], isOperator: false, primarySubject: sub, requestId };
+ return {
+ drive: claims.drive,
+ subjects: [sub],
+ isOperator: false,
+ primarySubject: sub,
+ requestId,
+ };
}
if (claims.principalType === "control-admin") {
- if (!(await isOperatorId(db, canonicalSub))) throw new Error("control admin is not active");
+ if (claims.authGeneration === undefined)
+ return denySubject("control admin token is missing generation");
+ const admin = await readActiveAdmin(db, canonicalSub);
+ if (!admin || !generationMatches(admin.session_version, claims.authGeneration)) {
+ return denySubject("control admin is not active");
+ }
return {
drive: claims.drive,
subjects: ["operator:"],
@@ -120,6 +205,14 @@ export async function resolveAuthzContext(
// This also keeps legacy/unmarked user tokens fail-closed during rollout.
// A user resolves to itself plus every team it is an ACTIVE member of
// (soft-deleted memberships excluded — deny-by-default).
+ if (!UUID_SUB.test(canonicalSub)) {
+ return denySubject("user principal must be a UUID");
+ }
+ if (claims.authGeneration === undefined) return denySubject("user token is missing generation");
+ const user = await readActiveUser(db, canonicalSub);
+ if (!user || !generationMatches(user.lifecycle_version, claims.authGeneration)) {
+ return denySubject("user is retired or token generation is stale");
+ }
const subjects = new Set<string>([`user:${canonicalSub}`]);
const res = await db.query(
`SELECT team_id FROM team_members WHERE user_id = $1 AND status = 'active'`,
diff --git a/scripts/tests/test-gfs-deploy-contract.sh b/scripts/tests/test-gfs-deploy-contract.sh
index 3b4fa5a58..eeaeaca1e 100755
--- a/scripts/tests/test-gfs-deploy-contract.sh
+++ b/scripts/tests/test-gfs-deploy-contract.sh
@@ -19,7 +19,7 @@ role_migration="$(sed -n "/version: '0074_gfs_runtime_role_exact_contract'/,/^
[[ "$role_migration" != *'NOLOGIN'* && "$role_migration" != *'LOGIN'* && "$role_migration" != *'PASSWORD'* && "$role_migration" != *'DROP ROLE'* ]] || fail 'role-contract migration changes credentials or replaces a role'
[[ "$role_migration" == *"ARRAY['gfs_controller', 'gfs_controller_reader']"* && "$role_migration" == *"EXECUTE format('REVOKE %I FROM %I'"* ]] || fail 'role-contract migration leaves inherited memberships'
provision_contract="$(sed -n '/verify_role_contract()/,/^}/p' deploy/scripts/provision-gfs-db.sh)"
-[[ "$provision_contract" == *"has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')"* && "$provision_contract" == *"has_column_privilege(:'role_name', 'team_members', 'status', 'SELECT')"* && "$provision_contract" == *"column_name NOT IN ('id', 'status')"* && "$provision_contract" == *"column_name NOT IN ('team_id', 'user_id', 'status')"* ]] || fail 'provisioner does not verify the exact subject-column contract'
+[[ "$provision_contract" == *"has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')"* && "$provision_contract" == *"has_column_privilege(:'role_name', 'control_admin_users', 'session_version', 'SELECT')"* && "$provision_contract" == *"has_column_privilege(:'role_name', 'users', 'lifecycle_version', 'SELECT')"* && "$provision_contract" == *"has_column_privilege(:'role_name', 'gfs_desktop_operator_links', 'lineage_id', 'SELECT')"* && "$provision_contract" == *"column_name NOT IN ('id', 'status', 'session_version')"* && "$provision_contract" == *"column_name NOT IN ('team_id', 'user_id', 'status')"* ]] || fail 'provisioner does not verify the exact subject-column contract'
writer_case="$(sed -n '/rotate-writer)/,/;;/p' deploy/scripts/provision-gfs-db.sh)"
[[ "$writer_case" == *'reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer true'* && "$writer_case" != *'gfsc-reader'* ]] || fail 'writer rollout scope'
runtime_script="$(sed '/^[[:space:]]*#/d' deploy/scripts/provision-gfs-runtime.sh)"