Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: harden plugin workload sdk request boundaries
Alfredo Lopez23946afa3b92
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 6059fe77a..7f6c63bb9 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.402",+ "version": "0.1.403","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.402",+ "version": "0.1.403","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",@@ -16,6 +16,7 @@"bcryptjs": "^3.0.3","cron-parser": "^5.5.0","express": "^4.21.2",+ "express-rate-limit": "^8.5.1","google-auth-library": "^10.6.1","jsonwebtoken": "^9.0.2","pg": "^8.13.1",@@ -1617,6 +1618,48 @@"url": "https://opencollective.com/express"}},+ "node_modules/express-rate-limit": {+ "version": "8.6.1",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.1.tgz",+ "integrity": "sha512-0D493aP61w0TJ2A0wy27riRsO7FMQ7FK+KUHOKCSfPvYo0R55aiC6emCVgFUeShH0fq0ICPVzNcgoS+BsbXQCA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "ip-address": "^10.2.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/express-rate-limit/node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/express-rate-limit/node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },"node_modules/extend": {"version": "3.0.2","resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",diff --git a/control-api/package.json b/control-api/package.jsonindex da67d9803..8f26f28d7 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.402",+ "version": "0.1.403","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {@@ -24,6 +24,7 @@"bcryptjs": "^3.0.3","cron-parser": "^5.5.0","express": "^4.21.2",+ "express-rate-limit": "^8.5.1","google-auth-library": "^10.6.1","jsonwebtoken": "^9.0.2","pg": "^8.13.1",diff --git a/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts b/control-api/src/middleware/pluginWorkloadSdkRateLimits.tsnew file mode 100644index 000000000..e38a5aed1--- /dev/null+++ b/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts@@ -0,0 +1,52 @@+import type { RequestHandler } from 'express'+import { rateLimit } from 'express-rate-limit'+import { rateLimitMiddleware } from './rateLimitMiddleware.js'++/**+ * High-ceiling IP guard placed before mcp-host/internal JWT verification.+ * Business quotas and the authenticated recipe limiter remain separate: this+ * layer only bounds unauthenticated crypto work (the outer app owns the JSON+ * body-size/parser boundary).+ */+export function createPluginWorkloadSdkPreAuthRateLimit(): RequestHandler {+ return rateLimit({+ windowMs: 60_000,+ limit: 600,+ standardHeaders: 'draft-8',+ legacyHeaders: false,+ message: { error: 'Too Many Requests', retryable: true },+ })+}++/**+ * Distributed recipe-scoped guard for all authenticated SDK gateway routes.+ * The pre-auth IP limiter cannot provide caller isolation, while this PG+ * bucket cannot protect JWT verification; both layers are intentional.+ */+export function createPluginWorkloadSdkRequestRateLimit(): RequestHandler {+ return rateLimitMiddleware({+ bucketType: 'plugin_workload_sdk_request',+ // Keep the shared authenticated bucket above the provider-attempt burst+ // budget. Credential-ticket issuance/introspection have their own tighter+ // bucket; status and notification traffic must not starve each other.+ maxPerMinute: 600,+ getBucketKey: req => {+ const claims = req.mcpHostJwt+ if (!claims) return 'plugin_workload_sdk_request:unauthenticated'+ return `plugin_workload_sdk_request:${claims.recipeNamespace}/${claims.recipeName}`+ },+ })+}++/** WRC revocation is idempotent but still takes advisory locks and writes an audit row. */+export function createPluginWorkloadSdkInternalRateLimit(): RequestHandler {+ return rateLimitMiddleware({+ bucketType: 'plugin_workload_sdk_internal',+ maxPerMinute: 120,+ getBucketKey: req => {+ const claims = req.internalControl+ if (!claims) return 'plugin_workload_sdk_internal:unauthenticated'+ return `plugin_workload_sdk_internal:${claims.iss}:${claims.sub}`+ },+ })+}diff --git a/control-api/src/routes/internal/pluginWorkloadSdk.ts b/control-api/src/routes/internal/pluginWorkloadSdk.tsindex 15697827e..cec9d1112 100644--- a/control-api/src/routes/internal/pluginWorkloadSdk.ts+++ b/control-api/src/routes/internal/pluginWorkloadSdk.ts@@ -1,6 +1,10 @@import { Router } from 'express'import { asyncHandler } from '../../http/asyncHandler.js'import { requireInternalControlJwt } from '../../middleware/internalControlJwt.js'+import {+ createPluginWorkloadSdkInternalRateLimit,+ createPluginWorkloadSdkPreAuthRateLimit,+} from '../../middleware/pluginWorkloadSdkRateLimits.js'import {type PluginWorkloadSdkRevocationActor,finalizePluginWorkloadSdkRevocation,@@ -49,9 +53,19 @@ function wrcRevocationActor(claims: InternalControlClaims): PluginWorkloadSdkRev*/export function createInternalPluginWorkloadSdkRouter(): Router {const router = Router()++ // Revocation takes advisory locks and writes audit rows. Protect both the+ // unauthenticated JWT boundary and the authenticated WRC principal once at+ // the prefix so every current/future internal SDK route inherits the guard.+ router.use(+ '/internal/plugin-workload-sdk',+ createPluginWorkloadSdkPreAuthRateLimit(),+ requireInternalControlJwt,+ createPluginWorkloadSdkInternalRateLimit()+ )+router.post('/internal/plugin-workload-sdk/revoke',- requireInternalControlJwt,asyncHandler(async (req, res) => {const internalControl = req.internalControlif (internalControl?.iss !== 'wrc' || internalControl.sub !== 'wrc-provisioner') {@@ -74,7 +88,6 @@ export function createInternalPluginWorkloadSdkRouter(): Router {router.post('/internal/plugin-workload-sdk/finalize-revocation',- requireInternalControlJwt,asyncHandler(async (req, res) => {const internalControl = req.internalControlif (internalControl?.iss !== 'wrc' || internalControl.sub !== 'wrc-provisioner') {diff --git a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.tsindex 269ae2a4a..788833fc6 100644--- a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts+++ b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts@@ -2,6 +2,10 @@ import { type Request, type Response, Router } from 'express'import { pool } from '../../db.js'import { asyncHandler } from '../../http/asyncHandler.js'import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'+import {+ createPluginWorkloadSdkPreAuthRateLimit,+ createPluginWorkloadSdkRequestRateLimit,+} from '../../middleware/pluginWorkloadSdkRateLimits.js'import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'import { pluginWorkloadSdkNotificationAuthDurationSeconds } from '../../observability/metrics.js'import { enqueuePluginWorkloadSdkNotification } from '../../services/notificationEmitter.js'@@ -510,6 +514,17 @@ async function handlePromptBridgeAuthorization(export function createMcpHostPluginWorkloadSdkRoutes(): Router {const router = Router()+ // This router contains no unauthenticated endpoint. Apply the boundary+ // protections once, scoped to the SDK prefix, so newly added SDK routes+ // cannot accidentally omit either the pre-auth flood guard or the+ // recipe-scoped PG limiter (the outer app bounds JSON bodies).+ router.use(+ '/mcp-host/plugin-workload-sdk',+ createPluginWorkloadSdkPreAuthRateLimit(),+ requireMcpHostJwt,+ createPluginWorkloadSdkRequestRateLimit()+ )+router.post(// JIT fallback-ticket contract for mcp-host:// - call only after the prior provider attempt has failed;@@ -518,7 +533,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {// The server derives caller and allowed suffix from the persisted// invocation, verifies current policy, and emits a new one-shot jti.'/mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket',- requireMcpHostJwt,pluginWorkloadSdkCredentialRateLimit,asyncHandler(async (req, res) => {const claims = req.mcpHostJwt!@@ -559,7 +573,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {// is absent instead of falling back to bootstrap credentials.router.post('/mcp-host/plugin-workload-sdk/prompt-bridge/v2',- requireMcpHostJwt,asyncHandler(async (req, res) =>handlePromptBridgeAuthorization(req, res, {requireContractVersion: true,@@ -573,7 +586,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {// the current persisted policy but does not require the new bootstrap fields.router.post('/mcp-host/plugin-workload-sdk/prompt-bridge',- requireMcpHostJwt,asyncHandler(async (req, res) =>handlePromptBridgeAuthorization(req, res, {requireContractVersion: false,@@ -585,7 +597,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {router.get('/mcp-host/plugin-workload-sdk/capabilities',- requireMcpHostJwt,asyncHandler(async (_req, res) => {const claims = _req.mcpHostJwt!const grant = await findGrant(claims.recipeNamespace, claims.recipeName, 'promptBridge')@@ -617,7 +628,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {router.post('/mcp-host/plugin-workload-sdk/client-notification',- requireMcpHostJwt,asyncHandler(async (req, res) => {const claims = req.mcpHostJwt!const body = isPlainObject(req.body) ? req.body : {}@@ -695,7 +705,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {// path); it consumes no quota and writes no audit row.router.post('/mcp-host/plugin-workload-sdk/client-notification/recipients',- requireMcpHostJwt,asyncHandler(async (req, res) => {const claims = req.mcpHostJwt!const body = isPlainObject(req.body) ? req.body : {}@@ -720,7 +729,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {// secret; it only attests that the ticket still matches the current policy.router.post('/mcp-host/plugin-workload-sdk/credential-ticket/introspect',- requireMcpHostJwt,pluginWorkloadSdkCredentialRateLimit,asyncHandler(async (req, res) => {const claims = req.mcpHostJwt!@@ -746,12 +754,10 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {attemptGeneration < 1 ||providerAttemptIndex < 1) {- res- .status(400)- .json({- error:- 'credentialTicket, invocationId, targetRef, providerAttemptId and attemptGeneration are required',- })+ res.status(400).json({+ error:+ 'credentialTicket, invocationId, targetRef, providerAttemptId and attemptGeneration are required',+ })return}const ticketClaims = verifyPluginWorkloadSdkCredentialTicket(ticket)@@ -843,7 +849,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {// in_progress → complete | failed | provider_unavailable.router.post('/mcp-host/plugin-workload-sdk/invocations/:id/status',- requireMcpHostJwt,asyncHandler(async (req, res) => {const claims = req.mcpHostJwt!const body = isPlainObject(req.body) ? req.body : {}@@ -906,7 +911,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {router.post('/mcp-host/plugin-workload-sdk/provider-attempts/:id/status',- requireMcpHostJwt,asyncHandler(async (req, res) => {const claims = req.mcpHostJwt!const body = isPlainObject(req.body) ? req.body : {}@@ -925,11 +929,9 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {providerAttemptIndex < 1 ||!['complete', 'failed', 'provider_unavailable'].includes(String(status))) {- res- .status(400)- .json({- error: 'invocationId, attemptGeneration, providerAttemptIndex and status are required',- })+ res.status(400).json({+ error: 'invocationId, attemptGeneration, providerAttemptIndex and status are required',+ })return}const attempt = await getPluginWorkloadSdkProviderAttempt(req.params.id)@@ -962,7 +964,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {router.get('/mcp-host/plugin-workload-sdk/invocations/:recipeRef',- requireMcpHostJwt,asyncHandler(async (req, res) => {const claims = req.mcpHostJwt!// Cross-recipe isolation: the path recipeRef must match the JWT'sdiff --git a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.tsindex 0d87eb412..d12b6bae0 100644--- a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts+++ b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts@@ -939,7 +939,13 @@ describe('POST /mcp-host/plugin-workload-sdk/credential-ticket/introspect', () =})it('rate-limits credential-ticket introspection before expensive ticket work', async () => {- vi.mocked(pool.query).mockResolvedValueOnce({ rows: [{ count: 121 }], rowCount: 1 } as never)+ // The SDK prefix now applies the high-ceiling authenticated gateway bucket+ // before the tighter credential-ticket bucket. Keep the first query under+ // that outer limit and exhaust the credential-specific bucket on the+ // second query so this test remains focused on ticket work protection.+ vi.mocked(pool.query)+ .mockResolvedValueOnce({ rows: [{ count: 1 }], rowCount: 1 } as never)+ .mockResolvedValueOnce({ rows: [{ count: 121 }], rowCount: 1 } as never)const res = await request(buildApp()).post('/mcp-host/plugin-workload-sdk/credential-ticket/introspect').set('Authorization', `Bearer ${issueSdkToken()}`)diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.tsindex 451832511..c12caee33 100644--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts@@ -262,7 +262,7 @@ describe('invocation retry lifecycle timestamps', () => {it('sweeps by the latest retry timestamp rather than the original reservation', async () => {await expect(failStaleInvocations(150)).resolves.toBe(1)- const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]+ const [sql] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]expect(sql).toContain('lease_expires_at < now()')expect(sql).not.toContain('created_at < now()')})diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 74878c544..3b8562910 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.222",+ "version": "0.1.223","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.222",+ "version": "0.1.223","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",@@ -25,6 +25,7 @@"docx": "^9.6.1","exceljs": "^4.4.0","express": "^5.2.1",+ "express-rate-limit": "^8.5.1","jose": "^6.2.1","jsonwebtoken": "^9.0.2","openai": "^4.70.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 61ac20f36..def3b13e6 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.222",+ "version": "0.1.223","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {@@ -41,6 +41,7 @@"docx": "^9.6.1","exceljs": "^4.4.0","express": "^5.2.1",+ "express-rate-limit": "^8.5.1","jose": "^6.2.1","jsonwebtoken": "^9.0.2","openai": "^4.70.0",diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.tsindex f5d229f8c..440c806ce 100644--- a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts@@ -1,5 +1,6 @@import express, { type NextFunction, type Request, type Response } from 'express'import type http from 'node:http'+import { createMcpHostPreAuthRateLimit } from '../shared/httpRateLimit'import type { ConfigureResponse, PluginWorkloadSdkBootstrapRequest } from '../workflow/types'import {requireWorkflowAuth,@@ -32,6 +33,10 @@ export class PluginWorkloadSdkBootstrapServer {constructor(private readonly opts: PluginWorkloadSdkBootstrapServerOptions) {this.app.disable('x-powered-by')+ // Bound invalid-token floods before Express parses request bodies. Scope+ // this guard to bootstrap so liveness/readiness cannot be starved by an+ // attacker exhausting an unrelated control bucket.+ this.app.use('/api/v1/workflow/plugin-workload-sdk/bootstrap', createMcpHostPreAuthRateLimit())this.app.use(express.json({ limit: '16kb' }))this.app.get('/v1/runtime/health', (_req, res) => {res.status(200).json({ status: 'healthy', mode: 'sdk-only', ready: true })diff --git a/mcp-host/src/shared/httpRateLimit.ts b/mcp-host/src/shared/httpRateLimit.tsnew file mode 100644index 000000000..e8643ab59--- /dev/null+++ b/mcp-host/src/shared/httpRateLimit.ts@@ -0,0 +1,19 @@+import { rateLimit } from 'express-rate-limit'++/**+ * Protects the HTTP boundary before JWT verification and body parsing.+ *+ * The authenticated, recipe-scoped limiters remain responsible for product+ * quotas. This limiter has a deliberately higher IP ceiling: its only job is+ * to bound unauthenticated crypto/body-parser work and prevent a caller from+ * bypassing the per-principal controls by rotating invalid tokens.+ */+export function createMcpHostPreAuthRateLimit() {+ return rateLimit({+ windowMs: 60_000,+ limit: 600,+ standardHeaders: 'draft-8',+ legacyHeaders: false,+ message: { error: 'Too Many Requests', retryable: true },+ })+}diff --git a/mcp-host/src/workflow/workflowRouter.ts b/mcp-host/src/workflow/workflowRouter.tsindex e9a62e848..5bc9f8bc1 100644--- a/mcp-host/src/workflow/workflowRouter.ts+++ b/mcp-host/src/workflow/workflowRouter.ts@@ -15,6 +15,7 @@import { NextFunction, Request, Response, Router } from 'express'import * as fs from 'fs'import * as path from 'path'+import { createMcpHostPreAuthRateLimit } from '../shared/httpRateLimit'import {ArtifactPathError,type OpenedArtifactFile,@@ -94,6 +95,13 @@ function startExecuteStream(res: Response): ReturnType<typeof setInterval> {export function createWorkflowRouter(service: WorkflowService): Router {const router = Router()+ // Protect the boundary before JWT verification. The outer server already+ // bounds request bodies; the recipe/principal limiter remains a separate+ // control-plane guard, while this high-ceiling IP bucket prevents+ // unauthenticated floods from making token verification the expensive+ // denial path.+ router.use(createMcpHostPreAuthRateLimit())+// POST /execute — execute a single step (requires scope: execute, sub: coordinator)router.post('/execute', requireWorkflowAuth('execute'), async (req: Request, res: Response) => {if (!validateWorkflowBinding(req, res, { expectedSub: 'coordinator' })) returndiff --git a/scripts/e2e/admin-credentials.sh b/scripts/e2e/admin-credentials.shold mode 100644new mode 100755diff --git a/scripts/e2e/load-dotenv.sh b/scripts/e2e/load-dotenv.shold mode 100644new mode 100755diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex 616c3b6ea..bf17913bc 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.263",+ "version": "0.1.264","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.263",+ "version": "0.1.264","license": "SEE LICENSE IN LICENSE","dependencies": {"@aws-sdk/client-s3": "^3.1009.0",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex 44550fa70..af8508543 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.263",+ "version": "0.1.264","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/mcp/server.ts b/workflow-recipes/src/mcp/server.tsindex 01df28cfd..d9bcd438d 100644--- a/workflow-recipes/src/mcp/server.ts+++ b/workflow-recipes/src/mcp/server.ts@@ -332,6 +332,152 @@ export class ClerumMcpServer {return server}+ /**+ * Handle the ordinary workflow REST surface after the route name has been+ * bound to a verified JWT. Keeping this branch separate from the SDK+ * credential broker makes the broker's path guard an early abort rather+ * than a user-controlled condition around Secret resolution.+ */+ private async handleStandardWorkflowRestRequest(+ req: http.IncomingMessage,+ res: http.ServerResponse,+ routeRecipeName: string,+ subPath: string+ ): Promise<void> {+ const url = req.url ?? ''+ const authHeader = req.headers.authorization+ const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''+ let claims+ try {+ claims = await verifyIncomingToken(token)+ } catch (authErr) {+ console.error(+ `[WRC-AUTH] Token verification failed for ${req.method} ${url}:`,+ authErr instanceof Error ? authErr.message : authErr+ )+ res.writeHead(401, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Unauthorized' }))+ return+ }++ // The URL is only a routing hint. Every workflow operation below uses+ // the recipe identity from the verified token after this binding check;+ // no path-controlled value reaches a handler or Kubernetes resolver.+ if (claims.recipeName !== routeRecipeName || claims.recipeNamespace !== this.sandboxNamespace) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Workflow recipe binding mismatch' }))+ return+ }+ const recipeName = claims.recipeName++ if (!this.workflowHandlers) {+ this.workflowHandlers = createWorkflowEndpointHandlers(+ this.customApi,+ this.sandboxNamespace,+ this.tokenFactory ?? undefined,+ { traceReporter: this.provider.getTraceReporter() }+ )+ }+ const handlers = this.workflowHandlers++ const artifactMatch = subPath.match(/^\/artifacts\/([^/]+)$/)+ if (req.method === 'GET' && artifactMatch) {+ const filename = decodeURIComponent(artifactMatch[1])+ const result = await handlers.getArtifact(recipeName, filename, claims)+ if (result.status === 200 && Buffer.isBuffer(result.body)) {+ res.writeHead(200, result.headers ?? { 'Content-Type': 'application/octet-stream' })+ res.end(result.body)+ } else {+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ }+ return+ }++ if (req.method === 'DELETE' && artifactMatch) {+ const filename = decodeURIComponent(artifactMatch[1])+ const result = await handlers.deleteArtifactFile(recipeName, filename, claims)+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(result.status === 204 ? '' : JSON.stringify(result.body))+ return+ }++ if (req.method === 'DELETE' && subPath === '/artifacts') {+ const result = await handlers.deleteArtifact(recipeName, claims)+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(result.status === 204 ? '' : JSON.stringify(result.body))+ return+ }++ if (req.method === 'GET' && subPath === '/status') {+ const result = await handlers.getWorkflowStatus(recipeName, claims)+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ return+ }++ if (req.method === 'GET' && subPath === '/health') {+ const result = await handlers.getHealth(recipeName, claims)+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ return+ }++ if (req.method === 'GET' && subPath === '/signals') {+ const result = await handlers.getSignals(recipeName, claims)+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ return+ }++ if (req.method === 'POST') {+ const parseResult = await parseJsonBody(req)+ if (!parseResult.ok) {+ const status = parseResult.reason === 'too_large' ? 413 : 400+ const error =+ parseResult.reason === 'too_large' ? 'Request body too large' : 'Invalid JSON body'+ res.writeHead(status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error }))+ return+ }+ const body = parseResult.body++ if (subPath === '/status') {+ const result = await handlers.postStepStatus(recipeName, claims, body as never)+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ return+ }++ if (subPath === '/configure-model') {+ const result = await handlers.configureModel(+ recipeName,+ claims,+ body as never,+ this.modelConfigHandler ?? undefined+ )+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ return+ }++ if (subPath === '/injections/model') {+ const result = await handlers.requestModelInjection(+ recipeName,+ claims,+ body as never,+ this.modelConfigHandler ?? undefined+ )+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ return+ }+ }++ res.writeHead(404, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Not found' }))+ }+private async handleHttpRequest(req: http.IncomingMessage,res: http.ServerResponse@@ -411,302 +557,172 @@ export class ClerumMcpServer {// ─── Workflow REST API (/api/v1/workflow/:name/...) ──────────────const workflowMatch = url.match(/^\/api\/v1\/workflow\/([^/]+)(\/.*)?$/)- if (workflowMatch) {- const recipeName = decodeURIComponent(workflowMatch[1])- const subPath = workflowMatch[2] ?? ''-- // SEC: validate recipeName matches K8s RFC 1123 DNS label format before any API call.- // Prevents Host header injection and path traversal via crafted recipe names.- if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(recipeName)) {- res.writeHead(400, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Invalid recipe name format' }))- return- }-- // Plugin Workload SDK credential broker. This route deliberately uses a- // different audience from the workflow REST API: an mcp-host runtime JWT- // authenticates the caller and a second short-lived signed ticket binds- // the exact target that control-api already authorized.- // lgtm[js/user-controlled-bypass]- // The request path only selects the handler. Before any Secret read, the- // handler verifies the JWT issuer/audience/scope, binds the token claims- // to the server-owned namespace and recipe, and then validates the- // signed invocation/target ticket against the current control-api policy.- if (req.method === 'POST' && subPath === '/plugin-workload-sdk/credentials') {- const authHeader = req.headers.authorization- const runtimeToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''- let callerClaims- try {- callerClaims = await verifyPluginSdkBrokerCallerToken(runtimeToken)- } catch {- res.writeHead(401, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Unauthorized' }))- return- }- if (- callerClaims.recipeName !== recipeName ||- callerClaims.recipeNamespace !== this.sandboxNamespace ||- !callerClaims.workflowControlScopes.includes('plugin-workload-sdk')- ) {- res.writeHead(403, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Credential broker scope denied' }))- return- }-- const parseResult = await parseJsonBody(req)- if (!parseResult.ok) {- res.writeHead(parseResult.reason === 'too_large' ? 413 : 400, {- 'Content-Type': 'application/json',- })- res.end(JSON.stringify({ error: 'Invalid credential broker request' }))- return- }- const body = parseResult.body- const target = body.target as PluginSdkCredentialTarget | undefined- if (- body.recipeNamespace !== this.sandboxNamespace ||- typeof body.invocationId !== 'string' ||- !Number.isInteger(body.attemptGeneration) ||- Number(body.attemptGeneration) < 1 ||- typeof body.providerAttemptId !== 'string' ||- !body.providerAttemptId ||- !Number.isInteger(body.providerAttemptIndex) ||- Number(body.providerAttemptIndex) < 1 ||- !target ||- typeof target.targetRef !== 'string' ||- typeof target.provider !== 'string' ||- typeof target.model !== 'string' ||- typeof target.credentialSlot !== 'string' ||- typeof body.credentialTicket !== 'string'- ) {- res.writeHead(400, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Invalid credential broker request' }))- return- }-- let ticket- try {- ticket = await verifyPluginSdkCredentialTicket(body.credentialTicket)- } catch {- res.writeHead(403, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Credential ticket denied' }))- return- }- // Derive the resolver target directly from the verified JWT claims.- // `target` is an untrusted diagnostic echo and must not flow into any- // policy, revalidation, or Secret-resolution operation.- const signedTarget: PluginSdkCredentialTarget = {- targetRef: ticket.targetRef,- provider: ticket.provider,- model: ticket.model,- credentialSlot: ticket.credentialSlot,- }- if (- ticket.recipeName !== recipeName ||- ticket.recipeNamespace !== this.sandboxNamespace ||- ticket.invocationId !== body.invocationId ||- ticket.attemptGeneration !== Number(body.attemptGeneration) ||- ticket.providerAttemptId !== body.providerAttemptId ||- ticket.providerAttemptIndex !== Number(body.providerAttemptIndex) ||- !pluginSdkCredentialTargetEchoMatches(signedTarget, target)- ) {- res.writeHead(403, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Credential ticket denied' }))- return- }- // The request body is only an equality check. Once the signed ticket- // is verified, use its claims as the sole identity passed to the- // Secret resolver and to all subsequent policy revalidation calls.- const boundInvocationId = ticket.invocationId- // TOCTOU gate: ticket signature proves what was authorized, while this- // control-api read proves that the invocation and policy revision/hash- // are still current immediately before the Secret lookup.- const ticketStillActive = await revalidatePluginSdkCredentialTicket({- runtimeToken,- credentialTicket: body.credentialTicket,- invocationId: boundInvocationId,- targetRef: signedTarget.targetRef,- attemptGeneration: ticket.attemptGeneration,- providerAttemptId: ticket.providerAttemptId,- providerAttemptIndex: ticket.providerAttemptIndex,- })- if (!ticketStillActive) {- res.writeHead(403, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Credential ticket denied' }))- return- }- if (!this.modelConfigHandler) {- res.writeHead(503, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Credential broker unavailable' }))- return- }- const result = await this.modelConfigHandler.resolvePluginSdkCredential(signedTarget)- // Re-check after the Secret read as well as before it. Control API- // and the WRC Secret store are separate systems, so a single remote- // check cannot be atomic with the read; the post-read gate ensures a- // revocation observed during resolution never returns credentials.- if (result.status === 200) {- const ticketStillActiveAfterResolve = await revalidatePluginSdkCredentialTicket({- runtimeToken,- credentialTicket: body.credentialTicket,- invocationId: boundInvocationId,- targetRef: signedTarget.targetRef,- attemptGeneration: ticket.attemptGeneration,- providerAttemptId: ticket.providerAttemptId,- providerAttemptIndex: ticket.providerAttemptIndex,- redeem: true,- })- if (!ticketStillActiveAfterResolve) {- res.writeHead(403, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Credential ticket denied' }))- return- }- if (!this.consumePluginSdkTicket(ticket.jti)) {- res.writeHead(403, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Credential ticket denied' }))- return- }- }- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(JSON.stringify(result.body))- return- }-- // JWT authentication — dual-issuer aware (clerum-wrc OR control-api)- const authHeader = req.headers.authorization- const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''- let claims- try {- claims = await verifyIncomingToken(token)- } catch (authErr) {- console.error(- `[WRC-AUTH] Token verification failed for ${req.method} ${url}:`,- authErr instanceof Error ? authErr.message : authErr- )- res.writeHead(401, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Unauthorized' }))- return- }-- if (!this.workflowHandlers) {- this.workflowHandlers = createWorkflowEndpointHandlers(- this.customApi,- this.sandboxNamespace,- this.tokenFactory ?? undefined,- { traceReporter: this.provider.getTraceReporter() }- )- }- const handlers = this.workflowHandlers-- // GET /api/v1/workflow/:name/artifacts/:filename — admin artifact download proxy- const artifactMatch = subPath.match(/^\/artifacts\/([^/]+)$/)- if (req.method === 'GET' && artifactMatch) {- const filename = decodeURIComponent(artifactMatch[1])- const result = await handlers.getArtifact(recipeName, filename, claims)- if (result.status === 200 && Buffer.isBuffer(result.body)) {- res.writeHead(200, result.headers ?? { 'Content-Type': 'application/octet-stream' })- res.end(result.body)- } else {- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(JSON.stringify(result.body))- }- return- }+ if (!workflowMatch) {+ res.writeHead(404, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Not found' }))+ return+ }+ const routeRecipeName = decodeURIComponent(workflowMatch[1])+ const subPath = workflowMatch[2] ?? ''++ // SEC: validate the route label before any API call.+ // Prevents Host header injection and path traversal via crafted recipe names.+ if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(routeRecipeName)) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Invalid recipe name format' }))+ return+ }- // DELETE /api/v1/workflow/:name/artifacts/:filename — admin single file delete- if (req.method === 'DELETE' && artifactMatch) {- const filename = decodeURIComponent(artifactMatch[1])- const result = await handlers.deleteArtifactFile(recipeName, filename, claims)- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(result.status === 204 ? '' : JSON.stringify(result.body))- return- }+ // The standard workflow branch is an early abort. The broker below is+ // reached only after this path/method guard, so a user-controlled URL does+ // not syntactically wrap the sensitive Secret-resolution operation.+ if (req.method !== 'POST' || subPath !== '/plugin-workload-sdk/credentials') {+ await this.handleStandardWorkflowRestRequest(req, res, routeRecipeName, subPath)+ return+ }- // DELETE /api/v1/workflow/:name/artifacts — admin bulk delete- if (req.method === 'DELETE' && subPath === '/artifacts') {- const result = await handlers.deleteArtifact(recipeName, claims)- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(result.status === 204 ? '' : JSON.stringify(result.body))- return- }+ // Plugin Workload SDK credential broker. This route deliberately uses a+ // different audience from the workflow REST API: an mcp-host runtime JWT+ // authenticates the caller and a second short-lived signed ticket binds+ // the exact target that control-api already authorized.+ const authHeader = req.headers.authorization+ const runtimeToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''+ let callerClaims+ try {+ callerClaims = await verifyPluginSdkBrokerCallerToken(runtimeToken)+ } catch {+ res.writeHead(401, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Unauthorized' }))+ return+ }+ const boundRecipeName = callerClaims.recipeName+ if (+ boundRecipeName !== routeRecipeName ||+ callerClaims.recipeNamespace !== this.sandboxNamespace ||+ !callerClaims.workflowControlScopes.includes('plugin-workload-sdk')+ ) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential broker scope denied' }))+ return+ }- // GET /api/v1/workflow/:name/status- if (req.method === 'GET' && subPath === '/status') {- const result = await handlers.getWorkflowStatus(recipeName, claims)- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(JSON.stringify(result.body))- return- }+ const parseResult = await parseJsonBody(req)+ if (!parseResult.ok) {+ res.writeHead(parseResult.reason === 'too_large' ? 413 : 400, {+ 'Content-Type': 'application/json',+ })+ res.end(JSON.stringify({ error: 'Invalid credential broker request' }))+ return+ }+ const body = parseResult.body+ const target = body.target as PluginSdkCredentialTarget | undefined+ if (+ body.recipeNamespace !== this.sandboxNamespace ||+ typeof body.invocationId !== 'string' ||+ !Number.isInteger(body.attemptGeneration) ||+ Number(body.attemptGeneration) < 1 ||+ typeof body.providerAttemptId !== 'string' ||+ !body.providerAttemptId ||+ !Number.isInteger(body.providerAttemptIndex) ||+ Number(body.providerAttemptIndex) < 1 ||+ !target ||+ typeof target.targetRef !== 'string' ||+ typeof target.provider !== 'string' ||+ typeof target.model !== 'string' ||+ typeof target.credentialSlot !== 'string' ||+ typeof body.credentialTicket !== 'string'+ ) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Invalid credential broker request' }))+ return+ }- // GET /api/v1/workflow/:name/health- if (req.method === 'GET' && subPath === '/health') {- const result = await handlers.getHealth(recipeName, claims)- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(JSON.stringify(result.body))+ let ticket+ try {+ ticket = await verifyPluginSdkCredentialTicket(body.credentialTicket)+ } catch {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential ticket denied' }))+ return+ }+ // Derive the resolver target directly from the verified JWT claims.+ // `target` is an untrusted diagnostic echo and must not flow into any+ // policy, revalidation, or Secret-resolution operation.+ const signedTarget: PluginSdkCredentialTarget = {+ targetRef: ticket.targetRef,+ provider: ticket.provider,+ model: ticket.model,+ credentialSlot: ticket.credentialSlot,+ }+ if (+ ticket.recipeName !== boundRecipeName ||+ ticket.recipeNamespace !== this.sandboxNamespace ||+ ticket.invocationId !== body.invocationId ||+ ticket.attemptGeneration !== Number(body.attemptGeneration) ||+ ticket.providerAttemptId !== body.providerAttemptId ||+ ticket.providerAttemptIndex !== Number(body.providerAttemptIndex) ||+ !pluginSdkCredentialTargetEchoMatches(signedTarget, target)+ ) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential ticket denied' }))+ return+ }+ // The request body is only an equality check. Once the signed ticket+ // is verified, use its claims as the sole identity passed to the+ // Secret resolver and to all subsequent policy revalidation calls.+ const boundInvocationId = ticket.invocationId+ // TOCTOU gate: ticket signature proves what was authorized, while this+ // control-api read proves that the invocation and policy revision/hash+ // are still current immediately before the Secret lookup.+ const ticketStillActive = await revalidatePluginSdkCredentialTicket({+ runtimeToken,+ credentialTicket: body.credentialTicket,+ invocationId: boundInvocationId,+ targetRef: signedTarget.targetRef,+ attemptGeneration: ticket.attemptGeneration,+ providerAttemptId: ticket.providerAttemptId,+ providerAttemptIndex: ticket.providerAttemptIndex,+ })+ if (!ticketStillActive) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential ticket denied' }))+ return+ }+ if (!this.modelConfigHandler) {+ res.writeHead(503, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential broker unavailable' }))+ return+ }+ const result = await this.modelConfigHandler.resolvePluginSdkCredential(signedTarget)+ // Re-check after the Secret read as well as before it. Control API+ // and the WRC Secret store are separate systems, so a single remote+ // check cannot be atomic with the read; the post-read gate ensures a+ // revocation observed during resolution never returns credentials.+ if (result.status === 200) {+ const ticketStillActiveAfterResolve = await revalidatePluginSdkCredentialTicket({+ runtimeToken,+ credentialTicket: body.credentialTicket,+ invocationId: boundInvocationId,+ targetRef: signedTarget.targetRef,+ attemptGeneration: ticket.attemptGeneration,+ providerAttemptId: ticket.providerAttemptId,+ providerAttemptIndex: ticket.providerAttemptIndex,+ redeem: true,+ })+ if (!ticketStillActiveAfterResolve) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential ticket denied' }))return}-- // GET /api/v1/workflow/:name/signals- if (req.method === 'GET' && subPath === '/signals') {- const result = await handlers.getSignals(recipeName, claims)- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(JSON.stringify(result.body))+ if (!this.consumePluginSdkTicket(ticket.jti)) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential ticket denied' }))return}-- // POST endpoints — parse body- if (req.method === 'POST') {- const parseResult = await parseJsonBody(req)- if (!parseResult.ok) {- const status = parseResult.reason === 'too_large' ? 413 : 400- const error =- parseResult.reason === 'too_large' ? 'Request body too large' : 'Invalid JSON body'- res.writeHead(status, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error }))- return- }- const body = parseResult.body-- // POST /api/v1/workflow/:name/status- if (subPath === '/status') {- const result = await handlers.postStepStatus(recipeName, claims, body as never)- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(JSON.stringify(result.body))- return- }-- // POST /api/v1/workflow/:name/configure-model- if (subPath === '/configure-model') {- // Token factory injected at construction signs a fresh WRC→mcp-host- // configure token per call inside handlers.configureModel — no store.- const result = await handlers.configureModel(- recipeName,- claims,- body as never,- this.modelConfigHandler ?? undefined- )- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(JSON.stringify(result.body))- return- }-- // POST /api/v1/workflow/:name/injections/model- if (subPath === '/injections/model') {- const result = await handlers.requestModelInjection(- recipeName,- claims,- body as never,- this.modelConfigHandler ?? undefined- )- res.writeHead(result.status, { 'Content-Type': 'application/json' })- res.end(JSON.stringify(result.body))- return- }- }}-- res.writeHead(404, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: 'Not found' }))+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ return}async start(): Promise<void> {