Skip to content

fix(telegram): bound Bot API response reads to prevent OOM - #97271

Merged
vincentkoc merged 2 commits into
openclaw:mainfrom
hugenshen:fix/telegram-bound-bot-api-response-reads
Jun 28, 2026
Merged

vincentkoc merged 2 commits into
openclaw:mainfrom
hugenshen:fix/telegram-bound-bot-api-response-reads

Conversation

@hugenshen

Copy link
Copy Markdown
Contributor

What Problem This Solves

Three Telegram Bot API response paths use unbounded await response.json() on the success path, leaving the gateway exposed to OOM if a misbehaving or hostile endpoint streams an oversized response body:

File Endpoint Risk
extensions/telegram/src/probe.ts getMe, getWebhookInfo Called on every probe / health-check
extensions/telegram/src/audit-membership-runtime.ts getChatMember Called during group-membership audit
extensions/telegram/src/telegram-ingress-worker.runtime.ts getUpdates Hot path — called every polling cycle in the ingress worker

Legitimate Telegram Bot API responses for these endpoints are tiny (< 1 KiB for getMe/getChatMember, < 500 KiB for 100 getUpdates). An unbounded read allows any interceptor or rogue endpoint to force the gateway to buffer an arbitrarily large body before returning control.

This continues the response-limit campaign already merged for Discord, xAI, fal, MiniMax, OpenRouter, embeddings, speech, and other surfaces.

Changes

  • extensions/telegram/src/probe.ts

    • Imports readResponseWithLimit from openclaw/plugin-sdk/response-limit-runtime
    • Adds TELEGRAM_BOT_API_MAX_RESPONSE_BYTES = 4 MiB constant
    • Replaces await meRes.json() (getMe) with readResponseWithLimit + JSON.parse
    • Replaces await webhookRes.json() (getWebhookInfo) with readResponseWithLimit + JSON.parse
  • extensions/telegram/src/audit-membership-runtime.ts

    • Imports readResponseWithLimit from openclaw/plugin-sdk/response-limit-runtime
    • Adds TELEGRAM_BOT_API_MAX_RESPONSE_BYTES = 4 MiB constant
    • Replaces await res.json() (getChatMember) with readResponseWithLimit + JSON.parse
  • extensions/telegram/src/telegram-ingress-worker.runtime.ts

    • Imports readResponseWithLimit from openclaw/plugin-sdk/response-limit-runtime
    • Adds TELEGRAM_GET_UPDATES_MAX_RESPONSE_BYTES = 4 MiB constant
    • Replaces await response.json() (getUpdates) with readResponseWithLimit + JSON.parse
  • extensions/telegram/src/probe.test.ts

    • Adds a vi.mock pass-through for openclaw/plugin-sdk/response-limit-runtime so existing
      plain-object fetch mocks continue to work without requiring real Response body streams
  • scripts/proof-telegram-bound.mjs — local proof script (see Evidence below)

Real behavior proof

  • Behavior addressed: Unbounded response.json() on Telegram Bot API success paths — a misbehaving endpoint can stream an arbitrarily large body, exhausting gateway heap before the read returns
  • Real environment tested: node:http createServer on 127.0.0.1:0, Node v22+, macOS
  • Exact steps run after this patch:
    node --import tsx/esm scripts/proof-telegram-bound.mjs
    
  • Evidence after fix: see Evidence section below
  • Observed result: readResponseWithLimit cancelled the stream after reading ~1.1 MiB (server wrote ~1.4 MiB total including HTTP framing); the unbounded .json() negative-control read the full 25 MiB; a normal 99-byte happy-path response parsed correctly
  • What was not tested: live Telegram Bot API calls; the api-fetch.ts getChat path (already guarded by .catch(() => null), lower risk)
  • Proof limitations: Byte tracking is server-side write counters. TCP framing adds overhead so server-written bytes are slightly above the 1 MiB cap; the reader itself stops at the cap.

shen@192 openclaw % node --import tsx/esm scripts/proof-telegram-bound.mjs

[proof] Telegram Bot API response-limit
cap=1048576 bytes (1 MiB), would-stream≈25165824 bytes (24 MiB)

ok: oversized body rejected (threw=true)
ok: error message contains limit info: "Content too large: 1072391 bytes (limit: 1048576 bytes)"
ok: server wrote ≈1572885 bytes, well below 24 MiB (stream was cancelled early)
ok: negative control: unbounded .json() caused server to write ≈25165847 bytes (>> 1048576)
ok: small response parsed correctly (ok=true id=123456789)
ok: result bytes within cap (99 < 1048576)

ALL PROOF ASSERTIONS PASSED
shen@192 openclaw % pnpm test extensions/telegram/src/probe.test.ts

$ node scripts/test-projects.mjs extensions/telegram/src/probe.test.ts
[test] starting test/vitest/vitest.extension-telegram.config.ts

RUN v4.1.8 /Users/shen/Documents/GitHub/openclaw

✓ extension-telegram extensions/telegram/src/probe.test.ts (12 tests) 19ms

