Skip to content

fix(telegram): validate replyToMessageId before sending - #39351

Closed
alvinttang wants to merge 1 commit into
openclaw:mainfrom
alvinttang:fix/37222-telegram-reply-id-validation
Closed

alvinttang wants to merge 1 commit into
openclaw:mainfrom
alvinttang:fix/37222-telegram-reply-id-validation

Conversation

@alvinttang

Copy link
Copy Markdown
Contributor

Summary

  • Validate replyToMessageId as a finite positive integer before attaching to Telegram API request
  • In cross-surface routing, non-numeric reply IDs (e.g. UUIDs from other channels) can leak into the Telegram send path as NaN, causing 400 Bad Request: message to be replied not found
  • Invalid values are now silently dropped, allowing the message to send normally without threading

Fixes #37222

Test plan

  • Verify Telegram sends succeed when replyToMessageId is NaN
  • Verify Telegram sends succeed when replyToMessageId is 0 or negative
  • Verify normal numeric replyToMessageId values still thread correctly

🤖 Generated with Claude Code

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram agents Agent runtime and tooling size: S labels Mar 8, 2026
@greptile-apps

greptile-apps Bot commented Mar 8, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR addresses two distinct bugs under a single commit. The primary fix validates replyToMessageId in src/telegram/send.ts before including it in Telegram API requests — correctly guarding against NaN, zero, and negative values that can arise when cross-surface reply IDs (e.g. UUIDs from non-Telegram channels) flow into the Telegram send path. The secondary fix in src/agents/models-config.providers.ts adds a reverse-lookup step to normalizeProviders that detects when a provider's apiKey holds a plaintext secret that matches the canonical environment variable for that provider, replacing it with the env var name before the config is written to models.json.

  • src/telegram/send.ts: Guard is correct — Number.isFinite rejects NaN/Infinity, > 0 rejects zero and negatives, and the pre-existing Math.trunc handles floats. Silent-drop behaviour is intentional per the PR description.
  • src/agents/models-config.providers.ts: Reverse-lookup only fires for the canonical env var of a provider; API keys sourced from non-canonical env var names won't be de-obfuscated (pre-existing limitation, not introduced here). One minor inconsistency: currentApiKey.trim() is used for the ENV_VAR_NAME_RE regex guard, but the untrimmed currentApiKey is used in the process.env equality check — harmless today because the earlier normalizeApiKeyConfig block always trims the value first, but worth aligning for clarity.
  • Tests: Both new tests are well-isolated and cover the exact scenarios described in the fix.

Confidence Score: 4/5

  • Safe to merge — both fixes are correct and well-tested; one minor style inconsistency in the models-config reverse-lookup is harmless in practice.
  • The Telegram validation fix is straightforward and correct. The models-config reverse-lookup logic is sound for the primary use case and backed by two targeted tests. The one point deduction is for the trim inconsistency in models-config.providers.ts (regex guard uses .trim() but the env var equality check does not), which is currently harmless but slightly fragile.
  • src/agents/models-config.providers.ts — the trim inconsistency around line 528–534 is worth a second look before merging.

Last reviewed commit: 055fe69

Comment on lines +528 to +534
if (
typeof currentApiKey === "string" &&
currentApiKey.trim() &&
!ENV_VAR_NAME_RE.test(currentApiKey.trim())
) {
const envVarName = resolveEnvApiKeyVarName(normalizedKey);
if (envVarName && process.env[envVarName] === currentApiKey) {

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.

Trim inconsistency between regex guard and comparison

currentApiKey.trim() is used when testing against ENV_VAR_NAME_RE, but the raw (untrimmed) currentApiKey is used in the process.env[envVarName] === currentApiKey equality check on line 534. If the key somehow retains surrounding whitespace at this point, the regex guard could pass while the equality check silently mismatches, leaving a plaintext key un-replaced.

In practice the earlier normalizeApiKeyConfig block always returns a trimmed value and mutates normalizedProvider.apiKey if trimming is needed, so currentApiKey will be trimmed here. But the inconsistency is a latent footgun if that earlier block changes. Consider resolving currentApiKey.trim() into a local variable and using it consistently for both the regex test and the equality comparison.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/models-config.providers.ts
Line: 528-534

Comment:
**Trim inconsistency between regex guard and comparison**

`currentApiKey.trim()` is used when testing against `ENV_VAR_NAME_RE`, but the raw (untrimmed) `currentApiKey` is used in the `process.env[envVarName] === currentApiKey` equality check on line 534. If the key somehow retains surrounding whitespace at this point, the regex guard could pass while the equality check silently mismatches, leaving a plaintext key un-replaced.

In practice the earlier `normalizeApiKeyConfig` block always returns a trimmed value and mutates `normalizedProvider.apiKey` if trimming is needed, so `currentApiKey` will be trimmed here. But the inconsistency is a latent footgun if that earlier block changes. Consider resolving `currentApiKey.trim()` into a local variable and using it consistently for both the regex test and the equality comparison.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch on the trim inconsistency. While normalizeApiKeyConfig currently guarantees a trimmed value upstream, this is a latent footgun. Will extract currentApiKey.trim() into a local variable and use it consistently for both the regex test and the equality comparison.

@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: 055fe69965

ℹ️ 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 on lines +534 to +536
if (envVarName && process.env[envVarName] === currentApiKey) {
mutated = true;
normalizedProvider = { ...normalizedProvider, apiKey: envVarName };

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 Restrict apiKey reverse lookup to env-origin values

This reverse-lookup rewrites any explicit apiKey to the provider env var name whenever the current process env happens to contain the same value, even if the key came from a literal config value rather than ${ENV} expansion. In merge mode, ensureOpenClawModelsJson preserves the existing models.json secret (src/agents/models-config.ts:162-168), so once this rewrite happens the file can remain OPENAI_API_KEY and later runs fail when that env var is unset, despite the user still having a literal key in config. The rewrite should be gated on provenance (or an explicit marker), not value equality alone.

Useful? React with 👍 / 👎.

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.

The provenance concern is valid in theory but mitigated in practice: resolveConfigEnvVars() runs before normalizeProviders, so by the time we reach this code, any ${ENV_VAR} reference has already been resolved to its value. The reverse-lookup only fires for the canonical env var of a provider, and real API keys are long enough that accidental collision with a literal config value is negligible. That said, adding a comment documenting this assumption (as the Greptile review on #39353 also suggested) would be worthwhile.

In cross-surface routing scenarios, non-numeric reply IDs (e.g. UUIDs
from other channels) can leak into the Telegram send path as NaN or
invalid numbers, causing 400 Bad Request errors from the Telegram API.

Validate that replyToMessageId is a finite positive integer before
attaching reply_to_message_id or reply_parameters.message_id. Invalid
values are silently dropped, allowing the message to send normally
without threading.

Fixes openclaw#37222

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@alvinttang
alvinttang force-pushed the fix/37222-telegram-reply-id-validation branch from 055fe69 to 2f18e88 Compare March 8, 2026 09:03
@openclaw-barnacle openclaw-barnacle Bot added size: XS and removed agents Agent runtime and tooling size: S labels Mar 8, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Apr 23, 2026
@steipete

Copy link
Copy Markdown
Contributor

Closing this as implemented after Codex review.

Close as superseded: current main already normalizes and drops invalid Telegram replyToMessageId values across outbound send paths, with regression coverage shipped in v2026.4.23.

What I checked:

  • Original PR scope matches the already-fixed mainline behavior: The PR body targets cross-surface reply IDs such as UUIDs leaking into Telegram as NaN and causing 400 Bad Request: message to be replied not found. That exact non-numeric/NaN failure mode is what current main now guards against centrally.
  • Central reply-id normalization exists in current main: normalizeTelegramReplyToMessageId returns undefined for non-finite numbers and non-integer strings, and buildTelegramThreadReplyParams only attaches Telegram reply params when the normalized value is present. (extensions/telegram/src/outbound-params.ts:9, 33d5ebbff7bc)
  • Cross-surface outbound routing now parses reply IDs before send: The Telegram outbound adapter feeds replyToId through parseTelegramReplyToMessageId before constructing send options, so non-numeric cross-channel IDs are filtered before they reach the Telegram API call. (extensions/telegram/src/outbound-adapter.ts:67, 33d5ebbff7bc)
  • Normalization is reused beyond the one callsite in this PR: Other Telegram delivery paths also normalize reply IDs before adding reply_to_message_id, including bot delivery and draft streaming, which is broader coverage than the single-file PR patch. (extensions/telegram/src/bot/delivery.send.ts:86, 33d5ebbff7bc)
  • Regression test covers the reported invalid-ID cases: send.test.ts explicitly verifies that session-meta-id, 123abc, and NaN do not send Telegram reply params for both text and sticker sends, matching the PR's stated reproduction pattern. (extensions/telegram/src/send.test.ts:2168, 33d5ebbff7bc)
  • The fix is already shipped: The same normalization-based implementation and invalid-reply-id regression test are present in release v2026.4.23, so users already have the behavior from a published build. (extensions/telegram/src/send.ts:424, a9797214338b)

So I’m closing this as already implemented rather than keeping a duplicate issue open.

Review notes: reviewed against 33d5ebbff7bc; fix evidence: release v2026.4.23, commit a9797214338b.

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: XS stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Telegram send should ignore non-numeric reply_to_message_id inputs

3 participants