Skip to content

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

TypeScript

fix(auth): close review gaps on external sessions and GFS

Alfredo Lopez7b7849212d7a
diff --git a/control-api/src/middleware/externalSessionAuth.ts b/control-api/src/middleware/externalSessionAuth.ts
index 9f1096712..76c300c71 100644
--- a/control-api/src/middleware/externalSessionAuth.ts
+++ b/control-api/src/middleware/externalSessionAuth.ts
@@ -14,6 +14,13 @@ export type ExternalAuthedRequest = Request & {
* same denial to avoid user enumeration.
*/
export async function isCurrentExternalSession(claims: AuthClaims): Promise<boolean> {
+ const authGeneration = claims.authGeneration
+ if (
+ typeof authGeneration !== 'number' ||
+ !Number.isSafeInteger(authGeneration) ||
+ authGeneration < 1
+ )
+ return false
const result = await pool.query(
`SELECT lifecycle_state, lifecycle_version
FROM users
@@ -25,11 +32,7 @@ export async function isCurrentExternalSession(claims: AuthClaims): Promise<bool
| { 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
+ return Number(row.lifecycle_version) === authGeneration
}
export async function assertCurrentExternalSession(claims: AuthClaims): Promise<void> {
@@ -68,11 +71,7 @@ async function requireValidExternalSessionTokenAsync(
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))) {
+ if (!(await isCurrentExternalSession(claims))) {
res.status(401).json({ error: 'Unauthorized' })
return
}
diff --git a/control-api/src/routes/external/decisions.routes.ts b/control-api/src/routes/external/decisions.routes.ts
index a22716c9a..077186c64 100644
--- a/control-api/src/routes/external/decisions.routes.ts
+++ b/control-api/src/routes/external/decisions.routes.ts
@@ -1,4 +1,5 @@
import { NextFunction, Request, Response, Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { requireApprovalDecisionAccess } from '../../middleware/approvalDecisionAccess.js'
import { requireValidExternalSessionToken } from '../../middleware/externalSessionAuth.js'
@@ -43,9 +44,16 @@ function userAgent(req: Request): string | null {
export function createExternalUserApprovalDecisionsRouter(): Router {
const router = Router()
+ const externalApprovalEdgeRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
router.get(
'/external/workflow-approvals/pending',
+ externalApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_user_approval_requests_pending'),
requireValidExternalSessionToken,
rateLimitMiddleware({
@@ -83,6 +91,7 @@ export function createExternalUserApprovalDecisionsRouter(): Router {
router.post(
'/external/workflow-approvals/:id/decide',
+ externalApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_user_approval_requests_decide'),
requireValidExternalSessionToken,
requireValidApprovalIdParam,
diff --git a/control-api/src/routes/external/directory.ts b/control-api/src/routes/external/directory.ts
index 7d6ba9af7..87bb228a3 100644
--- a/control-api/src/routes/external/directory.ts
+++ b/control-api/src/routes/external/directory.ts
@@ -1,23 +1,36 @@
-import { Router } from "express";
-import { requireExternalTeamParamMatch, requireValidExternalSessionToken } from "../../middleware/externalSessionAuth.js";
-import { searchDirectory } from "../../services/directory/index.js";
+import { Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
+import { config } from '../../config.js'
+import {
+ requireExternalTeamParamMatch,
+ requireValidExternalSessionToken,
+} from '../../middleware/externalSessionAuth.js'
+import { searchDirectory } from '../../services/directory/index.js'
export function createExternalDirectoryRouter(): Router {
- const router = Router();
- router.use("/external/directory", requireValidExternalSessionToken);
+ const router = Router()
+ const externalDirectoryRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
+ router.use('/external/directory', externalDirectoryRateLimit, requireValidExternalSessionToken)
- router.get("/external/directory/search",
- requireExternalTeamParamMatch(),
+ router.get(
+ '/external/directory/search',
+ requireExternalTeamParamMatch(),
async (req, res, next) => {
- try {
- const teamId = String(req.query.teamId || "").trim();
- const q = String(req.query.q || "").trim();
- if (!teamId) return res.status(400).json({ error: "teamId is required" });
- return res.status(200).json({ items: await searchDirectory(teamId, q) });
- } catch (error) {
- return next(error);
+ try {
+ const teamId = String(req.query.teamId || '').trim()
+ const q = String(req.query.q || '').trim()
+ if (!teamId) return res.status(400).json({ error: 'teamId is required' })
+ return res.status(200).json({ items: await searchDirectory(teamId, q) })
+ } catch (error) {
+ return next(error)
+ }
}
- });
+ )
- return router;
+ return router
}
diff --git a/control-api/src/routes/external/invitations.ts b/control-api/src/routes/external/invitations.ts
index f4c38e2d6..9d5331b17 100644
--- a/control-api/src/routes/external/invitations.ts
+++ b/control-api/src/routes/external/invitations.ts
@@ -1,5 +1,7 @@
import { Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
import { randomBytes } from 'node:crypto'
+import { config } from '../../config.js'
import {
type ExternalAuthedRequest,
rejectBodyUserTeamMismatch,
@@ -32,6 +34,12 @@ function invitationLookupIpKey(req: {
export function createExternalInvitationsRouter(): Router {
const router = Router()
+ const externalInvitationsEdgeRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
router.get(
'/external/invitations/token/:token',
@@ -67,6 +75,7 @@ export function createExternalInvitationsRouter(): Router {
router.post(
'/external/invitations/password-token',
+ externalInvitationsEdgeRateLimit,
rateLimitMiddleware({
bucketType: 'external_invitation_password_token',
maxPerMinute: 10,
@@ -155,6 +164,7 @@ export function createExternalInvitationsRouter(): Router {
router.post(
'/external/invitations/password',
+ externalInvitationsEdgeRateLimit,
requireValidExternalSessionToken,
rejectBodyUserTeamMismatch,
async (req, res, next) => {
@@ -200,6 +210,7 @@ export function createExternalInvitationsRouter(): Router {
router.post(
'/external/invitations/desktop-authorization',
+ externalInvitationsEdgeRateLimit,
requireValidExternalSessionToken,
rejectBodyUserTeamMismatch,
async (req, res, next) => {
diff --git a/control-api/src/routes/external/members.ts b/control-api/src/routes/external/members.ts
index 54822ebdb..9e306bfed 100644
--- a/control-api/src/routes/external/members.ts
+++ b/control-api/src/routes/external/members.ts
@@ -1,4 +1,6 @@
import { Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
+import { config } from '../../config.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -26,7 +28,13 @@ function currentUserId(req: ExternalAuthedRequest): string | null {
export function createExternalMembersRouter(): Router {
const router = Router()
- router.use('/external/members', requireValidExternalSessionToken)
+ const externalMembersRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
+ router.use('/external/members', externalMembersRateLimit, requireValidExternalSessionToken)
router.get(
'/external/members/manageable-teams',
diff --git a/control-api/src/routes/external/notifications.routes.ts b/control-api/src/routes/external/notifications.routes.ts
index b744ed38d..044daa254 100644
--- a/control-api/src/routes/external/notifications.routes.ts
+++ b/control-api/src/routes/external/notifications.routes.ts
@@ -1,4 +1,5 @@
import { Request, Response, Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import {
@@ -91,9 +92,16 @@ function setStreamHeaders(res: Response): void {
export function createExternalNotificationsRouter(): Router {
const router = Router()
+ const externalNotificationsEdgeRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
router.get(
'/external/notifications/stream',
+ externalNotificationsEdgeRateLimit,
mcpHostHttpMetrics('external_notifications_stream'),
requireValidExternalSessionToken,
rateLimitMiddleware({
@@ -326,6 +334,7 @@ export function createExternalNotificationsRouter(): Router {
router.post(
'/external/notifications/:id/ack',
+ externalNotificationsEdgeRateLimit,
mcpHostHttpMetrics('external_notification_ack'),
requireValidExternalSessionToken,
rateLimitMiddleware({
@@ -358,6 +367,7 @@ export function createExternalNotificationsRouter(): Router {
router.get(
'/external/me/notification-preferences',
+ externalNotificationsEdgeRateLimit,
mcpHostHttpMetrics('external_notification_preferences_get'),
requireValidExternalSessionToken,
asyncHandler(async (req: Request, res: Response) => {
@@ -373,6 +383,7 @@ export function createExternalNotificationsRouter(): Router {
router.put(
'/external/me/notification-preferences',
+ externalNotificationsEdgeRateLimit,
mcpHostHttpMetrics('external_notification_preferences_put'),
requireValidExternalSessionToken,
asyncHandler(async (req: Request, res: Response) => {
diff --git a/control-api/src/routes/external/oauthGrants.ts b/control-api/src/routes/external/oauthGrants.ts
index 807cdcedd..ef7e2c6f9 100644
--- a/control-api/src/routes/external/oauthGrants.ts
+++ b/control-api/src/routes/external/oauthGrants.ts
@@ -1,8 +1,10 @@
import { Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
+import { config } from '../../config.js'
import { pool } from '../../db.js'
import {
- requireValidExternalSessionToken,
type ExternalAuthedRequest,
+ requireValidExternalSessionToken,
} from '../../middleware/externalSessionAuth.js'
import { deleteOAuthGrant, listUserOAuthGrants } from '../../oauth/store.js'
@@ -21,11 +23,18 @@ function dbClient() {
*/
export function createExternalOauthGrantsRouter(): Router {
const router = Router()
+ const externalOauthGrantsRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
// GET /external/oauth/grants
// Returns all grants for the authenticated user.
router.get(
'/external/oauth/grants',
+ externalOauthGrantsRateLimit,
requireValidExternalSessionToken,
(req: ExternalAuthedRequest, res, next) => {
void (async () => {
@@ -51,6 +60,7 @@ export function createExternalOauthGrantsRouter(): Router {
// row existed (no information leak).
router.delete(
'/external/oauth/grants/:recipeNamespace/:recipeName/:oauthClientId',
+ externalOauthGrantsRateLimit,
requireValidExternalSessionToken,
(req: ExternalAuthedRequest, res, next) => {
void (async () => {
diff --git a/control-api/src/routes/external/sharedFilesystems.ts b/control-api/src/routes/external/sharedFilesystems.ts
index 8e21a1634..3688b5465 100644
--- a/control-api/src/routes/external/sharedFilesystems.ts
+++ b/control-api/src/routes/external/sharedFilesystems.ts
@@ -1,4 +1,5 @@
import { Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import type { K8sGateway } from '../../k8s.js'
@@ -181,10 +182,20 @@ function curatedSfsMessage(phase: string | null | undefined): string | null {
export function createExternalSharedFilesystemsRouter(gateway: K8sGateway): Router {
const router = Router()
+ const externalSharedFilesystemsRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
const sfsNs = config.sharedFilesystemsNamespace
const ctxNs = config.contextsNamespace
- router.use('/external/contexts/:contextId/shared-filesystems', requireValidExternalSessionToken)
+ router.use(
+ '/external/contexts/:contextId/shared-filesystems',
+ externalSharedFilesystemsRateLimit,
+ requireValidExternalSessionToken
+ )
// Reject anything but GET/HEAD up-front so the proxy below can never be
// coerced into forwarding a write to wfc.
diff --git a/control-api/src/routes/external/teams.ts b/control-api/src/routes/external/teams.ts
index 9998a8c2c..04b663a96 100644
--- a/control-api/src/routes/external/teams.ts
+++ b/control-api/src/routes/external/teams.ts
@@ -1,4 +1,5 @@
import { Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import type { K8sGateway } from '../../k8s.js'
import type { ExternalAuthedRequest } from '../../middleware/externalSessionAuth.js'
@@ -40,7 +41,13 @@ function sendInvitationServiceError(
export function createExternalTeamsRouter(gateway: K8sGateway): Router {
const router = Router()
- router.use('/external/teams', requireValidExternalSessionToken)
+ const externalTeamsRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
+ router.use('/external/teams', externalTeamsRateLimit, requireValidExternalSessionToken)
router.get(
'/external/teams/:teamId/users/:userId/current',
diff --git a/control-api/src/routes/external/users.ts b/control-api/src/routes/external/users.ts
index eb91c4acb..3d97d3c49 100644
--- a/control-api/src/routes/external/users.ts
+++ b/control-api/src/routes/external/users.ts
@@ -1,4 +1,5 @@
import { Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import type { K8sGateway } from '../../k8s.js'
import {
@@ -75,7 +76,13 @@ async function mapWithConcurrencyLimit<T, R>(
export function createExternalUsersRouter(gateway: K8sGateway): Router {
const router = Router()
- router.use('/external/users', requireValidExternalSessionToken)
+ const externalUsersRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
+ router.use('/external/users', externalUsersRateLimit, requireValidExternalSessionToken)
router.get(
'/external/users/:userId/teams',
diff --git a/control-api/src/routes/external/workflow-approval-mediums.routes.ts b/control-api/src/routes/external/workflow-approval-mediums.routes.ts
index 6f2285f95..ade1bd33d 100644
--- a/control-api/src/routes/external/workflow-approval-mediums.routes.ts
+++ b/control-api/src/routes/external/workflow-approval-mediums.routes.ts
@@ -1,4 +1,6 @@
import { Router } from 'express'
+import { rateLimit } from 'express-rate-limit'
+import { config } from '../../config.js'
import type { K8sGateway } from '../../k8s.js'
import {
type ExternalAuthedRequest,
@@ -70,9 +72,16 @@ function displayNameFromBody(body: unknown): string | null {
export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway): Router {
const router = Router()
+ const externalWorkflowApprovalEdgeRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.approvalRlExternalPerMin,
+ standardHeaders: 'draft-7',
+ legacyHeaders: false,
+ })
router.post(
'/external/workflow-approval-mediums/challenges',
+ externalWorkflowApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_workflow_approval_medium_challenge'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -160,6 +169,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.post(
'/external/workflow-approval-mediums/link-sessions',
+ externalWorkflowApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_workflow_approval_medium_link_session'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -249,6 +259,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.post(
'/external/workflow-approval-mediums/challenges/:id/confirm',
+ externalWorkflowApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_workflow_approval_medium_confirm'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -294,6 +305,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.get(
'/external/workflow-approval-mediums',
+ externalWorkflowApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_workflow_approval_medium_list'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -327,6 +339,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.get(
'/external/workflow-approval-mediums/targets',
+ externalWorkflowApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_workflow_approval_medium_targets'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -361,6 +374,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.put(
'/external/workflow-approval-mediums/:id/preference',
+ externalWorkflowApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_workflow_approval_medium_preference'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -385,6 +399,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.patch(
'/external/workflow-approval-mediums/:id/display-name',
+ externalWorkflowApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_workflow_approval_medium_display_name'),
requireValidExternalSessionToken,
(req, res, next) => {
@@ -422,6 +437,7 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
router.delete(
'/external/workflow-approval-mediums/:id',
+ externalWorkflowApprovalEdgeRateLimit,
mcpHostHttpMetrics('external_workflow_approval_medium_delete'),
requireValidExternalSessionToken,
(req, res, next) => {
diff --git a/control-api/src/routes/workflows/shared/auth.ts b/control-api/src/routes/workflows/shared/auth.ts
index 252506e06..cee86a2cc 100644
--- a/control-api/src/routes/workflows/shared/auth.ts
+++ b/control-api/src/routes/workflows/shared/auth.ts
@@ -50,11 +50,7 @@ export async function requireExternalWorkflowCaller(
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))) {
+ if (!(await isCurrentExternalSession(claims))) {
return unauthorized(res)
}
return { kind: 'user-session', claims }
diff --git a/control-api/src/utils/auth/externalSessionAuthToken.ts b/control-api/src/utils/auth/externalSessionAuthToken.ts
index 3dc5aee6f..e1f4a5141 100644
--- a/control-api/src/utils/auth/externalSessionAuthToken.ts
+++ b/control-api/src/utils/auth/externalSessionAuthToken.ts
@@ -16,9 +16,10 @@ export function signExternalSessionToken(
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.
+ // A zero generation is an explicit legacy marker. The lifecycle gate
+ // rejects it after verification, so old sessions cannot survive a
+ // retirement even while isolated legacy issuers remain structurally
+ // compatible during rollout.
authGeneration: typeof claims.authGeneration === 'number' ? claims.authGeneration : 0,
},
config.sessionJwtPrivateKey,
@@ -48,7 +49,7 @@ export function verifyExternalSessionToken(token: string): AuthClaims | null {
typeof payload?.role !== 'string' ||
typeof payload?.exp !== 'number' ||
!Number.isSafeInteger(authGeneration) ||
- Number(authGeneration) < 0
+ Number(authGeneration) < 1
) {
return null
}
diff --git a/control-api/test/gfsReaderRole.realPostgres.integration.test.ts b/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
index 0844d4a38..e212bfd45 100644
--- a/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
+++ b/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
@@ -116,6 +116,19 @@ describeRealPostgres('GFS reader and writer login isolation', () => {
expect(migration).toBeDefined()
await migration!.apply(pool)
+ // 0074 is intentionally re-applied here to simulate a legacy role
+ // reconciliation on a cluster that already contains the newer GFS
+ // lifecycle migrations. That historical migration rebuilds the runtime
+ // envelope and therefore removes the 0095 subject-projection grants;
+ // replay the current projection migration before readiness assertions so
+ // this test models the supported post-reconciliation state rather than a
+ // permanently half-migrated database.
+ const lifecycleProjection = CONTROL_API_MIGRATIONS.find(
+ candidate => candidate.version === '0095_gfs_lifecycle_authority_projection'
+ )
+ expect(lifecycleProjection).toBeDefined()
+ await lifecycleProjection!.apply(pool)
+
const attributes = await pool.query(
`SELECT rolname, rolcanlogin, rolinherit, rolsuper, rolcreatedb, rolcreaterole,
rolreplication, rolbypassrls
diff --git a/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts b/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts
index 3362f36bb..4c0d15e20 100644
--- a/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts
+++ b/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
@@ -36,6 +36,15 @@ function app() {
}
describe('external session lifecycle gate', () => {
+ beforeEach(() => {
+ poolQuery.mockClear()
+ verifyToken.mockClear()
+ poolQuery.mockResolvedValue({
+ rows: [{ lifecycle_state: 'active', lifecycle_version: 4 }],
+ rowCount: 1,
+ })
+ })
+
it('accepts an active session whose generation matches the user row', async () => {
verifyToken.mockReturnValueOnce(claims)
poolQuery.mockResolvedValueOnce({
@@ -56,4 +65,11 @@ describe('external session lifecycle gate', () => {
const response = await request(app()).get('/protected').set('x-user-session-token', 'session')
expect(response.status).toBe(401)
})
+
+ it('denies a verified legacy marker before querying the lifecycle row', async () => {
+ verifyToken.mockReturnValueOnce({ ...claims, authGeneration: 0 })
+ const response = await request(app()).get('/protected').set('x-user-session-token', 'session')
+ expect(response.status).toBe(401)
+ expect(poolQuery).not.toHaveBeenCalled()
+ })
})
diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.ts
index c374ee208..91c5834f0 100644
--- a/control-api/test/routes.externalGfs.test.ts
+++ b/control-api/test/routes.externalGfs.test.ts
@@ -89,6 +89,7 @@ const SESSION = {
teamId: T1,
role: 'member' as const,
+ authGeneration: 1,
exp: Math.floor(Date.now() / 1000) + 3600,
}
const R = '11111111-1111-1111-1111-111111111111'
@@ -161,6 +162,12 @@ beforeEach(() => {
mockIsDesktopUserActive.mockReset()
mockResolveActiveLink.mockResolvedValue(null)
mockIsDesktopUserActive.mockResolvedValue(true)
+ mockQuery.mockImplementation(async (text: string) => {
+ if (text.includes('SELECT lifecycle_state, lifecycle_version')) {
+ return { rows: [{ lifecycle_state: 'active', lifecycle_version: 1 }] }
+ }
+ return { rows: [] }
+ })
mockWithTransaction.mockImplementation(
async (work: (db: { query: typeof mockQuery }) => Promise<unknown>) =>
work({ query: mockQuery })
@@ -175,6 +182,14 @@ afterEach(() => vi.unstubAllGlobals())
const auth = () => mockVerifyExternalSessionToken.mockReturnValue(SESSION)
+function activeSessionLifecycleResult(
+ text: string
+): { rows: [{ lifecycle_state: string; lifecycle_version: number }] } | null {
+ return text.includes('SELECT lifecycle_state, lifecycle_version')
+ ? { rows: [{ lifecycle_state: 'active', lifecycle_version: 1 }] }
+ : null
+}
+
function combinedAuthorityRow(
grants: Record<string, unknown>[],
values?: unknown[]
@@ -209,6 +224,8 @@ function dbReturning(
// host-grant fixtures represent an in-directory agent.
const callerAgentNames = opts.callerAgentNames ?? ['agent-a']
mockQuery.mockImplementation(async (text: string, values?: unknown[]) => {
+ const lifecycle = activeSessionLifecycleResult(text)
+ if (lifecycle) return lifecycle
if (text.includes('FROM user_agents')) {
return { rows: callerAgentNames.map(name => ({ agent_name: name })) }
}
@@ -255,7 +272,10 @@ describe('POST /external/gfs/token (user mint — existing signer, sub=users.id)
expect(mockVerifyExternalSessionToken).toHaveBeenCalledTimes(31)
expect(mockResolveActiveLink).not.toHaveBeenCalled()
- expect(mockQuery).not.toHaveBeenCalled()
+ expect(mockQuery.mock.calls).toHaveLength(31)
+ expect(mockQuery.mock.calls.every(call => String(call[0]).includes('lifecycle_state'))).toBe(
+ true
+ )
})
it('enforces the configurable ingress backstop before session or authority work', async () => {
@@ -280,7 +300,10 @@ describe('POST /external/gfs/token (user mint — existing signer, sub=users.id)
expect(exhausted.status).toBe(429)
expect(mockVerifyExternalSessionToken).toHaveBeenCalledTimes(3)
expect(mockResolveActiveLink).not.toHaveBeenCalled()
- expect(mockQuery).not.toHaveBeenCalled()
+ expect(mockQuery.mock.calls).toHaveLength(3)
+ expect(mockQuery.mock.calls.every(call => String(call[0]).includes('lifecycle_state'))).toBe(
+ true
+ )
} finally {
;(config as { externalGfsIngressRlPerMin: number }).externalGfsIngressRlPerMin =
previousIngressLimit
@@ -361,6 +384,7 @@ describe('POST /external/gfs/token (user mint — existing signer, sub=users.id)
drive: 'main',
scopes: ['gfs.read', 'gfs.write'],
pathBindings: [],
+ authGeneration: 1,
principalType: 'user',
})
})
@@ -482,6 +506,8 @@ describe('linked Desktop operator authority contract', () => {
it('uses the existing root tree primitive for a full operator root view', async () => {
linked()
mockQuery.mockImplementation(async (text: string) => {
+ const lifecycle = activeSessionLifecycleResult(text)
+ if (lifecycle) return lifecycle
if (text.includes('parent_resource_id IS NULL')) {
return {
rows: [{ resource_id: R, drive: 'main', name: '', kind: 'directory', path_cache: '/' }],
@@ -594,9 +620,9 @@ describe('linked Desktop operator authority contract', () => {
// The boundary rate limiter is deliberately the only DB-backed work that
// precedes the authority resolver. A resolver failure must not invoke a
// route handler or any of its database queries.
- expect(mockQuery.mock.calls.every(call => String(call[0]).includes('rate_limit_buckets'))).toBe(
- true
- )
+ expect(
+ mockQuery.mock.calls.every(call => /rate_limit_buckets|lifecycle_state/.test(String(call[0])))
+ ).toBe(true)
expect(mockSignGfsToken).not.toHaveBeenCalled()
})
@@ -614,7 +640,8 @@ describe('linked Desktop operator authority contract', () => {
expect(res.status).toBe(404)
expect(res.body).toEqual({ error: 'Not Found' })
expect(mockResolveActiveLink).not.toHaveBeenCalled()
- expect(mockQuery).not.toHaveBeenCalled()
+ expect(mockQuery.mock.calls).toHaveLength(1)
+ expect(mockQuery.mock.calls[0]?.[0]).toContain('lifecycle_state')
})
it('rejects a pre-resolution rate limit before resolver or route work', async () => {
@@ -623,6 +650,8 @@ describe('linked Desktop operator authority contract', () => {
true
mockResolveActiveLink.mockResolvedValue(ACTIVE_LINK)
mockQuery.mockImplementation(async (text: string) => {
+ const lifecycle = activeSessionLifecycleResult(text)
+ if (lifecycle) return lifecycle
if (text.includes('rate_limit_buckets')) return { rows: [{ count: 121 }] }
throw new Error(`unexpected route query: ${text}`)
})
@@ -636,14 +665,17 @@ describe('linked Desktop operator authority contract', () => {
expect(res.headers['x-ratelimit-limit']).toBe('120')
expect(mockResolveActiveLink).not.toHaveBeenCalled()
expect(mockSignGfsToken).not.toHaveBeenCalled()
- expect(mockQuery.mock.calls).toHaveLength(1)
- expect(mockQuery.mock.calls[0]?.[1]?.[0]).toMatch(/^gfs-ext:pre:resource:session:[0-9a-f]{64}$/)
+ expect(mockQuery.mock.calls).toHaveLength(2)
+ expect(mockQuery.mock.calls[0]?.[0]).toContain('lifecycle_state')
+ expect(mockQuery.mock.calls[1]?.[1]?.[0]).toMatch(/^gfs-ext:pre:resource:session:[0-9a-f]{64}$/)
})
it('does not resolve or elevate when the feature flag is off', async () => {
auth()
mockResolveActiveLink.mockResolvedValue(ACTIVE_LINK)
- mockQuery.mockResolvedValue({ rows: [] })
+ mockQuery.mockImplementation(
+ async (text: string) => activeSessionLifecycleResult(text) ?? { rows: [] }
+ )
const res = await request(await buildApp())
.get('/external/gfs/resources')
@@ -715,6 +747,8 @@ describe('PUT /external/gfs/grants (user delegation via existing engine)', () =>
},
]
mockQuery.mockImplementation(async (text: string, values?: unknown[]) => {
+ const lifecycle = activeSessionLifecycleResult(text)
+ if (lifecycle) return lifecycle
if (text.includes('FROM team_members')) return { rows: [{ team_id: T2 }] }
if (text.includes('authority_grants AS') && text.includes('authority_shares AS')) {
return combinedAuthorityRow(teamGrants, values)
@@ -1185,7 +1219,9 @@ describe('authenticated bulk grant/share transport', () => {
'gives subject transport precedence for %s even when resourceId is invalid',
async (_label, method, path, subjectFields) => {
auth()
- mockQuery.mockResolvedValue({ rows: [] })
+ mockQuery.mockImplementation(
+ async (text: string) => activeSessionLifecycleResult(text) ?? { rows: [] }
+ )
const app = await buildApp()
const res = await request(app)
@@ -1209,7 +1245,9 @@ describe('authenticated bulk grant/share transport', () => {
'serializes an invalid resource consistently for %s writes',
async (_label, method, path) => {
auth()
- mockQuery.mockResolvedValue({ rows: [] })
+ mockQuery.mockImplementation(
+ async (text: string) => activeSessionLifecycleResult(text) ?? { rows: [] }
+ )
const app = await buildApp()
const res = await request(app)
@@ -1415,6 +1453,8 @@ describe('GET /external/gfs/resources/:id/affordances', () => {
it('includes permissions held through any active team, not only the session teamId', async () => {
auth()
mockQuery.mockImplementation(async (text: string, values?: unknown[]) => {
+ const lifecycle = activeSessionLifecycleResult(text)
+ if (lifecycle) return lifecycle
if (text.includes('FROM team_members')) return { rows: [{ team_id: T2 }] }
if (text.includes('WITH RECURSIVE chain'))
return { rows: [{ resource_id: String(values?.[1]) }] }
@@ -1485,6 +1525,7 @@ describe('user resource mutations via gfsc proxy', () => {
subject: U1,
drive: 'main',
scopes: ['gfs.write'],
+ authGeneration: 1,
principalType: 'user',
})
expect(fetchMock).toHaveBeenCalledWith(
@@ -1519,6 +1560,7 @@ describe('user resource mutations via gfsc proxy', () => {
subject: U1,
drive: 'main',
scopes: ['gfs.delete'],
+ authGeneration: 1,
principalType: 'user',
})
expect(fetchMock).toHaveBeenCalledWith(
@@ -1603,6 +1645,8 @@ describe('GET /external/gfs/resources', () => {
it('lists readable direct user resources and active-team resources as Desktop entry points', async () => {
auth()
mockQuery.mockImplementation(async (text: string, values?: unknown[]) => {
+ const lifecycle = activeSessionLifecycleResult(text)
+ if (lifecycle) return lifecycle
if (text.includes('FROM team_members')) return { rows: [{ team_id: T1 }] }
if (text.includes('FROM gfs_grants') && text.includes('JOIN requested_subjects')) {
expect(values?.[1]).toEqual(['user', 'team'])
@@ -1904,6 +1948,7 @@ describe('user read proxy via gfsc (GET /external/gfs/proxy/:rid)', () => {
subject: U1,
drive: 'main',
scopes: ['gfs.read'],
+ authGeneration: 1,
principalType: 'user',
})
expect(fetchMock).toHaveBeenCalledWith(
diff --git a/control-api/test/routes.externalSharedFilesystems.test.ts b/control-api/test/routes.externalSharedFilesystems.test.ts
index 5bcea7840..36c51842e 100644
--- a/control-api/test/routes.externalSharedFilesystems.test.ts
+++ b/control-api/test/routes.externalSharedFilesystems.test.ts
@@ -8,6 +8,11 @@ const mockVerifyExternalSessionToken = vi.fn()
const mockGetUserContexts = vi.fn()
const mockGetTeamContexts = vi.fn()
const mockSignWfcBrowsingCredential = vi.hoisted(() => vi.fn())
+const mockPoolQuery = vi.hoisted(() => vi.fn())
+
+vi.mock('../src/db.js', () => ({
+ pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },
+}))
vi.mock('../src/utils/auth/externalSessionAuthToken.js', () => ({
verifyExternalSessionToken: (...args: unknown[]) => mockVerifyExternalSessionToken(...args),
@@ -36,6 +41,7 @@ const SESSION = {
teamId: 'team-1',
role: 'member' as const,
+ authGeneration: 1,
exp: Math.floor(Date.now() / 1000) + 3600,
}
@@ -70,6 +76,8 @@ beforeEach(() => {
mockGetUserContexts.mockReset()
mockGetTeamContexts.mockReset()
mockSignWfcBrowsingCredential.mockReset()
+ mockPoolQuery.mockReset()
+ mockPoolQuery.mockResolvedValue({ rows: [{ lifecycle_state: 'active', lifecycle_version: 1 }] })
mockSignWfcBrowsingCredential.mockReturnValue({ token: 'browsing-token', expiresInSeconds: 60 })
})
diff --git a/control-api/test/routes.externalWorkflows.test.ts b/control-api/test/routes.externalWorkflows.test.ts
index 38a20936f..be766bc4b 100644
--- a/control-api/test/routes.externalWorkflows.test.ts
+++ b/control-api/test/routes.externalWorkflows.test.ts
@@ -18,7 +18,12 @@ const mockIsAdminTokenRevoked = vi.fn()
vi.mock('../src/db.js', () => ({
pool: {
- query: (...args: unknown[]) => mockPoolQuery(...args),
+ query: (...args: unknown[]) => {
+ if (String(args[0]).includes('SELECT lifecycle_state, lifecycle_version')) {
+ return Promise.resolve({ rows: [{ lifecycle_state: 'active', lifecycle_version: 1 }] })
+ }
+ return mockPoolQuery(...args)
+ },
},
withTransaction: (...args: unknown[]) => mockWithTransaction(...args),
}))
@@ -79,6 +84,7 @@ const USER_SESSION_CLAIMS = {
teamId: 'team-1',
role: 'member' as const,
+ authGeneration: 1,
exp: Math.floor(Date.now() / 1000) + 3600,
}
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
index 754d9d57d..e278cbee1 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
@@ -547,6 +547,58 @@ describe('useGfsBrowserController', () => {
expect(screen.getByTestId('current').textContent).toBe(rootResourceId)
})
+ it('keeps the browser session active when a resource children listing returns a generic 403', async () => {
+ const resource = {
+ resourceId: 'shared-folder',
+ rid: 'sharedfolder',
+ gfsUri: 'gfs://main/sharedfolder',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'Shared folder',
+ kind: 'directory' as const,
+ path: '/Shared folder',
+ version: 1,
+ bytes: 0,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: true,
+ }
+ const listChildren = vi.fn(async () => {
+ throw new Error('403 Forbidden')
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible: vi.fn(async () => ({ items: [resource], nextCursor: null })),
+ resolve: vi.fn(),
+ listChildren,
+ affordances: vi.fn(async () => ({
+ held: ['read'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ })),
+ },
+ },
+ })
+
+ render(<Probe />, { wrapper: Harness })
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'open Shared folder' })).toBeTruthy()
+ )
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open Shared folder' }).click()
+ })
+
+ await waitFor(() =>
+ expect(listChildren).toHaveBeenCalledWith('shared-folder', 'main', undefined)
+ )
+ expect(screen.getByTestId('access-state').textContent).toBe('active')
+ expect(screen.getByTestId('current').textContent).toBe('shared-folder')
+ })
+
it('refreshes cached affordances after permissions change outside Desktop', async () => {
let held = ['read']
const affordances = vi.fn(async () => ({
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index 8da6467ab..16af91510 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -366,9 +366,23 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
// remains the sole authority that can restore the operator root.
setAccessState('active')
}, [])
- const queryAuthorizationError = [accessibleQuery.error, childrenQuery.error]
- .map(error => (error ? toMessage(error) : null))
- .find(error => error !== null && isGfsSessionAuthorityFailure(error, 'discovery'))
+ // Root discovery is a session/authority boundary. A children request is a
+ // per-resource read: a generic 401/403 there can mean that one shared
+ // folder was revoked while the rest of the session remains valid. Only
+ // explicit lifecycle codes may revoke from that surface; do not collapse
+ // the entire browser state for a resource-scoped policy denial.
+ const queryAuthorizationError = [
+ accessibleQuery.error
+ ? { message: toMessage(accessibleQuery.error), surface: 'discovery' as const }
+ : null,
+ childrenQuery.error
+ ? { message: toMessage(childrenQuery.error), surface: 'operation' as const }
+ : null,
+ ]
+ .filter(
+ (entry): entry is { message: string; surface: 'discovery' | 'operation' } => entry !== null
+ )
+ .find(entry => isGfsSessionAuthorityFailure(entry.message, entry.surface))
useEffect(() => {
if (queryAuthorizationError && accessState !== 'revoked') revokeAccess()
}, [accessState, queryAuthorizationError, revokeAccess])
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index e7eecf31b..9348ad2a8 100644
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.70",
+ "version": "0.1.71",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.70",
+ "version": "0.1.71",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index fe0cdaf72..f9ca2d12f 100644
--- a/external-rest-api/package.json
+++ b/external-rest-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.70",
+ "version": "0.1.71",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.ts
index 8dd982511..b3a43192d 100644
--- a/external-rest-api/src/routes/gfs.ts
+++ b/external-rest-api/src/routes/gfs.ts
@@ -143,10 +143,14 @@ export function createGfsRouter(options?: { edgeLimits?: ExternalGfsEdgeLimits }
identifier: `gfs-edge-${bucket}`,
...(options?.keyGenerator ? { keyGenerator: options.keyGenerator } : {}),
handler: (_req, res) => {
+ const retryAfterHeader = Number(res.getHeader('Retry-After'))
+ const retryAfterSeconds =
+ Number.isSafeInteger(retryAfterHeader) && retryAfterHeader > 0 ? retryAfterHeader : 1
res.status(429).json({
error: 'Too Many Requests',
rateLimitLayer: 'external-rest-edge',
rateLimitBucket: bucket,
+ retryAfterSeconds,
})
},
})
diff --git a/external-rest-api/test/routes.gfs.test.ts b/external-rest-api/test/routes.gfs.test.ts
index 0ca5f2722..32ea0f8df 100644
--- a/external-rest-api/test/routes.gfs.test.ts
+++ b/external-rest-api/test/routes.gfs.test.ts
@@ -225,6 +225,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
error: 'Too Many Requests',
rateLimitLayer: 'external-rest-edge',
rateLimitBucket: 'aggregate-ip',
+ retryAfterSeconds: expect.any(Number),
})
expect(authTokenMock.verifyToken).toHaveBeenCalledTimes(2)
expect(clientMock.controlApiRequest).not.toHaveBeenCalled()