Skip to content

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

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

Copy link
Copy Markdown
Contributor

Summary

  • Problem: In webhook mode the gateway ACKs Telegram's delivery with 200 before processing completes. If the gateway restarts between the ACK and completion the message is permanently lost -- Telegram considers it delivered and will not retry.
  • Why it matters: Users send messages that silently vanish during routine restarts (config change, update, RPC). The window is small but non-zero, and on busy gateways it causes visible message loss.
  • What changed: Disk-backed webhook queue with atomic writes (write-tmp-then-rename). Updates are enqueued before processing and dequeued only after all deferred work (media group assembly, text fragment buffering, inbound debouncing) settles. On startup, pending entries are replayed in enqueue-time order through the normal Grammy middleware pipeline. Compound channelId+deduplicationId dedup key prevents cross-channel collisions. channelId validation rejects malformed entries. Filenames use safeFileKey sanitization (matching the existing pairing-store.ts pattern) to prevent path traversal.
  • What did NOT change: Grammy middleware pipeline ordering, existing Telegram bot lifecycle, non-Telegram webhook paths. The queue is purely additive -- if disk writes fail, processing continues as before.

Design notes

The queue provides at-least-once delivery. Failed updates stay on disk for replay (cleaned up after 1h TTL). This is intentional and documented in code -- idempotency of the downstream handlers already handles duplicates.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

User-visible / Behavior Changes

Messages received during a gateway restart window are now replayed on next startup instead of being silently dropped. No new config required -- the queue directory (webhook-queue/ inside the state dir) is created automatically.

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No -- webhook payloads already pass through the same middleware; disk persistence adds no new data access
  • Path traversal: safeFileKey() strips /\:*?"<>| and .. from channel/dedup IDs before constructing filenames. Queue directory created with mode 0o700, files with 0o600. Tested explicitly (see path traversal test).

Repro + Verification

Environment

  • OS: macOS / Linux
  • Runtime/container: Node 22+
  • Model/provider: N/A (transport layer)
  • Integration/channel: Telegram (webhook mode)
  • Relevant config: default Telegram webhook config

Steps

  1. Start gateway with Telegram webhook channel
  2. Send a message via Telegram
  3. Immediately restart the gateway (kill -9 or openclaw gateway restart)
  4. Wait for gateway to come back up

Expected

  • Message is replayed on startup and reaches the agent

Actual (before this PR)

  • Message is lost permanently

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets

16 unit tests (src/infra/webhook-queue.test.ts): enqueue/dequeue round-trip, replay ordering, dedup by compound key, TTL cleanup, orphan .tmp cleanup, malformed entry handling, path traversal containment, cross-channel preservation, channelId validation, deterministic tie-breaking, 50-entry bulk replay.

1 integration test (src/telegram/webhook.test.ts): end-to-end enqueue on webhook receipt -> dequeue on onUpdateProcessed callback.

pnpm build, pnpm check, pnpm test green.

Human Verification (required)

  • Verified scenarios: gateway restart during active message processing; queue file appears on disk after webhook receipt; file removed after processing; replayed messages arrive at agent on restart
  • Edge cases checked: media group spanning restart (deferred resolvers prevent premature dequeue), text fragment buffer flush, concurrent updates, path traversal attempts
  • What I did not verify: non-Telegram webhook channels (no queue integration for those yet), extremely high-volume replay (>1000 queued entries)

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No -- queue directory is created on first webhook receipt

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: revert this commit; queue directory can be safely deleted (rm -rf <stateDir>/webhook-queue)
  • Files/config to restore: none
  • Known bad symptoms: duplicate messages on startup (at-least-once semantics -- existing handler idempotency covers this), disk space growth (1h TTL cleanup prevents unbounded growth)

Risks and Mitigations

  • Risk: Disk write latency adds to webhook response time
    • Mitigation: Single atomic write (write-tmp + rename) per update; queue failures are caught and do not block processing
  • Risk: Stale entries accumulate after unclean shutdown
    • Mitigation: 1h TTL cleanup during replay; orphaned .tmp files cleaned up on replay scan

This PR was developed with AI assistance (Claude). All code was reviewed, tested, and verified by a human contributor.

Disk-backed webhook queue with atomic writes (tmp+rename), deferred
dequeue for media groups and text fragments, and ordered replay on
startup. Dedup key scoped to channelId+deduplicationId to prevent
cross-channel collisions. Validate channelId in replay (clean up
malformed entries). At-least-once delivery guarantee.
@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 Unbounded deferred-work await can hang Telegram update completion (debouncer never flushes)
2 🟡 Medium Pre-auth request body parsing enables unauthenticated resource-consumption DoS on Telegram webhook
3 🔵 Low Insecure temporary file write in disk-backed webhook queue enables symlink/hardlink overwrite (local attacker)

1. 🟠 Unbounded deferred-work await can hang Telegram update completion (debouncer never flushes)

Property Value
Severity High
CWE CWE-400
Location src/telegram/bot.ts:223-255

Description

The new deferred-work tracking waits for all registered promises to settle before calling onUpdateProcessed (used to dequeue persisted webhook payloads). This can be exploited to hang update completion indefinitely and cause unbounded memory/disk growth.

Key points:

  • Each inbound message registers a deferred promise tied to its update_id before being enqueued into the inbound debouncer.
  • The debouncer only flushes after a period of inactivity; if an attacker continuously sends messages within the debounce window for the same debounceKey, the flush timer is perpetually reset and never fires.
  • As a result, the deferred promise never resolves, and the middleware in bot.ts blocks forever on await Promise.all(deferred), so:
    • opts.onUpdateProcessed never runs => webhook-queue entries are never dequeued (persisted JSON files accumulate until TTL cleanup)
    • the in-flight middleware stack (and pendingUpdateIds watermark tracking) accumulates => memory/resource exhaustion

Vulnerable code (awaiting deferred work without timeout/cap):

const deferred = deferredWork.get(updateId);
if (deferred) {
  deferredWork.delete(updateId);
  await Promise.all(deferred);
}
opts.onUpdateProcessed?.(updateId);

This is a denial-of-service risk because remote Telegram users can keep a conversation “hot” (never idle) and prevent the debounce from flushing, indefinitely postponing update completion and queue dequeue.

Recommendation

Add hard limits so deferred-work cannot block indefinitely, and ensure debounced buffers eventually flush.

Suggested hardening (do both):

  1. Bound debouncer lifetime/size (prevents never-flush): add max wait and max buffered items per key.
​// in createInboundDebouncer
const MAX_WAIT_MS = 2000;      // example
const MAX_ITEMS = 50;          // example
​// store firstEnqueuedAt, and when scheduling, cap delay so flush happens by MAX_WAIT_MS
​// also flush immediately when items.length exceeds MAX_ITEMS
  1. Timeout deferred-work awaiting in the bot middleware, so webhook processing can complete even if a deferred task hangs:
const MAX_DEFERRED_WAIT_MS = 5000;
if (deferred?.length) {
  await Promise.race([
    Promise.allSettled(deferred),
    new Promise<void>((r) => setTimeout(r, MAX_DEFERRED_WAIT_MS)),
  ]);
}

If you must preserve replay semantics, consider:

  • not dequeuing on timeout (keep entry on disk), but still avoid holding the middleware forever
  • logging/metrics when deferred timeouts occur and/or forcing a debouncer flush for that key.

2. 🟡 Pre-auth request body parsing enables unauthenticated resource-consumption DoS on Telegram webhook

Property Value
Severity Medium
CWE CWE-400
Location src/telegram/webhook.ts:179-227

Description

The Telegram webhook handler fully reads and parses the request body (up to 1MB with a 30s timeout) before validating the x-telegram-bot-api-secret-token header.

This allows unauthenticated callers to:

  • Open many connections and stream up to TELEGRAM_WEBHOOK_MAX_BODY_BYTES per request
  • Hold connections open until TELEGRAM_WEBHOOK_BODY_TIMEOUT_MS elapses
  • Force CPU/memory work (buffering + JSON.parse) even though the request will later be rejected as unauthorized

