Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): enforce live admin revocation on workflow routes
Alfredo Lopez5579185db39d
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex a9498bea7..96d3badce 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.476",+ "version": "0.1.477","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.476",+ "version": "0.1.477","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --git a/control-api/package.json b/control-api/package.jsonindex 71c56655a..b1393ab58 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.476",+ "version": "0.1.477","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/middleware/controlUIAuth.ts b/control-api/src/middleware/controlUIAuth.tsindex 1c3c600a0..17b5c6a1d 100644--- a/control-api/src/middleware/controlUIAuth.ts+++ b/control-api/src/middleware/controlUIAuth.ts@@ -1,6 +1,5 @@import { NextFunction, Request, Response } from 'express'-import { findAdminById, isAdminTokenRevoked } from '../services/adminAuthService.js'-import { verifyAdminToken } from '../utils/auth/adminAuthToken.js'+import { authenticateAdminSession } from '../services/adminSessionAuth.js'import { AdminAuthClaims } from '../utils/auth/adminAuthTypes.js'import { CONTROL_UI_ADMIN_SESSION_COOKIE, readCookie } from '../utils/auth/sessionCookies.js'@@ -19,32 +18,12 @@ export async function requireAuthForControlUI(): Promise<void> {try {const token = extractControlUiSessionToken(req)- if (!token || token.length > 4096) {- res.status(401).json({ error: 'Unauthorized' })- return- }-- const claims = verifyAdminToken(token)+ const claims = await authenticateAdminSession(token)if (!claims) {res.status(401).json({ error: 'Unauthorized' })return}- if (await isAdminTokenRevoked(claims.jti)) {- res.status(401).json({ error: 'Unauthorized' })- return- }-- const admin = await findAdminById(claims.sub)- if (- !admin ||- admin.status !== 'active' ||- Number(claims.sessionVersion || 0) !== admin.sessionVersion- ) {- res.status(401).json({ error: 'Unauthorized' })- return- }-req.adminAuth = claimsnext()} catch (error) {diff --git a/control-api/src/routes/workflows/shared/auth.ts b/control-api/src/routes/workflows/shared/auth.tsindex cee86a2cc..37456eded 100644--- a/control-api/src/routes/workflows/shared/auth.ts+++ b/control-api/src/routes/workflows/shared/auth.ts@@ -1,8 +1,7 @@import { Request, Response } from 'express'import { isCurrentExternalSession } from '../../../middleware/externalSessionAuth.js'-import { isAdminTokenRevoked } from '../../../services/adminAuthService.js'+import { authenticateAdminSession } from '../../../services/adminSessionAuth.js'import type { WorkflowCaller } from '../../../services/workflows/types.js'-import { verifyAdminToken } from '../../../utils/auth/adminAuthToken.js'import { verifyExternalSessionToken } from '../../../utils/auth/externalSessionAuthToken.js'import {type McpHostControlScope,@@ -34,10 +33,8 @@ export async function requireAdminWorkflowCaller(res: Response): Promise<Extract<WorkflowCaller, { kind: 'admin-ui' }> | null> {const adminToken = getAdminUiToken(req)- if (!adminToken || adminToken.length > 4096) return unauthorized(res)-- const adminClaims = verifyAdminToken(adminToken)- if (!adminClaims || (await isAdminTokenRevoked(adminClaims.jti))) return unauthorized(res)+ const adminClaims = await authenticateAdminSession(adminToken)+ if (!adminClaims) return unauthorized(res)return { kind: 'admin-ui', userId: adminClaims.sub }}diff --git a/control-api/src/services/adminSessionAuth.ts b/control-api/src/services/adminSessionAuth.tsnew file mode 100644index 000000000..8e4b2d88b--- /dev/null+++ b/control-api/src/services/adminSessionAuth.ts@@ -0,0 +1,38 @@+import { verifyAdminToken } from '../utils/auth/adminAuthToken.js'+import type { AdminAuthClaims } from '../utils/auth/adminAuthTypes.js'+import { findAdminById, isAdminTokenRevoked } from './adminAuthService.js'++const MAX_ADMIN_SESSION_TOKEN_LENGTH = 4096++/**+ * Canonical live administrator session decision shared by Control UI middleware+ * and admin workflow route helpers. Account lock (`lockedUntil`) is intentionally+ * out of scope here — it blocks login, not already-issued sessions.+ */+export async function authenticateAdminSession(+ token: string | null | undefined+): Promise<AdminAuthClaims | null> {+ if (!token || token.length > MAX_ADMIN_SESSION_TOKEN_LENGTH) {+ return null+ }++ const claims = verifyAdminToken(token)+ if (!claims) {+ return null+ }++ if (await isAdminTokenRevoked(claims.jti)) {+ return null+ }++ const admin = await findAdminById(claims.sub)+ if (+ !admin ||+ admin.status !== 'active' ||+ Number(claims.sessionVersion ?? 0) !== admin.sessionVersion+ ) {+ return null+ }++ return claims+}diff --git a/control-api/test/middleware.controlUIAuth.test.ts b/control-api/test/middleware.controlUIAuth.test.tsindex dfc4a63b7..2fa918111 100644--- a/control-api/test/middleware.controlUIAuth.test.ts+++ b/control-api/test/middleware.controlUIAuth.test.ts@@ -16,6 +16,23 @@ const adminSvcMock = vi.hoisted(() => ({vi.mock('../src/utils/auth/adminAuthToken.js', () => adminTokenMock)vi.mock('../src/services/adminAuthService.js', () => adminSvcMock)+const BASE_CLAIMS = {+ sub: 'admin-id',+ typ: 'user' as const,+ role: 'admin' as const,+ jti: 'j1',+ exp: 9999999999,+ sessionVersion: 2,+}++function makeProtectedApp() {+ const app = express()+ app.get('/protected', requireAuthForControlUI, (req: UiAuthedRequest, res) => {+ res.status(200).json({ adminId: req.adminAuth?.sub })+ })+ return app+}+describe('middleware/controlUIAuth', () => {beforeEach(() => {adminTokenMock.verifyAdminToken.mockReset()@@ -24,14 +41,7 @@ describe('middleware/controlUIAuth', () => {})it('accepts the HttpOnly admin session cookie as the UI auth token', async () => {- adminTokenMock.verifyAdminToken.mockReturnValue({- sub: 'admin-id',- typ: 'user',- role: 'admin',- jti: 'j1',- exp: 9999999999,- sessionVersion: 2,- })+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)adminSvcMock.findAdminById.mockResolvedValue({id: 'admin-id',@@ -39,12 +49,7 @@ describe('middleware/controlUIAuth', () => {sessionVersion: 2,})- const app = express()- app.get('/protected', requireAuthForControlUI, (req: UiAuthedRequest, res) => {- res.status(200).json({ adminId: req.adminAuth?.sub })- })-- const res = await request(app)+ const res = await request(makeProtectedApp()).get('/protected').set('cookie', 'control_ui_admin_session=admin-cookie-token').expect(200)@@ -54,13 +59,76 @@ describe('middleware/controlUIAuth', () => {})it('rejects legacy bearer tokens for Control UI browser auth', async () => {+ await request(makeProtectedApp())+ .get('/protected')+ .set('authorization', 'Bearer old-admin-token')+ .expect(401)++ expect(adminTokenMock.verifyAdminToken).not.toHaveBeenCalled()+ })++ it('rejects revoked administrator JTIs', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(true)++ await request(makeProtectedApp())+ .get('/protected')+ .set('cookie', 'control_ui_admin_session=admin-cookie-token')+ .expect(401)++ expect(adminSvcMock.findAdminById).not.toHaveBeenCalled()+ })++ it('rejects stale sessionVersion claims after password reset', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue({ ...BASE_CLAIMS, sessionVersion: 1 })+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockResolvedValue({+ id: 'admin-id',+ status: 'active',+ sessionVersion: 2,+ })++ await request(makeProtectedApp())+ .get('/protected')+ .set('cookie', 'control_ui_admin_session=admin-cookie-token')+ .expect(401)+ })++ it('rejects disabled administrator accounts', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockResolvedValue({+ id: 'admin-id',+ status: 'disabled',+ sessionVersion: 2,+ })++ await request(makeProtectedApp())+ .get('/protected')+ .set('cookie', 'control_ui_admin_session=admin-cookie-token')+ .expect(401)+ })++ it('propagates findAdminById failures via Express error handling', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockRejectedValue(new Error('pg connection terminated'))+const app = express()app.get('/protected', requireAuthForControlUI, (_req, res) => {res.status(200).json({ ok: true })})+ app.use(+ (err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {+ res.status(500).json({ error: err.message })+ }+ )- await request(app).get('/protected').set('authorization', 'Bearer old-admin-token').expect(401)+ const res = await request(app)+ .get('/protected')+ .set('cookie', 'control_ui_admin_session=admin-cookie-token')+ .expect(500)- expect(adminTokenMock.verifyAdminToken).not.toHaveBeenCalled()+ expect(res.body).toEqual({ error: 'pg connection terminated' })})})diff --git a/control-api/test/routes.adminWorkflows.test.ts b/control-api/test/routes.adminWorkflows.test.tsindex 6791defd5..035c6fbe9 100644--- a/control-api/test/routes.adminWorkflows.test.ts+++ b/control-api/test/routes.adminWorkflows.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import express from 'express'import request from 'supertest'+import { createAdminOutputsRouter } from '../src/routes/admin/outputs.js'import { createWorkflowsAdminRouter } from '../src/routes/admin/workflows/index.js'import { createMcpHostWorkflowRoutes } from '../src/routes/mcp-host/workflows/index.js'import { currentAdministrativeRequestContext } from '../src/services/tracing/adminOperationContext.js'@@ -18,6 +19,7 @@ const mockIsHostRefAuthorized = vi.fn()const mockVerifyAdminToken = vi.fn()const mockVerifyExternalSessionToken = vi.fn()const mockIsAdminTokenRevoked = vi.fn()+const mockFindAdminById = vi.fn()const mockListWorkflowGrants = vi.fn()const mockSetWorkflowGrants = vi.fn()const mockListTeamWorkflowGrants = vi.fn()@@ -63,6 +65,7 @@ vi.mock('../src/utils/auth/externalSessionAuthToken.js', () => ({vi.mock('../src/services/adminAuthService.js', () => ({isAdminTokenRevoked: (...args: unknown[]) => mockIsAdminTokenRevoked(...args),+ findAdminById: (...args: unknown[]) => mockFindAdminById(...args),}))vi.mock('../src/services/directory/index.js', () => ({@@ -137,6 +140,8 @@ const USER_SESSION_CLAIMS = {exp: Math.floor(Date.now() / 1000) + 3600,}+const ADMIN_SESSION_VERSION = 2+const ADMIN_CLAIMS = {// Production `signAdminToken` always sets `sub` to `users.id`, which is a// UUID. Using a valid UUID here (instead of 'admin-1') keeps the fixture@@ -148,6 +153,38 @@ const ADMIN_CLAIMS = {role: 'admin' as const,jti: 'admin-jti',exp: Math.floor(Date.now() / 1000) + 3600,+ sessionVersion: ADMIN_SESSION_VERSION,+}++function mockLiveAdminSession(+ overrides: {+ tokenSessionVersion?: number+ adminSessionVersion?: number+ status?: 'active' | 'disabled'+ revoked?: boolean+ missingAdmin?: boolean+ } = {}+) {+ const tokenSessionVersion = overrides.tokenSessionVersion ?? ADMIN_SESSION_VERSION+ mockVerifyAdminToken.mockImplementation(token =>+ token === 'admin-token' || token === 'admin-token-stale'+ ? { ...ADMIN_CLAIMS, sessionVersion: tokenSessionVersion }+ : null+ )+ mockIsAdminTokenRevoked.mockResolvedValue(overrides.revoked ?? false)+ if (overrides.missingAdmin) {+ mockFindAdminById.mockResolvedValue(null)+ return+ }+ mockFindAdminById.mockResolvedValue({+ id: ADMIN_CLAIMS.sub,+ status: overrides.status ?? 'active',+ sessionVersion: overrides.adminSessionVersion ?? ADMIN_SESSION_VERSION,+ })+}++function mockRateLimiterAllowed() {+ mockPoolQuery.mockResolvedValueOnce({ rows: [{ count: 1 }], rowCount: 1 })}const WORKFLOW_CONTROL_CLAIMS = {@@ -184,6 +221,13 @@ function makeApiRuntimeApp(gateway: MockGateway) {return app}+function makeOutputsApp(gateway: MockGateway) {+ const app = express()+ app.use(express.json())+ app.use(createAdminOutputsRouter(gateway as never))+ return app+}+describe('routes/admin/workflows', () => {let gateway: MockGateway@@ -197,6 +241,7 @@ describe('routes/admin/workflows', () => {mockVerifyAdminToken.mockReset()mockVerifyExternalSessionToken.mockReset()mockIsAdminTokenRevoked.mockReset()+ mockFindAdminById.mockReset()mockListWorkflowGrants.mockReset()mockSetWorkflowGrants.mockReset()mockListTeamWorkflowGrants.mockReset()@@ -211,12 +256,10 @@ describe('routes/admin/workflows', () => {expiresInSeconds: 600,})mockIsAdminTokenRevoked.mockResolvedValue(false)+ mockLiveAdminSession()mockVerifyExternalSessionToken.mockImplementation(token =>token === 'user-session-token' ? USER_SESSION_CLAIMS : null)- mockVerifyAdminToken.mockImplementation(token =>- token === 'admin-token' ? ADMIN_CLAIMS : null- )mockVerifyWorkflowControlToken.mockImplementation(token =>token === 'mcp-host-workflow-control-token' ? WORKFLOW_CONTROL_CLAIMS : null)@@ -2422,4 +2465,284 @@ describe('routes/admin/workflows', () => {expect(res.body).toEqual({ teamId: VALID_TEAM_UUID, removed: false })})})++ describe('live administrator session enforcement (F4)', () => {+ const VALID_TEAM_UUID = '11111111-2222-4333-8444-555555555555'+ const VALID_GRANT_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'+ const RUN_ID = '00000000-0000-4000-8000-000000000456'++ async function seedRecipe(): Promise<void> {+ await gateway.createResource('workflowrecipes', VALID_RECIPE as never, RECIPE_NS)+ }++ function expectUnauthorized(res: { status: number; body: { error?: string } }): void {+ expect(res.status).toBe(401)+ expect(res.body).toEqual({ error: 'Unauthorized' })+ }++ it('rejects revoked administrator JTIs before business logic', async () => {+ mockLiveAdminSession({ revoked: true })+ const res = await request(makeApp(gateway))+ .get('/admin/workflows')+ .set('Authorization', 'Bearer admin-token')+ expectUnauthorized(res)+ expect(mockPoolQuery).not.toHaveBeenCalled()+ })++ it('rejects tokens issued before password reset (stale sessionVersion)', async () => {+ mockLiveAdminSession({ tokenSessionVersion: 1, adminSessionVersion: 2 })+ const res = await request(makeApp(gateway))+ .get('/admin/workflows')+ .set('Authorization', 'Bearer admin-token-stale')+ expectUnauthorized(res)+ })++ it('rejects disabled administrator accounts', async () => {+ mockLiveAdminSession({ status: 'disabled' })+ const res = await request(makeApp(gateway))+ .get('/admin/workflows')+ .set('Authorization', 'Bearer admin-token')+ expectUnauthorized(res)+ })++ it('rejects missing administrator records', async () => {+ mockLiveAdminSession({ missingAdmin: true })+ const res = await request(makeApp(gateway))+ .get('/admin/workflows')+ .set('Authorization', 'Bearer admin-token')+ expectUnauthorized(res)+ })++ it('rejects stale HttpOnly cookie sessions', async () => {+ mockLiveAdminSession({ tokenSessionVersion: 1, adminSessionVersion: 2 })+ const res = await request(makeApp(gateway))+ .get('/admin/workflows')+ .set('Cookie', 'control_ui_admin_session=admin-token-stale')+ expectUnauthorized(res)+ })++ it('rejects stale bearer tokens even when a valid cookie is also present', async () => {+ mockVerifyAdminToken.mockImplementation(token => {+ if (token === 'admin-token-stale') {+ return { ...ADMIN_CLAIMS, sessionVersion: 1 }+ }+ if (token === 'admin-token') {+ return { ...ADMIN_CLAIMS, sessionVersion: ADMIN_SESSION_VERSION }+ }+ return null+ })+ mockIsAdminTokenRevoked.mockResolvedValue(false)+ mockFindAdminById.mockResolvedValue({+ id: ADMIN_CLAIMS.sub,+ status: 'active',+ sessionVersion: ADMIN_SESSION_VERSION,+ })++ const res = await request(makeApp(gateway))+ .get('/admin/workflows')+ .set('Authorization', 'Bearer admin-token-stale')+ .set('Cookie', 'control_ui_admin_session=admin-token')+ expectUnauthorized(res)+ })++ it('accepts a valid bearer token for admin workflow routes', async () => {+ mockLiveAdminSession()+ const res = await request(makeApp(gateway))+ .get('/admin/workflows')+ .set('Authorization', 'Bearer admin-token')+ expect(res.status).toBe(200)+ })++ const staleHandlerMatrix: Array<{+ label: string+ method: 'get' | 'post' | 'put' | 'delete'+ path: string+ auth: 'bearer' | 'cookie'+ useOutputsApp?: boolean+ setup?: () => Promise<void>+ headers?: Record<string, string>+ body?: Record<string, unknown>+ }> = [+ { label: 'list workflows', method: 'get', path: '/admin/workflows', auth: 'bearer' },+ {+ label: 'workflow detail',+ method: 'get',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe`,+ auth: 'bearer',+ setup: seedRecipe,+ },+ {+ label: 'workflow health',+ method: 'get',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/health`,+ auth: 'bearer',+ setup: seedRecipe,+ },+ {+ label: 'workflow trigger',+ method: 'post',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/trigger`,+ auth: 'bearer',+ setup: async () => {+ mockRateLimiterAllowed()+ await seedRecipe()+ },+ headers: { 'Idempotency-Key': 'stale-trigger-key' },+ body: { inputs: { topic: 'alpha' } },+ },+ {+ label: 'workflow grants read',+ method: 'get',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/grants`,+ auth: 'bearer',+ setup: async () => {+ mockRateLimiterAllowed()+ await seedRecipe()+ },+ },+ {+ label: 'workflow grants write',+ method: 'put',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/grants`,+ auth: 'bearer',+ setup: async () => {+ mockRateLimiterAllowed()+ await seedRecipe()+ },+ body: { userIds: [] },+ },+ {+ label: 'team grants read',+ method: 'get',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/team-grants`,+ auth: 'bearer',+ setup: async () => {+ mockRateLimiterAllowed()+ await seedRecipe()+ },+ },+ {+ label: 'team grants write',+ method: 'put',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/team-grants`,+ auth: 'bearer',+ setup: async () => {+ mockRateLimiterAllowed()+ await seedRecipe()+ },+ body: { teamIds: [] },+ },+ {+ label: 'approval allowlist read',+ method: 'get',+ path: `/admin/workflow-recipes/${RECIPE_NS}/test-recipe/allowed-teams`,+ auth: 'bearer',+ setup: async () => {+ mockRateLimiterAllowed()+ await seedRecipe()+ },+ },+ {+ label: 'approval allowlist grant',+ method: 'put',+ path: `/admin/workflow-recipes/${RECIPE_NS}/test-recipe/allowed-teams/${VALID_TEAM_UUID}`,+ auth: 'bearer',+ setup: async () => {+ mockRateLimiterAllowed()+ await seedRecipe()+ },+ },+ {+ label: 'approval allowlist revoke',+ method: 'delete',+ path: `/admin/workflow-recipes/${RECIPE_NS}/test-recipe/allowed-teams/${VALID_TEAM_UUID}`,+ auth: 'bearer',+ setup: async () => {+ mockRateLimiterAllowed()+ await seedRecipe()+ },+ },+ { label: 'workflow leader', method: 'get', path: '/admin/workflows/leader', auth: 'bearer' },+ {+ label: 'runs stream',+ method: 'get',+ path: '/admin/workflows/runs/stream',+ auth: 'cookie',+ },+ {+ label: 'workflow runs list',+ method: 'get',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/runs`,+ auth: 'bearer',+ setup: seedRecipe,+ },+ {+ label: 'workflow run detail',+ method: 'get',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/runs/${RUN_ID}`,+ auth: 'bearer',+ setup: seedRecipe,+ },+ {+ label: 'run artifacts list',+ method: 'get',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/runs/${RUN_ID}/artifacts`,+ auth: 'bearer',+ setup: seedRecipe,+ },+ {+ label: 'run artifact download',+ method: 'get',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/runs/${RUN_ID}/artifacts/report.md/download`,+ auth: 'bearer',+ setup: seedRecipe,+ },+ {+ label: 'run artifact delete',+ method: 'delete',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/runs/${RUN_ID}/artifacts/report.md`,+ auth: 'bearer',+ setup: seedRecipe,+ },+ {+ label: 'run artifacts bulk delete',+ method: 'delete',+ path: `/admin/workflows/${RECIPE_NS}/test-recipe/runs/${RUN_ID}/artifacts`,+ auth: 'bearer',+ setup: seedRecipe,+ },+ {+ label: 'admin outputs',+ method: 'get',+ path: '/admin/outputs',+ auth: 'cookie',+ useOutputsApp: true,+ },+ ]++ it.each(staleHandlerMatrix)(+ 'rejects stale administrator sessions on $label',+ async ({ method, path, auth, useOutputsApp, setup, headers, body }) => {+ mockLiveAdminSession({ tokenSessionVersion: 1, adminSessionVersion: 2 })+ if (setup) await setup()++ const app = useOutputsApp ? makeOutputsApp(gateway) : makeApp(gateway)+ let req = request(app)[method](path)+ if (auth === 'bearer') {+ req = req.set('Authorization', 'Bearer admin-token-stale')+ } else {+ req = req.set('Cookie', 'control_ui_admin_session=admin-token-stale')+ }+ for (const [header, value] of Object.entries(headers ?? {})) {+ req = req.set(header, value)+ }+ if (body) req = req.send(body)++ const res = await req+ expectUnauthorized(res)+ expect(mockListWorkflowGrants).not.toHaveBeenCalled()+ expect(mockSetWorkflowGrants).not.toHaveBeenCalled()+ }+ )+ })})diff --git a/control-api/test/services.adminSessionAuth.test.ts b/control-api/test/services.adminSessionAuth.test.tsnew file mode 100644index 000000000..4e6d75433--- /dev/null+++ b/control-api/test/services.adminSessionAuth.test.ts@@ -0,0 +1,148 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { authenticateAdminSession } from '../src/services/adminSessionAuth.js'++const adminTokenMock = vi.hoisted(() => ({+ verifyAdminToken: vi.fn(),+}))++const adminSvcMock = vi.hoisted(() => ({+ findAdminById: vi.fn(),+ isAdminTokenRevoked: vi.fn(),+}))++vi.mock('../src/utils/auth/adminAuthToken.js', () => adminTokenMock)+vi.mock('../src/services/adminAuthService.js', () => adminSvcMock)++const BASE_CLAIMS = {+ sub: '00000000-0000-4000-8000-000000000001',+ typ: 'user' as const,+ role: 'admin' as const,+ jti: 'admin-jti',+ exp: 9999999999,+ sessionVersion: 2,+}++const ACTIVE_ADMIN = {+ id: BASE_CLAIMS.sub,+ username: 'admin',+ email: '[email protected]',+ passwordHash: 'hash',+ sessionVersion: 2,+ role: 'admin' as const,+ status: 'active' as const,+ failedAttempts: 0,+ lockedUntil: null,+}++describe('services/adminSessionAuth', () => {+ beforeEach(() => {+ adminTokenMock.verifyAdminToken.mockReset()+ adminSvcMock.findAdminById.mockReset()+ adminSvcMock.isAdminTokenRevoked.mockReset()+ })++ it('accepts a valid administrator session with matching sessionVersion', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockResolvedValue(ACTIVE_ADMIN)++ await expect(authenticateAdminSession('valid-token')).resolves.toEqual(BASE_CLAIMS)+ })++ it('rejects missing or oversized tokens without calling downstream services', async () => {+ await expect(authenticateAdminSession(null)).resolves.toBeNull()+ await expect(authenticateAdminSession('')).resolves.toBeNull()+ await expect(authenticateAdminSession('x'.repeat(4097))).resolves.toBeNull()+ expect(adminTokenMock.verifyAdminToken).not.toHaveBeenCalled()+ })++ it('rejects invalid JWTs', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(null)+ await expect(authenticateAdminSession('bad-token')).resolves.toBeNull()+ expect(adminSvcMock.isAdminTokenRevoked).not.toHaveBeenCalled()+ })++ it('rejects revoked JTIs', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(true)++ await expect(authenticateAdminSession('valid-token')).resolves.toBeNull()+ expect(adminSvcMock.findAdminById).not.toHaveBeenCalled()+ })++ it('rejects tokens issued before password reset (stale sessionVersion)', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue({ ...BASE_CLAIMS, sessionVersion: 1 })+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockResolvedValue({ ...ACTIVE_ADMIN, sessionVersion: 2 })++ await expect(authenticateAdminSession('stale-token')).resolves.toBeNull()+ })++ it('rejects tokens when sessionVersion claim exceeds the current admin record', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue({ ...BASE_CLAIMS, sessionVersion: 3 })+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockResolvedValue({ ...ACTIVE_ADMIN, sessionVersion: 2 })++ await expect(authenticateAdminSession('future-token')).resolves.toBeNull()+ })++ it('treats absent sessionVersion claims as version 0', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue({+ ...BASE_CLAIMS,+ sessionVersion: undefined,+ })+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockResolvedValue({ ...ACTIVE_ADMIN, sessionVersion: 0 })++ await expect(authenticateAdminSession('legacy-token')).resolves.toEqual({+ ...BASE_CLAIMS,+ sessionVersion: undefined,+ })+ })++ it('rejects disabled administrators', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockResolvedValue({ ...ACTIVE_ADMIN, status: 'disabled' })++ await expect(authenticateAdminSession('valid-token')).resolves.toBeNull()+ })++ it('rejects missing administrator records', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockResolvedValue(null)++ await expect(authenticateAdminSession('valid-token')).resolves.toBeNull()+ })++ it('allows locked administrators because lockedUntil is login-only (F4 out of scope)', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockResolvedValue({+ ...ACTIVE_ADMIN,+ lockedUntil: new Date(Date.now() + 60_000),+ })++ await expect(authenticateAdminSession('valid-token')).resolves.toEqual(BASE_CLAIMS)+ })++ it('propagates revocation lookup failures instead of mapping them to unauthorized', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockRejectedValue(new Error('pg connection terminated'))++ await expect(authenticateAdminSession('valid-token')).rejects.toThrow(+ 'pg connection terminated'+ )+ })++ it('propagates findAdminById failures instead of mapping them to unauthorized', async () => {+ adminTokenMock.verifyAdminToken.mockReturnValue(BASE_CLAIMS)+ adminSvcMock.isAdminTokenRevoked.mockResolvedValue(false)+ adminSvcMock.findAdminById.mockRejectedValue(new Error('pg connection terminated'))++ await expect(authenticateAdminSession('valid-token')).rejects.toThrow(+ 'pg connection terminated'+ )+ })+})