Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): harden admin workflow rate-limit isolation
Alfredo Lopez5274c736f570
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 514fcfe60..d6782a6cb 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.487",+ "version": "0.1.488","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.487",+ "version": "0.1.488","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 3c2f3cd96..895f64295 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.487",+ "version": "0.1.488","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/workflows/grants.routes.ts b/control-api/src/routes/admin/workflows/grants.routes.tsindex 9d7e99b6f..f6f409c12 100644--- a/control-api/src/routes/admin/workflows/grants.routes.ts+++ b/control-api/src/routes/admin/workflows/grants.routes.ts@@ -39,10 +39,12 @@ function withAdministrativeTraceContext<T>(req: Request, operatorSub: string, wo// product contracts, even though both mutate workflow authorization policy.export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {const router = Router()+ const readRateLimits = workflowGrantReadRateLimits()+ const writeRateLimits = workflowGrantWriteRateLimits()router.get(`${BASE}/:ns/:name/grants`,- ...workflowGrantReadRateLimits(),+ ...readRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {if (!requireBoundAdminWorkflowCaller(req, res)) return@@ -62,7 +64,7 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.put(`${BASE}/:ns/:name/grants`,- ...workflowGrantWriteRateLimits(),+ ...writeRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {const caller = requireBoundAdminWorkflowCaller(req, res)@@ -108,7 +110,7 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.get(`${BASE}/:ns/:name/team-grants`,- ...workflowGrantReadRateLimits(),+ ...readRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {if (!requireBoundAdminWorkflowCaller(req, res)) return@@ -128,7 +130,7 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.put(`${BASE}/:ns/:name/team-grants`,- ...workflowGrantWriteRateLimits(),+ ...writeRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {const caller = requireBoundAdminWorkflowCaller(req, res)@@ -174,7 +176,7 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.get(`/admin/workflow-recipes/:ns/:name/allowed-teams`,- ...workflowGrantReadRateLimits(),+ ...readRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {if (!requireBoundAdminWorkflowCaller(req, res)) return@@ -198,7 +200,7 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.put(`/admin/workflow-recipes/:ns/:name/allowed-teams/:teamId`,- ...workflowGrantWriteRateLimits(),+ ...writeRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {const caller = requireBoundAdminWorkflowCaller(req, res)@@ -238,7 +240,7 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.delete(`/admin/workflow-recipes/:ns/:name/allowed-teams/:teamId`,- ...workflowGrantWriteRateLimits(),+ ...writeRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {const caller = requireBoundAdminWorkflowCaller(req, res)diff --git a/control-api/src/routes/admin/workflows/read.routes.ts b/control-api/src/routes/admin/workflows/read.routes.tsindex c3511645d..8c294a2d5 100644--- a/control-api/src/routes/admin/workflows/read.routes.ts+++ b/control-api/src/routes/admin/workflows/read.routes.ts@@ -20,10 +20,11 @@ const BASE = '/admin/workflows'export function createAdminWorkflowReadRoutes(gateway: K8sGateway): Router {const router = Router()+ const readRateLimits = workflowAdminReadRateLimits()router.get(BASE,- ...workflowAdminReadRateLimits(),+ ...readRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {const caller = requireBoundAdminWorkflowCaller(req, res)@@ -36,7 +37,7 @@ export function createAdminWorkflowReadRoutes(gateway: K8sGateway): Router {router.get(`${BASE}/:ns/:name`,- ...workflowAdminReadRateLimits(),+ ...readRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {const caller = requireBoundAdminWorkflowCaller(req, res)@@ -67,7 +68,7 @@ export function createAdminWorkflowReadRoutes(gateway: K8sGateway): Router {router.get(`${BASE}/:ns/:name/health`,- ...workflowAdminReadRateLimits(),+ ...readRateLimits,bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {const caller = requireBoundAdminWorkflowCaller(req, res)diff --git a/control-api/src/routes/admin/workflows/trigger.routes.ts b/control-api/src/routes/admin/workflows/trigger.routes.tsindex cbe74cb72..229457780 100644--- a/control-api/src/routes/admin/workflows/trigger.routes.ts+++ b/control-api/src/routes/admin/workflows/trigger.routes.ts@@ -11,7 +11,7 @@ import {triggerWorkflow,} from '../../../services/workflows/workflowTriggerService.js'import { requireAdminWorkflowCaller } from '../../workflows/shared/auth.js'-import { workflowTriggerRateLimit } from '../../workflows/shared/rateLimit.js'+import { adminWorkflowTriggerRateLimit } from '../../workflows/shared/rateLimit.js'const BASE = '/admin/workflows'const logger = rootLogger.child({ module: 'admin-workflows' })@@ -21,7 +21,7 @@ export function createAdminWorkflowTriggerRoutes(gateway: K8sGateway): Router {router.post(`${BASE}/:ns/:name/trigger`,- workflowTriggerRateLimit(),+ adminWorkflowTriggerRateLimit(),asyncHandler(async (req: Request, res: Response) => {const caller = await requireAdminWorkflowCaller(req, res)if (!caller) returndiff --git a/control-api/src/routes/workflows/shared/rateLimit.ts b/control-api/src/routes/workflows/shared/rateLimit.tsindex f7c1cd6c3..56474616a 100644--- a/control-api/src/routes/workflows/shared/rateLimit.ts+++ b/control-api/src/routes/workflows/shared/rateLimit.ts@@ -23,7 +23,7 @@ export function adminWorkflowRateLimitCredential(req: Request): string | null {return cookie || null}-/** Persist PG buckets only for cryptographically verified admin subjects. */+/** Extract the signed administrator subject for direct callers. */export function verifiedAdminRateLimitSubject(credential: string | null): string | null {if (!credential) return nullconst claims = verifyAdminToken(credential)@@ -33,9 +33,9 @@ export function verifiedAdminRateLimitSubject(credential: string | null): stringfunction hashedAdminWorkflowCredentialBucket(prefix: string) {return (req: Request): string | null => {const credential = adminWorkflowRateLimitCredential(req)- const subject = verifiedAdminRateLimitSubject(credential)- if (subject) {- const hash = createHash('sha256').update(subject).digest('hex').slice(0, 32)+ const sessionIdentity = verifiedAdminRateLimitIdentity(credential)+ if (sessionIdentity) {+ const hash = createHash('sha256').update(sessionIdentity).digest('hex').slice(0, 32)return `${prefix}:${hash}`}if (!credential) return null@@ -55,13 +55,13 @@ export function shouldSkipWorkflowGrantEdgeRateLimit(req: Request): boolean {/*** Edge backstop key:- * - Verified admin cookie/bearer → per-subject bucket (isolates Control UI admins)+ * - Verified admin cookie/bearer → per-session bucket (isolates live sessions)* - Unverified credential → IP bucket (rotation cannot mint fresh identities)*/export function workflowGrantEdgeRateLimitKey(prefix: string, req: Request): string {- const subject = verifiedAdminRateLimitSubject(adminWorkflowRateLimitCredential(req))- if (subject) {- const hash = createHash('sha256').update(subject).digest('hex').slice(0, 32)+ const sessionIdentity = verifiedAdminRateLimitIdentity(adminWorkflowRateLimitCredential(req))+ if (sessionIdentity) {+ const hash = createHash('sha256').update(sessionIdentity).digest('hex').slice(0, 32)return `${prefix}:sub:${hash}`}return `${prefix}:ip:${ipKeyGenerator(req.ip ?? 'unknown')}`@@ -95,8 +95,8 @@ function createWorkflowEdgeRateLimit(prefix: string, limit: number) {}/**- * Fresh stack per call so route tests stay isolated. Shared MemoryStore- * across grant-write registrations is a follow-up (Low 1), not this PR.+ * Fresh stack per call so route factories and tests can scope their stores.+ * Routers that own a rate-limit family instantiate the tuple once and reuse it.*/export function workflowGrantReadEdgeRateLimit() {return createWorkflowEdgeRateLimit('workflow_grants_read_edge', WORKFLOW_GRANT_READ_PER_MINUTE)@@ -130,6 +130,25 @@ export function adminOutputsReadRateLimits() {return [adminOutputsReadEdgeRateLimit(), adminOutputsReadRateLimit()] as const}+function adminWorkflowTriggerRateLimitKey(req: Request): string | null {+ const value = adminWorkflowRateLimitCredential(req)+ if (!value) return null+ const identity = verifiedAdminRateLimitIdentity(value)+ if (identity) {+ const hash = createHash('sha256').update(identity).digest('hex').slice(0, 32)+ return `workflow_trigger_admin:${hash}`+ }+ return `workflow_trigger_admin:ip:${ipKeyGenerator(req.ip ?? 'unknown')}`+}++export function adminWorkflowTriggerRateLimit() {+ return rateLimitMiddleware({+ bucketType: 'workflow_trigger',+ maxPerMinute: WORKFLOW_TRIGGER_PER_MINUTE,+ getBucketKey: adminWorkflowTriggerRateLimitKey,+ })+}+function workflowTriggerRateLimitCredential(req: Request): string | null {const bearer = extractBearerToken(req)if (bearer) {@@ -191,3 +210,9 @@ export function workflowGrantWriteRateLimit() {getBucketKey: hashedAdminWorkflowCredentialBucket('workflow_grants_write'),})}++/** Keep distinct signed sessions in distinct pre-auth quota buckets. */+export function verifiedAdminRateLimitIdentity(input: string | null): string | null {+ if (!input || !verifiedAdminRateLimitSubject(input)) return null+ return input+}diff --git a/control-api/test/workflows.shared.rateLimit.test.ts b/control-api/test/workflows.shared.rateLimit.test.tsindex 6b60ecc7d..be5b422f8 100644--- a/control-api/test/workflows.shared.rateLimit.test.ts+++ b/control-api/test/workflows.shared.rateLimit.test.ts@@ -4,6 +4,7 @@ import request from 'supertest'import {adminOutputsReadRateLimits,adminWorkflowRateLimitCredential,+ adminWorkflowTriggerRateLimit,shouldSkipWorkflowGrantEdgeRateLimit,verifiedAdminRateLimitSubject,workflowAdminReadRateLimits,@@ -101,6 +102,26 @@ describe('routes/workflows/shared/rateLimit', () => {)})+ it('keeps rotated signed sessions in separate pre-auth buckets', () => {+ mockVerifyAdminToken.mockImplementation((value: string) =>+ value.startsWith('signed-') ? signedClaims('same-admin') : null+ )+ const reqA = {+ ip: '203.0.113.10',+ header: (name: string) =>+ name.toLowerCase() === 'cookie' ? 'control_ui_admin_session=signed-admin-a' : undefined,+ } as express.Request+ const reqB = {+ ip: '203.0.113.10',+ header: (name: string) =>+ name.toLowerCase() === 'cookie' ? 'control_ui_admin_session=signed-admin-b' : undefined,+ } as express.Request++ expect(workflowGrantEdgeRateLimitKey('workflow_grants_read_edge', reqA)).not.toBe(+ workflowGrantEdgeRateLimitKey('workflow_grants_read_edge', reqB)+ )+ })+it('workflowGrantEdgeRateLimitKey aggregates unverified cookies on the same IP', () => {const reqA = {ip: '203.0.113.10',@@ -333,6 +354,39 @@ describe('routes/workflows/shared/rateLimit', () => {expect(mockCheckAndIncrement.mock.calls[0]?.[0]).toMatch(/^workflow_trigger:[0-9a-f]{32}$/)})+ it('adminWorkflowTriggerRateLimit isolates rotated signed sessions', async () => {+ mockVerifyAdminToken.mockImplementation((value: string) =>+ value.startsWith('signed-') ? signedClaims('same-admin') : null+ )+ mockCheckAndIncrement.mockReset()+ mockCheckAndIncrement.mockResolvedValue({+ allowed: true,+ remaining: 9,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ })++ const app = express()+ app.post('/trigger', adminWorkflowTriggerRateLimit(), (_req, res) => {+ res.status(200).json({ ok: true })+ })++ await request(app)+ .post('/trigger')+ .set('Cookie', 'control_ui_admin_session=signed-admin-a')+ .expect(200)+ await request(app)+ .post('/trigger')+ .set('Cookie', 'control_ui_admin_session=signed-admin-b')+ .expect(200)++ expect(mockCheckAndIncrement).toHaveBeenCalledTimes(2)+ expect(mockCheckAndIncrement.mock.calls[0]?.[0]).not.toBe(+ mockCheckAndIncrement.mock.calls[1]?.[0]+ )+ })+it('workflowGrantReadRateLimit meters cookie-only admin workflow callers', async () => {mockCheckAndIncrement.mockReset()mockCheckAndIncrement.mockResolvedValue({diff --git a/control-ui/components/WorkflowAccessPanel/index.tsx b/control-ui/components/WorkflowAccessPanel/index.tsxindex 59430b77d..2d6fbd00f 100644--- a/control-ui/components/WorkflowAccessPanel/index.tsx+++ b/control-ui/components/WorkflowAccessPanel/index.tsx@@ -10,6 +10,7 @@ import {allowWorkflowApprovalTeam,getAdminTeams,getAdminUsers,+ isSilentApiError,listWorkflowApprovalAllowedTeams,listWorkflowGrants,listWorkflowTeamGrants,@@ -46,6 +47,21 @@ function uniqueIds(ids: string[]): string[] {return [...new Set(ids.map(id => id.trim()).filter(Boolean))]}+function apiErrorStatus(error: unknown): number | null {+ if (!error || typeof error !== 'object') return null+ const status = (error as { status?: unknown }).status+ return typeof status === 'number' ? status : null+}++function apiErrorRetryAfterSeconds(error: unknown): number | null {+ if (apiErrorStatus(error) !== 429 || !error || typeof error !== 'object') return null+ const body = (error as { body?: unknown }).body+ if (!body || typeof body !== 'object') return null+ const raw = (body as Record<string, unknown>).retryAfterSeconds+ const seconds = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN+ return Number.isFinite(seconds) && seconds > 0 ? Math.ceil(seconds) : null+}+function removeId(ids: string[], id: string): string[] {return ids.filter(existing => existing !== id)}@@ -297,26 +313,54 @@ export function WorkflowAccessPanel(props: WorkflowAccessPanelProps): React.JSX.const removed = current.filter(id => !nextTeamIds.includes(id))setSectionPatch('approval-target-teams', { mutating: true, mutateError: null })const errors: string[] = []+ let rateLimited = false+ let retryAfterSeconds: number | null = null+ let appliedMutations = 0+ const recordMutationError = (error: unknown): boolean => {+ if (isSilentApiError(error)) throw error+ if (apiErrorStatus(error) === 429) {+ rateLimited = true+ const retry = apiErrorRetryAfterSeconds(error)+ retryAfterSeconds = Math.max(retryAfterSeconds ?? 0, retry ?? 0) || null+ return true+ }+ errors.push(error instanceof Error ? error.message : String(error))+ return false+ }+ let stopMutations = falsetry {// Serialize allow/revoke so a shared 20/min grant-write bucket cannot// leave a partial write behind a Promise.all rejection.for (const teamId of added) {try {await allowWorkflowApprovalTeam(namespace, recipeName, teamId)+ appliedMutations += 1} catch (error) {- errors.push(error instanceof Error ? error.message : String(error))+ stopMutations = recordMutationError(error)+ if (stopMutations) break}}- for (const teamId of removed) {+ for (const teamId of stopMutations ? [] : removed) {try {await revokeWorkflowApprovalTeam(namespace, recipeName, teamId)+ appliedMutations += 1} catch (error) {- errors.push(error instanceof Error ? error.message : String(error))+ stopMutations = recordMutationError(error)+ if (stopMutations) break}}await loadApprovalTeams()- if (errors.length > 0) {- throw new Error(errors.join('; '))+ if (rateLimited || errors.length > 0) {+ const messages = [...errors]+ if (rateLimited) {+ const partialPrefix = appliedMutations > 0 ? 'Some changes were saved. ' : ''+ messages.unshift(+ retryAfterSeconds === null+ ? `${partialPrefix}Too many approval target team changes. Try again shortly.`+ : `${partialPrefix}Too many approval target team changes. Try again in about ${retryAfterSeconds} seconds.`+ )+ }+ throw new Error(messages.join('; '))}if (added.length > 0) {showToast('Approval target team allowed.', { tone: 'success' })@@ -326,7 +370,7 @@ export function WorkflowAccessPanel(props: WorkflowAccessPanelProps): React.JSX.showToast('Approval target teams updated.', { tone: 'success' })}} catch (error) {- if (!mountedRef.current) return+ if (!mountedRef.current || isSilentApiError(error)) returnsetSectionPatch('approval-target-teams', {mutateError:error instanceof Error ? error.message : 'Failed to save approval target teams',diff --git a/control-ui/components/__tests__/WorkflowAccessPanel.test.tsx b/control-ui/components/__tests__/WorkflowAccessPanel.test.tsxindex 4d9fd3f97..125232631 100644--- a/control-ui/components/__tests__/WorkflowAccessPanel.test.tsx+++ b/control-ui/components/__tests__/WorkflowAccessPanel.test.tsx@@ -2,11 +2,13 @@ import React, { useState } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import {+ allowWorkflowApprovalTeam,getAdminTeams,getAdminUsers,listWorkflowApprovalAllowedTeams,listWorkflowGrants,listWorkflowTeamGrants,+ revokeWorkflowApprovalTeam,setWorkflowGrants,setWorkflowTeamGrants,} from '@lib/api'@@ -19,6 +21,8 @@ vi.mock('@lib/api', () => ({listWorkflowGrants: vi.fn(),listWorkflowTeamGrants: vi.fn(),listWorkflowApprovalAllowedTeams: vi.fn(),+ isSilentApiError: (error: unknown) =>+ Boolean(error && typeof error === 'object' && (error as { silent?: unknown }).silent),setWorkflowGrants: vi.fn(),setWorkflowTeamGrants: vi.fn(),allowWorkflowApprovalTeam: vi.fn(),@@ -77,6 +81,8 @@ const triggerTeamGrant = {createdAt: '2026-01-01T00:00:00Z',}const nextTeamGrant = { id: 'team-next', name: 'Next Team', createdAt: '2026-01-01T00:00:00Z' }+const finalTeamGrant = { id: 'team-final', name: 'Final Team', createdAt: '2026-01-01T00:00:00Z' }+const lastTeamGrant = { id: 'team-last', name: 'Last Team', createdAt: '2026-01-01T00:00:00Z' }beforeEach(() => {vi.mocked(getAdminUsers).mockResolvedValue({@@ -89,6 +95,8 @@ beforeEach(() => {items: [{ ...triggerTeamGrant, memberCount: 2 },{ ...nextTeamGrant, memberCount: 2 },+ { ...finalTeamGrant, memberCount: 2 },+ { ...lastTeamGrant, memberCount: 2 },],})vi.mocked(listWorkflowGrants).mockResolvedValue({ items: [] })@@ -260,4 +268,80 @@ describe('WorkflowAccessPanel', () => {]))})++ it('serializes approval-team writes, reloads after a rate limit, and shows one retry message', async () => {+ const firstAllow = createDeferred<{ teamId: string }>()+ const rateLimitError = Object.assign(new Error('429 Too Many Requests'), {+ status: 429,+ body: { error: 'Too Many Requests', retryAfterSeconds: 12 },+ })+ vi.mocked(listWorkflowApprovalAllowedTeams).mockResolvedValue({ items: [triggerTeamGrant] })+ vi.mocked(allowWorkflowApprovalTeam)+ .mockReturnValueOnce(firstAllow.promise)+ .mockRejectedValueOnce(rateLimitError)++ render(<EditHarness />)++ fireEvent.click(screen.getByRole('tab', { name: /Approval target teams/ }))+ const section = screen.getByTestId('workflow-access-approval-target-teams')+ await waitFor(() => expect(within(section).getByText('Trigger Team')).toBeInTheDocument())++ fireEvent.click(within(section).getByRole('option', { name: 'Next Team' }))+ fireEvent.click(within(section).getByRole('option', { name: 'Final Team' }))+ fireEvent.click(within(section).getByRole('option', { name: 'Last Team' }))+ fireEvent.click(within(section).getByRole('button', { name: 'Allow teams' }))++ await waitFor(() => expect(allowWorkflowApprovalTeam).toHaveBeenCalledTimes(1))+ expect(allowWorkflowApprovalTeam).toHaveBeenCalledWith(+ 'sandbox-recipes',+ 'installed-recipe',+ 'team-next'+ )+ expect(allowWorkflowApprovalTeam).toHaveBeenCalledTimes(1)++ await act(async () => {+ firstAllow.resolve({ teamId: 'team-next' })+ })++ await waitFor(() => expect(allowWorkflowApprovalTeam).toHaveBeenCalledTimes(2))+ await waitFor(() => expect(listWorkflowApprovalAllowedTeams).toHaveBeenCalledTimes(2))+ expect(allowWorkflowApprovalTeam).toHaveBeenLastCalledWith(+ 'sandbox-recipes',+ 'installed-recipe',+ 'team-final'+ )+ expect(allowWorkflowApprovalTeam).not.toHaveBeenCalledWith(+ 'sandbox-recipes',+ 'installed-recipe',+ 'team-last'+ )+ expect(revokeWorkflowApprovalTeam).not.toHaveBeenCalled()+ expect(within(section).getByRole('alert')).toHaveTextContent(+ 'Some changes were saved. Too many approval target team changes. Try again in about 12 seconds.'+ )+ expect(screen.queryByText('Approval target teams updated.')).not.toBeInTheDocument()+ })++ it('stops approval-team writes when the session expires', async () => {+ const authExpired = Object.assign(new Error('Session expired'), {+ status: 401,+ silent: true,+ })+ vi.mocked(allowWorkflowApprovalTeam).mockRejectedValueOnce(authExpired)++ render(<EditHarness />)++ fireEvent.click(screen.getByRole('tab', { name: /Approval target teams/ }))+ const section = screen.getByTestId('workflow-access-approval-target-teams')+ await waitFor(() =>+ expect(within(section).getByRole('option', { name: 'Next Team' })).toBeInTheDocument()+ )+ fireEvent.click(within(section).getByRole('option', { name: 'Next Team' }))+ fireEvent.click(within(section).getByRole('button', { name: 'Allow team' }))++ await waitFor(() => expect(allowWorkflowApprovalTeam).toHaveBeenCalledOnce())+ expect(revokeWorkflowApprovalTeam).not.toHaveBeenCalled()+ expect(listWorkflowApprovalAllowedTeams).toHaveBeenCalledOnce()+ expect(within(section).queryByRole('alert')).not.toBeInTheDocument()+ })})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex 925383b5f..84ba05af0 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -225,20 +225,27 @@ export async function apiGet(const text = await res.text().catch(() => '')let message = `${res.status} ${res.statusText}`let code: string | undefined+ let body: Record<string, unknown> | undefinedtry {- const parsed = JSON.parse(text) as { error?: unknown; message?: unknown }+ const parsed = JSON.parse(text) as unknownif (parsed && typeof parsed === 'object') {- if (typeof parsed.message === 'string' && parsed.message.trim()) {- message = parsed.message+ body = parsed as Record<string, unknown>+ if (typeof body.message === 'string' && body.message.trim()) {+ message = body.message}- if (typeof parsed.error === 'string') code = parsed.error+ if (typeof body.error === 'string') code = body.error}} catch {/* non-JSON error body: keep the status-text message */}- const error = new Error(message) as Error & { status?: number; code?: string }+ const error = new Error(message) as Error & {+ status?: number+ code?: string+ body?: Record<string, unknown>+ }error.status = res.statusif (code) error.code = code+ if (body) error.body = bodythrow error}return parseJsonResponse(res)diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex f82798ed4..285ef880b 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.443",+ "version": "0.1.444","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.443",+ "version": "0.1.444","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 930743b63..e63ae6c3c 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.443",+ "version": "0.1.444","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/docs/how-to/codeql-js-missing-rate-limiting.md b/docs/how-to/codeql-js-missing-rate-limiting.mdindex 7099c959f..610df3038 100644--- a/docs/how-to/codeql-js-missing-rate-limiting.md+++ b/docs/how-to/codeql-js-missing-rate-limiting.md@@ -18,41 +18,47 @@ may still alert until an `express-rate-limit` **edge backstop** is added (see## Approved patterns-| Pattern | Purpose |-| -------- | -------- |-| `rateLimitMiddleware` only | Production enforcement (cross-replica) |-| PG + `express-rate-limit` backstop | Production + CodeQL/SAST visibility |+| Pattern | Purpose |+| ------------------------------------------------------ | --------------------------------------------------------------- |+| `rateLimitMiddleware` only | Production enforcement (cross-replica) |+| PG + `express-rate-limit` backstop | Production + CodeQL/SAST visibility || Auth as Express middleware **before** business handler | Keeps authorization out of the final handler node CodeQL labels |-Tier defaults (requests/minute, per admin credential hash unless noted):+Tier defaults (requests/minute, per verified admin session identity unless noted):-| Tier | Limit | Config anchor |-| ---- | ----- | ------------- |-| Admin public token | 20 | `adminPublicTokenRlPerMin` |-| Admin workflow grant read | 60 | `workflowGrantReadRateLimit` |-| Admin workflow grant write | 20 | `workflowGrantWriteRateLimit` |-| Registry identity voucher | 30 | inline in `registry.ts` |-| Registry connect request | 3 | inline in `registryConnect.ts` |+| Tier | Limit | Config anchor |+| ---------------------------- | -------- | ---------------------------------------------------------- |+| Admin public token | 20 | `adminPublicTokenRlPerMin` |+| Admin workflow grant read | 60 | `workflowGrantReadRateLimit` |+| Admin workflow grant write | 20 | `workflowGrantWriteRateLimit` |+| Registry identity voucher | 30 | inline in `registry.ts` |+| Registry connect request | 3 | inline in `registryConnect.ts` || External GFS read / mutation | 120 / 30 | `externalGfsReadRlPerMin` / `externalGfsOperationRlPerMin` |## PR #428 / F4 scope (fixed in branch)-| Alert | Location | Resolution |-| ----- | -------- | ---------- |-| [#81](https://github.com/evenfire-ai/evenfire/security/code-scanning/81) | `grants.routes.ts:173` | Fixed: cookie bucket + dual limiter + auth middleware |-| [#82](https://github.com/evenfire-ai/evenfire/security/code-scanning/82) | `grants.routes.ts:197` | Fixed: same |-| [#83](https://github.com/evenfire-ai/evenfire/security/code-scanning/83) | `grants.routes.ts:236` | Fixed: same |-| [#63](https://github.com/evenfire-ai/evenfire/security/code-scanning/63) | `outputs.ts:35` | Fixed: `adminOutputsReadRateLimits()` PG + edge backstop (30/min) |--Edge backstop keys: **cookie hash** for Control UI sessions, **source IP** for bearer-only automation, **skipped** when no credential (anonymous). PG tiers remain per admin credential hash.+| Alert | Location | Resolution |+| ------------------------------------------------------------------------ | ---------------------- | ----------------------------------------------------------------- |+| [#81](https://github.com/evenfire-ai/evenfire/security/code-scanning/81) | `grants.routes.ts:173` | Fixed: cookie bucket + dual limiter + auth middleware |+| [#82](https://github.com/evenfire-ai/evenfire/security/code-scanning/82) | `grants.routes.ts:197` | Fixed: same |+| [#83](https://github.com/evenfire-ai/evenfire/security/code-scanning/83) | `grants.routes.ts:236` | Fixed: same |+| [#63](https://github.com/evenfire-ai/evenfire/security/code-scanning/63) | `outputs.ts:35` | Fixed: `adminOutputsReadRateLimits()` PG + edge backstop (30/min) |++Edge backstop keys: a **verified admin session identity hash** for signed+Control UI sessions/bearers and a **source-IP fallback** for credentials that+fail verification; requests with no credential are **skipped** (anonymous).+PG tiers use the same verified-session identity, with the source-IP fallback+only for an unverified credential. Distinct signed sessions for one admin are+kept separate so a revoked/stale session cannot consume the replacement+session's quota.Additional tiers shipped in PR #428:-| Tier | Limit | Config anchor |-| ---- | ----- | ------------- |-| Admin workflow read | 60 | `workflowAdminReadRateLimits` |-| Admin outputs read | 30 | `adminOutputsReadRateLimits` |-| Admin workflow trigger | 10 | `workflowTriggerRateLimit` |+| Tier | Limit | Config anchor |+| ---------------------- | ----- | ------------------------------- |+| Admin workflow read | 60 | `workflowAdminReadRateLimits` |+| Admin outputs read | 30 | `adminOutputsReadRateLimits` |+| Admin workflow trigger | 10 | `adminWorkflowTriggerRateLimit` |## Out-of-scope dispositions (Layer 3)@@ -60,33 +66,33 @@ Follow-up implementation tracked separately (`fix/codeql-control-api-rate-limit-### False positive — PG limiter or non-route sink present-| Alert | Location | Evidence |-| ----- | -------- | -------- |-| [#57](https://github.com/evenfire-ai/evenfire/security/code-scanning/57) | `app.ts:131` | Middleware mount only; per-route limiters apply downstream |-| [#58](https://github.com/evenfire-ai/evenfire/security/code-scanning/58) | `app.ts:219` | 404 guard for unknown `/gfs/*`; no expensive work |-| [#60](https://github.com/evenfire-ai/evenfire/security/code-scanning/60) | `auth.ts:572` | Handler under `publicAdminTokenRateLimit()` (`adminPublicTokenRlPerMin`) |-| [#171](https://github.com/evenfire-ai/evenfire/security/code-scanning/171) | `registry.ts:24` | `rateLimitMiddleware` 30/min at `:28-35` |-| [#826](https://github.com/evenfire-ai/evenfire/security/code-scanning/826) | `registryConnect.ts:321` | `rateLimitMiddleware` 3/min at `:329-336` |-| [#803](https://github.com/evenfire-ai/evenfire/security/code-scanning/803) | `gfs/grants.ts:849` | Internal DB helper, not an HTTP route handler |+| Alert | Location | Evidence |+| -------------------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------ |+| [#57](https://github.com/evenfire-ai/evenfire/security/code-scanning/57) | `app.ts:131` | Middleware mount only; per-route limiters apply downstream |+| [#58](https://github.com/evenfire-ai/evenfire/security/code-scanning/58) | `app.ts:219` | 404 guard for unknown `/gfs/*`; no expensive work |+| [#60](https://github.com/evenfire-ai/evenfire/security/code-scanning/60) | `auth.ts:572` | Handler under `publicAdminTokenRateLimit()` (`adminPublicTokenRlPerMin`) |+| [#171](https://github.com/evenfire-ai/evenfire/security/code-scanning/171) | `registry.ts:24` | `rateLimitMiddleware` 30/min at `:28-35` |+| [#826](https://github.com/evenfire-ai/evenfire/security/code-scanning/826) | `registryConnect.ts:321` | `rateLimitMiddleware` 3/min at `:329-336` |+| [#803](https://github.com/evenfire-ai/evenfire/security/code-scanning/803) | `gfs/grants.ts:849` | Internal DB helper, not an HTTP route handler |### Won't fix (accepted) — real gap, follow-up backstop PRTracked for `fix/codeql-control-api-rate-limit-backstops`. No auth bypass; missingSAST-visible backstop (and in some cases PG limiter — see Notes).-| Alert | Location | Planned tier | Notes |-| ----- | -------- | ------------ | ----- |-| [#61](https://github.com/evenfire-ai/evenfire/security/code-scanning/61) | `auth.ts:607` | 60/min session read | `/admin/auth/me` SPA hydration |-| [#62](https://github.com/evenfire-ai/evenfire/security/code-scanning/62) | `controlAdmins.ts:327` | 10/min write | Admin invitation POST |-| [#70](https://github.com/evenfire-ai/evenfire/security/code-scanning/70) | `registryConnect.ts:520` | 10/min write | Claim redemption |-| [#71](https://github.com/evenfire-ai/evenfire/security/code-scanning/71) | `registryConnect.ts:715` | 10/min write | Key rotation |-| [#133](https://github.com/evenfire-ai/evenfire/security/code-scanning/133) | `gfs/proxy.ts:31` | 120 read | Control UI GFS |-| [#138](https://github.com/evenfire-ai/evenfire/security/code-scanning/138) | `gfs/resolve.ts:80` | 120 read | Control UI GFS |-| [#140](https://github.com/evenfire-ai/evenfire/security/code-scanning/140) | `gfs/resolve.ts:89` | 120 read | Control UI GFS |-| [#144](https://github.com/evenfire-ai/evenfire/security/code-scanning/144) | `gfs/token.ts:44` | 30 mutation | GFS token mint |-| [#145](https://github.com/evenfire-ai/evenfire/security/code-scanning/145) | `gfs/resources.ts:350` | 30 mutation | PATCH resource |-| [#149](https://github.com/evenfire-ai/evenfire/security/code-scanning/149) | `gfs/tree.ts:24` | 120 read | Tree browse |-| [#150](https://github.com/evenfire-ai/evenfire/security/code-scanning/150) | `gfs/tree.ts:51` | 120 read | Children paging |+| Alert | Location | Planned tier | Notes |+| -------------------------------------------------------------------------- | ------------------------ | ------------------- | ------------------------------ |+| [#61](https://github.com/evenfire-ai/evenfire/security/code-scanning/61) | `auth.ts:607` | 60/min session read | `/admin/auth/me` SPA hydration |+| [#62](https://github.com/evenfire-ai/evenfire/security/code-scanning/62) | `controlAdmins.ts:327` | 10/min write | Admin invitation POST |+| [#70](https://github.com/evenfire-ai/evenfire/security/code-scanning/70) | `registryConnect.ts:520` | 10/min write | Claim redemption |+| [#71](https://github.com/evenfire-ai/evenfire/security/code-scanning/71) | `registryConnect.ts:715` | 10/min write | Key rotation |+| [#133](https://github.com/evenfire-ai/evenfire/security/code-scanning/133) | `gfs/proxy.ts:31` | 120 read | Control UI GFS |+| [#138](https://github.com/evenfire-ai/evenfire/security/code-scanning/138) | `gfs/resolve.ts:80` | 120 read | Control UI GFS |+| [#140](https://github.com/evenfire-ai/evenfire/security/code-scanning/140) | `gfs/resolve.ts:89` | 120 read | Control UI GFS |+| [#144](https://github.com/evenfire-ai/evenfire/security/code-scanning/144) | `gfs/token.ts:44` | 30 mutation | GFS token mint |+| [#145](https://github.com/evenfire-ai/evenfire/security/code-scanning/145) | `gfs/resources.ts:350` | 30 mutation | PATCH resource |+| [#149](https://github.com/evenfire-ai/evenfire/security/code-scanning/149) | `gfs/tree.ts:24` | 120 read | Tree browse |+| [#150](https://github.com/evenfire-ai/evenfire/security/code-scanning/150) | `gfs/tree.ts:51` | 120 read | Children paging |## Dismissal template (Security tab / API)