From 5f5ae39dc28fe18e1b023a553a97d825a48b8c4b Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 23:39:06 -0500 Subject: [PATCH 01/10] AI-3804: a signed Twilio call webhook that runs the pre-answer checks Co-Authored-By: Claude Opus 5.5 --- acceleration/README.md | 4 +- acceleration/cmd/router/main.go | 1 + acceleration/internal/api/callhook.go | 93 +++++++++++++++++++ acceleration/internal/api/handwritten.go | 21 +++++ acceleration/internal/api/hookbody.go | 2 +- .../internal/api/router_suite_test.go | 4 + acceleration/internal/api/server.go | 6 ++ acceleration/internal/api/telnyxhook.go | 88 +++--------------- acceleration/internal/api/twilioevents.go | 27 ++++-- acceleration/internal/api/twiliohook.go | 83 +++++++++++++++++ acceleration/internal/config/config.go | 7 +- acceleration/internal/phone/twilio/answer.go | 33 +++++++ 12 files changed, 280 insertions(+), 89 deletions(-) create mode 100644 acceleration/internal/api/callhook.go create mode 100644 acceleration/internal/api/twiliohook.go create mode 100644 acceleration/internal/phone/twilio/answer.go diff --git a/acceleration/README.md b/acceleration/README.md index 04ed0826e1..b78c10fbef 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -155,10 +155,10 @@ the other commands that read them there. | `EXA_API_KEY` | Exa credentials. Also what reads a URL into a knowledge base | | `PERPLEXITY_API_KEY` | Perplexity credentials, for the ranked index and for Sonar | | `DAYTONA_API_KEY` | Daytona credentials. Without it a session cannot ask for a sandbox | -| `TWILIO_ACCOUNT_SID` | Twilio credentials, for buying and operating numbers | +| `TWILIO_ACCOUNT_SID` | Twilio credentials, for buying and operating numbers. A call to `/v1/phone/hooks/twilio` that names another account is hung up | | `TWILIO_AUTH_TOKEN` | Twilio credentials. With `TWILIO_API_KEY_SID` set, that key's secret | | `TWILIO_API_KEY_SID` | Optional Twilio API key (SK...). Requests are signed with it instead of the account SID | -| `TWILIO_WEBHOOK_AUTH_TOKEN` | Auth Token of the Twilio account whose webhooks the router checks (`X-Twilio-Signature`). It only checks signatures: those of the Monitor alerts and usage-trigger callbacks sent to `/v1/phone/hooks/twilio/events`, signed over `ROUTER_PUBLIC_URL` and the path. Without it, or without `ROUTER_PUBLIC_URL`, that route answers 404. A token with whitespace in it stops the router at start | +| `TWILIO_WEBHOOK_AUTH_TOKEN` | Auth Token of the Twilio account whose webhooks the router checks (`X-Twilio-Signature`). It only checks signatures: those of the Monitor alerts and usage-trigger callbacks sent to `/v1/phone/hooks/twilio/events`, and the calls sent to `/v1/phone/hooks/twilio`, each signed over `ROUTER_PUBLIC_URL` and the path. Without it, or without `ROUTER_PUBLIC_URL`, both routes answer 404. A token with whitespace in it stops the router at start | | `TELNYX_API_KEY` | Telnyx credentials | | `TELNYX_CONNECTION_ID` | The Telnyx TeXML application numbers and calls are on. Calls to the webhook from any other application are hung up | | `TELNYX_PUBLIC_KEY` | Telnyx's public key (base64), to check the calls it sends to `/v1/phone/hooks/telnyx` and the account events it sends to `/v1/phone/hooks/telnyx/events`. Without it Telnyx numbers are not answered and the events route answers 404. Telnyx numbers also need a key encryption keyring (`ROUTER_DEV_KEK` locally, `ROUTER_AUTH_KEK_V_WRAPPED` hosted): without one they cannot be attached | diff --git a/acceleration/cmd/router/main.go b/acceleration/cmd/router/main.go index c430691239..5fe36c2ccc 100644 --- a/acceleration/cmd/router/main.go +++ b/acceleration/cmd/router/main.go @@ -1495,6 +1495,7 @@ func run(settings config.Config, logger *slog.Logger) error { TelnyxPublicKey: telnyxPublicKey, ChatInboundKeys: chatInboundKeys, TwilioAuthToken: settings.Twilio.WebhookAuthToken, + TwilioAccountSID: settings.Twilio.AccountSID, TelnyxConnectionID: settings.Telnyx.ConnectionID, Simulations: simulations, DLC: registrations, diff --git a/acceleration/internal/api/callhook.go b/acceleration/internal/api/callhook.go new file mode 100644 index 0000000000..906c7d82a8 --- /dev/null +++ b/acceleration/internal/api/callhook.go @@ -0,0 +1,93 @@ +package api + +import ( + "errors" + "log/slog" + "net/http" + + "github.com/GetStream/Vision-Agents/acceleration/internal/activity" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" +) + +// callPlans are the answers a vendor's call webhook gives, each in that vendor's dialect. +type callPlans struct { + // vendor names the vendor in the store and in every line logged about its calls. + vendor string + renderDial func(phone.Bridge) (phone.Plan, error) + renderReject func() phone.Plan + renderHangup func() phone.Plan +} + +// answerCall answers a vendor's signed call to the number to: it runs the checks a call to the +// number passes before it is answered (phone.Service.InboundBridge), then dials the number's +// trunk, or rejects or hangs up the call when one of them refuses it. +func (s *Server) answerCall(w http.ResponseWriter, r *http.Request, logger *slog.Logger, plans callPlans, to string) { + if s.phone == nil { + plans.hangUp(w, logger, "hung up a "+plans.vendor+" call: telephony is not configured", "to", to) + return + } + + bridge, err := s.phone.InboundBridge(r.Context(), plans.vendor, to) + // InboundBridge notes the number's app once the number resolves, before it refuses one. + logger = logger.With("customer", activity.NotedCustomer(r.Context())) + if errors.Is(err, phone.ErrNoSealer) { + plans.hangUp(w, logger, "hung up a "+plans.vendor+" call: this router has no key to open trunk passwords: "+ + "set ROUTER_DEV_KEK (local), or ROUTER_AUTH_KEK_V1_WRAPPED with ROUTER_AUTH_KMS_KEY (hosted), then attach the number again", "to", to) + return + } + if errors.Is(err, store.ErrNoNumber) { + plans.hangUp(w, logger, "hung up a "+plans.vendor+" call to a number that is unknown, released or not attached", "to", to) + return + } + // A refusal past InboundBridge, which noted the number's app, is answered 200 as the vendor + // wants it; its code is noted for the activity record, which would count it answered. + if errors.Is(err, phone.ErrSuspended) { + noteRefusal(w, codeTelephonySuspended) + plans.refuse(w, logger, "rejected a "+plans.vendor+" call to a number of an app whose telephony is suspended", "to", to) + return + } + if answer, refused := moneyError(err); refused { + noteRefusal(w, answer.Code) + plans.refuse(w, logger, "rejected a "+plans.vendor+" call to a number of an organization that may not pay for it", + "to", to, "code", answer.Code) + return + } + if errors.Is(err, store.ErrNoStoredBridge) { + plans.hangUp(w, logger, "hung up a "+plans.vendor+" call to a number attached before its trunk was kept: "+ + "attach the number again", "to", to) + return + } + // The router's own failure, which an API route answers 500: refused, once noted. + if err != nil { + noteRefusal(w, internalError().Code) + plans.hangUp(w, logger, "hung up a "+plans.vendor+" call: could not find its trunk", "to", to, "error", err) + return + } + plan, err := plans.renderDial(bridge) + if err != nil { + noteRefusal(w, internalError().Code) + plans.hangUp(w, logger, "hung up a "+plans.vendor+" call: could not render its trunk", "to", to, "error", err) + return + } + writePlan(w, logger, plan) +} + +func (p callPlans) hangUp(w http.ResponseWriter, logger *slog.Logger, why string, attributes ...any) { + logger.Warn(why, attributes...) + writePlan(w, logger, p.renderHangup()) +} + +// refuse rejects a call without answering it, for a refusal the customer is billed nothing for. +// It is a warning all the same: the person calling the customer's number reached nobody. +func (p callPlans) refuse(w http.ResponseWriter, logger *slog.Logger, why string, attributes ...any) { + logger.Warn(why, attributes...) + writePlan(w, logger, p.renderReject()) +} + +func writePlan(w http.ResponseWriter, logger *slog.Logger, plan phone.Plan) { + w.Header().Set("Content-Type", plan.ContentType) + if _, err := w.Write(plan.Body); err != nil { + logger.Error("could not serve a call plan", "error", err) + } +} diff --git a/acceleration/internal/api/handwritten.go b/acceleration/internal/api/handwritten.go index f4d9096535..e0fb3ff026 100644 --- a/acceleration/internal/api/handwritten.go +++ b/acceleration/internal/api/handwritten.go @@ -782,6 +782,27 @@ func documentHandWritten(api huma.API) { "413": {Description: "The event is over 64 KiB"}, }, }) + document.AddOperation(&huma.Operation{ + OperationID: "receiveTwilioCall", + Method: http.MethodPost, + Path: twilioCallHookPath, + Summary: "Receive a Twilio call", + Description: "Where Twilio asks what to do with a call to one of this router's Twilio numbers. " + + "Unauthenticated because Twilio is not a customer: each call is checked against " + + "X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this " + + "path, and must name TWILIO_ACCOUNT_SID. The call then passes the checks a Telnyx call " + + "passes, and the answer dials that number's own trunk and no other, or rejects or hangs " + + "up the call. A deployment with no Twilio webhook token or no public URL answers 404, so " + + "the path never hands out trunk credentials unsigned.", + Security: []map[string][]string{}, + Responses: map[string]*huma.Response{ + "200": {Description: "TwiML dialling the number's trunk, rejecting the call, or hanging up", Content: map[string]*huma.MediaType{"application/xml": {Schema: &huma.Schema{Type: huma.TypeString}}}}, + "400": {Description: "The body is not a form"}, + "401": {Description: "The call is not signed by Twilio"}, + "404": {Description: "Twilio calls are not configured"}, + "413": {Description: "The call is over 64 KiB"}, + }, + }) document.AddOperation(&huma.Operation{ OperationID: "receiveTwilioEvent", Method: http.MethodPost, diff --git a/acceleration/internal/api/hookbody.go b/acceleration/internal/api/hookbody.go index 8e473cca3f..76eb42c60f 100644 --- a/acceleration/internal/api/hookbody.go +++ b/acceleration/internal/api/hookbody.go @@ -29,7 +29,7 @@ var errTooLarge = errors.New("api: that delivery is larger than any event Stream // isHook reports whether a path is one Stream, Telnyx or Twilio delivers events to. None is a // customer, so nothing a request to one of them says about who is calling is read. func isHook(path string) bool { - for _, hook := range []string{phone.CallHookPath, chat.MessageHookPath, telnyxCallHookPath, twilioEventsHookPath, + for _, hook := range []string{phone.CallHookPath, chat.MessageHookPath, telnyxCallHookPath, twilioCallHookPath, chatInboundPath} { if path == hook || strings.HasPrefix(path, hook+"/") { return true diff --git a/acceleration/internal/api/router_suite_test.go b/acceleration/internal/api/router_suite_test.go index c46193615f..ad8d3053d1 100644 --- a/acceleration/internal/api/router_suite_test.go +++ b/acceleration/internal/api/router_suite_test.go @@ -428,6 +428,9 @@ type RouterSuite struct { // twilioAuthToken, set by a suite about Twilio's webhooks before it starts the harness, is // the Auth Token Twilio's requests are checked against. Empty leaves it unconfigured. twilioAuthToken string + // twilioAccountSID is the Twilio account the router's Twilio numbers are under, for the + // same suite to set. Empty is a router with none, which answers no Twilio call. + twilioAccountSID string // chatInboundKeys, set by a suite about Stream Chat's delivery endpoint before it starts // the harness, are what its deliveries are checked against, on every node. Nil leaves it // unconfigured. @@ -812,6 +815,7 @@ func (s *RouterSuite) SetupSuite() { HookSecret: suiteStreamSecret, TelnyxPublicKey: s.telnyxPublicKey, TwilioAuthToken: s.twilioAuthToken, + TwilioAccountSID: s.twilioAccountSID, ChatInboundKeys: s.chatInboundKeys, TelnyxConnectionID: s.telnyxConnectionID, AudioFloor: s.audioFloor, diff --git a/acceleration/internal/api/server.go b/acceleration/internal/api/server.go index 4c5a4f2df2..937ed7d30a 100644 --- a/acceleration/internal/api/server.go +++ b/acceleration/internal/api/server.go @@ -234,6 +234,9 @@ type Options struct { // TwilioAuthToken checks that a webhook came from Twilio (TWILIO_WEBHOOK_AUTH_TOKEN). // Without it no Twilio webhook is believed. TwilioAuthToken string + // TwilioAccountSID is the Twilio account this router's Twilio numbers are under + // (TWILIO_ACCOUNT_SID). A call webhook naming any other is hung up. + TwilioAccountSID string // TelnyxConnectionID is the TeXML application this router's Telnyx numbers are on // (TELNYX_CONNECTION_ID). A call webhook for any other is hung up. TelnyxConnectionID string @@ -369,6 +372,7 @@ type Server struct { chatInboundKeys []ed25519.PublicKey twilioAuthToken string twilioAlertSids rueidis.Client // nil without Redis: every copy of an alert is counted + twilioAccountSID string telnyxConnectionID string simulations *simulation.Runner knowledge *metered.Knowledge @@ -598,6 +602,7 @@ func NewServer(options Options, with ...Option) (*Server, error) { telnyxPublicKey: options.TelnyxPublicKey, chatInboundKeys: options.ChatInboundKeys, twilioAuthToken: options.TwilioAuthToken, + twilioAccountSID: options.TwilioAccountSID, telnyxConnectionID: options.TelnyxConnectionID, simulations: options.Simulations, knowledge: options.Knowledge, @@ -814,6 +819,7 @@ func (s *Server) Handler() http.Handler { handle(mux, "POST "+phone.CallHookPath+"/{app}", "PhoneHook", s.receiveCallEvent) handle(mux, "POST "+telnyxCallHookPath, "ReceiveTelnyxCall", s.receiveTelnyxCall) handle(mux, "POST "+telnyxEventsHookPath, "ReceiveTelnyxEvent", s.receiveTelnyxEvent) + handle(mux, "POST "+twilioCallHookPath, "ReceiveTwilioCall", s.receiveTwilioCall) handle(mux, "POST "+twilioEventsHookPath, "ReceiveTwilioEvent", s.receiveTwilioEvent) handle(mux, "POST "+chat.MessageHookPath, "ChatHook", s.receiveMessageEvent) handle(mux, "POST "+chat.MessageHookPath+"/{app}", "ChatHook", s.receiveMessageEvent) diff --git a/acceleration/internal/api/telnyxhook.go b/acceleration/internal/api/telnyxhook.go index e7bc2a0e21..b3d6bcdab2 100644 --- a/acceleration/internal/api/telnyxhook.go +++ b/acceleration/internal/api/telnyxhook.go @@ -3,15 +3,11 @@ package api import ( "errors" "io" - "log/slog" "net/http" "net/url" "time" - "github.com/GetStream/Vision-Agents/acceleration/internal/activity" - "github.com/GetStream/Vision-Agents/acceleration/internal/phone" phonetelnyx "github.com/GetStream/Vision-Agents/acceleration/internal/phone/telnyx" - "github.com/GetStream/Vision-Agents/acceleration/internal/store" "github.com/GetStream/Vision-Agents/acceleration/internal/telnyxsig" ) @@ -19,6 +15,12 @@ import ( // Telnyx number is on. Telnyx asks it what to do with each call to one of them. const telnyxCallHookPath = "/v1/phone/hooks/telnyx" +// telnyxPlans are the TeXML answers to a Telnyx call. +var telnyxPlans = callPlans{ + vendor: "telnyx", renderDial: phonetelnyx.RenderInbound, + renderReject: phonetelnyx.RenderReject, renderHangup: phonetelnyx.RenderHangup, +} + // telnyxCallLimit caps the form Telnyx posts, which is a few hundred bytes. const telnyxCallLimit = 64 << 10 @@ -55,97 +57,31 @@ func (s *Server) receiveTelnyxCall(w http.ResponseWriter, r *http.Request) { form, err := url.ParseQuery(string(body)) if err != nil { - hangUp(w, s.logger, "hung up a telnyx call whose form could not be read") + telnyxPlans.hangUp(w, s.logger, "hung up a telnyx call whose form could not be read") return } logger := s.logger.With("call_sid", form.Get("CallSid")) if direction := form.Get("Direction"); direction != "inbound" { - hangUp(w, logger, "hung up a telnyx call that is not inbound", "direction", direction) + telnyxPlans.hangUp(w, logger, "hung up a telnyx call that is not inbound", "direction", direction) return } if s.telnyxConnectionID == "" { // Otherwise a signed call that names no application would match. - hangUp(w, logger, "hung up a telnyx call: TELNYX_CONNECTION_ID is not set") + telnyxPlans.hangUp(w, logger, "hung up a telnyx call: TELNYX_CONNECTION_ID is not set") return } // Dev and hosted routers share one Telnyx account, so a call for the other router's // application is signed with the same key. Its numbers are not in this database, but the // check keeps that from being the only thing that stops it. if connection := form.Get("ConnectionId"); connection != s.telnyxConnectionID { - hangUp(w, logger, "hung up a telnyx call on another TeXML application than TELNYX_CONNECTION_ID", + telnyxPlans.hangUp(w, logger, "hung up a telnyx call on another TeXML application than TELNYX_CONNECTION_ID", "connection_id", connection) return } to := form.Get("To") if to == "" { - hangUp(w, logger, "hung up a telnyx call that names no number") - return - } - if s.phone == nil { - hangUp(w, logger, "hung up a telnyx call: telephony is not configured", "to", to) - return - } - - bridge, err := s.phone.InboundBridge(r.Context(), "telnyx", to) - // InboundBridge notes the number's app once the number resolves, before it refuses one. - logger = logger.With("customer", activity.NotedCustomer(r.Context())) - if errors.Is(err, phone.ErrNoSealer) { - hangUp(w, logger, "hung up a telnyx call: this router has no key to open trunk passwords: "+ - "set ROUTER_DEV_KEK (local), or ROUTER_AUTH_KEK_V1_WRAPPED with ROUTER_AUTH_KMS_KEY (hosted), then attach the number again", "to", to) - return - } - if errors.Is(err, store.ErrNoNumber) { - hangUp(w, logger, "hung up a telnyx call to a number that is unknown, released or not attached", "to", to) - return - } - // A refusal past InboundBridge, which noted the number's app, is answered 200 as Telnyx - // wants it; its code is noted for the activity record, which would count it answered. - if errors.Is(err, phone.ErrSuspended) { - noteRefusal(w, codeTelephonySuspended) - reject(w, logger, "rejected a telnyx call to a number of an app whose telephony is suspended", "to", to) - return - } - if answer, refused := moneyError(err); refused { - noteRefusal(w, answer.Code) - reject(w, logger, "rejected a telnyx call to a number of an organization that may not pay for it", - "to", to, "code", answer.Code) - return - } - if errors.Is(err, store.ErrNoStoredBridge) { - hangUp(w, logger, "hung up a telnyx call to a number attached before its trunk was kept: "+ - "attach the number again", "to", to) - return - } - // The router's own failure, which an API route answers 500: refused, once noted. - if err != nil { - noteRefusal(w, internalError().Code) - hangUp(w, logger, "hung up a telnyx call: could not find its trunk", "to", to, "error", err) - return - } - plan, err := phonetelnyx.RenderInbound(bridge) - if err != nil { - noteRefusal(w, internalError().Code) - hangUp(w, logger, "hung up a telnyx call: could not render its trunk", "to", to, "error", err) + telnyxPlans.hangUp(w, logger, "hung up a telnyx call that names no number") return } - writePlan(w, logger, plan) -} - -func hangUp(w http.ResponseWriter, logger *slog.Logger, why string, attributes ...any) { - logger.Warn(why, attributes...) - writePlan(w, logger, phonetelnyx.RenderHangup()) -} - -// reject refuses a call without answering it, for a refusal the customer is billed nothing for. -// It is a warning all the same: the person calling the customer's number reached nobody. -func reject(w http.ResponseWriter, logger *slog.Logger, why string, attributes ...any) { - logger.Warn(why, attributes...) - writePlan(w, logger, phonetelnyx.RenderReject()) -} - -func writePlan(w http.ResponseWriter, logger *slog.Logger, plan phone.Plan) { - w.Header().Set("Content-Type", plan.ContentType) - if _, err := w.Write(plan.Body); err != nil { - logger.Error("could not serve a call plan", "error", err) - } + s.answerCall(w, r, logger, telnyxPlans, to) } diff --git a/acceleration/internal/api/twilioevents.go b/acceleration/internal/api/twilioevents.go index 3790f6739e..67f06fa55d 100644 --- a/acceleration/internal/api/twilioevents.go +++ b/acceleration/internal/api/twilioevents.go @@ -63,8 +63,7 @@ type twilioAlertPayload struct { // is answered as the first was and not counted again. A usage trigger fires at most once per // interval (https://www.twilio.com/docs/usage/api/usage-trigger), so each callback is counted. func (s *Server) receiveTwilioEvent(w http.ResponseWriter, r *http.Request) { - public := strings.TrimRight(s.publicURL, "/") - if s.twilioAuthToken == "" || public == "" { + if !s.twilioConfigured() { // Without the token anyone could raise the counter a monitor pages on, and without the // public URL no signature Twilio made over it can match. writeError(w, notFound("Twilio events are not configured")) @@ -86,13 +85,7 @@ func (s *Server) receiveTwilioEvent(w http.ResponseWriter, r *http.Request) { writeError(w, invalidRequest("that is not a form")) return } - // The router is behind a proxy, so the URL Twilio called and signed is the public one. - called := public + twilioEventsHookPath - if r.URL.RawQuery != "" { - called += "?" + r.URL.RawQuery - } - err = twiliosig.Verify(s.twilioAuthToken, called, form, r.Header.Get(twiliosig.SignatureHeader)) - if err != nil { + if err := s.twilioSigned(r, twilioEventsHookPath, form); err != nil { s.logger.Warn("refused a twilio account event", "reason", err.Error()) writeError(w, unauthenticated("that is not an event from Twilio")) return @@ -129,6 +122,22 @@ func (s *Server) receiveTwilioEvent(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } +// twilioConfigured reports whether the router can check a Twilio signature: it needs the +// account's Auth Token, and the public URL Twilio signs over. +func (s *Server) twilioConfigured() bool { + return s.twilioAuthToken != "" && strings.TrimRight(s.publicURL, "/") != "" +} + +// twilioSigned checks the X-Twilio-Signature of a form Twilio posted to path. The router is +// behind a proxy, so the URL Twilio called and signed is the public one. +func (s *Server) twilioSigned(r *http.Request, path string, form url.Values) error { + called := strings.TrimRight(s.publicURL, "/") + path + if r.URL.RawQuery != "" { + called += "?" + r.URL.RawQuery + } + return twiliosig.Verify(s.twilioAuthToken, called, form, r.Header.Get(twiliosig.SignatureHeader)) +} + // firstTwilioAlert marks the alert sid as counted for twilioAlertRepeatsFor, and reports // whether no copy of it was counted in that time. Without Redis, with a Sid longer than // twilioAlertSidLimit, or when Redis fails, the alert counts as new: a copy counted twice diff --git a/acceleration/internal/api/twiliohook.go b/acceleration/internal/api/twiliohook.go new file mode 100644 index 0000000000..ca28af9dda --- /dev/null +++ b/acceleration/internal/api/twiliohook.go @@ -0,0 +1,83 @@ +package api + +import ( + "errors" + "io" + "net/http" + "net/url" + + phonetwilio "github.com/GetStream/Vision-Agents/acceleration/internal/phone/twilio" +) + +// twilioCallHookPath is the voice URL a Twilio number is to be pointed at. Twilio asks it what +// to do with each call to the number. +const twilioCallHookPath = "/v1/phone/hooks/twilio" + +// twilioCallLimit caps the form Twilio posts, which is a few hundred bytes +// (https://www.twilio.com/docs/voice/twiml, "Twilio's request to your application"). +const twilioCallLimit = 64 << 10 + +// twilioPlans are the TwiML answers to a Twilio call. +var twilioPlans = callPlans{ + vendor: "twilio", renderDial: phonetwilio.RenderInbound, + renderReject: phonetwilio.RenderReject, renderHangup: phonetwilio.RenderHangup, +} + +// receiveTwilioCall answers a call to one of the router's Twilio numbers with TwiML that dials +// that number's Stream trunk, its credentials in the answer's body. +// +// Once the request is known to be Twilio's, every failure is a hangup or a reject rather than an +// HTTP error, as for a Telnyx call: Twilio would otherwise play its own error to the caller. +func (s *Server) receiveTwilioCall(w http.ResponseWriter, r *http.Request) { + if !s.twilioConfigured() { + // Without the token anyone could ask this path for a number's trunk credentials. + writeError(w, notFound("twilio calls are not configured")) + return + } + + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, twilioCallLimit)) + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + writeError(w, payloadTooLarge("that call is too large")) + return + } + if err != nil { + writeError(w, invalidRequest("could not read that call")) + return + } + // Twilio signs the form, so one that cannot be read cannot be shown to be Twilio's. + form, err := url.ParseQuery(string(body)) + if err != nil { + writeError(w, invalidRequest("that is not a form")) + return + } + if err := s.twilioSigned(r, twilioCallHookPath, form); err != nil { + s.logger.Warn("refused a twilio call webhook", "reason", err.Error()) + writeError(w, unauthenticated("that is not a call from Twilio")) + return + } + + logger := s.logger.With("call_sid", form.Get("CallSid")) + if s.twilioAccountSID == "" { + // Otherwise a signed call that names no account would match. + twilioPlans.hangUp(w, logger, "hung up a twilio call: TWILIO_ACCOUNT_SID is not set") + return + } + // The token signs for one account, but a call naming another is not this router's to answer + // even so: its numbers are bought and attached under TWILIO_ACCOUNT_SID. + if account := form.Get("AccountSid"); account != s.twilioAccountSID { + twilioPlans.hangUp(w, logger, "hung up a twilio call on another account than TWILIO_ACCOUNT_SID", + "account_sid", account) + return + } + if direction := form.Get("Direction"); direction != "inbound" { + twilioPlans.hangUp(w, logger, "hung up a twilio call that is not inbound", "direction", direction) + return + } + to := form.Get("To") + if to == "" { + twilioPlans.hangUp(w, logger, "hung up a twilio call that names no number") + return + } + s.answerCall(w, r, logger, twilioPlans, to) +} diff --git a/acceleration/internal/config/config.go b/acceleration/internal/config/config.go index 8eb06f2bb6..ca4f295631 100644 --- a/acceleration/internal/config/config.go +++ b/acceleration/internal/config/config.go @@ -569,8 +569,11 @@ type Telnyx struct { } // Twilio is what the router checks Twilio's webhooks with. The Twilio provider reads its own -// credentials, TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN. +// credentials, TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN, which export writes back. type Twilio struct { + // AccountSID is the account the router's Twilio numbers are under. A call webhook naming + // any other is hung up. + AccountSID string `koanf:"account_sid"` // WebhookAuthToken is the Auth Token of the account whose webhooks are checked. It only // checks signatures: nothing calls Twilio with it. WebhookAuthToken string `koanf:"webhook_auth_token"` @@ -673,6 +676,7 @@ var variables = map[string]string{ "telnyx.connection_id": "TELNYX_CONNECTION_ID", "telnyx.public_key": "TELNYX_PUBLIC_KEY", + "twilio.account_sid": "TWILIO_ACCOUNT_SID", "twilio.webhook_auth_token": "TWILIO_WEBHOOK_AUTH_TOKEN", "usage.url": "ROUTER_USAGE_URL", @@ -1289,6 +1293,7 @@ func (c Config) export() error { "telnyx.connection_id": c.Telnyx.ConnectionID, "telnyx.public_key": c.Telnyx.PublicKey, + "twilio.account_sid": c.Twilio.AccountSID, "twilio.webhook_auth_token": c.Twilio.WebhookAuthToken, "usage.url": c.Usage.URL, diff --git a/acceleration/internal/phone/twilio/answer.go b/acceleration/internal/phone/twilio/answer.go new file mode 100644 index 0000000000..5d16019d61 --- /dev/null +++ b/acceleration/internal/phone/twilio/answer.go @@ -0,0 +1,33 @@ +package twilio + +import ( + "encoding/xml" + + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" +) + +// twimlContentType is one of the types Twilio reads a webhook's answer as TwiML from +// (https://www.twilio.com/docs/voice/twiml, "Twilio's request to your application"). +const twimlContentType = "application/xml" + +// RenderInbound answers Twilio's webhook for a call to one of our numbers: dial that number's +// Stream trunk. The trunk's credentials are in the answer's body, which is the only place they go. +func RenderInbound(bridge phone.Bridge) (phone.Plan, error) { + instructions, err := dialBridge(bridge) + if err != nil { + return phone.Plan{}, err + } + return phone.Plan{ContentType: twimlContentType, Body: []byte(instructions)}, nil +} + +// RenderReject refuses a call without answering it, so the caller hears it rejected and no +// second of it is billed. Twilio only leaves a call unanswered when Reject is its first verb +// (https://www.twilio.com/docs/voice/twiml/reject). +func RenderReject() phone.Plan { + return phone.Plan{ContentType: twimlContentType, Body: []byte(xml.Header + ``)} +} + +// RenderHangup ends a call there is nowhere to send. +func RenderHangup() phone.Plan { + return phone.Plan{ContentType: twimlContentType, Body: []byte(xml.Header + "")} +} From 66624dcad04e4e7e4cd492209baf9f830e142468 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 23:42:11 -0500 Subject: [PATCH 02/10] AI-3804: regenerate the spec and clients Co-Authored-By: Claude Opus 5.5 --- acceleration/api/openapi.yaml | 23 +++ .../api/default/receive_twilio_call.py | 172 ++++++++++++++++++ sdks/go/acceleration/generated.go | 168 +++++++++++++++++ sdks/js/src/generated/api.ts | 69 +++++++ .../getstream/vision_agents/generated/spec.rb | 6 + 5 files changed, 438 insertions(+) create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/api/default/receive_twilio_call.py diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index 068f372bca..6b9dc4b300 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -24454,6 +24454,29 @@ paths: $ref: '#/components/responses/InternalError' security: [] summary: Receive a Telnyx account event + /v1/phone/hooks/twilio: + post: + description: 'Where Twilio asks what to do with a call to one of this router''s Twilio numbers. Unauthenticated because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the account''s Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The call then passes the checks a Telnyx call passes, and the answer dials that number''s own trunk and no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public URL answers 404, so the path never hands out trunk credentials unsigned.' + operationId: receiveTwilioCall + responses: + "200": + content: + application/xml: + schema: + type: string + description: TwiML dialling the number's trunk, rejecting the call, or hanging up + "400": + description: The body is not a form + "401": + description: The call is not signed by Twilio + "404": + description: Twilio calls are not configured + "413": + description: The call is over 64 KiB + "500": + $ref: '#/components/responses/InternalError' + security: [] + summary: Receive a Twilio call /v1/phone/hooks/twilio/events: post: description: 'Where the Twilio account sends its Monitor alerts (the Debugger webhook) and its usage triggers'' callbacks, as form posts. Unauthenticated because Twilio is not a customer: each event is checked against X-Twilio-Signature, made with the account''s Auth Token over ROUTER_PUBLIC_URL and this path, then logged and counted in vendor_account_events_total by its error code or usage category and its level. An alert whose Sid was counted in the last hour is answered 204 and not counted again. A deployment with no Twilio webhook token or no public URL answers 404, so nobody else can raise the count.' diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/receive_twilio_call.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/receive_twilio_call.py new file mode 100644 index 0000000000..a89d308d04 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/receive_twilio_call.py @@ -0,0 +1,172 @@ +from http import HTTPStatus +from typing import Any, cast + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.error_response import ErrorResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/v1/phone/hooks/twilio", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Any | ErrorResponse | None: + if response.status_code == 400: + response_400 = cast(Any, None) + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = cast(Any, None) + return response_404 + + if response.status_code == 413: + response_413 = cast(Any, None) + return response_413 + + if response.status_code == 500: + response_500 = ErrorResponse.from_dict(response.json()) + + return response_500 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Response[Any | ErrorResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[Any | ErrorResponse]: + """Receive a Twilio call + + Where Twilio asks what to do with a call to one of this router's Twilio numbers. Unauthenticated + because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the + account's Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The + call then passes the checks a Telnyx call passes, and the answer dials that number's own trunk and + no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public + URL answers 404, so the path never hands out trunk credentials unsigned. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ErrorResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, +) -> Any | ErrorResponse | None: + """Receive a Twilio call + + Where Twilio asks what to do with a call to one of this router's Twilio numbers. Unauthenticated + because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the + account's Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The + call then passes the checks a Telnyx call passes, and the answer dials that number's own trunk and + no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public + URL answers 404, so the path never hands out trunk credentials unsigned. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ErrorResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[Any | ErrorResponse]: + """Receive a Twilio call + + Where Twilio asks what to do with a call to one of this router's Twilio numbers. Unauthenticated + because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the + account's Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The + call then passes the checks a Telnyx call passes, and the answer dials that number's own trunk and + no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public + URL answers 404, so the path never hands out trunk credentials unsigned. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ErrorResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, +) -> Any | ErrorResponse | None: + """Receive a Twilio call + + Where Twilio asks what to do with a call to one of this router's Twilio numbers. Unauthenticated + because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the + account's Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The + call then passes the checks a Telnyx call passes, and the answer dials that number's own trunk and + no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public + URL answers 404, so the path never hands out trunk credentials unsigned. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ErrorResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 60993af0ff..468ca89046 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -15833,6 +15833,13 @@ type ClientInterface interface { // Corresponds with POST /v1/phone/hooks/telnyx/events (the `ReceiveTelnyxEvent` operationId). ReceiveTelnyxEvent(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + // ReceiveTwilioCall Receive a Twilio call + // + // Where Twilio asks what to do with a call to one of this router's Twilio numbers. Unauthenticated because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The call then passes the checks a Telnyx call passes, and the answer dials that number's own trunk and no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public URL answers 404, so the path never hands out trunk credentials unsigned. + // + // Corresponds with POST /v1/phone/hooks/twilio (the `ReceiveTwilioCall` operationId). + ReceiveTwilioCall(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + // ReceiveTwilioEvent Receive a Twilio account event // // Where the Twilio account sends its Monitor alerts (the Debugger webhook) and its usage triggers' callbacks, as form posts. Unauthenticated because Twilio is not a customer: each event is checked against X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this path, then logged and counted in vendor_account_events_total by its error code or usage category and its level. An alert whose Sid was counted in the last hour is answered 204 and not counted again. A deployment with no Twilio webhook token or no public URL answers 404, so nobody else can raise the count. @@ -21802,6 +21809,23 @@ func (c *Client) ReceiveTelnyxEvent(ctx context.Context, reqEditors ...RequestEd return c.Client.Do(req) } +// ReceiveTwilioCall Receive a Twilio call +// +// Where Twilio asks what to do with a call to one of this router's Twilio numbers. Unauthenticated because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The call then passes the checks a Telnyx call passes, and the answer dials that number's own trunk and no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public URL answers 404, so the path never hands out trunk credentials unsigned. +// +// Corresponds with POST /v1/phone/hooks/twilio (the `ReceiveTwilioCall` operationId). +func (c *Client) ReceiveTwilioCall(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewReceiveTwilioCallRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + // ReceiveTwilioEvent Receive a Twilio account event // // Where the Twilio account sends its Monitor alerts (the Debugger webhook) and its usage triggers' callbacks, as form posts. Unauthenticated because Twilio is not a customer: each event is checked against X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this path, then logged and counted in vendor_account_events_total by its error code or usage category and its level. An alert whose Sid was counted in the last hour is answered 204 and not counted again. A deployment with no Twilio webhook token or no public URL answers 404, so nobody else can raise the count. @@ -32637,6 +32661,33 @@ func NewReceiveTelnyxEventRequest(server string) (*http.Request, error) { return req, nil } +// NewReceiveTwilioCallRequest constructs an http.Request for the ReceiveTwilioCall method +func NewReceiveTwilioCallRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/phone/hooks/twilio") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + // NewReceiveTwilioEventRequest constructs an http.Request for the ReceiveTwilioEvent method func NewReceiveTwilioEventRequest(server string) (*http.Request, error) { var err error @@ -39292,6 +39343,15 @@ type ClientWithResponsesInterface interface { // Corresponds with POST /v1/phone/hooks/telnyx/events (the `ReceiveTelnyxEvent` operationId). ReceiveTelnyxEventWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ReceiveTelnyxEventResponse, error) + // ReceiveTwilioCallWithResponse Receive a Twilio call + // + // Where Twilio asks what to do with a call to one of this router's Twilio numbers. Unauthenticated because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The call then passes the checks a Telnyx call passes, and the answer dials that number's own trunk and no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public URL answers 404, so the path never hands out trunk credentials unsigned. + // + // Returns a wrapper object for the known response body format(s). + // + // Corresponds with POST /v1/phone/hooks/twilio (the `ReceiveTwilioCall` operationId). + ReceiveTwilioCallWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ReceiveTwilioCallResponse, error) + // ReceiveTwilioEventWithResponse Receive a Twilio account event // // Where the Twilio account sends its Monitor alerts (the Debugger webhook) and its usage triggers' callbacks, as form posts. Unauthenticated because Twilio is not a customer: each event is checked against X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this path, then logged and counted in vendor_account_events_total by its error code or usage category and its level. An alert whose Sid was counted in the last hour is answered 204 and not counted again. A deployment with no Twilio webhook token or no public URL answers 404, so nobody else can raise the count. @@ -60304,6 +60364,54 @@ func (r ReceiveTelnyxEventResponse) ContentType() string { return "" } +type ReceiveTwilioCallResponse struct { + Body []byte + HTTPResponse *http.Response + // XML200 the response for an HTTP 200 `application/xml` response + XML200 *string + // JSON500 the response for an HTTP 500 `application/json` response + JSON500 *InternalError +} + +// GetXML200 returns the response for an HTTP 200 `application/xml` response +func (r ReceiveTwilioCallResponse) GetXML200() *string { + return r.XML200 +} + +// GetJSON500 returns the response for an HTTP 500 `application/json` response +func (r ReceiveTwilioCallResponse) GetJSON500() *InternalError { + return r.JSON500 +} + +// GetBody returns the raw response body bytes +func (r ReceiveTwilioCallResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r ReceiveTwilioCallResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ReceiveTwilioCallResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ReceiveTwilioCallResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ReceiveTwilioEventResponse struct { Body []byte HTTPResponse *http.Response @@ -72172,6 +72280,21 @@ func (c *ClientWithResponses) ReceiveTelnyxEventWithResponse(ctx context.Context return ParseReceiveTelnyxEventResponse(rsp) } +// ReceiveTwilioCallWithResponse Receive a Twilio call +// +// Where Twilio asks what to do with a call to one of this router's Twilio numbers. Unauthenticated because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The call then passes the checks a Telnyx call passes, and the answer dials that number's own trunk and no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public URL answers 404, so the path never hands out trunk credentials unsigned. +// +// Returns a wrapper object for the known response body format(s). +// +// Corresponds with POST /v1/phone/hooks/twilio (the `ReceiveTwilioCall` operationId). +func (c *ClientWithResponses) ReceiveTwilioCallWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ReceiveTwilioCallResponse, error) { + rsp, err := c.ReceiveTwilioCall(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseReceiveTwilioCallResponse(rsp) +} + // ReceiveTwilioEventWithResponse Receive a Twilio account event // // Where the Twilio account sends its Monitor alerts (the Debugger webhook) and its usage triggers' callbacks, as form posts. Unauthenticated because Twilio is not a customer: each event is checked against X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this path, then logged and counted in vendor_account_events_total by its error code or usage category and its level. An alert whose Sid was counted in the last hour is answered 204 and not counted again. A deployment with no Twilio webhook token or no public URL answers 404, so nobody else can raise the count. @@ -97089,6 +97212,51 @@ func ParseReceiveTelnyxEventResponse(rsp *http.Response) (*ReceiveTelnyxEventRes return response, nil } +// ParseReceiveTwilioCallResponse parses an HTTP response from a ReceiveTwilioCallWithResponse call +func ParseReceiveTwilioCallResponse(rsp *http.Response) (*ReceiveTwilioCallResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ReceiveTwilioCallResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "xml") && rsp.StatusCode == 200: + var dest string + if err := xml.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.XML200 = &dest + + case rsp.StatusCode == 400: + break // No content-type + + case rsp.StatusCode == 401: + break // No content-type + + case rsp.StatusCode == 404: + break // No content-type + + case rsp.StatusCode == 413: + break // No content-type + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + // ParseReceiveTwilioEventResponse parses an HTTP response from a ReceiveTwilioEventWithResponse call func ParseReceiveTwilioEventResponse(rsp *http.Response) (*ReceiveTwilioEventResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index 4abdc7012b..ba507d6e09 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -3480,6 +3480,26 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; + readonly "/v1/phone/hooks/twilio": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly get?: never; + readonly put?: never; + /** + * Receive a Twilio call + * @description Where Twilio asks what to do with a call to one of this router's Twilio numbers. Unauthenticated because Twilio is not a customer: each call is checked against X-Twilio-Signature, made with the account's Auth Token over ROUTER_PUBLIC_URL and this path, and must name TWILIO_ACCOUNT_SID. The call then passes the checks a Telnyx call passes, and the answer dials that number's own trunk and no other, or rejects or hangs up the call. A deployment with no Twilio webhook token or no public URL answers 404, so the path never hands out trunk credentials unsigned. + */ + readonly post: operations["receiveTwilioCall"]; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; readonly "/v1/phone/hooks/twilio/events": { readonly parameters: { readonly query?: never; @@ -20212,6 +20232,55 @@ export interface operations { readonly 500: components["responses"]["InternalError"]; }; }; + readonly receiveTwilioCall: { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description TwiML dialling the number's trunk, rejecting the call, or hanging up */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/xml": string; + }; + }; + /** @description The body is not a form */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content?: never; + }; + /** @description The call is not signed by Twilio */ + readonly 401: { + headers: { + readonly [name: string]: unknown; + }; + content?: never; + }; + /** @description Twilio calls are not configured */ + readonly 404: { + headers: { + readonly [name: string]: unknown; + }; + content?: never; + }; + /** @description The call is over 64 KiB */ + readonly 413: { + headers: { + readonly [name: string]: unknown; + }; + content?: never; + }; + readonly 500: components["responses"]["InternalError"]; + }; + }; readonly receiveTwilioEvent: { readonly parameters: { readonly query?: never; diff --git a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb index 3a12e7e06f..aed8a9eb7c 100644 --- a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb +++ b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb @@ -1442,6 +1442,12 @@ module Generated body: nil, body_required: false, socket: false, client_accessible: false }.freeze, + "receiveTwilioCall" => { + method: :post, path: "/v1/phone/hooks/twilio", + path_params: [].freeze, query: [].freeze, + body: nil, body_required: false, + socket: false, client_accessible: false + }.freeze, "receiveTwilioEvent" => { method: :post, path: "/v1/phone/hooks/twilio/events", path_params: [].freeze, query: [].freeze, From b1a0e80ec72aac52ced3ea8f8afdb56c7326101e Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 23:49:06 -0500 Subject: [PATCH 03/10] AI-3804: test the Twilio call webhook Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/admission_test.go | 30 +- acceleration/internal/api/telnyxhook_test.go | 15 +- .../internal/api/twiliohook_spec_test.go | 34 ++ acceleration/internal/api/twiliohook_test.go | 349 ++++++++++++++++++ acceleration/internal/config/config_test.go | 24 ++ .../internal/phone/twilio/twilio_test.go | 25 ++ 6 files changed, 471 insertions(+), 6 deletions(-) create mode 100644 acceleration/internal/api/twiliohook_spec_test.go create mode 100644 acceleration/internal/api/twiliohook_test.go diff --git a/acceleration/internal/api/admission_test.go b/acceleration/internal/api/admission_test.go index 34cab8d87b..6bc68cf8da 100644 --- a/acceleration/internal/api/admission_test.go +++ b/acceleration/internal/api/admission_test.go @@ -43,8 +43,10 @@ import ( // acks let go of what was held against them. type AdmissionSuite struct { RouterSuite - // line is Telnyx ringing the suite's numbers, and logged what the router said of it. + // line is Telnyx ringing the suite's numbers, twilio is Twilio ringing them, and logged + // what the router said of it. line telnyxRinger + twilio twilioRinger logged *lockedLog // sharing is the Redis the router shares its holds through, behind a proxy a test can // take down. @@ -63,6 +65,7 @@ func (s *AdmissionSuite) SetupSuite() { public, private, err := ed25519.GenerateKey(rand.Reader) s.Require().NoError(err) s.telnyxPublicKey, s.telnyxConnectionID = public, "1234567890" + s.twilioAuthToken, s.twilioAccountSID, s.publicURL = rand.Text(), twilioAccount(), twilioCallPublicURL s.logged = &lockedLog{} s.logs = s.logged // A voice the deployment runs itself, reached by name only, so a voiced session on a free @@ -72,6 +75,7 @@ func (s *AdmissionSuite) SetupSuite() { routing.ProviderConfig{Provider: "plain", Model: "local-voice", Languages: []string{"la"}, Local: true}) s.RouterSuite.SetupSuite() s.line = telnyxRinger{suite: &s.RouterSuite, private: private} + s.twilio = twilioRinger{suite: &s.RouterSuite, token: s.twilioAuthToken, account: s.twilioAccountSID} // A run cut short leaves its campaigns ringing, and this run's dialer would ring them. _, err = s.store.GlobalDB().ExecContext(context.Background(), "UPDATE campaigns SET state = ? WHERE state IN (?, ?, ?)", store.Stopped, store.Scheduled, store.Running, store.Paused) @@ -567,6 +571,30 @@ func (s *AdmissionSuite) TestACallToANumberOfAnOrganizationThatMayNotPayIsReject s.Contains(s.logged.String(), "code=account_suspended") } +// Defect: a Twilio call to a number of an organization out of credit answered, or answered +// first and then hung up, which bills the call. +func (s *AdmissionSuite) TestATwilioCallToANumberOfAnOrganizationThatMayNotPayIsRejectedUnanswered() { + e164 := s.utils.number() + s.twilio.attach(e164, "sip:"+e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + s.refused(http.MethodPost, "/v1/search", SearchRequest{Query: "anything"}) + form := s.twilio.call(e164) + + status, _, body := s.twilio.deliver(form, s.twilio.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, ``) + s.NotContains(body, "trunk-password") + s.Contains(s.logged.String(), "rejected a twilio call to a number of an organization that may not pay for it") + s.Contains(s.logged.String(), "code=insufficient_credits") + + s.usage.Credit(s.T(), s.organization(), 10_000_000) + s.Eventually(func() bool { + form := s.twilio.call(e164) + _, _, body := s.twilio.deliver(form, s.twilio.sign(form)) + return strings.Contains(body, "sip:"+e164+"@trunk.sip.example.test") + }, 10*time.Second, 50*time.Millisecond, "answered once it has credit") +} + func (s *AdmissionSuite) TestACallArrivingOverStreamForAnOrganizationThatMayNotPayIsNotAnswered() { for _, refused := range []string{codeInsufficientCredits, codeAccountSuspended} { s.Run(refused, func() { diff --git a/acceleration/internal/api/telnyxhook_test.go b/acceleration/internal/api/telnyxhook_test.go index c7e0fa90c2..cd586a1fa7 100644 --- a/acceleration/internal/api/telnyxhook_test.go +++ b/acceleration/internal/api/telnyxhook_test.go @@ -332,13 +332,18 @@ func (l telnyxRinger) deliver(form url.Values, signed bool) (int, string, string } // attach holds the number at Telnyx for the suite's app and attaches it on a trunk of its -// own, as the phone service does, its trunk password sealed under the service's key. An empty -// uri is a number attached before trunks were kept. +// own, as attachOwnTrunk does. func (l telnyxRinger) attach(e164, uri, username, password string) { - s := l.suite + attachOwnTrunk(l.suite, "telnyx", e164, uri, username, password) +} + +// attachOwnTrunk holds the number at the vendor for the suite's app and attaches it on a trunk +// of its own, as the phone service does, its trunk password sealed under the service's key. An +// empty uri is a number attached before trunks were kept. +func attachOwnTrunk(s *RouterSuite, vendor, e164, uri, username, password string) { ctx := context.Background() s.Require().NoError(s.store.PhoneNumbers.Insert(ctx, &store.PhoneNumber{ - E164: e164, Vendor: "telnyx", Country: "US", CustomerID: s.customerID(), PurchasedAt: time.Now().UTC(), + E164: e164, Vendor: vendor, Country: "US", CustomerID: s.customerID(), PurchasedAt: time.Now().UTC(), })) attachment := store.NumberAttachment{TrunkID: "trunk-" + s.utils.uuid(), CallType: "default"} if uri == "" { @@ -349,7 +354,7 @@ func (l telnyxRinger) attach(e164, uri, username, password string) { s.Require().NoError(err) sealed, err := sealer.SealWithAAD(password, []byte("phone_numbers/"+s.customerID()+"/"+e164)) s.Require().NoError(err) - group := store.TrunkGroup{CustomerID: s.customerID(), Vendor: "telnyx"} + group := store.TrunkGroup{CustomerID: s.customerID(), Vendor: vendor} s.Require().NoError(s.store.StreamTrunks.InGroup(ctx, group, func(_ context.Context, tx *store.TrunkGroupTx) error { err := tx.SaveTrunk(store.StreamTrunk{ ID: attachment.TrunkID, BridgeURI: uri, BridgeUsername: username, diff --git a/acceleration/internal/api/twiliohook_spec_test.go b/acceleration/internal/api/twiliohook_spec_test.go new file mode 100644 index 0000000000..cc592abd0a --- /dev/null +++ b/acceleration/internal/api/twiliohook_spec_test.go @@ -0,0 +1,34 @@ +package api + +import ( + "net/http" + "os" + "testing" + + "github.com/go-chi/chi/v5" + "github.com/stretchr/testify/require" +) + +// TestTheTwilioCallHookIsDeclared is the handwritten call webhook: public, named in the spec +// with every answer it gives, in the committed document, and a hook, so nothing it carries is +// read as who is calling. +func TestTheTwilioCallHookIsDeclared(t *testing.T) { + item := (&Server{}).newAPI(chi.NewRouter()).OpenAPI().Paths[twilioCallHookPath] + require.NotNil(t, item) + require.NotNil(t, item.Post) + require.Equal(t, "receiveTwilioCall", item.Post.OperationID) + require.Equal(t, http.MethodPost, item.Post.Method) + require.NotNil(t, item.Post.Security) + require.Empty(t, item.Post.Security) + for _, code := range []string{"200", "400", "401", "404", "413"} { + require.Contains(t, item.Post.Responses, code) + } + require.Contains(t, item.Post.Responses["200"].Content, "application/xml") + + committed, err := os.ReadFile("../../api/openapi.yaml") + require.NoError(t, err) + require.Contains(t, string(committed), "/v1/phone/hooks/twilio:") + + require.True(t, isHook(twilioCallHookPath)) + require.True(t, isHook(twilioEventsHookPath), "the events hook is under the call hook's path") +} diff --git a/acceleration/internal/api/twiliohook_test.go b/acceleration/internal/api/twiliohook_test.go new file mode 100644 index 0000000000..3397641d77 --- /dev/null +++ b/acceleration/internal/api/twiliohook_test.go @@ -0,0 +1,349 @@ +//go:build integration + +package api + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/xml" + "io" + "log/slog" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/GetStream/Vision-Agents/acceleration/internal/activity" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" + "github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig" +) + +// twilioCallPublicURL is the suite's ROUTER_PUBLIC_URL, with the trailing slash an operator may +// write; Twilio signs over it trimmed, then the path. +const twilioCallPublicURL = "http://localhost:8080/" + +// TwilioHookSuite is Twilio asking the router where a call to one of its Twilio numbers goes, +// signed with the account's Auth Token as Twilio signs it. +type TwilioHookSuite struct { + RouterSuite + line twilioRinger + logged *lockedLog + // since is how much of logged had been written when the current test started. + since int + e164 string +} + +func TestTwilioHookSuite(t *testing.T) { + runSuite(t, new(TwilioHookSuite)) +} + +func (s *TwilioHookSuite) SetupSuite() { + s.twilioAuthToken = rand.Text() + s.twilioAccountSID = twilioAccount() + s.publicURL = twilioCallPublicURL + s.logged = &lockedLog{} + s.logs = s.logged + s.RouterSuite.SetupSuite() + s.line = twilioRinger{suite: &s.RouterSuite, token: s.twilioAuthToken, account: s.twilioAccountSID} +} + +func (s *TwilioHookSuite) SetupTest() { + s.since = len(s.logged.String()) + s.useApp(s.data.createApp()) + s.e164 = s.utils.number() +} + +func (s *TwilioHookSuite) TestACallIsSentToTheNumbersOwnTrunkWithItsCredentialsInTheBodyOnly() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-pa$$") + form := s.line.call(s.e164) + + status, contentType, body := s.line.deliver(form, s.line.sign(form)) + + s.Require().Equal(http.StatusOK, status, body) + s.Equal("application/xml", contentType) + var parsed struct { + Dial struct { + Sip struct { + URI string `xml:",chardata"` + Username string `xml:"username,attr"` + Password string `xml:"password,attr"` + } `xml:"Sip"` + } `xml:"Dial"` + } + s.Require().NoError(xml.Unmarshal([]byte(body), &parsed)) + s.Equal("sip:"+s.e164+"@trunk.sip.example.test", parsed.Dial.Sip.URI) + s.Equal("trunk-user", parsed.Dial.Sip.Username) + s.Equal("trunk-pa$$", parsed.Dial.Sip.Password) + s.Require().Eventually(func() bool { return s.loggedLine(`msg="served a request"`, " path="+twilioCallHookPath+" ") }, + settleFor, 10*time.Millisecond) + s.NotContains(s.logged.String(), "trunk-pa$$", "the password is never logged") + s.NotContains(s.logged.String(), "trunk-pa$$<word>", "nor its TwiML") +} + +func (s *TwilioHookSuite) TestACallNotSignedWithTheAccountsTokenOverThisURLIsRefused() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + form := s.line.call(s.e164) + for name, signature := range map[string]string{ + "unsigned": "", + "another token": twiliosig.Sign(rand.Text(), s.line.signedURL(twilioCallHookPath), form), + "another path": twiliosig.Sign(s.twilioAuthToken, s.line.signedURL(twilioEventsHookPath), form), + "another public URL": twiliosig.Sign(s.twilioAuthToken, "http://localhost:9090"+twilioCallHookPath, form), + } { + status, _, body := s.line.deliver(form, signature) + + s.Equal(http.StatusUnauthorized, status, name) + s.NotContains(body, "trunk-password", name) + s.NotContains(body, "", name) + } + s.True(s.loggedLine("level=WARN", "refused a twilio call webhook")) +} + +func (s *TwilioHookSuite) TestASignedCallOnAnotherAccountIsHungUp() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + form := s.line.call(s.e164) + other := twilioAccount() + form.Set("AccountSid", other) + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.NotContains(body, "trunk-password") + s.True(s.loggedLine("another account than TWILIO_ACCOUNT_SID", "account_sid="+other)) +} + +// With no account configured, a signed call that names none must not match "". +func (s *TwilioHookSuite) TestWithoutAConfiguredAccountNoCallIsAnswered() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + configured := s.router.twilioAccountSID + s.router.twilioAccountSID = "" + defer func() { s.router.twilioAccountSID = configured }() + form := s.line.call(s.e164) + form.Del("AccountSid") + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.NotContains(body, "trunk-password") + s.True(s.loggedLine("TWILIO_ACCOUNT_SID is not set")) +} + +func (s *TwilioHookSuite) TestASignedCallThatIsNotInboundIsHungUp() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + form := s.line.call(s.e164) + form.Set("Direction", "outbound-api") + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.NotContains(body, "trunk-password") + s.True(s.loggedLine("not inbound", "direction=outbound-api")) +} + +func (s *TwilioHookSuite) TestASignedCallThatNamesNoNumberIsHungUp() { + form := s.line.call(s.e164) + form.Del("To") + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.True(s.loggedLine("hung up a twilio call that names no number")) +} + +// The number is looked up as a Twilio one: the same number attached at Telnyx is not its trunk. +func (s *TwilioHookSuite) TestACallToANumberNotAttachedAtTwilioIsHungUp() { + attachOwnTrunk(&s.RouterSuite, "telnyx", s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + form := s.line.call(s.e164) + + status, contentType, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Equal("application/xml", contentType) + s.Contains(body, "") + s.NotContains(body, "trunk-password") + s.True(s.loggedLine("hung up a twilio call to a number that is unknown, released or not attached", masked(s.e164))) +} + +// A refusal of the pre-answer checks leaves the call unanswered and is counted refused. +func (s *TwilioHookSuite) TestACallToASuspendedAppIsRejectedUnansweredAndCountedRefused() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + s.Require().NoError(s.store.TelephonySuspensions.Upsert(context.Background(), &store.TelephonySuspension{ + CustomerID: s.customerID(), Reason: "fraud", SuspendedBy: "ops@example.test", + })) + form := s.line.call(s.e164) + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Require().Equal(http.StatusOK, status) + s.Contains(body, ``, + "Reject as the first verb leaves the call unanswered, so no second of it is billed") + s.NotContains(body, "trunk-password") + s.True(s.loggedLine("rejected a twilio call to a number of an app whose telephony is suspended", masked(s.e164))) + row := s.countedOnce(activity.AreaPhoneSMS, store.AuditSourceAPI) + s.Equal(int64(1), row.refused) + s.Equal(codeTelephonySuspended, row.code) +} + +func (s *TwilioHookSuite) TestANumberAttachedBeforeItsTrunkWasKeptIsHungUpAndSaysWhatToDo() { + s.line.attach(s.e164, "", "", "") + form := s.line.call(s.e164) + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.True(s.loggedLine(masked(s.e164), "hung up a twilio call", "attach the number again")) +} + +func (s *TwilioHookSuite) TestWithoutAKeyringACallSaysWhatToSet() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + sealed := s.router.phone + s.router.phone = s.telephonySealedBy(nil, nil, slog.New(slog.NewTextHandler(s.logged, &slog.HandlerOptions{ReplaceAttr: store.RedactLogAttr}))) + defer func() { s.router.phone = sealed }() + form := s.line.call(s.e164) + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.NotContains(body, "trunk-password") + s.True(s.loggedLine(masked(s.e164), "hung up a twilio call: this router has no key to open trunk passwords")) +} + +func (s *TwilioHookSuite) TestWithoutTelephonyACallIsHungUp() { + configured := s.router.phone + s.router.phone = nil + defer func() { s.router.phone = configured }() + form := s.line.call(s.e164) + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.True(s.loggedLine("hung up a twilio call: telephony is not configured")) +} + +// Without the token or the public URL no signature can be checked, so nothing is answered. +func (s *TwilioHookSuite) TestWithoutATokenOrAPublicURLNoCallIsAnswered() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + form := s.line.call(s.e164) + signature := s.line.sign(form) + token, public := s.router.twilioAuthToken, s.router.publicURL + defer func() { s.router.twilioAuthToken, s.router.publicURL = token, public }() + + for name, unset := range map[string]func(){ + "no token": func() { s.router.twilioAuthToken, s.router.publicURL = "", public }, + "no public URL": func() { s.router.twilioAuthToken, s.router.publicURL = token, "/" }, + } { + unset() + status, _, body := s.line.deliver(form, signature) + + s.Equal(http.StatusNotFound, status, name) + s.Contains(body, "twilio calls are not configured", name) + s.NotContains(body, "trunk-password", name) + } +} + +func (s *TwilioHookSuite) TestABodyThatIsNoFormOrTooLargeIsRefused() { + for name, sent := range map[string]struct { + body string + status int + }{ + "not a form": {"To=%zz", http.StatusBadRequest}, + "too large": {"To=" + strings.Repeat("1", twilioCallLimit), http.StatusRequestEntityTooLarge}, + } { + request, err := http.NewRequest(http.MethodPost, s.server.URL+twilioCallHookPath, strings.NewReader(sent.body)) + s.Require().NoError(err) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + response, err := http.DefaultClient.Do(request) + s.Require().NoError(err) + answered, err := io.ReadAll(response.Body) + s.Require().NoError(response.Body.Close()) + s.Require().NoError(err) + + s.Equal(sent.status, response.StatusCode, name) + s.NotContains(string(answered), "", name) + } +} + +// loggedLine reports whether one line the current test logged holds every part. +func (s *TwilioHookSuite) loggedLine(parts ...string) bool { + for _, line := range strings.Split(s.logged.String()[s.since:], "\n") { + found := true + for _, part := range parts { + found = found && strings.Contains(line, part) + } + if found { + return true + } + } + return false +} + +// twilioAccount is a Twilio account SID of the documented shape: AC and 32 hex digits +// (https://www.twilio.com/docs/voice/twiml, AccountSid). +func twilioAccount() string { + digits := make([]byte, 16) + _, _ = rand.Read(digits) + return "AC" + hex.EncodeToString(digits) +} + +// twilioRinger is Twilio calling the suite's router about one of its numbers, signing what it +// posts with token over the suite's public URL. +type twilioRinger struct { + suite *RouterSuite + token string + account string +} + +// call is the form Twilio posts when someone rings a number +// (https://www.twilio.com/docs/voice/twiml, "Twilio's request to your application"). +func (l twilioRinger) call(to string) url.Values { + return url.Values{ + "AccountSid": {l.account}, + "ApiVersion": {"2010-04-01"}, + "CallSid": {"CA" + strings.ReplaceAll(l.suite.utils.uuid(), "-", "")}, + "CallStatus": {"ringing"}, + "Direction": {"inbound"}, + "From": {"+15550001111"}, + "To": {to}, + } +} + +// signedURL is the URL Twilio calls, and signs, for a path on the suite's router. +func (l twilioRinger) signedURL(path string) string { + return strings.TrimRight(l.suite.publicURL, "/") + path +} + +// sign is the X-Twilio-Signature Twilio sends with the form. +func (l twilioRinger) sign(form url.Values) string { + return twiliosig.Sign(l.token, l.signedURL(twilioCallHookPath), form) +} + +// deliver posts the form as Twilio does, with signature unless it is empty, and answers with +// what came back. +func (l twilioRinger) deliver(form url.Values, signature string) (int, string, string) { + request, err := http.NewRequest(http.MethodPost, l.suite.server.URL+twilioCallHookPath, strings.NewReader(form.Encode())) + l.suite.Require().NoError(err) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + if signature != "" { + request.Header.Set(twiliosig.SignatureHeader, signature) + } + response, err := http.DefaultClient.Do(request) + l.suite.Require().NoError(err) + defer response.Body.Close() + answered, err := io.ReadAll(response.Body) + l.suite.Require().NoError(err) + return response.StatusCode, response.Header.Get("Content-Type"), string(answered) +} + +// attach holds the number at Twilio for the suite's app on a trunk of its own, as +// attachOwnTrunk does. +func (l twilioRinger) attach(e164, uri, username, password string) { + attachOwnTrunk(l.suite, "twilio", e164, uri, username, password) +} diff --git a/acceleration/internal/config/config_test.go b/acceleration/internal/config/config_test.go index 1baeaec470..3aa1830eef 100644 --- a/acceleration/internal/config/config_test.go +++ b/acceleration/internal/config/config_test.go @@ -1362,6 +1362,30 @@ func (s *ConfigSuite) TestTheTwilioWebhookAuthTokenInAFileReachesTheEnvironment( s.Equal("token-from-file", os.Getenv("TWILIO_WEBHOOK_AUTH_TOKEN")) } +func (s *ConfigSuite) TestTheTwilioAccountSIDIsReadFromTheEnvironment() { + config, _, err := Load("") + s.Require().NoError(err) + s.Empty(config.Twilio.AccountSID, "unset, no Twilio call is answered") + + s.T().Setenv("TWILIO_ACCOUNT_SID", "AC-from-env") + config, _, err = Load("") + s.Require().NoError(err) + + s.Equal("AC-from-env", config.Twilio.AccountSID) +} + +// The Twilio provider reads TWILIO_ACCOUNT_SID itself, so the setting in a file has to reach it. +func (s *ConfigSuite) TestTheTwilioAccountSIDInAFileReachesTheEnvironment() { + path := filepath.Join(s.T().TempDir(), "router.yaml") + s.Require().NoError(os.WriteFile(path, []byte("twilio:\n account_sid: AC-from-file\n"), 0o600)) + + config, _, err := Load(path) + s.Require().NoError(err) + + s.Equal("AC-from-file", config.Twilio.AccountSID) + s.Equal("AC-from-file", os.Getenv("TWILIO_ACCOUNT_SID")) +} + func (s *ConfigSuite) TestASingleNodeSetsNoShard() { config, _, err := Load("") s.Require().NoError(err) diff --git a/acceleration/internal/phone/twilio/twilio_test.go b/acceleration/internal/phone/twilio/twilio_test.go index dfa3255fb1..4df9e81bb1 100644 --- a/acceleration/internal/phone/twilio/twilio_test.go +++ b/acceleration/internal/phone/twilio/twilio_test.go @@ -871,6 +871,31 @@ func (s *TwilioSuite) TestTheInstructionsTwilioIsGivenAreValidXML() { s.Equal("u", parsed.Dial.SIP.Username) } +// The answer to Twilio's call webhook dials the trunk with its credentials as attributes, escaped, +// in a content type Twilio reads TwiML from. +func (s *TwilioSuite) TestTheAnswerToACallDialsTheTrunkWithItsCredentials() { + plan, err := RenderInbound(phone.Bridge{URI: "sip:+15125550100@trunk.sip.example.test", Username: "u", Password: `pa"ss<&>`}) + s.Require().NoError(err) + + s.Equal("application/xml", plan.ContentType) + s.True(strings.HasPrefix(string(plan.Body), "`, parsed.Dial.SIP.Password) + + _, err = RenderInbound(phone.Bridge{URI: "https://trunk.example.test", Username: "u", Password: "p"}) + s.Error(err, "a trunk that is not a SIP URI is not dialled") +} + +func (s *TwilioSuite) TestARefusedCallIsRejectedOrHungUp() { + s.Equal("application/xml", RenderReject().ContentType) + s.Equal(``+"\n"+``, string(RenderReject().Body)) + s.Equal("application/xml", RenderHangup().ContentType) + s.Equal(``+"\n"+``, string(RenderHangup().Body)) +} + func (s *TwilioSuite) TestAnAnswerThatIsNotJSONIsAVendorErrorWithoutTheBody() { s.respond = func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("not json")) } From 1d5b1e5c68fbc8c62395edf03bbede853bf47983 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 23:52:18 -0500 Subject: [PATCH 04/10] AI-3804: test the router's own failure and the account wiring Co-Authored-By: Claude Opus 5.5 --- .../cmd/router/startup_integration_test.go | 33 +++++++++++++++++++ acceleration/internal/api/twiliohook_test.go | 20 +++++++++++ 2 files changed, 53 insertions(+) diff --git a/acceleration/cmd/router/startup_integration_test.go b/acceleration/cmd/router/startup_integration_test.go index e3af936903..1d563d39cf 100644 --- a/acceleration/cmd/router/startup_integration_test.go +++ b/acceleration/cmd/router/startup_integration_test.go @@ -479,6 +479,39 @@ func (s *RouterStartSuite) TestAStartingRouterWithNoTwilioTokenHasNoTwilioEvents s.Equal(http.StatusNotFound, s.postTwilioAlert(settings.Addr, form, signature)) } +// The router run builds from its settings hands TWILIO_ACCOUNT_SID to the Twilio call route; unwired, +// every call Twilio signs for the account is hung up as naming another. +func (s *RouterStartSuite) TestAStartingRouterTakesATwilioCallOnItsOwnAccount() { + settings := s.settings + settings.Addr = freeAddress(s.T()) + settings.PublicURL = "https://router.example.test" + settings.Twilio.WebhookAuthToken = rand.Text() + settings.Twilio.AccountSID = "AC" + strings.Repeat("0", 31) + "1" + stop, logs := s.startLogged(settings) + + form := url.Values{"AccountSid": {settings.Twilio.AccountSID}, "Direction": {"inbound"}, "To": {"+15125550100"}} + signature := twiliosig.Sign(settings.Twilio.WebhookAuthToken, settings.PublicURL+"/v1/phone/hooks/twilio", form) + request, err := http.NewRequest(http.MethodPost, "http://"+settings.Addr+"/v1/phone/hooks/twilio", + strings.NewReader(form.Encode())) + s.Require().NoError(err) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + request.Header.Set(twiliosig.SignatureHeader, signature) + response, err := http.DefaultClient.Do(request) + s.Require().NoError(err) + s.Require().NoError(response.Body.Close()) + s.Require().NoError(stop()) + + s.Equal(http.StatusOK, response.StatusCode) + var hungUp []string + for _, warning := range logs.warned() { + if strings.HasPrefix(warning, "hung up a twilio call") { + hungUp = append(hungUp, warning) + } + } + s.Require().Len(hungUp, 1, "warnings: %q", logs.warned()) + s.NotContains(hungUp[0], "TWILIO_ACCOUNT_SID", "the call names the router's own account") +} + func (s *RouterStartSuite) postTwilioAlert(address string, form url.Values, signature string) int { request, err := http.NewRequest(http.MethodPost, "http://"+address+"/v1/phone/hooks/twilio/events", strings.NewReader(form.Encode())) diff --git a/acceleration/internal/api/twiliohook_test.go b/acceleration/internal/api/twiliohook_test.go index 3397641d77..b67e18ce41 100644 --- a/acceleration/internal/api/twiliohook_test.go +++ b/acceleration/internal/api/twiliohook_test.go @@ -215,6 +215,26 @@ func (s *TwilioHookSuite) TestWithoutAKeyringACallSaysWhatToSet() { s.True(s.loggedLine(masked(s.e164), "hung up a twilio call: this router has no key to open trunk passwords")) } +// The router's own failure, here a trunk password its key cannot open, is a hang-up counted as +// a server error rather than an answered call. +func (s *TwilioHookSuite) TestATrunkPasswordThatCannotBeOpenedIsHungUpAndCountedRefused() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + _, err := s.store.GlobalDB().NewUpdate().Table("stream_trunks"). + Set("bridge_password_sealed = ?", []byte("not sealed")). + Where("customer_id = ?", s.customerID()).Exec(context.Background()) + s.Require().NoError(err) + form := s.line.call(s.e164) + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.True(s.loggedLine("hung up a twilio call: could not find its trunk", masked(s.e164))) + row := s.countedOnce(activity.AreaPhoneSMS, store.AuditSourceAPI) + s.Equal(int64(1), row.refused) + s.Equal(internalError().Code, row.code) +} + func (s *TwilioHookSuite) TestWithoutTelephonyACallIsHungUp() { configured := s.router.phone s.router.phone = nil From 57f164ee34e33b6284f0cacb61c5bf7ea40d5cfa Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 00:21:30 -0500 Subject: [PATCH 05/10] AI-3804: the too-large test names the declared limit Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/twiliohook_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/api/twiliohook_test.go b/acceleration/internal/api/twiliohook_test.go index b67e18ce41..4cc2c597e0 100644 --- a/acceleration/internal/api/twiliohook_test.go +++ b/acceleration/internal/api/twiliohook_test.go @@ -275,7 +275,8 @@ func (s *TwilioHookSuite) TestABodyThatIsNoFormOrTooLargeIsRefused() { status int }{ "not a form": {"To=%zz", http.StatusBadRequest}, - "too large": {"To=" + strings.Repeat("1", twilioCallLimit), http.StatusRequestEntityTooLarge}, + // The 64 KiB the spec declares, written out so a changed limit cannot pass. + "too large": {"To=" + strings.Repeat("1", 64<<10), http.StatusRequestEntityTooLarge}, } { request, err := http.NewRequest(http.MethodPost, s.server.URL+twilioCallHookPath, strings.NewReader(sent.body)) s.Require().NoError(err) From 3bc51c9ba3c292f72707d27ba34d2cb8e4eb612a Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 07:52:59 -0500 Subject: [PATCH 06/10] AI-3804: .env.example names the Twilio call hook its two settings turn on Co-Authored-By: Claude Opus 5.5 --- .env.example | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index a74686976e..a6a8f78eca 100644 --- a/.env.example +++ b/.env.example @@ -151,12 +151,14 @@ MEM0_API_KEY=your_mem0_api_key_here # is named, so setting one is enough. # Twilio and Telnyx do everything, including answering on a number. +# A call to /v1/phone/hooks/twilio that names another account than TWILIO_ACCOUNT_SID is hung up. TWILIO_ACCOUNT_SID=your_twilio_account_sid_here TWILIO_AUTH_TOKEN=your_twilio_auth_token_here # Optional: sign requests with an API key instead. TWILIO_AUTH_TOKEN then holds its secret. # TWILIO_API_KEY_SID=SK... # Optional: the Auth Token of the Twilio account whose webhooks the router checks; it only checks signatures. -# It turns on /v1/phone/hooks/twilio/events (Monitor alerts, usage triggers), which also needs ROUTER_PUBLIC_URL. +# It turns on /v1/phone/hooks/twilio/events (Monitor alerts, usage triggers) and /v1/phone/hooks/twilio (calls), +# which also need ROUTER_PUBLIC_URL. # TWILIO_WEBHOOK_AUTH_TOKEN= TELNYX_API_KEY=your_telnyx_api_key_here # The Telnyx TeXML application numbers and calls are on, needed for inbound and outbound From e961daccfb3f61518ec320b4932bd165a683ead4 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 07:58:09 -0500 Subject: [PATCH 07/10] AI-3804: test the fail-closed account, direction and signature-first rules Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/twiliohook_test.go | 52 +++++++++++++++----- 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/acceleration/internal/api/twiliohook_test.go b/acceleration/internal/api/twiliohook_test.go index 4cc2c597e0..b1f9c6998f 100644 --- a/acceleration/internal/api/twiliohook_test.go +++ b/acceleration/internal/api/twiliohook_test.go @@ -85,13 +85,20 @@ func (s *TwilioHookSuite) TestACallIsSentToTheNumbersOwnTrunkWithItsCredentialsI func (s *TwilioHookSuite) TestACallNotSignedWithTheAccountsTokenOverThisURLIsRefused() { s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") form := s.line.call(s.e164) - for name, signature := range map[string]string{ - "unsigned": "", - "another token": twiliosig.Sign(rand.Text(), s.line.signedURL(twilioCallHookPath), form), - "another path": twiliosig.Sign(s.twilioAuthToken, s.line.signedURL(twilioEventsHookPath), form), - "another public URL": twiliosig.Sign(s.twilioAuthToken, "http://localhost:9090"+twilioCallHookPath, form), + // The signature is checked before the account: an unsigned call is not answered TwiML. + onAnother := s.line.call(s.e164) + onAnother.Set("AccountSid", twilioAccount()) + for name, sent := range map[string]struct { + form url.Values + signature string + }{ + "unsigned": {form, ""}, + "unsigned, another account": {onAnother, ""}, + "another token": {form, twiliosig.Sign(rand.Text(), s.line.signedURL(twilioCallHookPath), form)}, + "another path": {form, twiliosig.Sign(s.twilioAuthToken, s.line.signedURL(twilioEventsHookPath), form)}, + "another public URL": {form, twiliosig.Sign(s.twilioAuthToken, "http://localhost:9090"+twilioCallHookPath, form)}, } { - status, _, body := s.line.deliver(form, signature) + status, _, body := s.line.deliver(sent.form, sent.signature) s.Equal(http.StatusUnauthorized, status, name) s.NotContains(body, "trunk-password", name) @@ -114,6 +121,20 @@ func (s *TwilioHookSuite) TestASignedCallOnAnotherAccountIsHungUp() { s.True(s.loggedLine("another account than TWILIO_ACCOUNT_SID", "account_sid="+other)) } +// A signed call that names no account is not on TWILIO_ACCOUNT_SID's. +func (s *TwilioHookSuite) TestASignedCallThatNamesNoAccountIsHungUp() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + form := s.line.call(s.e164) + form.Del("AccountSid") + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.NotContains(body, "trunk-password") + s.True(s.loggedLine("another account than TWILIO_ACCOUNT_SID")) +} + // With no account configured, a signed call that names none must not match "". func (s *TwilioHookSuite) TestWithoutAConfiguredAccountNoCallIsAnswered() { s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") @@ -133,15 +154,20 @@ func (s *TwilioHookSuite) TestWithoutAConfiguredAccountNoCallIsAnswered() { func (s *TwilioHookSuite) TestASignedCallThatIsNotInboundIsHungUp() { s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") - form := s.line.call(s.e164) - form.Set("Direction", "outbound-api") + for logged, direct := range map[string]func(url.Values){ + "direction=outbound-api": func(form url.Values) { form.Set("Direction", "outbound-api") }, + `direction=""`: func(form url.Values) { form.Del("Direction") }, + } { + form := s.line.call(s.e164) + direct(form) - status, _, body := s.line.deliver(form, s.line.sign(form)) + status, _, body := s.line.deliver(form, s.line.sign(form)) - s.Equal(http.StatusOK, status) - s.Contains(body, "") - s.NotContains(body, "trunk-password") - s.True(s.loggedLine("not inbound", "direction=outbound-api")) + s.Equal(http.StatusOK, status, logged) + s.Contains(body, "", logged) + s.NotContains(body, "trunk-password", logged) + s.True(s.loggedLine("not inbound", logged), logged) + } } func (s *TwilioHookSuite) TestASignedCallThatNamesNoNumberIsHungUp() { From 740d8e4481bf3f5621df461ac6b058bb18558553 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 08:37:26 -0500 Subject: [PATCH 08/10] AI-3804: answer a Twilio call's CallSid once, again only when the answer 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 --- acceleration/README.md | 2 +- acceleration/internal/api/server.go | 2 + acceleration/internal/api/twiliohook.go | 82 ++++++++++ acceleration/internal/api/twiliohook_test.go | 164 ++++++++++++++++++- 4 files changed, 244 insertions(+), 6 deletions(-) diff --git a/acceleration/README.md b/acceleration/README.md index 6813c95b48..7e998424ef 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -158,7 +158,7 @@ the other commands that read them there. | `TWILIO_ACCOUNT_SID` | Twilio credentials, for buying and operating numbers. A call to `/v1/phone/hooks/twilio` that names another account is hung up | | `TWILIO_AUTH_TOKEN` | Twilio credentials. With `TWILIO_API_KEY_SID` set, that key's secret | | `TWILIO_API_KEY_SID` | Optional Twilio API key (SK...). Requests are signed with it instead of the account SID | -| `TWILIO_WEBHOOK_AUTH_TOKEN` | Auth Token of the Twilio account whose webhooks the router checks (`X-Twilio-Signature`). It only checks signatures: those of the Monitor alerts and usage-trigger callbacks sent to `/v1/phone/hooks/twilio/events`, and the calls sent to `/v1/phone/hooks/twilio`, each signed over `ROUTER_PUBLIC_URL` and the path. Without it, or without `ROUTER_PUBLIC_URL`, both routes answer 404. A token with whitespace in it stops the router at start | +| `TWILIO_WEBHOOK_AUTH_TOKEN` | Auth Token of the Twilio account whose webhooks the router checks (`X-Twilio-Signature`). It only checks signatures: those of the Monitor alerts and usage-trigger callbacks sent to `/v1/phone/hooks/twilio/events`, and the calls sent to `/v1/phone/hooks/twilio`, each signed over `ROUTER_PUBLIC_URL` and the path. Without it, or without `ROUTER_PUBLIC_URL`, both routes answer 404. A call is answered once per `CallSid`, marked in Redis for a week: a copy of it is hung up, unless the first answer did not reach Twilio, and without Redis every call is hung up. A token with whitespace in it stops the router at start | | `TELNYX_API_KEY` | Telnyx credentials | | `TELNYX_CONNECTION_ID` | The Telnyx TeXML application numbers and calls are on. Calls to the webhook from any other application are hung up | | `TELNYX_PUBLIC_KEY` | Telnyx's public key (base64), to check the calls it sends to `/v1/phone/hooks/telnyx` and the account events it sends to `/v1/phone/hooks/telnyx/events`. Without it Telnyx numbers are not answered and the events route answers 404. Telnyx numbers also need a key encryption keyring (`ROUTER_DEV_KEK` locally, `ROUTER_AUTH_KEK_V_WRAPPED` hosted): without one they cannot be attached | diff --git a/acceleration/internal/api/server.go b/acceleration/internal/api/server.go index 90c04d59f1..704c3a3943 100644 --- a/acceleration/internal/api/server.go +++ b/acceleration/internal/api/server.go @@ -372,6 +372,7 @@ type Server struct { chatInboundKeys []ed25519.PublicKey twilioAuthToken string twilioAlertSids rueidis.Client // nil without Redis: every copy of an alert is counted + twilioCallSids rueidis.Client // nil without Redis: every Twilio call is hung up twilioAccountSID string telnyxConnectionID string simulations *simulation.Runner @@ -676,6 +677,7 @@ func NewServer(options Options, with ...Option) (*Server, error) { server.runSlots, server.runsPerApp = concurrency.New(options.Live.Redis(), nil), options.RunsPerApp server.newGuests = core.NewLimiter(options.Live.Redis(), nil) server.twilioAlertSids = options.Live.Redis() + server.twilioCallSids = options.Live.Redis() } server.imageHTTP = options.ImageHTTP server.documents = options.Documents diff --git a/acceleration/internal/api/twiliohook.go b/acceleration/internal/api/twiliohook.go index ca28af9dda..6a91bb0be3 100644 --- a/acceleration/internal/api/twiliohook.go +++ b/acceleration/internal/api/twiliohook.go @@ -1,10 +1,15 @@ package api import ( + "context" "errors" "io" + "log/slog" "net/http" "net/url" + "time" + + "github.com/redis/rueidis" phonetwilio "github.com/GetStream/Vision-Agents/acceleration/internal/phone/twilio" ) @@ -17,6 +22,27 @@ const twilioCallHookPath = "/v1/phone/hooks/twilio" // (https://www.twilio.com/docs/voice/twiml, "Twilio's request to your application"). const twilioCallLimit = 64 << 10 +// twilioCallKey prefixes the Redis key that marks a call's CallSid as answered. The key holds +// only the CallSid, which names the call at Twilio and no customer. +const twilioCallKey = "phone:twilio:call:" + +// twilioCallAnsweredFor is how long an answered CallSid is remembered, so how long a copy of a +// signed call is refused. Twilio's signature holds no time +// (https://www.twilio.com/docs/usage/webhooks/webhooks-security), so after it a copy is answered +// again. A week is far past any call: Twilio ends one after 4 hours, or 24 with its longer limit +// turned on (timeLimit, https://www.twilio.com/docs/voice/twiml/dial), and it bounds the keys to +// one week's calls. +const twilioCallAnsweredFor = 7 * 24 * time.Hour + +// twilioCallSidLimit is the longest CallSid that is marked. A Call's Sid is 34 characters +// (^CA[0-9a-fA-F]{32}$, https://www.twilio.com/docs/voice/api/call-resource), so 64 bytes keeps +// every key small; a call with a longer one, or none, is hung up. +const twilioCallSidLimit = 64 + +// twilioCallMarkTimeout bounds marking or forgetting a CallSid, as twilioAlertMarkTimeout does an +// alert's: one SET of one key is answered in well under a millisecond by a Redis that is up. +const twilioCallMarkTimeout = time.Second + // twilioPlans are the TwiML answers to a Twilio call. var twilioPlans = callPlans{ vendor: "twilio", renderDial: phonetwilio.RenderInbound, @@ -28,6 +54,13 @@ var twilioPlans = callPlans{ // // Once the request is known to be Twilio's, every failure is a hangup or a reject rather than an // HTTP error, as for a Telnyx call: Twilio would otherwise play its own error to the caller. +// +// Each CallSid is answered once: a signed call has no time in it, so a copy of it would get the +// trunk's credentials again. Twilio sends a call again only when it got no answer: by default +// after a failed connect or TLS handshake, and with the URL's overrides after a read timeout or a +// 5xx (https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). So the CallSid +// is marked before the answer and forgotten when the answer did not reach Twilio, and a copy of a +// call whose answer did is hung up. func (s *Server) receiveTwilioCall(w http.ResponseWriter, r *http.Request) { if !s.twilioConfigured() { // Without the token anyone could ask this path for a number's trunk credentials. @@ -79,5 +112,54 @@ func (s *Server) receiveTwilioCall(w http.ResponseWriter, r *http.Request) { twilioPlans.hangUp(w, logger, "hung up a twilio call that names no number") return } + sid := form.Get("CallSid") + if s.twilioCallSids == nil { + // Otherwise a copy of a signed call would be answered with the trunk's credentials again. + twilioPlans.hangUp(w, logger, "hung up a twilio call: there is no Redis to answer each call once") + return + } + if sid == "" || len(sid) > twilioCallSidLimit { + twilioPlans.hangUp(w, logger, "hung up a twilio call that names no CallSid, or one too long to mark") + return + } + first, err := s.markTwilioCall(r.Context(), sid) + if err != nil { + twilioPlans.hangUp(w, logger, "hung up a twilio call: could not mark it answered", "error", err) + return + } + if !first { + twilioPlans.hangUp(w, logger, "hung up a twilio call that was answered already") + return + } s.answerCall(w, r, logger, twilioPlans, to) + // Twilio, gone before the answer reached it, sends the call again; that copy is answered. + if err := http.NewResponseController(w).Flush(); err != nil || r.Context().Err() != nil { + s.forgetTwilioCall(r.Context(), logger, sid) + } +} + +// markTwilioCall marks the CallSid as answered for twilioCallAnsweredFor, and reports whether it +// was not marked already. +func (s *Server) markTwilioCall(ctx context.Context, sid string) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, twilioCallMarkTimeout) + defer cancel() + mark := s.twilioCallSids.B().Set().Key(twilioCallKey + sid).Value("1").Nx().Ex(twilioCallAnsweredFor).Build() + err := s.twilioCallSids.Do(ctx, mark).Error() + if rueidis.IsRedisNil(err) { + return false, nil + } + return err == nil, err +} + +// forgetTwilioCall drops the mark of a call whose answer did not reach Twilio. Twilio may have +// hung up, which ends the request's context, so the mark is dropped without it. +func (s *Server) forgetTwilioCall(ctx context.Context, logger *slog.Logger, sid string) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), twilioCallMarkTimeout) + defer cancel() + if err := s.twilioCallSids.Do(ctx, s.twilioCallSids.B().Del().Key(twilioCallKey+sid).Build()).Error(); err != nil { + logger.Warn("could not forget a twilio call whose answer did not reach Twilio; its retry is hung up", + "error", err) + return + } + logger.Warn("the answer to a twilio call did not reach Twilio; its retry is answered") } diff --git a/acceleration/internal/api/twiliohook_test.go b/acceleration/internal/api/twiliohook_test.go index b1f9c6998f..ec6c4e7799 100644 --- a/acceleration/internal/api/twiliohook_test.go +++ b/acceleration/internal/api/twiliohook_test.go @@ -7,14 +7,18 @@ import ( "crypto/rand" "encoding/hex" "encoding/xml" + "errors" "io" "log/slog" "net/http" + "net/http/httptest" "net/url" "strings" "testing" "time" + "github.com/redis/rueidis" + "github.com/GetStream/Vision-Agents/acceleration/internal/activity" "github.com/GetStream/Vision-Agents/acceleration/internal/store" "github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig" @@ -318,6 +322,150 @@ func (s *TwilioHookSuite) TestABodyThatIsNoFormOrTooLargeIsRefused() { } } +// A copy of a signed call, Twilio's own or a replay, gets no second Dial once the first was +// answered: the signature has no time in it, so the copy would get the password again. +func (s *TwilioHookSuite) TestACallAnsweredOnceIsHungUpWithoutItsPasswordWhenSentAgain() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "replayed-password") + form := s.line.call(s.e164) + signature := s.line.sign(form) + _, _, first := s.line.deliver(form, signature) + s.Require().Contains(first, `password="replayed-password"`) + + status, _, again := s.line.deliver(form, signature) + + s.Equal(http.StatusOK, status) + s.Contains(again, "") + s.NotContains(again, "replayed-password") + s.True(s.loggedLine("hung up a twilio call that was answered already", "call_sid="+form.Get("CallSid"))) + remembered, err := s.router.twilioCallSids.Do(context.Background(), + s.router.twilioCallSids.B().Ttl().Key("phone:twilio:call:"+form.Get("CallSid")).Build()).AsInt64() + s.Require().NoError(err) + s.InDelta(7*24*60*60, remembered, 60, "a copy is refused for a week, written out so a changed TTL cannot pass") +} + +// Twilio sends a call again when its answer never reached Twilio +// (https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides), and that copy is +// answered; the one after it is not. +func (s *TwilioHookSuite) TestACallWhoseAnswerDidNotReachTwilioIsAnsweredWhenSentAgain() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "retried-password") + for name, lost := range map[string]func(cancel context.CancelFunc) *lostAnswer{ + "the answer could not be sent": func(context.CancelFunc) *lostAnswer { + return &lostAnswer{ResponseRecorder: httptest.NewRecorder(), flush: errors.New("broken pipe")} + }, + "Twilio hung up while it was written": func(cancel context.CancelFunc) *lostAnswer { + return &lostAnswer{ResponseRecorder: httptest.NewRecorder(), onWrite: cancel} + }, + } { + form := s.line.call(s.e164) + signature := s.line.sign(form) + ctx, cancel := context.WithCancel(context.Background()) + answer := lost(cancel) + s.router.receiveTwilioCall(answer, s.line.request(ctx, form, signature)) + cancel() + s.Require().Contains(answer.Body.String(), `password="retried-password"`, name) + + _, _, retried := s.line.deliver(form, signature) + _, _, replayed := s.line.deliver(form, signature) + + s.Contains(retried, `password="retried-password"`, name) + s.Contains(replayed, "", name) + s.NotContains(replayed, "retried-password", name) + s.True(s.loggedLine("level=WARN", "did not reach Twilio; its retry is answered", "call_sid="+form.Get("CallSid")), name) + } +} + +// A Redis that fails to forget a lost answer leaves the call marked: its retry is hung up, and +// the failure says so. +func (s *TwilioHookSuite) TestACallWhoseLostAnswerCannotBeForgottenIsHungUpWhenSentAgain() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "kept-password") + marks, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{s.redisAddr}, DisableCache: true}) + s.Require().NoError(err) + sids := s.router.twilioCallSids + s.T().Cleanup(func() { s.router.twilioCallSids = sids }) + s.router.twilioCallSids = marks + form := s.line.call(s.e164) + signature := s.line.sign(form) + answer := &lostAnswer{ResponseRecorder: httptest.NewRecorder(), flush: errors.New("broken pipe"), onFlush: marks.Close} + + s.router.receiveTwilioCall(answer, s.line.request(context.Background(), form, signature)) + s.router.twilioCallSids = sids + _, _, retried := s.line.deliver(form, signature) + + s.Require().Contains(answer.Body.String(), `password="kept-password"`) + s.Contains(retried, "") + s.NotContains(retried, "kept-password") + s.True(s.loggedLine("level=WARN", "could not forget a twilio call", "call_sid="+form.Get("CallSid"), "error=")) +} + +// Without a place to mark a call answered, or with one that fails, no call is answered: each +// copy would get the password. +func (s *TwilioHookSuite) TestWithoutAWorkingRedisNoCallIsAnswered() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "unmarked-password") + closed, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{s.redisAddr}, DisableCache: true}) + s.Require().NoError(err) + closed.Close() + sids := s.router.twilioCallSids + s.T().Cleanup(func() { s.router.twilioCallSids = sids }) + + for logged, client := range map[string]rueidis.Client{ + "there is no Redis to answer each call once": nil, + "could not mark it answered": closed, + } { + s.router.twilioCallSids = client + form := s.line.call(s.e164) + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status, logged) + s.Contains(body, "", logged) + s.NotContains(body, "unmarked-password", logged) + s.True(s.loggedLine("level=WARN", "hung up a twilio call", logged), logged) + } +} + +// A call is marked by its CallSid, so one without a CallSid that can be marked is not answered. +func (s *TwilioHookSuite) TestACallWithNoCallSidOrOneTooLongIsHungUp() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "trunk-password") + for name, sid := range map[string]string{ + "no CallSid": "", + // 65 bytes, one past the 64 marked, written out so a changed limit cannot pass. + "too long": "CA" + strings.Repeat("0", 63), + } { + form := s.line.call(s.e164) + form.Set("CallSid", sid) + + status, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Equal(http.StatusOK, status, name) + s.Contains(body, "", name) + s.NotContains(body, "trunk-password", name) + s.True(s.loggedLine("hung up a twilio call that names no CallSid, or one too long to mark"), name) + } +} + +// lostAnswer is a response that never reaches Twilio: its flush fails, or writing it calls +// onWrite, as Twilio hanging up ends the request's context. +type lostAnswer struct { + *httptest.ResponseRecorder + flush error + onWrite context.CancelFunc + onFlush func() +} + +func (a *lostAnswer) Write(body []byte) (int, error) { + if a.onWrite != nil { + a.onWrite() + } + return a.ResponseRecorder.Write(body) +} + +func (a *lostAnswer) FlushError() error { + if a.onFlush != nil { + a.onFlush() + } + return a.flush +} + // loggedLine reports whether one line the current test logged holds every part. func (s *TwilioHookSuite) loggedLine(parts ...string) bool { for _, line := range strings.Split(s.logged.String()[s.since:], "\n") { @@ -372,16 +520,22 @@ func (l twilioRinger) sign(form url.Values) string { return twiliosig.Sign(l.token, l.signedURL(twilioCallHookPath), form) } -// deliver posts the form as Twilio does, with signature unless it is empty, and answers with -// what came back. -func (l twilioRinger) deliver(form url.Values, signature string) (int, string, string) { - request, err := http.NewRequest(http.MethodPost, l.suite.server.URL+twilioCallHookPath, strings.NewReader(form.Encode())) +// request is the form posted as Twilio does, with signature unless it is empty. +func (l twilioRinger) request(ctx context.Context, form url.Values, signature string) *http.Request { + request, err := http.NewRequestWithContext(ctx, http.MethodPost, l.suite.server.URL+twilioCallHookPath, + strings.NewReader(form.Encode())) l.suite.Require().NoError(err) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") if signature != "" { request.Header.Set(twiliosig.SignatureHeader, signature) } - response, err := http.DefaultClient.Do(request) + return request +} + +// deliver posts the form as Twilio does, with signature unless it is empty, and answers with +// what came back. +func (l twilioRinger) deliver(form url.Values, signature string) (int, string, string) { + response, err := http.DefaultClient.Do(l.request(context.Background(), form, signature)) l.suite.Require().NoError(err) defer response.Body.Close() answered, err := io.ReadAll(response.Body) From cded6659f0c9beb41992566c6cfb0f70b3183336 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 09:27:15 -0500 Subject: [PATCH 09/10] AI-3804: pin the atomic claim of a call and To over Called in tests Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/twiliohook_test.go | 50 ++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/acceleration/internal/api/twiliohook_test.go b/acceleration/internal/api/twiliohook_test.go index ec6c4e7799..840874470f 100644 --- a/acceleration/internal/api/twiliohook_test.go +++ b/acceleration/internal/api/twiliohook_test.go @@ -14,6 +14,7 @@ import ( "net/http/httptest" "net/url" "strings" + "sync" "testing" "time" @@ -343,6 +344,55 @@ func (s *TwilioHookSuite) TestACallAnsweredOnceIsHungUpWithoutItsPasswordWhenSen s.InDelta(7*24*60*60, remembered, 60, "a copy is refused for a week, written out so a changed TTL cannot pass") } +// Eight copies of one signed call arrive at once: exactly one is answered with the password. +// A mark checked first and written after lets several copies pass the check together. +func (s *TwilioHookSuite) TestCopiesOfOneCallSentAtOnceAreAnsweredOnlyOnce() { + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "parallel-password") + for round := range 20 { + form := s.line.call(s.e164) + signature := s.line.sign(form) + bodies := make([]string, 8) + errs := make([]error, len(bodies)) + var wg sync.WaitGroup + for i := range bodies { + wg.Go(func() { + response, err := http.DefaultClient.Do(s.line.request(context.Background(), form, signature)) + if err != nil { + errs[i] = err + return + } + defer response.Body.Close() + answered, err := io.ReadAll(response.Body) + bodies[i], errs[i] = string(answered), err + }) + } + wg.Wait() + answered := 0 + for i, body := range bodies { + s.Require().NoError(errs[i]) + if strings.Contains(body, "parallel-password") { + answered++ + } + } + s.Equal(1, answered, "round %d: copies answered with the password", round) + } +} + +// Twilio names the number it rang in To; Called is the same number on a plain call, but a +// forwarded one names the original number there, and the credentials are those of To. +func (s *TwilioHookSuite) TestACallIsAnsweredForToWhateverCalledNames() { + other := s.utils.number() + s.line.attach(s.e164, "sip:"+s.e164+"@trunk.sip.example.test", "trunk-user", "to-password") + s.line.attach(other, "sip:"+other+"@trunk.sip.example.test", "other-user", "other-password") + form := s.line.call(s.e164) + form.Set("Called", other) + + _, _, body := s.line.deliver(form, s.line.sign(form)) + + s.Contains(body, `password="to-password"`) + s.NotContains(body, "other-password") +} + // Twilio sends a call again when its answer never reached Twilio // (https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides), and that copy is // answered; the one after it is not. From 7651f8e329ac3ff9a1b803edb33daf263bd55a83 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 10:00:17 -0500 Subject: [PATCH 10/10] AI-3804: the Twilio call hook reaches its TwiML through the phone registry, not the vendor package Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/twiliohook.go | 6 +++--- .../internal/phone/vendors/twilioanswer.go | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 acceleration/internal/phone/vendors/twilioanswer.go diff --git a/acceleration/internal/api/twiliohook.go b/acceleration/internal/api/twiliohook.go index 6a91bb0be3..fe6c7f6774 100644 --- a/acceleration/internal/api/twiliohook.go +++ b/acceleration/internal/api/twiliohook.go @@ -11,7 +11,7 @@ import ( "github.com/redis/rueidis" - phonetwilio "github.com/GetStream/Vision-Agents/acceleration/internal/phone/twilio" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/vendors" ) // twilioCallHookPath is the voice URL a Twilio number is to be pointed at. Twilio asks it what @@ -45,8 +45,8 @@ const twilioCallMarkTimeout = time.Second // twilioPlans are the TwiML answers to a Twilio call. var twilioPlans = callPlans{ - vendor: "twilio", renderDial: phonetwilio.RenderInbound, - renderReject: phonetwilio.RenderReject, renderHangup: phonetwilio.RenderHangup, + vendor: "twilio", renderDial: vendors.TwilioCallAnswers.Dial, + renderReject: vendors.TwilioCallAnswers.Reject, renderHangup: vendors.TwilioCallAnswers.Hangup, } // receiveTwilioCall answers a call to one of the router's Twilio numbers with TwiML that dials diff --git a/acceleration/internal/phone/vendors/twilioanswer.go b/acceleration/internal/phone/vendors/twilioanswer.go new file mode 100644 index 0000000000..6f073eb73e --- /dev/null +++ b/acceleration/internal/phone/vendors/twilioanswer.go @@ -0,0 +1,19 @@ +package vendors + +import ( + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/twilio" +) + +// TwilioCallAnswers are the TwiML answers to Twilio's call webhook. They are here, in the +// registry, so the API that serves the webhook imports no vendor package. +var TwilioCallAnswers = CallAnswers{ + Dial: twilio.RenderInbound, Reject: twilio.RenderReject, Hangup: twilio.RenderHangup, +} + +// CallAnswers are the answers a vendor's call webhook gives, each in that vendor's dialect. +type CallAnswers struct { + Dial func(phone.Bridge) (phone.Plan, error) + Reject func() phone.Plan + Hangup func() phone.Plan +}