Test Files 1 passed (1)
Tests 12 passed (12)
Start at 21:56:43
Duration 2.09s (transform 1.17s, setup 253ms, import 1.74s, tests 19ms, environment 0ms)

[test] passed 1 Vitest shard in 5.36s

Evidence

node --import tsx/esm scripts/proof-telegram-bound.mjs

[proof] Telegram Bot API response-limit
  cap=1048576 bytes (1 MiB), would-stream≈25165824 bytes (24 MiB)

  ok: oversized body rejected (threw=true)
  ok: error message contains limit info: "Content too large: 1072391 bytes (limit: 1048576 bytes)"
  ok: server wrote ≈1441813 bytes, well below 24 MiB (stream was cancelled early)
  ok: negative control: unbounded .json() caused server to write ≈25165847 bytes (>> 1048576)
  ok: small response parsed correctly (ok=true id=123456789)
  ok: result bytes within cap (99 < 1048576)

ALL PROOF ASSERTIONS PASSED
pnpm test extensions/telegram/src/probe.test.ts

 Test Files  1 passed (1)
      Tests  12 passed (12)

Tests and validation

  • pnpm test extensions/telegram/src/probe.test.ts — 12/12 pass
  • pnpm test extensions/telegram — 2214/2218 pass (4 pre-existing failures in bot.create-telegram-bot.channel-post-media.test.ts, confirmed on main before this change)
  • scripts/proof-telegram-bound.mjs — ALL PROOF ASSERTIONS PASSED
  • Regression test added: N/A — size-cap behavior covered by the proof script; existing probe tests verify the happy-path JSON round-trip through the mock

Risk checklist

  • Did user-visible behavior change? No — only affects what happens when a Bot API endpoint returns an abnormally oversized response body; all normal responses are well under 4 MiB
  • Did config, environment, or migration behavior change? No
  • Did security, auth, secrets, network, or tool execution behavior change? No — defense-in-depth addition only
  • Highest-risk area: telegram-ingress-worker.runtime.ts (getUpdates hot path); new import from openclaw/plugin-sdk/response-limit-runtime in the worker thread
  • Mitigation: readResponseWithLimit uses only standard Web Streams + Buffer APIs available in Node.js worker threads; the 4 MiB cap is far above the largest realistic Bot API response

Current review state

  • Next action: awaiting maintainer review
  • Bot comments addressed: none yet
  • AI-assisted (Claude / Cursor Agent); human-run proof script on macOS

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram scripts Repository scripts size: S labels Jun 27, 2026
@clawsweeper

clawsweeper Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 27, 2026, 1:07 PM ET / 17:07 UTC.

Summary
The PR replaces Telegram getMe, getWebhookInfo, getChatMember, and getUpdates success-path .json() reads with readResponseWithLimit, updates probe test mocks, and adds a loopback proof script.

PR surface: Source +23, Tests +14, Other +142. Total +179 across 5 files.

Reproducibility: Do we have a high-confidence way to reproduce the issue? Yes from source and PR proof: current main still calls unbounded .json() in the targeted paths, and the PR body shows a loopback oversized-body negative control; I did not run a local OOM reproduction.

Review metrics: 1 noteworthy metric.

  • Telegram Bot API read policy: 3 paths capped here, 1 companion getChat PR open. Maintainers should decide whether to land the focused hot-path hardening separately or coordinate it with the remaining Telegram Bot API reader coverage.

Stored data model
Persistent data-model change detected: serialized state: extensions/telegram/src/audit-membership-runtime.ts, serialized state: extensions/telegram/src/probe.test.ts, serialized state: extensions/telegram/src/probe.ts, serialized state: extensions/telegram/src/telegram-ingress-worker.runtime.ts, serialized state: scripts/proof-telegram-bound.mjs. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Maintainers should explicitly accept the 4 MiB fail-closed cap and decide whether the companion getChat PR should land separately or in the same sweep.

Risk before merge

  • [P1] Merging introduces a 4 MiB fail-closed cap for existing Telegram getMe, getWebhookInfo, getChatMember, and getUpdates paths; self-hosted or proxied Bot API roots that return oversized success bodies would now fail instead of buffering the whole body.
  • [P2] For getUpdates, an oversized body becomes a non-recoverable polling error rather than a retryable transport blip, so maintainers should explicitly accept that operator-visible failure mode.
  • [P1] The PR body has strong loopback terminal proof but no live Telegram happy-path smoke; that is probably adequate for the hostile oversized-body path, but it is still a maintainer proof decision.

Maintainer options:

  1. Accept the focused 4 MiB cap (recommended)
    Land this PR once required checks finish if maintainers accept that oversized Telegram Bot API success bodies now fail closed on these four paths.
  2. Ask for live Telegram smoke first
    Request a redacted live Telegram startup or polling proof if maintainer confidence depends on showing normal cloud Bot API traffic still works after the capped reader change.
  3. Coordinate with getChat coverage
    Pause this PR until the companion getChat PR is reviewed if maintainers want the Telegram Bot API response-limit sweep to land as one coverage unit.

Next step before merge

  • [P2] No narrow automated repair remains on the latest head; the blocker is maintainer acceptance of the compatibility policy and proof level.

