Repository navigation
Conversation
…mpletions streams alive through idle-timeout proxies Made-with: Cursor
🔒 Aisle Security AnalysisWe found 1 potential security issue(s) in this PR:
1. 🟡 Potential DoS via unlimited long-lived SSE connections kept alive by periodic heartbeats
Description
While the helper is backpressure-aware (pauses on
As a result, an authenticated attacker (or any caller if the gateway is configured with
The change also makes this behavior default by calling Vulnerable code (new behavior): setSseHeaders(res);
startSseHeartbeat(res);This is a classic resource-exhaustion risk (CWE-400). RecommendationAdd explicit server-side limits for streaming responses so clients cannot keep connections open indefinitely. Recommended defenses (combine as appropriate):
Example (TTL cap inside export function startSseHeartbeat(res: ServerResponse, options?: { intervalMs?: number; maxLifetimeMs?: number }) {
const maxLifetimeMs = options?.maxLifetimeMs ?? 10 * 60_000;
const lifetimeTimer = setTimeout(() => {
try { res.end(); } finally { stop(); }
}, maxLifetimeMs);
function stop() {
clearInterval(timer);
clearTimeout(lifetimeTimer);
// ...
}
// ...
}Also consider moving concurrency enforcement into Analyzed PR: #70739 at commit Last updated on: 2026-04-23T19:18:38Z |
Greptile SummaryAdds a
Confidence Score: 5/5Safe to merge; all remaining findings are P2 style suggestions with no correctness impact. The change is narrowly scoped, thoroughly tested (7 new unit tests, all passing), and follows an established pattern already in the codebase. No auth, data, or schema changes. The only finding is a minor listener-cleanup improvement that does not affect correctness. No files require special attention. Prompt To Fix All With AIThis is a comment left during a code review.
Path: src/gateway/http-common.ts
Line: 145-153
Comment:
**Orphaned `once` listener after explicit `stop()`**
When `stop()` fires via one of the two `once` listeners (e.g. `finish`), the other listener (`close`) stays registered until that event also fires. Conversely, if the caller invokes the returned `stop()` directly (or some future caller does), both listeners remain registered on `res` until both events fire. Neither case causes incorrect behaviour today thanks to the `stopped` guard and `once` semantics, but it does leave a transient listener on the response object. Adding `res.removeListener` calls inside `stop()` would make the cleanup fully deterministic:
```typescript
const stop = () => {
if (stopped) {
return;
}
stopped = true;
clearInterval(timer);
res.removeListener("close", stop);
res.removeListener("finish", stop);
};
```
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix(gateway): add SSE heartbeat to keep ..." | Re-trigger Greptile |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 253148d9af
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Check the boolean return of res.write() and pause heartbeat writes until the response emits `drain`. Addresses CWE-400: without this, a slow SSE client or congested downstream proxy would let the heartbeat pile up ": ping" writes in Node's internal buffer at every interval tick, amplified linearly across all concurrent connections. A slowloris-style attacker could open many slow-reading streams and push the gateway into unbounded buffering and event-loop pressure. Also adds two unit tests: - pauses on res.write() returning false - resumes on `drain` event Made-with: Cursor
Backpressure fix + related issuesResponse to @aisle-research-botGood catch — addressed in a3af791. The heartbeat now:
Two new unit tests in `http-common.test.ts` cover the scenario:
Total test count for `startSseHeartbeat`: 9/9 passing. The real event writes (deltas, `response.completed`, etc.) experience the same Node-level backpressure through the same `res.write()`, but the heartbeat itself now never contributes to unbounded buffering. For belt-and-suspenders, the existing `watchClientDisconnect` helper still triggers `res.destroy()` if the underlying socket closes, which terminates any pending buffered data. Related issuesSearched `openclaw/openclaw` for prior reports. Mapping:
Linking these as Related, not Closes, since each has additional asks beyond SSE keepalive. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a3af791ee3
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| beforeEach(() => { | ||
| vi.useFakeTimers(); | ||
| }); |
There was a problem hiding this comment.
Restore real timers after heartbeat tests
This suite enables fake timers in beforeEach but never calls vi.useRealTimers(), so timer mode can leak beyond these cases. In Vitest runs that share a worker context (notably --isolate=false, which this repo explicitly supports), later tests can inherit fake timers and silently stop exercising real timeout/interval behavior, causing hangs or false positives. Add cleanup that restores real timers (and clears pending timers) after each test or after the suite.
Useful? React with 👍 / 👎.
… error events
Addresses CWE-248: even with writableEnded/destroyed checks, a client
disconnect can land between the check and the write. Node may:
- throw ERR_STREAM_WRITE_AFTER_END (or similar) synchronously from write(), or
- emit an 'error' event on the response/socket with no listener, which Node
escalates to an uncaught exception and terminates the process by default.
Either is remotely triggerable by a client disconnecting at the right moment,
turning the heartbeat tick into a DoS vector.
Fix:
- Wrap res.write() in try/catch; on error, stop the heartbeat.
- Register res.on('error', stop) so async socket errors cannot escape as
unhandled 'error' events.
- stop() removes the error listener to avoid accumulating handlers across
long-running processes.
Three new unit tests:
- sync throw from write() is caught and stops the helper
- async 'error' event does not throw and stops the helper
- stop() removes the error listener (no leak)
Made-with: Cursor
Response to the second @aisle-research-bot passFinding #1 — Unhandled exception / write-after-end race (CWE-248) — Fixed in 41d6e91Good catch, this is a real remotely-triggerable DoS. Applied the recommended hardening:
Three new unit tests cover the failure modes:
Total `startSseHeartbeat` coverage: 12/12 passing. Finding #2 — Per-connection timers (CWE-400) — Pushback with analysisI want to push back on the shared-scheduler refactor before applying it. The per-connection `setInterval` is actually the right trade-off here for several reasons: 1. Node's timer wheel handles this efficiently. libuv batches timers by expiration bucket with O(1) amortized insert/remove. A timer entry in Node is ~200 bytes. At 10,000 concurrent streaming connections — which is already well beyond normal gateway load — that's ~2 MB of memory for timers, dwarfed by:
Timer count is not where the gateway falls over under connection flood; sockets and response buffers are. The recommendation fixes a bottleneck that isn't the bottleneck. 2. CPU wakeups amortize naturally. Timers created at different points in time (connections arrive at varying times) spread across different buckets in libuv's wheel, so the 30s ticks distribute rather than concentrate. A shared interval that iterates over all entries actually concentrates the work into one CPU spike every tick — worse for tail latency and prompt-cache stability. 3. Shared scheduler introduces isolation bugs. A shared scheduler iterates over N responses in one callback. Any unexpected error path inside `res.write()` for one response — or an expensive `once("drain")` registration — delays or impacts the others. The current per-connection design has hard isolation: a misbehaving response only affects its own interval callback. With the CWE-248 fix in this PR (try/catch + error listener), the per-connection path is fully fail-safe. 4. The real DoS mitigation is connection limiting, which lives elsewhere. If a bad actor wants to exhaust the gateway, they open a flood of authenticated streaming requests. The appropriate defense is per-identity/per-IP connection caps and rate limiting. OpenClaw already has `src/gateway/auth-rate-limit.ts` for this purpose, and `handleGatewayPostJsonEndpoint` enforces it. Moving that defense into the heartbeat helper would be the wrong layer — the helper does not know the identity or rate-limit context. 5. The bot's own pseudocode has a subtle trade-off. The proposed shared scheduler uses `res.write(": ping\n\n")` without try/catch and without backpressure handling per-response. Applying it as-is would regress both CWE-248 (Finding #1 above) and the backpressure fix from a3af791. To keep those properties in a shared scheduler, each entry still needs per-response state (`waitingForDrain`, error listener, backpressure-paused flag), which reintroduces most of the per-entry bookkeeping while adding iteration complexity. Counter-proposal: if operators deploy this behind a threat model where attacker-controlled streaming connection counts exceed what `auth-rate-limit` catches, the right answer is either raising the rate-limit config or adding a dedicated streaming-connection cap to `handleOpenAiHttpRequest` / `handleOpenResponsesHttpRequest`. Happy to file that as a separate issue/PR if maintainers want it — it's orthogonal to heartbeat implementation. If maintainers still prefer the shared scheduler despite the trade-offs, I'll implement it with per-response state preserved (so Findings #1 and the backpressure fix don't regress). Just let me know. |
|
Thanks for the context here. I swept through the related work, and this is now duplicate or superseded. Keep this PR open: current main still lacks downstream SSE keepalive bytes on the two OpenAI-compatible streaming endpoints, but the branch is not merge-ready because real proxy/curl proof is missing and the patch still has interval-validation, timer-test cleanup, and long-lived-stream availability concerns. Canonical path: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review. So I’m closing this here because the remaining work is already tracked in the canonical issue. Review detailsBest possible solution: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review. Do we have a high-confidence way to reproduce the issue? Yes, source-level. Current main has streaming branches for both OpenAI-compatible endpoints with no periodic downstream bytes during quiet upstream windows; I did not run a live proxy reproduction in this read-only review. Is this the best way to solve the issue? No, not as-is. SSE comments are the right transport shape and match an existing gateway precedent, but the patch still needs interval hardening, timer cleanup, real behavior proof, and a maintainer decision on long-lived stream limits. Security review: Security review needs attention: No supply-chain change was found, but the patch introduces availability-sensitive long-lived stream behavior and a malformed-interval timer risk.
AGENTS.md: found and applied where relevant. What I checked:
Likely related people:
Codex review notes: model internal, reasoning high; reviewed against 6c88811b4bba. |
|
ClawSweeper PR egg 🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat. Where did the egg go?
|
|
Heads up: this PR needs to be updated against current |
|
This pull request has been automatically marked as stale due to inactivity. |
|
ClawSweeper applied the proposed close for this PR.
|
Summary
Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
Root Cause (if applicable)
The gateway emits `response.reasoning.delta` / `response.output_text.delta` / `chat.completion.chunk` events as the upstream model produces them. During reasoning pauses (the model is thinking internally but not producing visible tokens yet) or while waiting on an upstream provider, zero bytes cross the wire for potentially minutes. Any L4/L7 proxy between the client and gateway that tracks per-stream idle activity will consider the stream dead and close it, even though the connection is logically healthy.
Existing precedent in the repo: `src/gateway/sessions-history-http.ts` already writes `: keepalive\n\n` every 15s for exactly this reason. This PR generalizes the pattern into a reusable helper and applies it to the two public OpenAI-compatible streaming endpoints that lacked it.
Design / Behavior
Flow diagram
```text
Before (with Envoy stream_idle_timeout=240s):
t=0s client -> envoy -> gateway: POST /v1/responses (stream=true)
t=0s gateway writes: response.created, in_progress, output_item.added
t=0.5s model starts extended reasoning (silent, no deltas)
t=240s envoy: no bytes in 240s -> kills the stream
t=240s+ client: stream truncated, no response.completed
After:
t=0s gateway writes initial events
t=30s ": ping\n\n" (8 bytes cross envoy -> idle timer reset)
t=60s ": ping\n\n" (reset)
t=90s ": ping\n\n" (...)
...
t=Xs model emits response.output_text.delta -> stream continues normally
t=Ys response.completed, [DONE], res.end() -> finish event fires -> clearInterval
```
Lifecycle
The helper registers `res.once("close", stop)` and `res.once("finish", stop)`, so the interval is always cleared when the response ends through any existing path:
Defense in depth:
Security Impact (required)
No authentication or authorization logic is touched. The heartbeat fires only after the existing SSE stream is established, i.e. after full auth/authz checks have already passed and `setSseHeaders(res)` has been called. Each ping is 8 bytes; bandwidth impact is negligible.
Repro + Verification
Environment
Steps to repro (before this patch)
Expected (correct)
Stream continues until `response.completed` and `[DONE]`, regardless of thinking duration.
Actual (before this patch)
At `t=240s`, Envoy kills the stream. Curl returns `ECONNRESET` / truncated output. No `response.completed` event.
After this patch
Client sees intermixed `: ping` comment lines (invisible to `EventSource` / SDKs), stream continues indefinitely until the model actually completes.
Evidence
Human Verification (required)
Compatibility / Migration
Risks and Mitigations
Made with Cursor