Repository navigation
fix(webhooks): Telegram fail-closed verification + atomic update_id dedup - #1422
Conversation
…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
left a comment
There was a problem hiding this comment.
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 blockEvery other exit in that block is await handleX(...); return res.sendStatus(200). This one returns the promise.
Four links, each measured rather than reasoned:
eventsis async and can reject.backend/integrations/providers/telegramProvider.ts:111declaresevents: async (req, res) => {...}and:126doesawait Integration.findByIdAndUpdate(...)— a Mongo write.return promiseinsidetrydoes not reach thatcatch. Verified in isolation on node 22:
try { return boom(); } catch {...}→ ESCAPED;try { return await boom(); } catch {...}→ CAUGHT.- 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-errorsand noasyncHandlerwrapper anywhere inbackend/. - So the claim survives and the update is lost. No response is sent → Telegram times out → redelivers →
claimDeliveryreturns'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_TOKENappears nowhere underk8s/— not in theapi-keysExternalSecret, not in any deployment env block, not invalues-*. Same forTELEGRAM_WEBHOOK_ALLOW_UNVERIFIED.TELEGRAM_BOT_TOKENis wired:k8s/helm/commonly/templates/core/backend-deployment.yaml:334←api-keyskeytelegram-bot-token← the GCP secret attemplates/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.mocksWebhookDeliveryentirely, so the E11000 behaviour the whole design rests on is simulated, never exercised — that is worth knowing. But the assumption underneath it holds:autoIndexis not disabled anywhere inbackend/andmongoose.connectinconfig/db.tspasses no such option, so{ provider: 1, deliveryId: 1 } uniqueis built on first model use. - TTL via
index: { expires: 0 }onexpiresAtis 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.
|
Gate findings addressed at HEAD: |
… 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]>
…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]>
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"):
TELEGRAM_SECRET_TOKENmeant every webhook post was accepted unverified. Now missing config rejects (401) unlessTELEGRAM_WEBHOOK_ALLOW_UNVERIFIED=trueis set explicitly (dev/test escape hatch; warn-once logged either way).update_iddedup via a newWebhookDeliverymodel — unique{provider, deliveryId}index + TTL (10 min, matching Telegram's redelivery window). Contract is claim-before-run, forget-on-error:Deploy note (read before merging to a live-bridge env)
Set
TELEGRAM_SECRET_TOKENand re-register the webhook viasetWebhookwithsecret_tokenbefore deploying — otherwise the fail-closed check will reject Telegram's (headerless) deliveries. For envs without a secret, setTELEGRAM_WEBHOOK_ALLOW_UNVERIFIED=truedeliberately.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