Security
Cleared: The diff reduces an OOM-style availability risk and adds no dependency, lockfile, permission, CI, publishing, or secret-handling change.

Review details

Best possible solution:

Land the focused bounded-read hardening after maintainers accept the 4 MiB fail-closed policy, with the getChat companion coverage reviewed as separate but related work.

Do we have a high-confidence way to reproduce the issue?

Do we have a high-confidence way to reproduce the issue? Yes from source and PR proof: current main still calls unbounded .json() in the targeted paths, and the PR body shows a loopback oversized-body negative control; I did not run a local OOM reproduction.

Is this the best way to solve the issue?

Is this the best way to solve the issue? Yes for the targeted paths: using the existing plugin SDK response-limit helper is the narrow owner-boundary fix, while the cap value and getChat sequencing remain maintainer decisions.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 1bdde6695030.

Label changes

Label justifications:

  • P2: This is normal-priority Telegram availability hardening with focused code changes and no evidence of an active outage.
  • merge-risk: 🚨 compatibility: The new 4 MiB cap intentionally changes oversized Telegram Bot API success responses from unbounded buffering to fail-closed errors for existing setups.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes terminal proof from a real Node loopback server showing capped cancellation, an unbounded negative control draining the full stream, and a small successful parse after the fix.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes terminal proof from a real Node loopback server showing capped cancellation, an unbounded negative control draining the full stream, and a small successful parse after the fix.
Evidence reviewed

PR surface:

Source +23, Tests +14, Other +142. Total +179 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 27 4 +23
Tests 1 14 0 +14
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 142 0 +142
Total 5 183 4 +179

What I checked:

Likely related people:

  • vincentkoc: Blame on the current target .json() reads and the response-limit helper lines in this checkout points to ff18374293006dd77560fd4c3e9e921ad79383f4; recent local Telegram history also shows nearby Telegram maintenance by this author. (role: current target-path history; confidence: medium; commits: ff1837429300, b8e3de11608d; files: extensions/telegram/src/probe.ts, extensions/telegram/src/audit-membership-runtime.ts, extensions/telegram/src/telegram-ingress-worker.runtime.ts)
  • steipete: Recent merged Telegram probe/fetch work in 072d3ed7b5e488997629253a90a2a328c765443f touched adjacent transport/probe behavior and was authored and merged by this GitHub user. (role: recent area contributor and merger; confidence: high; commits: 072d3ed7b5e4; files: extensions/telegram/src/probe.ts, extensions/telegram/src/fetch.ts, extensions/telegram/src/probe.test.ts)
  • Cypherm: History for Telegram chat lookup paths includes 6b4c24c2e55b5b4013277bd799525086f6a0c40f, which added custom apiRoot support relevant to the self-hosted/proxied Bot API compatibility risk. (role: adjacent custom-apiRoot contributor; confidence: medium; commits: 6b4c24c2e55b; files: extensions/telegram/src/api-fetch.ts, extensions/telegram/src/api-fetch.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jun 27, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 27, 2026
@vincentkoc
vincentkoc merged commit a07d59e into openclaw:main Jun 28, 2026
105 of 111 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jun 29, 2026
…97271)

* fix(telegram): bound Bot API response reads to prevent OOM

* fix(scripts): make proof-telegram-bound.mjs lint-clean

---------

Co-authored-by: NIO <[email protected]>
chenyangjun-xy pushed a commit to chenyangjun-xy/openclaw that referenced this pull request Jul 1, 2026
…97271)

* fix(telegram): bound Bot API response reads to prevent OOM

* fix(scripts): make proof-telegram-bound.mjs lint-clean

---------

Co-authored-by: NIO <[email protected]>
amittell pushed a commit to amittell/openclaw that referenced this pull request Jul 2, 2026
…97271)

* fix(telegram): bound Bot API response reads to prevent OOM

* fix(scripts): make proof-telegram-bound.mjs lint-clean

---------

Co-authored-by: NIO <[email protected]>
(cherry picked from commit a07d59e)
Rorqualx pushed a commit to Rorqualx/cortex that referenced this pull request Jul 4, 2026
…97271)

* fix(telegram): bound Bot API response reads to prevent OOM

* fix(scripts): make proof-telegram-bound.mjs lint-clean

---------

Co-authored-by: NIO <[email protected]>
(cherry picked from commit a07d59e)
Rorqualx pushed a commit to Rorqualx/cortex that referenced this pull request Jul 8, 2026
…97271)

* fix(telegram): bound Bot API response reads to prevent OOM

* fix(scripts): make proof-telegram-bound.mjs lint-clean

---------

Co-authored-by: NIO <[email protected]>
(cherry picked from commit a07d59e)
wheakerd pushed a commit to wheakerd/clawdbot that referenced this pull request Jul 15, 2026
…97271)

* fix(telegram): bound Bot API response reads to prevent OOM

* fix(scripts): make proof-telegram-bound.mjs lint-clean

---------

Co-authored-by: NIO <[email protected]>
(cherry picked from commit a07d59e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants