Skip to content

fix(webhooks): Telegram fail-closed verification + atomic update_id dedup - #1422

Merged
lilyshen0722 merged 1 commit into
mainfrom
fix/telegram-webhook-dedup-ack
Sep 1, 2026
Merged

lilyshen0722 merged 1 commit into
mainfrom
fix/telegram-webhook-dedup-ack

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

What

First build from the ruled connector-hardening list (2026-08-31 connector engineering patterns study — gaps 2 "no webhook dedup" and 4 "fail-open verification"):

  1. Fail-closed secret verification. Previously a missing TELEGRAM_SECRET_TOKEN meant every webhook post was accepted unverified. Now missing config rejects (401) unless TELEGRAM_WEBHOOK_ALLOW_UNVERIFIED=true is set explicitly (dev/test escape hatch; warn-once logged either way).
  2. Atomic update_id dedup via a new WebhookDelivery model — unique {provider, deliveryId} index + TTL (10 min, matching Telegram's redelivery window). Contract is claim-before-run, forget-on-error:
    • duplicate redelivery → ack 200 immediately, no duplicate pod message / agent wake
    • processing throws after the claim → claim is released before the 500, so Telegram's redelivery is a retry rather than a swallowed drop
    • dedup-store outage → degrades to unclaimed processing (the bridge stays up; a rare duplicate beats an outage)

Deploy note (read before merging to a live-bridge env)

Set TELEGRAM_SECRET_TOKEN and re-register the webhook via setWebhook with secret_token before deploying — otherwise the fail-closed check will reject Telegram's (headerless) deliveries. For envs without a secret, set TELEGRAM_WEBHOOK_ALLOW_UNVERIFIED=true deliberately.

Tests

telegram.webhook.test.js: 15/15 passing (5 new: reject-when-unset, accept-correct-secret, duplicate-acks-200-without-processing, claim-released-on-throw, store-outage-doesn't-take-bridge-down).

🤖 Generated with Claude Code

https://claude.ai/code/session_01X8MxGhdgPini3Q14ay2vXS

…edup

First build from the ruled connector-hardening list (research/connector
engineering patterns study, gaps 2 and 4):

- Fail-closed secret verification: a missing TELEGRAM_SECRET_TOKEN now
  rejects webhook posts instead of accepting everything. Dev/test opt-out
  via TELEGRAM_WEBHOOK_ALLOW_UNVERIFIED=true (warn-once logged).
- Atomic update_id dedup via new WebhookDelivery model (unique
  {provider, deliveryId} index + TTL): claim-before-run, duplicate
  redeliveries ack 200 without reprocessing, and a processing throw
  releases the claim so Telegram's redelivery is a retry, not a drop.
- Store outage degrades to unclaimed processing (bridge stays up).

Deploy note: before deploying to any env with a live Telegram bridge,
set TELEGRAM_SECRET_TOKEN and re-register the webhook via setWebhook
with secret_token, or set TELEGRAM_WEBHOOK_ALLOW_UNVERIFIED=true.

Tests: 15/15 in telegram.webhook.test.js (5 new).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01X8MxGhdgPini3Q14ay2vXS

@lilyshen0722 lilyshen0722 left a comment

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.

Sprint Review gate — ❌ BLOCK at e794b1fc

The design is right and the pinning is unusually good — 8 of 8 mutations to the substantive claim/release paths are killed. One defect blocks, on the single line in this handler that isn't awaited, and it recreates the exact failure the release contract exists to prevent.


Blocking — return events(req, res) escapes the catch, so the claim is never released

backend/routes/webhooks/telegram.ts, last statement of the try:

return events(req, res);      // ← the only un-awaited return of 14 in this block

Every other exit in that block is await handleX(...); return res.sendStatus(200). This one returns the promise.

Four links, each measured rather than reasoned:

  1. events is async and can reject. backend/integrations/providers/telegramProvider.ts:111 declares events: async (req, res) => {...} and :126 does await Integration.findByIdAndUpdate(...) — a Mongo write.
  2. return promise inside try does not reach that catch. Verified in isolation on node 22:
    try { return boom(); } catch {...} → ESCAPED; try { return await boom(); } catch {...} → CAUGHT.
  3. Nothing downstream catches it. express is 4.21.2, which does not handle a rejected promise from an async handler, and there is no express-async-errors and no asyncHandler wrapper anywhere in backend/.
  4. So the claim survives and the update is lost. No response is sent → Telegram times out → redelivers → claimDelivery returns 'duplicate' → res.sendStatus(200) → the update is acked and dropped, permanently.

That is a new hazard, not a pre-existing one: before this PR the redelivery would simply have been reprocessed. The forget-on-error contract in models/WebhookDelivery.ts — "the claim must not survive to swallow that retry" — is violated on the buffer path specifically.

Fix is one word: return await events(req, res);. I applied it and re-ran: 15/15 still green.

Why the suite cannot see it, which is the more useful half. All three tests that reach this line stub the handler as const events = jest.fn((req, res) => res.sendStatus(200)) — synchronous, while the real one is async. The mock differs from the production shape in exactly the dimension the bug lives in, so the un-awaited return never has a rejection to leak. A test with jest.fn(async () => { throw ... }) asserting a released claim would pin it.


Mutation testing on the dedup claim/release paths — 8 killed, 2 survived

Method: mutate the diff in a worktree at the PR head, assert the anchor count actually moved (so a mutation that silently failed to apply cannot be scored as "the suite ignores it"), run, revert. Baseline 15/15.

Mutation Anchor Result
err.code === 11000 → return 'claimed' (dedup off) 1→0 killed (1 failed)
delete await releaseDelivery(updateId) 1→0 killed
duplicate no longer short-circuits 15→14 killed
return false → return true (fail-open again) 1→0 killed
ALLOW_UNVERIFIED === 'true' → !== 'true' 1→0 killed (13 failed)
deliveryId: String(updateId) → constant 1→0 killed
release targets provider: 'telegramX' 1→0 killed
store-outage returns 'duplicate' not 'claimed' 2→1 killed
delete the updateId !== undefined && !== null claim guard 2→1 SURVIVED
delete the same guard on the release side 2→1 SURVIVED

The two survivors are load-bearing, not decoration. With the claim guard gone, an update carrying no update_id claims the literal key 'undefined'; the first one takes it and every subsequent un-id'd update is acked and dropped until the TTL expires. Ten of the fifteen tests post exactly such an update, and all fifteen still pass. A future refactor deletes that condition as redundant and CI says nothing. One test — post two updates with no update_id, assert both are processed — pins it.


Deploy note: it is accurate, and its prerequisite is not met in our chart

You asked specifically whether it holds for our envs. It does not, yet.

  • TELEGRAM_SECRET_TOKEN appears nowhere under k8s/ — not in the api-keys ExternalSecret, not in any deployment env block, not in values-*. Same for TELEGRAM_WEBHOOK_ALLOW_UNVERIFIED.
  • TELEGRAM_BOT_TOKEN is wired: k8s/helm/commonly/templates/core/backend-deployment.yaml:334 ← api-keys key telegram-bot-token ← the GCP secret at templates/secrets/api-keys.yaml:175-177. So the bridge is provisioned, not dormant.

Merging and deploying this as-is therefore takes inbound Telegram to 401 on every update. The note says exactly that ("BEFORE shipping this to an env with a live bridge") — it is correct and it is a gate on the deploy, not on the merge. Concretely: add telegram-secret-token to the ExternalSecret and a TELEGRAM_SECRET_TOKEN env on the backend deployment, populate the GCP secret, setWebhook(secret_token=…), then deploy.

Disclosure on how I nearly got this backwards: my first sweep was git grep -i telegram -- k8s/ | head, and the skills-index JSON has 28 telegram hits that filled the window — I read "no deployment wiring" and was one step from reporting the bridge as not deployed, which would have inverted the recommendation. Re-run without head and excluding that file to reproduce.


Verified clean

  • The unique index will actually exist. The suite jest.mocks WebhookDelivery entirely, so the E11000 behaviour the whole design rests on is simulated, never exercised — that is worth knowing. But the assumption underneath it holds: autoIndex is not disabled anywhere in backend/ and mongoose.connect in config/db.ts passes no such option, so { provider: 1, deliveryId: 1 } unique is built on first model use.
  • TTL via index: { expires: 0 } on expiresAt is the right shape; Mongo's TTL monitor makes the effective window 10–11 min rather than exactly 10, which is fine for the stated purpose.
  • The fail-open on a dedup-store outage is deliberate, documented, and pinned by a test.

One scoping note, not blocking

The unique key is { provider: 'telegram', deliveryId }, and update_id is sequential per bot. The route header says "single bot, many chats", so this is correct today — but a second bot on the same route would collide id spaces and drop legitimate updates as duplicates. Worth a line in the model comment so the constraint is written down where the key is defined.


Fix the missing await and I'll re-gate immediately. The two surviving mutants and the deploy wiring can follow as their own changes if you'd rather not widen this one.

@lilyshen0722
lilyshen0722 merged commit cd49712 into main Sep 1, 2026
12 checks passed
@lilyshen0722
lilyshen0722 deleted the fix/telegram-webhook-dedup-ack branch September 1, 2026 11:01
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Gate findings addressed at HEAD: return await events(req, res) (with a comment on why), plus tests pinning both surviving mutants (async-rejecting handler releases the claim; no-update_id updates bypass the claim), plus the per-bot key-scope note in the model. Mutation-checked: removing the await hangs the new test (the exact production symptom). 17/17. Deploy wiring (ExternalSecret + env + setWebhook) will be a separate follow-up as suggested. @sprint-review ready for re-gate.

samxu01 pushed a commit that referenced this pull request Sep 1, 2026
… is released

#1422 merged at e794b1f with this outstanding. The last exit of the POST
handler's try block was the only un-awaited return of 14:

    return events(req, res);

`events` is async and awaits a Mongo write (telegramProvider.ts:111, :126), and
`return promise` inside a try does not reach that try's catch — only
`return await promise` does. express is 4.21.2 here with no express-async-errors
and no asyncHandler wrapper, so a rejection from the provider escapes the route
entirely: the forget-on-error release never runs, no response is sent, and
Telegram's redelivery is then acked 200 as a duplicate and dropped permanently.

That is the exact swallowed-drop the release contract exists to prevent — the
comment on the catch says so directly ("the claim must not survive to swallow
that retry") — and it is new behaviour, because before the dedup claim existed
the redelivery simply reprocessed.

The liveRelay branch immediately above already awaits its bridge call, so this
was the one escaping path.

The 15 shipped tests cannot see it: every test reaching this line stubs `events`
synchronously, while the real one is async. The added test stubs it async and
rejecting. Without the fix it times out — no response is ever sent, which is the
defect's own signature; with the fix, 16/16 pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Sep 1, 2026
…ion (#1444)

#1422 merged fail-closed webhook verification but the cluster had no
TELEGRAM_SECRET_TOKEN configured — the next deploy from main would have
401'd every Telegram delivery and killed the live bridge. This wires the
env from api-keys (ESO <- commonly-dev-telegram-secret-token, already
created in SM) ahead of that deploy. The webhook is already re-registered
with the matching secret_token; live pre-#1422 code ignores the header,
so ordering is downtime-free.


Claude-Session: https://claude.ai/code/session_01PTfziSyx2DzuwmibZHHY4s

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant