Repository navigation
[AI-3804] Twilio call webhook with pre-answer checks - #2433
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
[security R1] VERDICT: NO-GO (one Should fix, no Blocker)
Reviewed the new call hook, the shared answerCall, the Telnyx refactor and the signing helpers against the repo's security rules (go.md rules 5, 7 and 9, plus Coverage).
What holds: the signature is checked before any lookup, over ROUTER_PUBLIC_URL plus a constant path and never the Host header, compared in constant time. The account, direction and vendor-scoped number checks run in that order. The body is bounded. No x-client-accessible mark. No password in logs or errors. The Telnyx checks are unchanged. PostureSuite and the committed-spec test pass.
- [Should fix] S1.1
internal/api/twiliohook.go:54: no replay bound on a response that carries trunk credentials. See inline.
Author questions: 401 instead of 403 matches the other hooks and has no security effect. The missing sandbox row matches Telnyx; the sandbox work is in #2407. If TWILIO_ACCOUNT_SID is unset, every call is hung up.
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
[main R1] I reviewed 53666bd. It already contains the current main (0e5197a). There are 2 Should fix findings and no Blocker.
What I checked:
- Telnyx and the Twilio events hook behave as on base:
- The answers, the order of the checks and every log string are the same. I compared base
telnyxhook.gowithcallhook.go, with the vendor name filled in. - The 161 subtests of TwilioHook, TelnyxHook, TelnyxHookUnconfigured, TwilioEvents, Admission and CallHooks pass. The 3 Twilio tests in RouterStart pass.
- The answers, the order of the checks and every log string are the same. I compared base
- No number points at the new path.
twilioCallHookPathis used only ininternal/apiand its tests. - The generated files match their generators (
generated.sh). - The signature is checked over
ROUTER_PUBLIC_URLwith the path and the raw query, and the 64 KiB limit applies before the body is parsed. - The TwiML is built with
encoding/xml, so the username, password and URI are escaped. - A
Bridgethat reaches a log line is redacted byRedactLogAttr.
The replay finding (S1.1) is already on this PR from the security review, so I do not repeat it.
[Should fix] R1.2 .env.example:158-159 (not in the diff): this text still says TWILIO_WEBHOOK_AUTH_TOKEN turns on only /v1/phone/hooks/twilio/events. With this PR it also turns on /v1/phone/hooks/twilio, and TWILIO_ACCOUNT_SID is now also the account that call must name. Update the two lines to match the new README lines.
Author questions: 401 for a bad signature (Q1) and no sandbox row (Q2, #2407) need no change. TWILIO_ACCOUNT_SID on staging and prod (Q3) is a gate for the next piece (AI-3805), not for this PR.
The CI jobs are skipped while the PR is a draft. CI runs when the PR is marked ready.
…n on Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rules Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…wer did not reach Twilio A signed call has no time in it, so a copy got the trunk credentials again. The CallSid is marked in Redis (SET NX, a week) before the answer and forgotten when the answer could not be flushed or Twilio hung up, so Twilio's retry of a call it got no answer to is still dialled. Without Redis, or when it fails, the call is hung up. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
Delta round 2 on c544a25 (reviewed merged onto main 3d837a3; the 3 newer main commits touch no hook file). One Should fix left, a test gap in the new replay code.
Prior findings
- S1.1 fixed. A signed call sent twice: the second gets
<Response><Hangup/></Response>, no password in body or log lines (the log holdscall_sidonly); no Redis or a failing one: hung up, closed; the markphone:twilio:call:<CallSid>is set only after signature, account, direction and number checks, so a call that names another account never marks, and Twilio CallSids are global. Security probe P1 now passes (all 4 probes pass). Mutants: constant key, always-forget, SET without NX, Redis not wired: all killed. - R1.1 fixed: R3 (no AccountSid), R4 (no Direction), R10 (account before signature) mutants killed on re-run.
- R1.2 fixed: .env.example and README match the code.
Design limits, against Twilio's webhook connection-overrides page (https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides)
- (a) a retry while the first attempt still runs is hung up: by default Twilio retries only on a TCP connect or TLS failure (
rp=ct,rc=1), where the first attempt never reached the router; read-timeout and 5xx retries needrp/rtin the voice URL's fragment; call requests are capped at 15 s, and partial responses are not retried. So a slow Redis or DB answer cannot make Twilio's retry fail a real call under the default. Accepted. For piece 2 (AI-3805): ConfigureInbound must not putrp,rtor4xx/5xxretry overrides in the voice URL. - (b) a copy older than the one-week mark is answered again: Twilio's signature holds no time (webhooks-security) and a call lives at most 4 h, 24 h with the longer limit (voice/twiml/dial), so a week covers any call and bounds the keys. Accepted, as written in code, README and PR body.
- R9 (
Calleddiffers fromTo, untested): the code never readsCalled; the number isTo. Not a Should fix. Nit: a row where a signed form hasCalledset to another attached number still getsTo's credentials.
New finding
- [Should fix] twiliohook.go:146 — the atomic SET NX is what makes parallel copies of one signed call get one password, and no test pins it: replacing it with EXISTS then SET passes the whole TwilioHookSuite, yet 8 concurrent copies then get 2-5 passwords. Fix: add a test to TwilioHookSuite that delivers the same signed form from 8 goroutines, over 20 fresh CallSids, and asserts exactly one body holds the password. I checked it: 4 of 4 runs fail under the EXISTS-then-SET mutant, and it passes on head.
Suites on head merged onto main: TwilioHook, TelnyxHook, TwilioEvents, Admission, CallHooks and RouterStartSuite Twilio tests pass; vet clean. CI: draft, Analyze/CodeQL pass, the rest skipping (#2130).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO
Delta round 3 on cded665 (old reviewed c544a25). Test-only commit: acceleration/internal/api/twiliohook_test.go (+50). Head merged onto origin/main d89d15d cleanly; no conflict resolutions in the base merge.
Prior findings
- N2.1 (Should fix, atomic SET NX claim not pinned): fixed. TestCopiesOfOneCallSentAtOnceAreAnsweredOnlyOnce passes on head. Mutant EXISTS-then-SET fails it, 10/10 runs at default cpu and 10/10 at -cpu 1.
- N2.2 (Nit, Called over To): fixed. TestACallIsAnsweredForToWhateverCalledNames fails under the Called mutant and passes on head.
Suites
- TwilioHookSuite -count=5: ok. -race -count=3: ok. -cpu 1 -count=50 (concurrency and To tests): ok.
- Hook suites (TwilioHook|TelnyxHook|TwilioEvents|CallHooks), go vet -tags integration: ok.
- gh pr checks: go, unit, integration skipping (draft). No failure.
New findings
- Nit (unchanged code): acceleration/internal/api/twiliohook_test.go:381-382, the comment says a forwarded call names the original number in Called. I could not source this from Twilio's parameter docs. The test does not depend on it. Cite it or cut the sentence.
Details: scratch reviewer-3.md.
…istry, not the vendor package Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO
Delta round 4: cded665 -> 1dbf136 (fix 7651f8e plus a clean base merge, empty remerge-diff), checked merged onto main 4a6dd11.
- C1 (CI: TestOnlyRegistriesImportAVendor) is fixed.
internal/api/twiliohook.gonow importsinternal/phone/vendors, andvendors.TwilioCallAnswersholds the same three functions (twilio.RenderInbound,RenderReject,RenderHangup) by reference. The TwiML and status codes are unchanged, and the unchanged TwilioHookSuite passes. guard_test.go,internal/phone/twilioandcallhook.goare untouched.importsAlloweddid not grow.phone/vendorsis a notVendor and an importer in the guard, and the seam is a struct of three func fields with no logic.- Mutation: restoring the old
phonetwilioimport failsTestOnlyRegistriesImportAVendor("internal/api/twiliohook.go imports internal/phone/twilio"). On head it passes with and without the integration tag. - Suites on the scratch merge, all passing:
./internal/metered/(both tags),./internal/phone/...,./internal/api/, and the integration suites TwilioHook, TelnyxHook, TwilioEvents, Admission and CallHooks. - Earlier findings S1.1, R1.1, R1.2, N2.1 and N2.2 stay fixed. The delta did not touch their code or tests.
- New findings: none.
- CI at review time: unit, lint, integration (agent, routers) and sdks pass. go, integration (rest, api, router, store) and swift were still pending.
Piece 2/4 of [AI-3751](https://linear.app/stream/issue/AI-3751) ([AI-3805](https://linear.app/stream/issue/AI-3805)). Depends on #2433 (merged). Numbers attached before this PR move in [AI-3806](https://linear.app/stream/issue/AI-3806); the trunk IP allowlist is [AI-3807](https://linear.app/stream/issue/AI-3807). ## Why #2433 added the router's signed Twilio call webhook, which runs the pre-answer checks (suspension, money) and answers with the number's trunk in the response body. No number pointed at it yet. With this PR a newly attached Twilio number points at it. ## How it works ``` POST /v1/phone/numbers/{n}/attach -> phone.Service.Attach ├─ no keyring (Twilio now asks_for_trunk, as Telnyx) ──────────────> refused (ErrNoSealer) ├─ attached already in this app ──────────────────────────────────> answered as before, not re-pointed ├─ provider.(CallHooked).CallHookReady(ROUTER_PUBLIC_URL) (before anything is made) │ ├─ no TWILIO_WEBHOOK_AUTH_TOKEN ────────────────────────────> refused, not_configured │ ├─ no ROUTER_PUBLIC_URL ────────────────────────────────────> refused, not_configured │ └─ not a bare http(s) address (user, ?, #) ─────────────────> refused, not_configured ├─ Stream trunk + rule └─ finishAttach -> twilio.ConfigureInbound(Inbound{E164, Bridge, PublicURL}) └─ POST IncomingPhoneNumbers/<sid>.json VoiceUrl = ROUTER_PUBLIC_URL + /v1/phone/hooks/twilio (no #rp=/#rt= overrides) VoiceMethod = POST ``` No TWILIO_ACCOUNT_SID: the Twilio provider cannot be opened, so attach is refused as before (tested). | | before | after | |---|---|---| | new Twilio number's voice URL | inline TwiML, GET | `<ROUTER_PUBLIC_URL>/v1/phone/hooks/twilio`, POST | | what Twilio is told | the trunk's dial instruction | only the webhook URL | | attach without token / public URL / keyring | attached | refused, nothing made at Stream or Twilio | | Telnyx attach | TeXML app | unchanged (control: same requests as base 52435fe) | Callers of `ConfigureInbound`: `Service.finishAttach` (production), the telephony-latency bench (it now serves the same webhook itself on `-hook-listen`, signed with `TWILIO_WEBHOOK_AUTH_TOKEN`, and dials the bench), the Twilio integration test. `phone.TwilioCallHookPath` is the one path the provider and the API server use. The `phone` CLI's `attach` has no keyring, so it now refuses Twilio numbers as it already refused Telnyx ones. ## Deploy gate Before the staging deploy: staging must set `TWILIO_WEBHOOK_AUTH_TOKEN` and `ROUTER_PUBLIC_URL`, else new Twilio attaches are refused. ## Tests - `internal/phone/twilio`: voice URL is the hook on the public URL, POST, no fragment/query/user, no trunk value in anything sent; refused without the token (from options or `TWILIO_WEBHOOK_AUTH_TOKEN`) with no request to Twilio; a table of 14 public URL shapes. - `internal/api` `TwilioHookSuite` (real Twilio provider against a recording fake): attach, then a call signed over the voice URL Twilio was given is answered at it with the trunk; each missing setting (token, public URL, account SID, keyring) refuses with nothing at Twilio or Stream and the number unattached; an attached number re-attached without the settings still answers; Telnyx control. - `evals/telephony-latency`: the bench's webhook (signed call dials the bench, unsigned 401, bad form or too large 400, unknown number hangs up) and its server lifecycle. - Mutations: 28 mutants (every guard in the diff, the `asks_for_trunk` line, the hook path, the POST method, the check order and placement), all killed; the bench's `run` wiring is checked by build only (it needs real carriers). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Piece 1/4 of AI-3751 (AI-3804).
Why
Inbound calls to a Twilio number do not pass through the router before they are answered, so they skip the checks Telnyx calls pass (telephony suspension, money). This PR adds the router route that will answer them: a signed webhook that runs those checks and only then hands Twilio the number's trunk, in the response body. No number points at it yet: piece 2 moves new attaches to it, piece 3 moves existing numbers, piece 4 is the trunk IP allowlist. Behaviour for every existing number is unchanged.
How it works
Each CallSid is answered once
Twilio's signature has no time in it (Twilio docs), so a copy of a signed call would get the trunk password again. Twilio sends a call again only when it got no answer: by default after a failed connect or TLS handshake, and with URL overrides after a read timeout or a 5xx (connection overrides). The router answers 200 to every signed call, so the only retry that matters is one whose answer never reached Twilio.
So the CallSid is marked before the answer, and the mark is dropped when the answer could not be flushed or the request's context ended (Twilio hung up). A copy of a call whose answer reached Twilio gets
<Hangup/>. Why not "the same answer for a ringing window": a replay inside that window would still get the password, and the form holds no time to bound the window by. Why not the idempotency header: headers are not signed, so a replay can change it. The mark lives a week (Twilio ends a call after 4 h, or 24 h with the longer limit, Dial timeLimit); a copy sent after that week is answered again. Without Redis, or when Redis fails, the call is hung up. A retry that reaches the router while the first attempt is still running is hung up too.<Reject/>as the first verb leaves the call unanswered, so it is not billed (Twilio docs).Changes
InboundBridgerefusal mapping moves out of the Telnyx hook intoanswerCall, which takes the vendor's renderers. The Telnyx hook keeps the same answers and log linesinternal/api/callhook.go,telnyxhook.gointernal/api/twiliohook.go,handwritten.go,hookbody.go,server.gotwilioConfigured,twilioSigned)internal/api/twilioevents.godialBridge), reject, hang upinternal/phone/twilio/answer.gotwilio.account_sidsetting (TWILIO_ACCOUNT_SID, which the Twilio provider already reads), wired to the routeinternal/config/config.go,cmd/router/main.goacceleration/README.mdapi/openapi.yaml,sdks/,plugins/streamValidation
TwilioHookSuite/TestACallIsSentToTheNumbersOwnTrunkWithItsCredentialsInTheBodyOnlyTwilioHookSuite/TestACallNotSignedWithTheAccountsTokenOverThisURLIsRefusedTwilioHookSuite/TestASignedCallOnAnotherAccountIsHungUp,TestASignedCallThatNamesNoAccountIsHungUp,TestWithoutAConfiguredAccountNoCallIsAnsweredTwilioHookSuite/TestACallAnsweredOnceIsHungUpWithoutItsPasswordWhenSentAgainTwilioHookSuite/TestACallWhoseAnswerDidNotReachTwilioIsAnsweredWhenSentAgainTwilioHookSuite/TestACallWhoseLostAnswerCannotBeForgottenIsHungUpWhenSentAgain,TestWithoutAWorkingRedisNoCallIsAnswered,TestACallWithNoCallSidOrOneTooLongIsHungUpTwilioHookSuite/TestACallToANumberNotAttachedAtTwilioIsHungUpTwilioHookSuite/TestACallToASuspendedAppIsRejectedUnansweredAndCountedRefusedAdmissionSuite/TestATwilioCallToANumberOfAnOrganizationThatMayNotPayIsRejectedUnansweredTwilioHookSuiteno keyring, no stored trunk, unopenable password, no telephony, not inbound or noDirection, noTo, not a form, too large, not configuredRouterStartSuite/TestAStartingRouterTakesATwilioCallOnItsOwnAccountTWILIO_ACCOUNT_SIDnot wired into the routeTestTheTwilioCallHookIsDeclared,ConfigSuiteaccount SID tests,TwilioSuiterender testsTelnyx hook, Twilio events and admission suites pass unchanged. Each guard the diff adds was mutated: 44 mutants, each one failed a test listed above (list on the ticket). The once-per-CallSid mark added 12 more (no mark, never forgotten, flush or hang-up not seen, no Redis answered, Redis failing open, forget on the request context, empty or long CallSid marked, a one-hour mark, both log lines dropped): each failed a test. Not mutated: a render error after
InboundBridge(its bridge is already a checked SIP URI), a failedWriteto Twilio, and a body read error other than its size.🤖 Generated with Claude Code