Vulnerable flow:

  • Input: HTTP request body from any caller
  • Work/Sink: readJsonBodyWithLimit() buffers + parses JSON
  • Auth check happens later: if (secretHeader !== secret) unauthorized()

Vulnerable code:

const body = await readJsonBodyWithLimit(req, { maxBytes: 1024 * 1024, timeoutMs: 30_000, emptyObjectOnEmpty: false });
...
const secretHeaderRaw = req.headers["x-telegram-bot-api-secret-token"];
const secretHeader = Array.isArray(secretHeaderRaw) ? secretHeaderRaw[0] : secretHeaderRaw;
if (secretHeader !== secret) {
  await unauthorized();
  return;
}

Recommendation

Validate the secret header before reading/parsing the request body, and abort the connection early for unauthorized requests.

Example fix:

const secretHeaderRaw = req.headers["x-telegram-bot-api-secret-token"];
const secretHeader = Array.isArray(secretHeaderRaw) ? secretHeaderRaw[0] : secretHeaderRaw;

if (secretHeader !== secret) {
  ​// Stop reading any additional bytes from the client
  respondText(401, "unauthorized");
  req.destroy();
  return;
}

const body = await readJsonBodyWithLimit(req, {
  maxBytes: TELEGRAM_WEBHOOK_MAX_BODY_BYTES,
  timeoutMs: TELEGRAM_WEBHOOK_BODY_TIMEOUT_MS,
  emptyObjectOnEmpty: false,
});

Optionally also add per-IP rate limiting at the reverse proxy/load balancer and consider lowering timeoutMs to reduce slow-stream exhaustion.


3. 🔵 Insecure temporary file write in disk-backed webhook queue enables symlink/hardlink overwrite (local attacker)

Property Value
Severity Low
CWE CWE-377
Location src/infra/webhook-queue.ts:51-54

Description

The new disk-backed webhook queue writes to a predictable temporary file path using fs.promises.writeFile without exclusivity or symlink protections.

If an attacker can create files inside the queue directory (e.g., due to misconfigured state-dir/queue-dir permissions, group-writable deployments, or the queue directory being replaced with/inside a symlink), they can pre-create ${filePath}.${pid}.tmp as a symlink/hardlink to an arbitrary target. The subsequent writeFile() will follow the link and truncate/overwrite the target file with attacker-controlled JSON.

Key properties that make this exploitable in such scenarios:

  • Predictable temp filename: ${filePath}.${process.pid}.tmp
  • Non-exclusive create: writeFile() defaults to flag 'w' (truncate/overwrite)
  • No checks that queueDir is a real directory (not a symlink) and no permission fix-up when it already exists (mkdir({ recursive: true, mode }) does not chmod existing directories)

Vulnerable code:

const tmp = `${filePath}.${process.pid}.tmp`;
await fs.promises.writeFile(tmp, JSON.stringify(entry), { encoding: "utf-8", mode: 0o600 });
await fs.promises.rename(tmp, filePath);

Recommendation

Harden the queue directory and temp-file creation:

  1. Verify queueDir is not a symlink (and ideally owned by the current user) and enforce permissions on POSIX when the directory already exists.
  2. Use an unpredictable temp filename and exclusive create to prevent pre-creation attacks.
  3. Where supported, avoid following symlinks when creating the temp file.

Example (POSIX-focused):

import crypto from "node:crypto";
import { constants as C } from "node:fs";

await fs.promises.mkdir(queueDir, { recursive: true, mode: 0o700 });
const st = await fs.promises.lstat(queueDir);
if (!st.isDirectory() || st.isSymbolicLink()) {
  throw new Error("webhook queue dir is not a real directory");
}
​// Best-effort tighten perms if it already existed (POSIX)
await fs.promises.chmod(queueDir, 0o700).catch(() => {});

