Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(gfs): review m4/m5/m7 — GET header-only timeout, set-cookie, sanitize
Alfredo Lopezed21f51fd69c
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 2534f3b9f..198f4f00c 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.427",+ "version": "0.1.428","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.427",+ "version": "0.1.428","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex 62fc2c282..918533ca5 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.427",+ "version": "0.1.428","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/external/gfs.ts b/control-api/src/routes/external/gfs.tsindex c1ca65ece..bc254df4b 100644--- a/control-api/src/routes/external/gfs.ts+++ b/control-api/src/routes/external/gfs.ts@@ -528,14 +528,20 @@ async function proxyReadToGfsc(})const target = `${config.gfscBaseUrl.replace(/\/+$/, '')}${gfscPath}`let upstream: Response+ // Header-only deadline: bound the wait for gfsc to START responding, but never+ // the streamed download body — a large/slow read must not be truncated+ // mid-stream by the mutation budget. Cleared once headers arrive.+ const readDeadline = new AbortController()+ const readTimer = setTimeout(() => readDeadline.abort(), config.gfscProxyTimeoutMs)try {upstream = await fetch(target, {method: 'GET',headers: { authorization: `Bearer ${token}` },- signal: AbortSignal.timeout(config.gfscProxyTimeoutMs),+ signal: readDeadline.signal,})} catch (err) {- const timedOut = err instanceof Error && err.name === 'TimeoutError'+ const timedOut =+ readDeadline.signal.aborted || (err instanceof Error && err.name === 'TimeoutError')rootLogger.error({ err, gfscPath, timeoutMs: config.gfscProxyTimeoutMs },timedOut@@ -544,6 +550,8 @@ async function proxyReadToGfsc()res.status(timedOut ? 504 : 502).json({ error: timedOut ? 'gfsc_timeout' : 'gfsc_unreachable' })return+ } finally {+ clearTimeout(readTimer)}if (upstream.status >= 400) {// Error envelopes are small JSON: buffer, LOG, forward verbatim (a gfsc 5xx on adiff --git a/control-api/src/routes/gfs/proxy.ts b/control-api/src/routes/gfs/proxy.tsindex 6486fcb56..62bc54d35 100644--- a/control-api/src/routes/gfs/proxy.ts+++ b/control-api/src/routes/gfs/proxy.ts@@ -60,6 +60,14 @@ export function registerGfsProxyRoute(router: Router): void {}let upstreamRes: Response+ // Header-only deadline: guard the wait for gfsc to START responding, but do+ // NOT bound the streamed response body. A GET download can legitimately+ // stream longer than the mutation budget, and a total-deadline abort would+ // truncate it into a 200 with a short body (control-ui exempts GET for the+ // same reason). Cleared the moment headers arrive, so an upload still fails+ // loud (504) when gfsc never answers.+ const deadline = new AbortController()+ const deadlineTimer = setTimeout(() => deadline.abort(), config.gfscProxyTimeoutMs)try {upstreamRes = await fetch(target, {method: req.method,@@ -68,14 +76,12 @@ export function registerGfsProxyRoute(router: Router): void {req.method === 'GET' || req.method === 'HEAD'? undefined: JSON.stringify(req.body ?? {}),- // Homologous with the browser client and control-ui proxy (all 300s by- // default). Without this the fetch had NO timeout: a slow/large upload or- // a hung gfsc would pin the connection indefinitely.- signal: AbortSignal.timeout(config.gfscProxyTimeoutMs),+ signal: deadline.signal,})} catch (err) {// Never silent: a failed or timed-out gfsc fetch is logged with the target.- const timedOut = err instanceof Error && err.name === 'TimeoutError'+ const timedOut =+ deadline.signal.aborted || (err instanceof Error && err.name === 'TimeoutError')rootLogger.error({ err, target, method: req.method, timeoutMs: config.gfscProxyTimeoutMs },timedOut@@ -86,6 +92,8 @@ export function registerGfsProxyRoute(router: Router): void {.status(timedOut ? 504 : 502).json({ error: timedOut ? 'gfsc_timeout' : 'gfsc_unreachable' })return+ } finally {+ clearTimeout(deadlineTimer)}if (upstreamRes.status >= 400) {diff --git a/control-ui/app/control-api/[...path]/route.ts b/control-ui/app/control-api/[...path]/route.tsindex 78e1ea934..4216c0072 100644--- a/control-ui/app/control-api/[...path]/route.ts+++ b/control-ui/app/control-api/[...path]/route.ts@@ -123,13 +123,28 @@ function copyRequestHeaders(req: NextRequest): Headers {return headers}+// Response direction: unlike the request, KEEP `content-length` so the browser+// can show GFS download progress (the body streams through unchanged), and+// preserve EACH `set-cookie` separately — Headers.forEach collapses multiple+// set-cookie values into one, which corrupts any response that sets more than+// one cookie (e.g. admin login the day a second cookie is added to a response).+const RESPONSE_HOP_BY_HOP_HEADERS = new Set(+ [...HOP_BY_HOP_HEADERS].filter(header => header !== 'content-length')+)+function copyResponseHeaders(source: Headers): Headers {const headers = new Headers()source.forEach((value, key) => {- if (!HOP_BY_HOP_HEADERS.has(key.toLowerCase())) {+ const lower = key.toLowerCase()+ // set-cookie is re-added below via getSetCookie(); forEach would join them.+ if (lower === 'set-cookie') return+ if (!RESPONSE_HOP_BY_HOP_HEADERS.has(lower)) {headers.set(key, value)}})+ for (const cookie of source.getSetCookie()) {+ headers.append('set-cookie', cookie)+ }return headers}@@ -194,11 +209,11 @@ async function proxyControlApi(url: stripCrlf(upstreamUrl),method: req.method,status,- message,+ message: stripCrlf(message),name: err instanceof Error ? err.name : undefined,cause:err instanceof Error && 'cause' in err- ? String((err as { cause?: unknown }).cause)+ ? stripCrlf(String((err as { cause?: unknown }).cause)): undefined,})return NextResponse.json({ error: message }, { status })diff --git a/control-ui/lib/__tests__/controlApiProxyRoute.test.ts b/control-ui/lib/__tests__/controlApiProxyRoute.test.tsindex e502d0e7a..579b02e22 100644--- a/control-ui/lib/__tests__/controlApiProxyRoute.test.ts+++ b/control-ui/lib/__tests__/controlApiProxyRoute.test.ts@@ -263,4 +263,58 @@ describe('control-ui control-api proxy route', () => {expect(Buffer.from(init.body as ArrayBuffer).toString('utf8')).toBe(payload)})})++ describe('header handling', () => {+ afterEach(() => vi.restoreAllMocks())++ it('strips the Expect header before forwarding upstream (RC4)', async () => {+ const fetchMock = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(new Response('{}', { status: 200 }))++ const req = new NextRequest('http://localhost:3000/control-api/api/v1/gfs/proxy/x', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Expect: '100-continue',+ Authorization: 'Bearer t',+ },+ body: JSON.stringify({ a: 1 }),+ })++ await POST(req, { params: { path: ['api', 'v1', 'gfs', 'proxy', 'x'] } })+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit & { headers: Headers }]++ // undici's fetch throws NotSupportedError if `expect` reaches it — the proxy+ // must never forward it (RC4). Authorization still passes through.+ expect(init.headers.has('expect')).toBe(false)+ expect(init.headers.get('authorization')).toBe('Bearer t')+ })++ it('preserves each Set-Cookie separately and forwards Content-Length on responses', async () => {+ const upstream = new Response('body-bytes', {+ status: 200,+ headers: { 'content-length': '10', 'content-type': 'application/octet-stream' },+ })+ upstream.headers.append('set-cookie', 'a=1; Path=/')+ upstream.headers.append('set-cookie', 'b=2; Path=/; Expires=Wed, 21 Oct 2099 00:00:00 GMT')+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(upstream)++ const req = new NextRequest('http://localhost:3000/control-api/api/v1/gfs/tree', {+ method: 'GET',+ headers: { Authorization: 'Bearer t' },+ })++ const res = await GET(req, { params: { path: ['api', 'v1', 'gfs', 'tree'] } })++ // forEach would collapse these into one unsplittable value (the Expires comma);+ // getSetCookie() keeps them separate.+ expect(res.headers.getSetCookie()).toEqual([+ 'a=1; Path=/',+ 'b=2; Path=/; Expires=Wed, 21 Oct 2099 00:00:00 GMT',+ ])+ // content-length must survive on the response direction (browser download progress).+ expect(res.headers.get('content-length')).toBe('10')+ })+ })})diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 9368cfbce..dcca8f277 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.388",+ "version": "0.1.389","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.388",+ "version": "0.1.389","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 4397b10b0..d71b5a910 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.388",+ "version": "0.1.389","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",