Skip to content

Commit 0684f50

Browse files
authored
fix(gateway): harden hook admission and shutdown (#125893)
* fix(gateway): harden hook admission and shutdown Flush structured 413 and 408 hook responses before closing oversized or timed-out request sockets, and reject deferred wake requests that target an explicit session. Direct Gateway close now marks startup and readiness as draining immediately and attempts every HTTP listener shutdown before reporting an incomplete close. * test(gateway): model request destruction in fuzzing Give the HTTP request fuzz double the IncomingMessage destroy contract exercised after 413 and 408 responses finish. * fix(gateway): preserve response and shutdown bounds Route installed webhook body-limit failures through the shared response-first close owner and require complete Feishu 413/408 responses before terminal connection closure. Retain the current-main grace bound for agent-harness disposal so one stuck harness cannot block listener teardown. * test(telegram): model response-close request cleanup Keep the slow-body request alive through response finish, then assert cleanup when the mock response transport closes.
1 parent d33ba00 commit 0684f50

21 files changed

Lines changed: 420 additions & 106 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2965,7 +2965,7 @@ src/gateway/server-broadcast.ts 2
29652965
src/gateway/server-channels.ts 1
29662966
src/gateway/server-chat-state.ts 1
29672967
src/gateway/server-chat.ts 5
2968-
src/gateway/server-close.ts 2
2968+
src/gateway/server-close.ts 1
29692969
src/gateway/server-core-runtime.ts 2
29702970
src/gateway/server-cron-reconciled.ts 1
29712971
src/gateway/server-cron.ts 5

‎docs/automation/cron-jobs.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,7 @@ Query-string tokens are rejected.
578578
Target agent. When supplied, it must name a configured agent. It is required when the configured agent fleet has no implicit or retained legacy owner.
579579
</ParamField>
580580
<ParamField path="sessionKey" type="string">
581-
Target session. Requires `hooks.allowRequestSessionKey: true` and must match `hooks.allowedSessionKeyPrefixes` when configured. Both wake modes can target an explicit session.
581+
Target session. Requires `mode: "now"` and `hooks.allowRequestSessionKey: true`, and must match `hooks.allowedSessionKeyPrefixes` when configured. Deferred `next-heartbeat` wakes use the agent's main session.
582582
</ParamField>
583583

584584
</Accordion>

‎docs/gateway/configuration-reference.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1081,7 +1081,7 @@ Validation and safety notes:
10811081
**Endpoints:**
10821082

10831083
- `POST /hooks/wake` → `{ text, mode?: "now"|"next-heartbeat", agentId?, sessionKey? }`
1084-
- `sessionKey` is accepted only when `hooks.allowRequestSessionKey=true` (default: `false`) and must match `hooks.allowedSessionKeyPrefixes` when configured.
1084+
- `sessionKey` requires `mode: "now"`, is accepted only when `hooks.allowRequestSessionKey=true` (default: `false`), and must match `hooks.allowedSessionKeyPrefixes` when configured.
10851085
- A supplied `agentId` must name a configured agent.
10861086
- `POST /hooks/agent` → `{ message, name?, agentId?, sessionKey?, sessionMode?, wakeMode?, deliver?, channel?, to?, accountId?, model?, thinking?, timeoutSeconds? }`
10871087
- A supplied `agentId` must name a configured agent.

‎extensions/feishu/src/monitor.webhook-security.test.ts‎

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ async function waitForSlowBodyTimeoutResponse(
6060
const target = new URL(url);
6161
const startedAt = Date.now();
6262
let response = "";
63+
let settled = false;
6364
const socket = createConnection(
6465
{
6566
host: target.hostname,
@@ -76,17 +77,27 @@ async function waitForSlowBodyTimeoutResponse(
7677
);
7778

7879
socket.setEncoding("utf8");
79-
socket.on("error", () => {});
8080
socket.on("data", (chunk) => {
8181
response += chunk.toString();
82-
if (response.includes("Request body timeout")) {
82+
});
83+
socket.on("close", () => {
84+
if (settled) {
85+
return;
86+
}
87+
settled = true;
88+
clearTimeout(failTimer);
89+
resolve({ body: response, elapsedMs: Date.now() - startedAt });
90+
});
91+
socket.on("error", (error) => {
92+
if (!settled) {
93+
settled = true;
8394
clearTimeout(failTimer);
84-
socket.destroy();
85-
resolve({ body: response, elapsedMs: Date.now() - startedAt });
95+
reject(error);
8696
}
8797
});
8898

8999
const failTimer = setTimeout(() => {
100+
settled = true;
90101
socket.destroy();
91102
reject(new Error(`timeout response did not arrive within ${timeoutMs}ms`));
92103
}, timeoutMs);
@@ -120,32 +131,26 @@ async function waitForOversizedBodyResponse(url: string): Promise<string> {
120131
}
121132
settled = true;
122133
clearTimeout(failTimer);
123-
socket.destroy();
124134
resolve(result);
125135
};
126136

127137
socket.setEncoding("utf8");
128138
socket.on("data", (chunk) => {
129139
response += chunk.toString();
130-
if (response.includes("Payload too large")) {
131-
finish(response);
132-
}
133140
});
134141
socket.on("close", () => {
135-
if (response.includes("Payload too large")) {
136-
finish(response);
137-
}
142+
finish(response);
138143
});
139144
socket.on("error", (error: NodeJS.ErrnoException) => {
140-
if (response.includes("Payload too large")) {
141-
finish(response);
142-
return;
143-
}
144-
if (error.code === "ECONNRESET") {
145-
finish("ECONNRESET");
146-
return;
145+
if (!settled) {
146+
if (response.includes("Payload too large")) {
147+
finish(response);
148+
return;
149+
}
150+
settled = true;
151+
clearTimeout(failTimer);
152+
reject(new Error(`${error.message}; partial response: ${JSON.stringify(response)}`));
147153
}
148-
reject(error);
149154
});
150155

151156
const failTimer = setTimeout(() => {
@@ -267,12 +272,9 @@ describe("Feishu webhook security hardening", () => {
267272
async (url) => {
268273
const response = await waitForOversizedBodyResponse(url);
269274

270-
if (response === "ECONNRESET") {
271-
expect(response).toBe("ECONNRESET");
272-
} else {
273-
expect(response).toContain("413 Payload Too Large");
274-
expect(response).toContain("Payload too large");
275-
}
275+
expect(response).toContain("413 Payload Too Large");
276+
expect(response).toContain("Payload too large");
277+
expect(response).toMatch(/connection: close/i);
276278
},
277279
);
278280
});
@@ -291,6 +293,7 @@ describe("Feishu webhook security hardening", () => {
291293
const result = await waitForSlowBodyTimeoutResponse(url, 1_000);
292294
expect(result.body).toContain("408 Request Timeout");
293295
expect(result.body).toContain("Request body timeout");
296+
expect(result.body).toMatch(/connection: close/i);
294297
expect(result.elapsedMs).toBeLessThan(500);
295298
},
296299
);

‎extensions/telegram/src/miniapp/routes.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,8 @@ describe("registerTelegramMiniAppRoutes", () => {
484484

485485
expect(res.statusCode).toBe(408);
486486
expect(res.body).toBe("Request body timeout");
487+
expect(req.destroyed).toBe(false);
488+
res.emit("close");
487489
expect(req.destroyed).toBe(true);
488490
expectBodyReadListenersCleaned(req);
489491
expect(issueDeviceBootstrapToken).not.toHaveBeenCalled();

‎src/gateway/hooks.test.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,8 @@ describe("gateway hooks helpers", () => {
149149
sessionKey: "hook:wake:later",
150150
}),
151151
).toEqual({
152-
ok: true,
153-
value: {
154-
text: "wake later",
155-
mode: "next-heartbeat",
156-
sessionKey: "hook:wake:later",
157-
},
152+
ok: false,
153+
error: "sessionKey requires mode=now",
158154
});
159155
expect(normalizeWakePayload({ text: " ", mode: "now" }).ok).toBe(false);
160156
expect(normalizeWakePayload({ text: "wake", agentId: 42 })).toEqual({

‎src/gateway/hooks.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,11 @@ export async function readJsonBody(
196196
req: IncomingMessage,
197197
maxBytes: number,
198198
): Promise<Result<unknown, string>> {
199-
const result = await readJsonBodyWithLimit(req, { maxBytes, emptyObjectOnEmpty: true });
199+
const result = await readJsonBodyWithLimit(req, {
200+
maxBytes,
201+
emptyObjectOnEmpty: true,
202+
destroyOnLimit: false,
203+
});
200204
if (result.ok) {
201205
return result;
202206
}
@@ -256,6 +260,9 @@ export function normalizeWakePayload(
256260
if (payload.sessionKey !== undefined && !sessionKey) {
257261
return { ok: false, error: "sessionKey must be a non-empty string" };
258262
}
263+
if (mode === "next-heartbeat" && sessionKey) {
264+
return { ok: false, error: "sessionKey requires mode=now" };
265+
}
259266
return {
260267
ok: true,
261268
value: {

‎src/gateway/http-common.fuzz.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,14 @@ describe("fuzz: sendInvalidRequest", () => {
248248
});
249249

250250
describe("fuzz: readJsonBodyOrError", () => {
251-
const makeRequest = () => ({}) as IncomingMessage;
251+
const makeRequest = () => {
252+
const req = { destroyed: false } as IncomingMessage;
253+
req.destroy = vi.fn(() => {
254+
req.destroyed = true;
255+
return req;
256+
});
257+
return req;
258+
};
252259

253260
it("maps readJsonBody results to the documented status/body contract", async () => {
254261
const rng = makeRng(0xc0de);

‎src/gateway/http-common.test.ts‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,17 @@ describe("sendInvalidRequest", () => {
227227
});
228228

229229
describe("readJsonBodyOrError", () => {
230-
const makeRequest = () => ({}) as IncomingMessage;
230+
const makeRequest = (headers: Record<string, string> = {}) => {
231+
const req = Object.assign(new EventEmitter(), {
232+
destroyed: false,
233+
headers,
234+
destroy: vi.fn(() => {
235+
req.destroyed = true;
236+
return req;
237+
}),
238+
}) as IncomingMessage & { destroy: ReturnType<typeof vi.fn> };
239+
return req;
240+
};
231241

232242
it("returns the parsed body on success", async () => {
233243
readJsonBodyMock.mockResolvedValueOnce({ ok: true, value: { hello: "world" } });
@@ -243,7 +253,7 @@ describe("readJsonBodyOrError", () => {
243253
const events: DiagnosticEventPayload[] = [];
244254
const stop = onDiagnosticEvent((event) => events.push(event));
245255
const { res, end } = makeMockHttpResponse();
246-
const req = { headers: { "content-length": "2048" } } as IncomingMessage;
256+
const req = makeRequest({ "content-length": "2048" });
247257
const result = await readJsonBodyOrError(req, res, 1024);
248258
stop();
249259
expect(result).toBeUndefined();
@@ -259,30 +269,44 @@ describe("readJsonBodyOrError", () => {
259269
expect(event?.bytes).toBe(2048);
260270
expect(event?.limitBytes).toBe(1024);
261271
expect(event?.reason).toBe("json_body_limit");
272+
expect(req.destroy).not.toHaveBeenCalled();
273+
res.emit("finish");
274+
expect(req.destroy).not.toHaveBeenCalled();
275+
res.emit("close");
276+
expect(req.destroy).toHaveBeenCalledOnce();
262277
});
263278

264279
it("responds with 408 when the request body times out", async () => {
265280
readJsonBodyMock.mockResolvedValueOnce({ ok: false, error: "request body timeout" });
266281
const { res, end } = makeMockHttpResponse();
267-
const result = await readJsonBodyOrError(makeRequest(), res, 1024);
282+
const req = makeRequest();
283+
const result = await readJsonBodyOrError(req, res, 1024);
268284
expect(result).toBeUndefined();
269285
expect(res.statusCode).toBe(408);
270286
expect(end).toHaveBeenCalledWith(
271287
JSON.stringify({
272288
error: { message: "Request body timeout", type: "invalid_request_error" },
273289
}),
274290
);
291+
expect(req.destroy).not.toHaveBeenCalled();
292+
res.emit("finish");
293+
expect(req.destroy).not.toHaveBeenCalled();
294+
res.emit("close");
295+
expect(req.destroy).toHaveBeenCalledOnce();
275296
});
276297

277298
it("responds with 400 for other parse failures", async () => {
278299
readJsonBodyMock.mockResolvedValueOnce({ ok: false, error: "bad json" });
279300
const { res, end } = makeMockHttpResponse();
280-
const result = await readJsonBodyOrError(makeRequest(), res, 1024);
301+
const req = makeRequest();
302+
const result = await readJsonBodyOrError(req, res, 1024);
281303
expect(result).toBeUndefined();
282304
expect(res.statusCode).toBe(400);
283305
expect(end).toHaveBeenCalledWith(
284306
JSON.stringify({ error: { message: "bad json", type: "invalid_request_error" } }),
285307
);
308+
res.emit("finish");
309+
expect(req.destroy).not.toHaveBeenCalled();
286310
});
287311
});
288312

‎src/gateway/http-common.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// body-size errors, and client disconnect aborts.
33
import type { IncomingMessage, ServerResponse } from "node:http";
44
import { buildMissingScopeErrorDetails } from "../../packages/gateway-protocol/src/index.js";
5+
import { closeRequestAfterResponse } from "../infra/http-body.js";
56
import {
67
logRejectedLargePayload,
78
parseContentLengthHeader,
@@ -150,12 +151,14 @@ export async function readJsonBodyOrError(
150151
reason: "json_body_limit",
151152
...(contentLength !== undefined ? { bytes: contentLength } : {}),
152153
});
154+
closeRequestAfterResponse(req, res);
153155
sendJson(res, 413, {
154156
error: { message: "Payload too large", type: "invalid_request_error" },
155157
});
156158
return undefined;
157159
}
158160
if (body.error === "request body timeout") {
161+
closeRequestAfterResponse(req, res);
159162
sendJson(res, 408, {
160163
error: { message: "Request body timeout", type: "invalid_request_error" },
161164
});

0 commit comments

Comments
 (0)