Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): split workflow grant auth middleware for CodeQL (F4)
Alfredo Lopez7a5a341e4961
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.ymlindex a0b1b9dbb..8a55b7681 100644--- a/.github/workflows/codeql.yml+++ b/.github/workflows/codeql.yml@@ -7,6 +7,10 @@ name: CodeQL## build-mode: none — CodeQL analyses JS/TS from source and does not need the ~33# workspaces built, which keeps this a single job rather than a matrix.+#+# False-positive dispositions for js/missing-rate-limiting (custom PG limiter) are+# recorded in docs/how-to/codeql-js-missing-rate-limiting.md with Security-tab+# dismissals; do not globally exclude that query in config.on:push:diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 104651ab7..84a7667dc 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.480",+ "version": "0.1.481","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.480",+ "version": "0.1.481","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 7c512ae5c..614262d48 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.480",+ "version": "0.1.481","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 fa3b8602b..3fd44fe22 100644--- a/control-api/src/routes/admin/workflows/grants.routes.ts+++ b/control-api/src/routes/admin/workflows/grants.routes.ts@@ -1,4 +1,4 @@-import { type Request, type Response, Router } from 'express'+import { type NextFunction, type Request, type Response, Router } from 'express'import { asyncHandler } from '../../../http/asyncHandler.js'import type { K8sGateway } from '../../../k8s.js'import { rootLogger } from '../../../observability/logger.js'@@ -13,7 +13,10 @@ import {replaceWorkflowRecipeTeamGrants,revokeWorkflowRecipeApprovalTeam,} from '../../../services/workflows/workflowGrantManagementService.js'-import { requireAdminWorkflowCaller } from '../../workflows/shared/auth.js'+import {+ type AdminWorkflowAuthedRequest,+ requireAdminWorkflowCallerMiddleware,+} from '../../workflows/shared/auth.js'import {WORKFLOW_GRANT_READ_RATE_LIMITS,WORKFLOW_GRANT_WRITE_RATE_LIMITS,@@ -22,6 +25,14 @@ import {const BASE = '/admin/workflows'const logger = rootLogger.child({ module: 'admin-workflow-grants' })+function bindAdminWorkflowAuth(req: Request, res: Response, next: NextFunction): void {+ void requireAdminWorkflowCallerMiddleware(req as AdminWorkflowAuthedRequest, res, next)+}++function adminCaller(req: Request): AdminWorkflowAuthedRequest['adminWorkflowCaller'] {+ return (req as AdminWorkflowAuthedRequest).adminWorkflowCaller+}+function withAdministrativeTraceContext<T>(req: Request, operatorSub: string, work: () => T): T {return runWithAdministrativeRequestContext({ operatorSub, requestId: req.correlationId ?? null },@@ -40,9 +51,9 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.get(`${BASE}/:ns/:name/grants`,...WORKFLOW_GRANT_READ_RATE_LIMITS,+ bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {- const caller = await requireAdminWorkflowCaller(req, res)- if (!caller) return+ const caller = adminCaller(req)!try {const users = await listWorkflowRecipeGrants(gateway, req.params.ns, req.params.name)@@ -60,9 +71,9 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.put(`${BASE}/:ns/:name/grants`,...WORKFLOW_GRANT_WRITE_RATE_LIMITS,+ bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {- const caller = await requireAdminWorkflowCaller(req, res)- if (!caller) return+ const caller = adminCaller(req)!try {const result = await withAdministrativeTraceContext(req, caller.userId, () =>@@ -105,9 +116,9 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.get(`${BASE}/:ns/:name/team-grants`,...WORKFLOW_GRANT_READ_RATE_LIMITS,+ bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {- const caller = await requireAdminWorkflowCaller(req, res)- if (!caller) return+ const caller = adminCaller(req)!try {const teams = await listWorkflowRecipeTeamGrants(gateway, req.params.ns, req.params.name)@@ -125,9 +136,9 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.put(`${BASE}/:ns/:name/team-grants`,...WORKFLOW_GRANT_WRITE_RATE_LIMITS,+ bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {- const caller = await requireAdminWorkflowCaller(req, res)- if (!caller) return+ const caller = adminCaller(req)!try {const result = await withAdministrativeTraceContext(req, caller.userId, () =>@@ -170,9 +181,9 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.get(`/admin/workflow-recipes/:ns/:name/allowed-teams`,...WORKFLOW_GRANT_READ_RATE_LIMITS,+ bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {- const caller = await requireAdminWorkflowCaller(req, res)- if (!caller) return+ const caller = adminCaller(req)!try {const teams = await listWorkflowRecipeApprovalTeams({@@ -194,9 +205,9 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.put(`/admin/workflow-recipes/:ns/:name/allowed-teams/:teamId`,...WORKFLOW_GRANT_WRITE_RATE_LIMITS,+ bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {- const caller = await requireAdminWorkflowCaller(req, res)- if (!caller) return+ const caller = adminCaller(req)!try {const result = await withAdministrativeTraceContext(req, caller.userId, () =>@@ -233,9 +244,9 @@ export function createAdminWorkflowGrantRoutes(gateway: K8sGateway): Router {router.delete(`/admin/workflow-recipes/:ns/:name/allowed-teams/:teamId`,...WORKFLOW_GRANT_WRITE_RATE_LIMITS,+ bindAdminWorkflowAuth,asyncHandler(async (req: Request, res: Response) => {- const caller = await requireAdminWorkflowCaller(req, res)- if (!caller) return+ const caller = adminCaller(req)!try {const result = await withAdministrativeTraceContext(req, caller.userId, () =>diff --git a/control-api/src/routes/workflows/shared/auth.ts b/control-api/src/routes/workflows/shared/auth.tsindex 37456eded..8a99c0855 100644--- a/control-api/src/routes/workflows/shared/auth.ts+++ b/control-api/src/routes/workflows/shared/auth.ts@@ -1,4 +1,4 @@-import { Request, Response } from 'express'+import { NextFunction, Request, Response } from 'express'import { isCurrentExternalSession } from '../../../middleware/externalSessionAuth.js'import { authenticateAdminSession } from '../../../services/adminSessionAuth.js'import type { WorkflowCaller } from '../../../services/workflows/types.js'@@ -28,6 +28,10 @@ function unauthorized(res: Response): null {return null}+export type AdminWorkflowAuthedRequest = Request & {+ adminWorkflowCaller?: Extract<WorkflowCaller, { kind: 'admin-ui' }>+}+export async function requireAdminWorkflowCaller(req: Request,res: Response@@ -38,6 +42,18 @@ export async function requireAdminWorkflowCaller(return { kind: 'admin-ui', userId: adminClaims.sub }}+/** Express middleware — keeps authorization out of business handlers for SAST. */+export async function requireAdminWorkflowCallerMiddleware(+ req: AdminWorkflowAuthedRequest,+ res: Response,+ next: NextFunction+): Promise<void> {+ const caller = await requireAdminWorkflowCaller(req, res)+ if (!caller) return+ req.adminWorkflowCaller = caller+ next()+}+export async function requireExternalWorkflowCaller(req: Request,res: Responsediff --git a/docs/how-to/codeql-js-missing-rate-limiting.md b/docs/how-to/codeql-js-missing-rate-limiting.mdnew file mode 100644index 000000000..f39cf040a--- /dev/null+++ b/docs/how-to/codeql-js-missing-rate-limiting.md@@ -0,0 +1,95 @@+# CodeQL `js/missing-rate-limiting` — control-api disposition++This document records audited dispositions for [CodeQL](https://codeql.github.com/)+`js/missing-rate-limiting` findings. It supports Security-tab dismissals+(`dismissed_comment` + reason) per+[GitHub code scanning guidance](https://docs.github.com/en/code-security/how-tos/manage-security-alerts/manage-code-scanning-alerts/resolve-alerts#dismissing-alerts).++## Product invariant++Authenticated control-api routes that perform expensive work **must** be rate+limited. Enforcement uses the Postgres-backed `rateLimitMiddleware`+(`services/rateLimiterService.ts`) so limits are consistent across replicas.++CodeQL 2.x models `express-rate-limit` (and some framework plugins) but **does+not** model our custom PG limiter. Routes that only use `rateLimitMiddleware`+may still alert until an `express-rate-limit` **edge backstop** is added (see+`control-api/src/routes/external/gfs.ts`).++## Approved patterns++| 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 | 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 |++## Out-of-scope dispositions (Layer 3)++Follow-up implementation tracked separately (`fix/codeql-control-api-rate-limit-backstops`).++### 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 |++### Won't fix (accepted) — real gap, follow-up backstop PR++Tracked for `fix/codeql-control-api-rate-limit-backstops`. No auth bypass; missing+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 |+| [#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)++```+Documented in docs/how-to/codeql-js-missing-rate-limiting.md (alert #<NUMBER>).+<One-line evidence from table above>.+```++## Re-open triggers++Re-audit when:++- `rateLimitMiddleware` signature or call pattern changes repo-wide+- A listed route removes its PG limiter+- CodeQL adds modeling for our PG limiter (then remove redundant backstops)+- New authenticated route is added without an entry in this registry