Skip to content

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

TypeScript

fix(control-api): hybrid edge rate limit keys and closing test gaps (F4)

Alfredo Lopeze34593932080
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 75abe2bfa..0db0d5b9e 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.484",
+ "version": "0.1.485",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.484",
+ "version": "0.1.485",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 99ae29e39..ff8164e83 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.484",
+ "version": "0.1.485",
"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/workflows/shared/rateLimit.ts b/control-api/src/routes/workflows/shared/rateLimit.ts
index 6ec5e340a..a02a0992f 100644
--- a/control-api/src/routes/workflows/shared/rateLimit.ts
+++ b/control-api/src/routes/workflows/shared/rateLimit.ts
@@ -32,10 +32,26 @@ function hashedAdminWorkflowCredentialBucket(prefix: string) {
}
/**
- * Ingress-style edge key: IP-only so unverified bearer rotation cannot evade the
- * backstop. Per-credential quotas remain on the PG limiter downstream.
+ * Skip the edge backstop when no admin credential is present. Anonymous traffic
+ * must not share a single IP bucket (Control UI proxy often omits XFF).
+ */
+export function shouldSkipWorkflowGrantEdgeRateLimit(req: Request): boolean {
+ if (readCookie(req, CONTROL_UI_ADMIN_SESSION_COOKIE)) return false
+ if (extractBearerToken(req)) return false
+ return true
+}
+
+/**
+ * Edge backstop key:
+ * - HttpOnly admin cookie → per-session bucket (isolates Control UI admins)
+ * - Bearer only → IP bucket (unverified bearer rotation cannot mint fresh buckets)
*/
export function workflowGrantEdgeRateLimitKey(prefix: string, req: Request): string {
+ const cookie = readCookie(req, CONTROL_UI_ADMIN_SESSION_COOKIE)
+ if (cookie) {
+ const hash = createHash('sha256').update(cookie).digest('hex').slice(0, 32)
+ return `${prefix}:cred:${hash}`
+ }
return `${prefix}:ip:${ipKeyGenerator(req.ip ?? 'unknown')}`
}
@@ -64,6 +80,7 @@ export function workflowGrantReadEdgeRateLimit() {
limit: WORKFLOW_GRANT_READ_PER_MINUTE,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ skip: shouldSkipWorkflowGrantEdgeRateLimit,
keyGenerator: workflowGrantEdgeRateKey('workflow_grants_read_edge'),
handler: workflowGrantEdgeRateLimitHandler,
})
@@ -76,6 +93,7 @@ export function workflowGrantWriteEdgeRateLimit() {
limit: WORKFLOW_GRANT_WRITE_PER_MINUTE,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ skip: shouldSkipWorkflowGrantEdgeRateLimit,
keyGenerator: workflowGrantEdgeRateKey('workflow_grants_write_edge'),
handler: workflowGrantEdgeRateLimitHandler,
})
@@ -95,6 +113,7 @@ function workflowAdminReadEdgeRateLimit() {
limit: WORKFLOW_ADMIN_READ_PER_MINUTE,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ skip: shouldSkipWorkflowGrantEdgeRateLimit,
keyGenerator: workflowGrantEdgeRateKey('workflow_admin_read_edge'),
handler: workflowGrantEdgeRateLimitHandler,
})
@@ -106,6 +125,7 @@ function adminOutputsReadEdgeRateLimit() {
limit: ADMIN_OUTPUTS_READ_PER_MINUTE,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ skip: shouldSkipWorkflowGrantEdgeRateLimit,
keyGenerator: workflowGrantEdgeRateKey('admin_outputs_read_edge'),
handler: workflowGrantEdgeRateLimitHandler,
})
diff --git a/control-api/test/routes.adminWorkflows.test.ts b/control-api/test/routes.adminWorkflows.test.ts
index f05b79337..e24015975 100644
--- a/control-api/test/routes.adminWorkflows.test.ts
+++ b/control-api/test/routes.adminWorkflows.test.ts
@@ -542,6 +542,26 @@ describe('routes/admin/workflows', () => {
.get('/admin/workflows')
.set('Authorization', 'Bearer mcp-host-workflow-control-token')
.expect(401)
+
+ expect(mockPoolQuery).toHaveBeenCalledTimes(1)
+ })
+ })
+
+ describe('GET /admin/outputs', () => {
+ it('returns empty output aggregates for live admin cookie sessions', async () => {
+ mockLiveAdminSession()
+ mockRateLimiterAllowed()
+
+ const app = makeOutputsApp(gateway)
+ const res = await request(app)
+ .get('/admin/outputs')
+ .set('Cookie', 'control_ui_admin_session=admin-token')
+ .expect(200)
+
+ expect(res.body).toEqual({
+ workflowOutputs: [],
+ chatArtifacts: [],
+ })
})
})
diff --git a/control-api/test/workflows.shared.rateLimit.test.ts b/control-api/test/workflows.shared.rateLimit.test.ts
index 2953e2d1b..fc9978e08 100644
--- a/control-api/test/workflows.shared.rateLimit.test.ts
+++ b/control-api/test/workflows.shared.rateLimit.test.ts
@@ -1,11 +1,12 @@
import { describe, expect, it, vi } from 'vitest'
import express from 'express'
-import { rateLimit } from 'express-rate-limit'
import request from 'supertest'
import {
adminWorkflowRateLimitCredential,
+ shouldSkipWorkflowGrantEdgeRateLimit,
workflowGrantEdgeRateLimitKey,
workflowGrantReadRateLimit,
+ workflowGrantWriteRateLimits,
} from '../src/routes/workflows/shared/rateLimit.js'
const mockCheckAndIncrement = vi.hoisted(() => vi.fn())
@@ -17,6 +18,16 @@ vi.mock('../src/observability/metrics.js', () => ({
rateLimitHitsTotal: { inc: vi.fn() },
}))
+function pgAllows() {
+ mockCheckAndIncrement.mockResolvedValue({
+ allowed: true,
+ remaining: 59,
+ resetMs: Date.now() + 60_000,
+ windowStartMs: Date.now(),
+ count: 1,
+ })
+}
+
describe('routes/workflows/shared/rateLimit', () => {
it('adminWorkflowRateLimitCredential accepts HttpOnly admin session cookies', () => {
const req = {
@@ -31,7 +42,29 @@ describe('routes/workflows/shared/rateLimit', () => {
expect(adminWorkflowRateLimitCredential(req)).toBe('admin-cookie-token')
})
- it('workflowGrantEdgeRateLimitKey buckets by IP regardless of bearer token', () => {
+ it('shouldSkipWorkflowGrantEdgeRateLimit skips anonymous callers', () => {
+ const req = { header: () => undefined, ip: '203.0.113.10' } as express.Request
+ expect(shouldSkipWorkflowGrantEdgeRateLimit(req)).toBe(true)
+ })
+
+ it('workflowGrantEdgeRateLimitKey isolates distinct admin cookies on the same IP', () => {
+ const reqA = {
+ ip: '203.0.113.10',
+ header: (name: string) =>
+ name.toLowerCase() === 'cookie' ? 'control_ui_admin_session=cookie-a' : undefined,
+ } as express.Request
+ const reqB = {
+ ip: '203.0.113.10',
+ header: (name: string) =>
+ name.toLowerCase() === 'cookie' ? 'control_ui_admin_session=cookie-b' : undefined,
+ } as express.Request
+
+ expect(workflowGrantEdgeRateLimitKey('workflow_grants_read_edge', reqA)).not.toBe(
+ workflowGrantEdgeRateLimitKey('workflow_grants_read_edge', reqB)
+ )
+ })
+
+ it('workflowGrantEdgeRateLimitKey buckets distinct bogus bearer tokens from the same IP', () => {
const reqA = {
ip: '203.0.113.10',
header: () => 'Bearer token-a',
@@ -46,26 +79,47 @@ describe('routes/workflows/shared/rateLimit', () => {
)
})
- it('edge backstop caps distinct bogus bearer tokens from the same IP', async () => {
- const edgeLimit = rateLimit({
- windowMs: 60_000,
- limit: 2,
- standardHeaders: false,
- legacyHeaders: false,
- keyGenerator: req => workflowGrantEdgeRateLimitKey('workflow_grants_read_edge', req),
- handler: (_req, res) => {
- res.status(429).json({ error: 'Too Many Requests' })
- },
+ it('workflowGrantWriteRateLimits returns 429 from the real edge factory on the 21st cookie request', async () => {
+ mockCheckAndIncrement.mockReset()
+ pgAllows()
+
+ const app = express()
+ app.put('/grants', ...workflowGrantWriteRateLimits(), (_req, res) => {
+ res.status(200).json({ ok: true })
})
+ for (let i = 0; i < 20; i++) {
+ pgAllows()
+ await request(app)
+ .put('/grants')
+ .set('Cookie', 'control_ui_admin_session=admin-cookie-token')
+ .expect(200)
+ }
+
+ pgAllows()
+ const res = await request(app)
+ .put('/grants')
+ .set('Cookie', 'control_ui_admin_session=admin-cookie-token')
+ .expect(429)
+
+ expect(res.body).toMatchObject({
+ error: 'Too Many Requests',
+ retryAfterSeconds: expect.any(Number),
+ })
+ expect(res.headers['retry-after']).toBeDefined()
+ })
+
+ it('workflowGrantWriteRateLimits does not edge-limit anonymous callers', async () => {
+ mockCheckAndIncrement.mockReset()
+
const app = express()
- app.get('/grants', edgeLimit, (_req, res) => {
+ app.put('/grants', ...workflowGrantWriteRateLimits(), (_req, res) => {
res.status(200).json({ ok: true })
})
- await request(app).get('/grants').set('Authorization', 'Bearer bogus-1').expect(200)
- await request(app).get('/grants').set('Authorization', 'Bearer bogus-2').expect(200)
- await request(app).get('/grants').set('Authorization', 'Bearer bogus-3').expect(429)
+ for (let i = 0; i < 25; i++) {
+ await request(app).put('/grants').expect(200)
+ }
})
it('workflowTriggerRateLimit meters cookie-only admin workflow triggers', async () => {
diff --git a/docs/how-to/codeql-js-missing-rate-limiting.md b/docs/how-to/codeql-js-missing-rate-limiting.md
index f39cf040a..7099c959f 100644
--- a/docs/how-to/codeql-js-missing-rate-limiting.md
+++ b/docs/how-to/codeql-js-missing-rate-limiting.md
@@ -42,6 +42,17 @@ Tier defaults (requests/minute, per admin credential hash unless noted):
| [#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.
+
+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` |
## Out-of-scope dispositions (Layer 3)
@@ -65,7 +76,6 @@ SAST-visible backstop (and in some cases PG limiter — see Notes).
| Alert | Location | Planned tier | Notes |
| ----- | -------- | ------------ | ----- |
-| [#63](https://github.com/evenfire-ai/evenfire/security/code-scanning/63) | `outputs.ts:34` | 30/min heavy read | Uses `requireAdminWorkflowCaller` (F4 live auth) |
| [#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 |