Skip to content

[AI-3804] Twilio call webhook with pre-answer checks - #2433

Merged
kanat merged 16 commits into
mainfrom
kanat/ai-3804-twilio-call-hook
Nov 25, 2026
Merged

kanat merged 16 commits into
mainfrom
kanat/ai-3804-twilio-call-hook

Conversation

@kanat

@kanat kanat commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

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

Twilio POST /v1/phone/hooks/twilio  (form, X-Twilio-Signature)
 ├─ no TWILIO_WEBHOOK_AUTH_TOKEN or ROUTER_PUBLIC_URL ─> 404
 ├─ over 64 KiB ─> 413        not a form ─> 400
 ├─ signature not over ROUTER_PUBLIC_URL + path ─> 401 (no TwiML)
 ├─ TWILIO_ACCOUNT_SID unset, or AccountSid is another ─> <Hangup/>
 ├─ Direction != inbound, or no To ─> <Hangup/>
 ├─ no Redis, Redis fails, no CallSid ─> <Hangup/>
 ├─ SET NX phone:twilio:call:<CallSid> EX 1 week: already set ─> <Hangup/>  (answered already)
 ├─ answerCall(twilioPlans, To)       shared with the Telnyx hook
     └─ phone.Service.InboundBridge("twilio", To)
         ├─ no key to open passwords ─> <Hangup/>  (log says what to set)
         ├─ number not attached at Twilio ─> <Hangup/>
         ├─ telephony suspended ─> <Reject/>  (counted refused)
         ├─ organization may not pay ─> <Reject/>  (counted refused)
         ├─ attached before its trunk was kept ─> <Hangup/>
         ├─ the router's own failure ─> <Hangup/>  (counted internal_error)
         └─ ok ─> <Dial><Sip username password>trunk</Sip></Dial>
 └─ flush fails, or Twilio hung up ─> DEL the mark (Twilio's retry is answered)

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

Change Where
The InboundBridge refusal mapping moves out of the Telnyx hook into answerCall, which takes the vendor's renderers. The Telnyx hook keeps the same answers and log lines internal/api/callhook.go, telnyxhook.go
New Twilio call route, declared in the spec, on the hook list internal/api/twiliohook.go, handwritten.go, hookbody.go, server.go
The signature check is shared with the Twilio events hook (twilioConfigured, twilioSigned) internal/api/twilioevents.go
TwiML answers: dial (reuses dialBridge), reject, hang up internal/phone/twilio/answer.go
twilio.account_sid setting (TWILIO_ACCOUNT_SID, which the Twilio provider already reads), wired to the route internal/config/config.go, cmd/router/main.go
Docs for the route and the variables acceleration/README.md
Generated: spec, Go, Python, JS, Ruby clients. The other clients do not change (server-side operation) api/openapi.yaml, sdks/, plugins/stream

Validation

Test Defect it catches
TwilioHookSuite/TestACallIsSentToTheNumbersOwnTrunkWithItsCredentialsInTheBodyOnly wrong trunk, unescaped password, or the password in a log line
TwilioHookSuite/TestACallNotSignedWithTheAccountsTokenOverThisURLIsRefused unsigned (also naming another account), other token, other path or other public URL accepted
TwilioHookSuite/TestASignedCallOnAnotherAccountIsHungUp, TestASignedCallThatNamesNoAccountIsHungUp, TestWithoutAConfiguredAccountNoCallIsAnswered a call naming another account, or none, dialled
TwilioHookSuite/TestACallAnsweredOnceIsHungUpWithoutItsPasswordWhenSentAgain a replay of an answered call gets the password; the mark kept less than a week
TwilioHookSuite/TestACallWhoseAnswerDidNotReachTwilioIsAnsweredWhenSentAgain Twilio's retry after a failed flush, or after it hung up, refused; the retry's copy answered again
TwilioHookSuite/TestACallWhoseLostAnswerCannotBeForgottenIsHungUpWhenSentAgain, TestWithoutAWorkingRedisNoCallIsAnswered, TestACallWithNoCallSidOrOneTooLongIsHungUp a call answered with no working mark
TwilioHookSuite/TestACallToANumberNotAttachedAtTwilioIsHungUp a number looked up under another vendor
TwilioHookSuite/TestACallToASuspendedAppIsRejectedUnansweredAndCountedRefused a suspended app's call answered, or counted answered
AdmissionSuite/TestATwilioCallToANumberOfAnOrganizationThatMayNotPayIsRejectedUnanswered a call with no credit answered
TwilioHookSuite no keyring, no stored trunk, unopenable password, no telephony, not inbound or no Direction, no To, not a form, too large, not configured each branch answers as listed above
RouterStartSuite/TestAStartingRouterTakesATwilioCallOnItsOwnAccount TWILIO_ACCOUNT_SID not wired into the route
TestTheTwilioCallHookIsDeclared, ConfigSuite account SID tests, TwilioSuite render tests spec, hook list, setting, TwiML shape

Telnyx 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 failed Write to Twilio, and a body read error other than its size.

🤖 Generated with Claude Code

kanat and others added 6 commits November 24, 2026 23:39
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 kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[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.

Comment thread acceleration/internal/api/twiliohook.go Resolved

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.go with callhook.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.
  • No number points at the new path. twilioCallHookPath is used only in internal/api and its tests.
  • The generated files match their generators (generated.sh).
  • The signature is checked over ROUTER_PUBLIC_URL with 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 Bridge that reaches a log line is redacted by RedactLogAttr.

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.

Comment thread acceleration/internal/api/twiliohook.go Resolved
kanat and others added 6 commits November 25, 2026 07:51
…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 kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 holds call_sid only); no Redis or a failing one: hung up, closed; the mark phone: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 need rp/rt in 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 put rp, rt or 4xx/5xx retry 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 (Called differs from To, untested): the code never reads Called; the number is To. Not a Should fix. Nit: a row where a signed form has Called set to another attached number still gets To'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).

Comment thread acceleration/internal/api/twiliohook.go Resolved

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@kanat
kanat marked this pull request as ready for review November 25, 2026 14:40
kanat and others added 2 commits November 25, 2026 10:00
…istry, not the vendor package

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.go now imports internal/phone/vendors, and vendors.TwilioCallAnswers holds 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/twilio and callhook.go are untouched. importsAllowed did not grow. phone/vendors is 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 phonetwilio import fails TestOnlyRegistriesImportAVendor ("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.

@kanat
kanat merged commit 52435fe into main Nov 25, 2026
20 checks passed
@kanat
kanat deleted the kanat/ai-3804-twilio-call-hook branch November 25, 2026 15:28
kanat added a commit that referenced this pull request Nov 25, 2026
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant