Skip to content

feat(telegram): persist inbound webhooks to survive restarts - #40056

Closed
Diaspar4u wants to merge 1 commit into
openclaw:mainfrom
Diaspar4u:feat/webhook-queue
Closed

Diaspar4u wants to merge 1 commit into
openclaw:mainfrom
Diaspar4u:feat/webhook-queue

Conversation

@Diaspar4u

@Diaspar4u Diaspar4u commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Telegram webhook mode acknowledges messages with 200 OK immediately. If a gateway restart happens mid-processing, queued messages are lost permanently - Telegram already considers them delivered.

Solution

Persist inbound webhook payloads to disk before processing. On restart, replay any unprocessed payloads.

How it works

  1. enqueueWebhook() writes the raw payload to ~/.openclaw/webhook-queue/<deduplicationId>.json via atomic rename (write to .tmp, then rename)
  2. Handler processes the message normally
  3. dequeueWebhook() deletes the file after successful processing
  4. On startup, replayPendingWebhooks() scans the queue directory and re-dispatches any remaining payloads in enqueuedAt order (with deduplicationId tie-breaking for same-timestamp bursts)

Security

  • Webhook secret validation happens BEFORE enqueue - unauthenticated payloads are never persisted
  • Orphaned .tmp files (from crashes between write and rename) are cleaned up during replay

Config

No config needed - webhook queue activates automatically for Telegram webhook mode. Queue directory is created lazily on first webhook.

Supersedes #34702 (force-push after rebase broke reopen).

Validation

  • pnpm build -- clean
  • pnpm check -- clean
  • pnpm test src/infra/webhook-queue.test.ts -- passed

AI Disclosure

AI-assisted (Claude). Fully tested and reviewed.

Closes #42157

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: M labels Mar 8, 2026
@greptile-apps

greptile-apps Bot commented Mar 8, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a disk-backed webhook queue to survive Telegram gateway restarts — enqueuing payloads atomically before processing and dequeuing them after successful completion, with replay-on-startup. The overall design is sound and the test coverage is thorough.

Key issues found:

  • Replay fallback dequeue fires unconditionally (logic bug): bot.handleUpdate() never rejects because grammY's global bot.catch swallows all middleware errors internally. The fallback dequeueWebhook on webhook.ts:132 therefore runs after every handleUpdate call, including failed ones. Entries that fail processing during replay are immediately dequeued instead of being left on disk for retry, breaking the at-least-once delivery guarantee the PR is targeting.
  • Ambiguous filename separator (style): entryFilename joins channelId and deduplicationId with a plain dash (telegram-100.json). If a future channel ID contains a dash, filenames become ambiguous to parse. A non-dash separator would make this more robust as more channels are added.

Confidence Score: 2/5

  • Not safe to merge as-is — the replay fallback dequeue silently discards entries whose processing failed, negating the at-least-once guarantee.
  • The core queue mechanics (atomic write, idempotent dequeue, TTL cleanup) and the onUpdateProcessed hook are all correct. However, the fallback dequeueWebhook call in the replay loop always executes because bot.handleUpdate() never rejects (grammY absorbs errors via bot.catch). This is a logic bug that directly undermines the PR's stated goal: a message that fails to process during replay is dequeued rather than kept for retry on the next restart. The rest of the changes (normal webhook path enqueue/dequeue, bot middleware hook, tests) are solid.
  • Pay close attention to src/telegram/webhook.ts, specifically the replay loop (lines 127–139).

Last reviewed commit: ee28245

Comment thread src/telegram/webhook.ts Resolved
Comment thread src/infra/webhook-queue.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ee282452cc

ℹ️ 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".

Comment thread src/telegram/webhook.ts Resolved
@Diaspar4u
Diaspar4u force-pushed the feat/webhook-queue branch from ee28245 to 59d25b3 Compare March 10, 2026 02:10
@aisle-research-bot

aisle-research-bot Bot commented Mar 10, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 3 potential security issue(s) in this PR:

# Severity Title
1 🟠 High Telegram webhook response can be delayed up to 10s by awaiting deferred timers (DoS risk)
2 🟡 Medium Unbounded startup replay of persisted Telegram webhooks can cause denial of service
3 🔵 Low Symlink/TOCTOU arbitrary file write via on-disk webhook queue (untrusted stateDir/queueDir)

1. 🟠 Telegram webhook response can be delayed up to 10s by awaiting deferred timers (DoS risk)

Property Value
Severity High
CWE CWE-400
Location src/telegram/bot.ts:237-253

Description

The new deferred-work tracking causes the Telegram update middleware to await timers/debounced work before considering an update “processed”. In webhook mode, the HTTP handler awaits GrammY’s webhookCallback handler, so this added await can extend the webhook request duration, potentially to the configured webhook timeout (10s).

Impact:

  • Remote users who can message the bot can trigger buffering paths (text fragment buffering, media groups, inbound debounce) that are resolved only after setTimeout-based flushes.
  • This delays completion of the update middleware and thus can delay webhook request completion.
  • Slow webhook responses risk Telegram retries/duplicate delivery and can exhaust server resources (many concurrent open HTTP requests; additional disk queue writes from enqueueWebhook).

Why it happens (data flow):

  • Input: Telegram-sent updates (attacker-controlled message content/timing).
  • Deferred work registered: in src/telegram/bot-handlers.ts for text fragments/media groups/debounce.
  • Sink: src/telegram/bot.ts middleware waits await Promise.all(deferred) before calling onUpdateProcessed.
  • Webhook lifecycle: src/telegram/webhook.ts awaits handler(...) from webhookCallback before sending HTTP 200.

Maximum wait (observed in code):

  • Text fragment gap flush: DEFAULT_TEXT_FRAGMENT_MAX_GAP_MS = 1500ms (can accumulate across multiple fragments by continually resetting the timer; may exceed webhook timeout).
  • Media group flush: MEDIA_GROUP_TIMEOUT_MS = 500ms (timer reset on each part).
  • Inbound debounce: derived from config via resolveInboundDebounceMs with no upper bound; attacker can keep resetting debounce by sending messages frequently, delaying flush arbitrarily long (bounded only by webhook timeout behavior).
  • Webhook callback timeout: timeoutMilliseconds: 10_000 — worst-case a request can be held ~10s.

Vulnerable code:

​// src/telegram/bot.ts
await next();
const deferred = deferredWork.get(updateId);
if (deferred) {
  deferredWork.delete(updateId);
  await Promise.all(deferred); // waits for timeouts/debounces
}
opts.onUpdateProcessed?.(updateId);

Recommendation

Decouple webhook acknowledgement from deferred buffering timers.

Options (pick one or combine):

  1. Do not block the middleware on deferred work. Fire onUpdateProcessed asynchronously:
​// after await next()
const deferred = deferredWork.get(updateId);
deferredWork.delete(updateId);
void Promise.allSettled(deferred ?? []).then(() => {
  opts.onUpdateProcessed?.(updateId);
});

This allows bot.handleUpdate/webhook handling to complete quickly while still dequeuing once the buffered work finishes.

  1. Add an upper bound when waiting (so timers can’t hold requests):
const MAX_DEFERRED_WAIT_MS = 250; // e.g., keep well under Telegram webhook expectations
await Promise.race([
  Promise.all(deferred),
  new Promise<void>((r) => setTimeout(r, MAX_DEFERRED_WAIT_MS)),
]);
opts.onUpdateProcessed?.(updateId);
  1. For webhook mode specifically, ensure HTTP 200 is returned immediately (process updates out-of-band), while relying on the persisted webhook queue for reliability.

Also consider:

  • Enforcing a sane max for messages.inbound.debounceMs in config parsing.
  • Ensuring queued webhook files are eventually dequeued even if update processing errors/timeouts occur (to avoid disk growth).

2. 🟡 Unbounded startup replay of persisted Telegram webhooks can cause denial of service

Property Value
Severity Medium
CWE CWE-400
Location src/telegram/webhook.ts:125-141

Description

The Telegram webhook startup path replays all queued webhook payloads synchronously before the HTTP server starts listening, creating an unbounded-work startup phase that can be abused or triggered by backlog accumulation.

Impact (DoS):

  • Unbounded work at startup: replayPendingWebhooks() returns an array of all pending entries; startup then iterates and awaits bot.handleUpdate(...) for each entry. If many files accumulate, startup time grows linearly with backlog and can exceed readiness/liveness timeouts, causing restart loops.
  • Resource exhaustion: replayPendingWebhooks() reads and JSON.parses every *.json file and sorts in-memory (O(n log n)), which can spike CPU/RAM when many entries exist.
  • Backlog can accumulate remotely: each valid Telegram update is persisted to disk (up to 1 MiB request body limit) prior to processing. If processing is slow, crashes, or errors occur before onUpdateProcessed fires, entries can accumulate without any cap.

Vulnerable code (startup replay blocks listener):

const pending = await replayPendingWebhooks(queueChannelId, opts.stateDir);
for (const entry of pending) {
  await bot.handleUpdate(entry.payload as Parameters<typeof bot.handleUpdate>[0]);
}

Note: replayPendingWebhooks() currently has no maximum count/bytes/time budget; it attempts to load all entries from disk into memory.

Recommendation

Add explicit operational bounds and avoid blocking startup on unbounded replay.

Suggested mitigations (combine as appropriate):

  1. Cap replay work (count/time budget) and log/drop/defers the rest:
const MAX_REPLAY = 500;           // or config-driven
const REPLAY_DEADLINE_MS = 5000;  // time budget
const deadline = Date.now() + REPLAY_DEADLINE_MS;

const pending = await replayPendingWebhooks(queueChannelId, opts.stateDir, { limit: MAX_REPLAY });
for (const entry of pending) {
  if (Date.now() > deadline) break;
  await bot.handleUpdate(entry.payload as Parameters<typeof bot.handleUpdate>[0]);
}
  1. Start the HTTP server first, then perform replay in the background so readiness probes succeed, while applying backpressure (e.g., a single replay worker) to avoid overload.

  2. Stream processing in replayPendingWebhooks (process entries one-by-one or in small batches) instead of readFile + JSON.parse for all files followed by sort.

  3. Bound queue growth on enqueue:

  • enforce a max file count / max total bytes for webhook-queue
  • periodic cleanup (not only at startup)
  • consider deleting entries after N failed replays or persisting a retry counter

These changes prevent attacker-triggered or failure-induced backlog from making the service unable to restart.


3. 🔵 Symlink/TOCTOU arbitrary file write via on-disk webhook queue (untrusted stateDir/queueDir)

Property Value
Severity Low
CWE CWE-59
Location src/infra/webhook-queue.ts:24-50

Description

The on-disk webhook queue performs filesystem operations (mkdir/writeFile/rename/readFile/unlink) on paths derived from stateDir without verifying that the target directory is a real directory (not a symlink) with safe ownership/permissions.

If an attacker on the same host can influence OPENCLAW_STATE_DIR / stateDir (or can pre-create/modify the directory tree when it lives in a shared/writable location), they can exploit symlink/race conditions to redirect writes outside the intended queue directory:

  • ensureQueueDir() uses mkdir(..., { recursive: true, mode: 0o700 }), but does not validate an existing path (could already be a symlink) and does not tighten permissions/ownership if the dir already exists.
  • enqueueWebhook() writes to a predictable tmp path with writeFile() (follows symlinks) and then rename()s into place. If the queue directory (or tmp file path) is attacker-controlled, this can be turned into arbitrary file overwrite/clobber as the service user.

Concrete local exploit scenario (privilege impact depends on how the service is deployed):

  1. Attacker sets (or causes the service to run with) OPENCLAW_STATE_DIR=/tmp/openclaw-state (or any shared/writable location).
  2. Attacker creates /tmp/openclaw-state/webhook-queue as a symlink to a sensitive directory (e.g. /etc), or races creation/replacement between ensureQueueDir() and writeFile().
  3. On the next webhook, the process writes/renames telegram_<id>.json into the symlink target directory, clobbering files writable by the service user.

Vulnerable code:

await fs.promises.mkdir(queueDir, { recursive: true, mode: 0o700 });
...
await fs.promises.writeFile(tmp, JSON.stringify(entry), { encoding: "utf-8", mode: 0o600 });
await fs.promises.rename(tmp, filePath);

Recommendation

Harden directory and file handling against symlink/hardlink/TOCTOU attacks:

  1. Validate stateDir/queueDir before use
  • Resolve to a real path and ensure it is within the expected base.
  • Use lstat (not stat) to ensure the queue path is a directory and not a symlink.
  • Enforce ownership and permissions (at minimum, refuse group/other writable dirs).
  1. Avoid following symlinks for queue entries
  • Use readdir(..., { withFileTypes: true }) and skip dirent.isSymbolicLink() / non-files.
  1. Create temp files safely
  • Use fs.open with exclusive creation ('wx') and (where supported) O_NOFOLLOW, then writeFile via the returned fd.

Example hardening sketch:

import fs from "node:fs";

async function assertSafeDir(dir: string) {
  const st = await fs.promises.lstat(dir).catch((e) => {
    if (e && typeof e === "object" && "code" in e && (e as any).code === "ENOENT") return null;
    throw e;
  });
  if (st) {
    if (!st.isDirectory() || st.isSymbolicLink()) throw new Error(`Unsafe queue dir: ${dir}`);
    if (typeof st.mode === "number" && (st.mode & 0o022) !== 0) throw new Error(`Queue dir is writable by group/other: ${dir}`);
  }
}

async function ensureQueueDir(queueDir: string): Promise<void> {
  await fs.promises.mkdir(queueDir, { recursive: true, mode: 0o700 });
  await assertSafeDir(queueDir);
  await fs.promises.chmod(queueDir, 0o700).catch(() => {});
}

Also consider documenting that OPENCLAW_STATE_DIR must not point to shared/world-writable locations when running as a privileged user.


Analyzed PR: #40056 at commit ffb1339

Last updated on: 2026-03-10T14:16:26Z

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 59d25b30ff

ℹ️ 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".

Comment thread src/infra/webhook-queue.ts Resolved
Comment thread src/infra/webhook-queue.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7a10ea2956

ℹ️ 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".

Comment thread src/telegram/bot.ts Resolved
@Diaspar4u

Copy link
Copy Markdown
Contributor Author

Security-model assessment per SECURITY.md: OpenClaw runs as a trusted-operator gateway, not an adversarial multi-tenant service. The operator controls the filesystem, config, and state directory.

  • Symlink/TOCTOU arbitrary file overwrite via temp file in webhook queue: Exploitability requires write access to STATE_DIR, which is trusted operator state. SECURITY.md Out of Scope: "Reports that require write access to trusted local state (~/.openclaw, workspace files)." The operator already has full host access.

  • Unbounded on-disk webhook queue exhaustion: Telegram webhook payloads arrive only from Telegram's servers (validated via webhook secret). Volume is bounded by Telegram's own rate limits to the bot. Legitimate message volume from authorized users is trusted-operator traffic, not adversarial. Defense-in-depth TTL cleanup already runs at startup.

  • Unauthenticated request body parsing before webhook secret validation: The webhook endpoint is bound to loopback by default (gateway.bind="loopback"). Non-loopback exposure is explicitly out of scope per SECURITY.md ("Public Internet Exposure"). The 1MB limit and 30s timeout already bound resource usage. Moving the header check before body parsing is a minor optimization, not a security boundary issue.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f4efe448d4

ℹ️ 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".


// Sort oldest first; break timestamp ties deterministically by deduplicationId.
entries.sort(
(a, b) => a.enqueuedAt - b.enqueuedAt || a.deduplicationId.localeCompare(b.deduplicationId),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve numeric update order for replay tie-breaks

In replayPendingWebhooks, tie-breaking with localeCompare reorders numeric Telegram update_ids lexicographically (for example, "100" sorts before "99"), so updates enqueued in the same millisecond can replay out of chronological order. Because deduplicationId is populated from String(update_id), this can happen during burst traffic and cause message handling state to be reconstructed in the wrong sequence after restart.

Useful? React with 👍 / 👎.

@Diaspar4u
Diaspar4u force-pushed the feat/webhook-queue branch from f4efe44 to ffb1339 Compare March 10, 2026 13:31
@Diaspar4u

Copy link
Copy Markdown
Contributor Author

Closing to resubmit with a clean commit history and updated PR description. New PR incoming from the same branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Inbound Telegram webhook payloads lost on gateway restart

1 participant