const filePath = path.join(queueDir, entryFilename(channelId, deduplicationId));
const tmp = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp`;

const flags = C.O_WRONLY | C.O_CREAT | C.O_EXCL | (C.O_NOFOLLOW ?? 0);
const fh = await fs.promises.open(tmp, flags, 0o600);
try {
  await fh.writeFile(JSON.stringify(entry), { encoding: "utf-8" });
} finally {
  await fh.close();
}
await fs.promises.rename(tmp, filePath);

This prevents an attacker from planting a link at the temp path and reduces race risk even if directory permissions are not as strict as expected.


Analyzed PR: #42523 at commit 31ddd25

Last updated on: 2026-03-10T22:20:31Z

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: L labels Mar 10, 2026

@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: 31ddd254d0

ℹ️ 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
Comment on lines +130 to +133
for (const entry of pending) {
try {
await bot.handleUpdate(entry.payload as Parameters<typeof bot.handleUpdate>[0]);
// Dequeue happens via onUpdateProcessed in the bot middleware on success.

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.

P1 Badge Replay pending webhooks without per-update awaiting

The replay loop currently awaits each bot.handleUpdate before feeding the next queued update, which serializes recovery in a way that breaks cross-update buffering logic. For updates that rely on deferred coalescing (media groups, long-text fragment assembly, inbound debounce), the first replayed update waits for its timer-based flush before the second update is even injected, so grouped updates are processed separately after restart instead of being combined. This causes behavior drift exactly in the restart-recovery path this queue is intended to preserve.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Mar 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces a disk-backed webhook queue to provide Telegram webhook messages with at-least-once delivery semantics across gateway restarts. The design is well-thought-out: atomic write-then-rename ensures no partial files on disk, the 1-hour TTL prevents unbounded accumulation, deferred-work tracking ensures onUpdateProcessed fires only after buffered handlers (media groups, text fragments, inbound debounce) fully settle, and path traversal is mitigated by safeFileKey sanitization.

Two issues warrant attention:

  1. Filename collision risk (src/infra/webhook-queue.ts line 25–27): entryFilename separates the sanitized channelId and deduplicationId with a single _, but safeFileKey preserves underscores already present in either part. Two distinct (channelId, deduplicationId) pairs can therefore resolve to the same filename. This is safe today because Telegram update IDs are always integers (no underscores), but becomes a real collision risk if accountId values contain underscores (e.g., "my_account") or if the queue is reused for other integrations with non-numeric dedup IDs. Using a two-underscore separator (__) — which safeFileKey never produces on its own — would eliminate the ambiguity.

  2. console.warn in replayPendingWebhooks (src/infra/webhook-queue.ts line 98): The queue library uses a bare console.warn for directory-read failures instead of the application's runtime.log infrastructure, bypassing custom log routing used elsewhere in the codebase.

The deferred-work resolver pattern in bot-handlers.ts is implemented carefully: all three buffering paths resolve their promises in try/finally blocks.

Confidence Score: 3/5

  • Safe to merge after addressing the filename collision issue; the logging inconsistency is a style improvement.
  • The feature is well-designed and test coverage is thorough. The primary concern is the entryFilename collision: two distinct (channelId, deduplicationId) pairs can silently map to the same on-disk file when the sanitized channelId contains underscores (realistic if accountId contains underscores). In the current Telegram-only use case the deduplication ID is always a numeric string so no collision can occur today, but the latent risk warrants a fix before the queue is extended to other integrations. The console.warn issue is a style/consistency concern that does not affect correctness.
  • src/infra/webhook-queue.ts — specifically the entryFilename and safeFileKey functions for the collision risk, and line 98 for the logging path.

Last reviewed commit: 31ddd25

Comment on lines +25 to +27
function entryFilename(channelId: string, deduplicationId: string): string {
return `${safeFileKey(channelId)}_${safeFileKey(deduplicationId)}.json`;
}

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.

Filename collision risk when channelId or deduplicationId contains underscores

entryFilename joins the sanitized channelId and deduplicationId with a single _ separator, but safeFileKey preserves underscores already present in either part. This means two distinct (channelId, deduplicationId) pairs can resolve to the same filename.

Example: if accountId = "my_account" then channelId = "telegram_my_account". Pairing it with a Telegram deduplicationId like "100" produces telegram_my_account_100.json. But a future integration using a non-numeric deduplicationId (e.g., ("telegram", "my_account_100")) would produce the same filename, causing one entry to silently overwrite the other.

A safer separator that cannot appear after sanitization would eliminate the ambiguity — for example, two underscores (__), since safeFileKey never produces consecutive underscores:

Suggested change
function entryFilename(channelId: string, deduplicationId: string): string {
return `${safeFileKey(channelId)}_${safeFileKey(deduplicationId)}.json`;
}
function entryFilename(channelId: string, deduplicationId: string): string {
return `${safeFileKey(channelId)}__${safeFileKey(deduplicationId)}.json`;
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/webhook-queue.ts
Line: 25-27

Comment:
**Filename collision risk when channelId or deduplicationId contains underscores**

`entryFilename` joins the sanitized channelId and deduplicationId with a single `_` separator, but `safeFileKey` preserves underscores already present in either part. This means two distinct `(channelId, deduplicationId)` pairs can resolve to the same filename.

Example: if `accountId = "my_account"` then `channelId = "telegram_my_account"`. Pairing it with a Telegram deduplicationId like `"100"` produces `telegram_my_account_100.json`. But a future integration using a non-numeric deduplicationId (e.g., `("telegram", "my_account_100")`) would produce the same filename, causing one entry to silently overwrite the other.

A safer separator that cannot appear after sanitization would eliminate the ambiguity — for example, two underscores (`__`), since `safeFileKey` never produces consecutive underscores:

```suggestion
function entryFilename(channelId: string, deduplicationId: string): string {
  return `${safeFileKey(channelId)}__${safeFileKey(deduplicationId)}.json`;
}
```

How can I resolve this? If you propose a fix, please make it concise.

"code" in err &&
(err as { code?: string }).code !== "ENOENT"
) {
console.warn("[webhook-queue] failed to read queue directory:", err);

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.

Uses console.warn instead of the application's logger

The error path in replayPendingWebhooks bypasses the application's logging infrastructure with a bare console.warn. The rest of the codebase routes diagnostics through runtime.log?.(), which allows callers to redirect output to their chosen sink and keeps log formatting consistent.

Since replayPendingWebhooks is called from startTelegramWebhook where runtime is available, consider accepting an optional logging callback and using it as the primary path:

Suggested change
console.warn("[webhook-queue] failed to read queue directory:", err);
export async function replayPendingWebhooks(
channelId?: string,
stateDir?: string,
onWarn?: (msg: string) => void,
): Promise<WebhookQueueEntry[]> {
// ...
} catch (err) {
if (
err &&
typeof err === "object" &&
"code" in err &&
(err as { code?: string }).code !== "ENOENT"
) {
(onWarn ?? console.warn)("[webhook-queue] failed to read queue directory:", err);
}
return [];
}

Then pass runtime.log from the caller.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/webhook-queue.ts
Line: 98

Comment:
**Uses `console.warn` instead of the application's logger**

The error path in `replayPendingWebhooks` bypasses the application's logging infrastructure with a bare `console.warn`. The rest of the codebase routes diagnostics through `runtime.log?.()`, which allows callers to redirect output to their chosen sink and keeps log formatting consistent.

Since `replayPendingWebhooks` is called from `startTelegramWebhook` where `runtime` is available, consider accepting an optional logging callback and using it as the primary path:

```suggestion
export async function replayPendingWebhooks(
  channelId?: string,
  stateDir?: string,
  onWarn?: (msg: string) => void,
): Promise<WebhookQueueEntry[]> {
  // ...
  } catch (err) {
    if (
      err &&
      typeof err === "object" &&
      "code" in err &&
      (err as { code?: string }).code !== "ENOENT"
    ) {
      (onWarn ?? console.warn)("[webhook-queue] failed to read queue directory:", err);
    }
    return [];
  }
```

Then pass `runtime.log` from the caller.

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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