diff --git a/.claude/skills/phonecheck/SKILL.md b/.claude/skills/phonecheck/SKILL.md index 41a1193215..746ce2fe0e 100644 --- a/.claude/skills/phonecheck/SKILL.md +++ b/.claude/skills/phonecheck/SKILL.md @@ -37,8 +37,8 @@ skill asks what to test, sets it up, runs, reports and puts things back. or `printf 'header = "Authorization: Bearer %s"\n' "$TELNYX_PERSON_API_KEY" | curl -sS -K - …`. Pipe every reply through `jq` and keep only the fields named here. - **Voice URLs: classify, never print.** A vendor's voice URL or connection setting can embed a - password: an attached router number's Twilio voice URL holds the Stream SIP trunk's. Never - print a voice URL; keep one only after the credential check in "Voice URLs" below passes. + password: the voice URL of a router number attached before the router's call webhook existed + holds the Stream SIP trunk's. Never print a voice URL; keep one only after the credential check in "Voice URLs" below passes. - **Encode numbers.** A `+` in a query must be encoded: `curl -G --data-urlencode 'PhoneNumber=+15550100002'`, and the same for Telnyx `filter[…]` keys. In a router path it stays as is. - **Ask with AskUserQuestion,** one step at a time, defaults first. Accept several answers at once. @@ -128,12 +128,14 @@ to its database (migrations, and the router's own background work). 2. **Env names** (only the chosen vendors' matter): ```bash - bash -c 'set -a; . ; set +a; for k in STREAM_API_KEY STREAM_API_SECRET ROUTER_POSTGRES_DSN ROUTER_DEV_KEK TWILIO_PERSON_ACCOUNT_SID TWILIO_PERSON_AUTH_TOKEN TELNYX_PERSON_API_KEY TELNYX_PERSON_ACCOUNT_SID TELNYX_PERSON_CONNECTION_ID TWILIO_ACCOUNT_SID TWILIO_AUTH_TOKEN TELNYX_API_KEY TELNYX_CONNECTION_ID TELNYX_PUBLIC_KEY; do [ -n "${!k}" ] && echo "ok $k" || echo "MISSING $k"; done' + bash -c 'set -a; . ; set +a; for k in STREAM_API_KEY STREAM_API_SECRET ROUTER_POSTGRES_DSN ROUTER_DEV_KEK TWILIO_PERSON_ACCOUNT_SID TWILIO_PERSON_AUTH_TOKEN TELNYX_PERSON_API_KEY TELNYX_PERSON_ACCOUNT_SID TELNYX_PERSON_CONNECTION_ID TWILIO_ACCOUNT_SID TWILIO_AUTH_TOKEN TELNYX_API_KEY TELNYX_CONNECTION_ID TELNYX_PUBLIC_KEY TWILIO_WEBHOOK_AUTH_TOKEN; do [ -n "${!k}" ] && echo "ok $k" || echo "MISSING $k"; done' ``` Remote needs only the Stream keys and the person's. Local also needs `ROUTER_POSTGRES_DSN` (the `call_sites` row), the router's vendor keys, and `ROUTER_DEV_KEK` to attach a Telnyx - number. The `*_PERSON_*` account may be the router's (`TWILIO_PERSON_ACCOUNT_SID=$TWILIO_ACCOUNT_SID` + or Twilio number. Attaching a Twilio number also needs `TWILIO_WEBHOOK_AUTH_TOKEN` and the + router started with `ROUTER_PUBLIC_URL=`: the number's voice URL is the router's + `/v1/phone/hooks/twilio` there. The `*_PERSON_*` account may be the router's (`TWILIO_PERSON_ACCOUNT_SID=$TWILIO_ACCOUNT_SID` in `.env`, after the router's lines). See README §3. 3. **Local router.** Check nothing listens: `lsof -nP -iTCP:8080 -sTCP:LISTEN`; if something does, show it and ask. Starting it runs migrations, binds :8080 and may start background @@ -204,7 +206,8 @@ Show ONE summary and wait for an explicit yes: webhook), say plainly: while the test runs, real calls to that number reach the test script instead; it is put back afterwards. Recommend a number used only for tests. Never print the URL; - cleanup: what goes back (hooks, voice URLs, `connection_id`s, tunnel, router), what stays (the - bought numbers, until you say otherwise), and that release is asked per number afterwards. + bought numbers, until you say otherwise; a kept Twilio router number points at the closed + tunnel), and that release is asked per number afterwards. No yes: nothing is bought or changed; stop the router this skill started and end. @@ -220,7 +223,11 @@ In this order, each change into the state file: (the call hook only: a text to the agent's channel is not answered by this local router) (`-remove ` only if approved; `-app ` only for a router in app mode). A local Telnyx router's own TeXML app (`TELNYX_CONNECTION_ID`) needs its voice URL on the tunnel; the - human sets that. + human sets that. Before any Twilio router number is attached, restart the local router with + `ROUTER_PUBLIC_URL=` added to its start command (section 1, step 3), as the + Twilio number's voice URL is built from it: `kill` the router's id from the state file, wait + until nothing listens on :8080, start it again, and write the new process id to the state + file. The env file's `ROUTER_PUBLIC_URL` is a local address Twilio cannot reach. 2. **Router numbers.** Buy (see the table); add to "bought this run". For inbound, after its outbound runs: attach. 3. **Person numbers.** Twilio `POST …/IncomingPhoneNumbers.json` with `PhoneNumber=` (keep @@ -278,7 +285,9 @@ it lists, in reverse: release (see the table; it also unwires an attached one), while the router still runs. Person number: Twilio `DELETE …/IncomingPhoneNumbers/.json`, Telnyx `DELETE /v2/phone_numbers/`. Say what is kept and what stays attached: an attached - number blocks inbound tests on other numbers. + number blocks inbound tests on other numbers. A kept Twilio router number keeps its voice + URL on the closed tunnel: its calls fail until the router is reachable there again, so say + so. 4. Stop any phonecheck run left (`pkill -INT -x phonecheck`), then the tunnel, then the router: `kill ` for each process id in the state file, then their background tasks. Check that nothing is left: `pgrep -x phonecheck`, `pgrep -f 'cloudflared tunnel --url http://localhost:8080'` diff --git a/acceleration/README.md b/acceleration/README.md index 5d27cfb96c..bbad3fd737 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -160,7 +160,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 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 | +| `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 and a Twilio number cannot be attached: an attached number's voice URL is `ROUTER_PUBLIC_URL` and `/v1/phone/hooks/twilio`, by POST. `ROUTER_PUBLIC_URL` must be an https address for a Twilio attach, so a local router on `http://localhost` refuses it. 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/evals/telephony-latency/README.md b/acceleration/evals/telephony-latency/README.md index 7e38d2aa59..f8f3cb09cf 100644 --- a/acceleration/evals/telephony-latency/README.md +++ b/acceleration/evals/telephony-latency/README.md @@ -25,6 +25,7 @@ off the network, before any jitter buffer, so a handset would add its own on top ## Running it Credentials come from the environment: `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN`, +`TWILIO_WEBHOOK_AUTH_TOKEN` (the account's Auth Token, which signs Twilio's webhooks), `TELNYX_API_KEY`, `TELNYX_CONNECTION_ID` and `TELNYX_CALL_CONTROL_ID`. Optionally `IPINFO_TOKEN` for the report's address lookups. @@ -33,7 +34,7 @@ cd acceleration go run ./evals/telephony-latency provision # buys 2 numbers per vendor per city: 40 numbers ``` -Then on a VM in each GCP region, with UDP 5060 and 20000-20999 open to the carriers: +Then on a VM in each GCP region, with UDP 5060 and 20000-20999 and TCP 8080 open to the carriers: ```bash go run ./evals/telephony-latency run -host -region us-east1 @@ -53,7 +54,9 @@ for a smoke test, `-scope all` to call between cities as well, `-parallel` for c ### Carrier setup -- **Twilio** needs nothing: the bench sets each number's voice URL to TwiML that dials it. +- **Twilio** needs nothing more: the bench points each number's voice URL at the call webhook it + serves on `-hook-listen` (`http://:8080/v1/phone/hooks/twilio`), which answers each signed + call with TwiML that dials the bench. - **Telnyx** routes inbound calls through `TELNYX_CONNECTION_ID`. Make it an FQDN/IP connection pointing at the bench's address, with the destination number in E.164. Each region's bench needs its own connection, or the connection repointed before each run. diff --git a/acceleration/evals/telephony-latency/hook.go b/acceleration/evals/telephony-latency/hook.go new file mode 100644 index 0000000000..06fd71f54d --- /dev/null +++ b/acceleration/evals/telephony-latency/hook.go @@ -0,0 +1,53 @@ +package main + +import ( + "log/slog" + "net/http" + + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/twilio" + "github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig" +) + +// hookLimit caps the form Twilio posts to the hook, which is a few hundred bytes +// (https://www.twilio.com/docs/voice/twiml, "Twilio's request to your application"). +const hookLimit = 64 << 10 + +// TwilioHook answers Twilio's call webhook as the router does, with the bench as the trunk: a +// Twilio number is pointed at the webhook, so the bench serves it to be told where calls go. +type TwilioHook struct { + // Token is the Auth Token Twilio signs the webhook with. + Token string + // PublicURL is where Twilio reaches the bench's webhook, which the signature is over. + PublicURL string + // Bridges is where each number's calls go, by number. + Bridges map[string]phone.Bridge + Log *slog.Logger +} + +// ServeHTTP answers a signed call to one of the bench's numbers with TwiML dialing the bench, +// and any other signed call with a hangup. +func (h *TwilioHook) ServeHTTP(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, hookLimit) + if err := r.ParseForm(); err != nil { + http.Error(w, "that is not a form", http.StatusBadRequest) + return + } + signature := r.Header.Get(twiliosig.SignatureHeader) + if err := twiliosig.Verify(h.Token, h.PublicURL+phone.TwilioCallHookPath, r.PostForm, signature); err != nil { + http.Error(w, "that is not a call from Twilio", http.StatusUnauthorized) + return + } + + plan := twilio.RenderHangup() + if bridge, ok := h.Bridges[r.PostForm.Get("To")]; ok { + dial, err := twilio.RenderInbound(bridge) + if err != nil { + h.Log.Error("telephony-latency: render a twilio call", "to", r.PostForm.Get("To"), "error", err) + } else { + plan = dial + } + } + w.Header().Set("Content-Type", plan.ContentType) + _, _ = w.Write(plan.Body) +} diff --git a/acceleration/evals/telephony-latency/hook_test.go b/acceleration/evals/telephony-latency/hook_test.go new file mode 100644 index 0000000000..06b78145c2 --- /dev/null +++ b/acceleration/evals/telephony-latency/hook_test.go @@ -0,0 +1,160 @@ +package main + +import ( + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "net/netip" + "net/url" + "strings" + "testing" + + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" + "github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig" +) + +type TwilioHookSuite struct { + suite.Suite + hook *TwilioHook + server *httptest.Server +} + +func TestTwilioHookSuite(t *testing.T) { + suite.Run(t, new(TwilioHookSuite)) +} + +func (s *TwilioHookSuite) SetupTest() { + s.hook = &TwilioHook{ + Token: "bench-token", PublicURL: "http://203.0.113.7:8080", + Bridges: map[string]phone.Bridge{"+15125550100": {URI: "sip:+15125550100@203.0.113.7:5060"}}, + Log: slog.New(slog.DiscardHandler), + } + s.server = httptest.NewServer(s.hook) +} + +func (s *TwilioHookSuite) TearDownTest() { s.server.Close() } + +// post sends body to the hook with signature, as Twilio does, and answers the status and body. +func (s *TwilioHookSuite) post(body, signature string) (int, string) { + request, err := http.NewRequest(http.MethodPost, s.server.URL+phone.TwilioCallHookPath, strings.NewReader(body)) + 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) + defer response.Body.Close() + answered, err := io.ReadAll(response.Body) + s.Require().NoError(err) + return response.StatusCode, string(answered) +} + +// signed is the signature Twilio sends with form, over the bench's public URL and the path. +func (s *TwilioHookSuite) signed(form url.Values) string { + return twiliosig.Sign(s.hook.Token, s.hook.PublicURL+phone.TwilioCallHookPath, form) +} + +func (s *TwilioHookSuite) TestASignedCallToABenchNumberDialsTheBench() { + form := url.Values{"To": {"+15125550100"}, "Direction": {"inbound"}} + + status, body := s.post(form.Encode(), s.signed(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "sip:+15125550100@203.0.113.7:5060") +} + +func (s *TwilioHookSuite) TestASignedCallToAnotherNumberIsHungUp() { + form := url.Values{"To": {"+15125550199"}, "Direction": {"inbound"}} + + status, body := s.post(form.Encode(), s.signed(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") + s.NotContains(body, "") +} + +// A number whose bridge cannot be dialled is hung up rather than answered with an empty plan. +func (s *TwilioHookSuite) TestASignedCallToANumberWithABadBridgeIsHungUp() { + s.hook.Bridges["+15125550100"] = phone.Bridge{URI: "https://203.0.113.7/not-sip"} + form := url.Values{"To": {"+15125550100"}, "Direction": {"inbound"}} + + status, body := s.post(form.Encode(), s.signed(form)) + + s.Equal(http.StatusOK, status) + s.Contains(body, "") +} + +func (s *TwilioHookSuite) TestACallNotSignedOverTheBenchsURLIsRefused() { + form := url.Values{"To": {"+15125550100"}} + for name, signature := range map[string]string{ + "unsigned": "", + "another token": twiliosig.Sign("another-token", s.hook.PublicURL+phone.TwilioCallHookPath, form), + "another URL": twiliosig.Sign(s.hook.Token, "http://198.51.100.1:8080"+phone.TwilioCallHookPath, form), + } { + s.Run(name, func() { + status, body := s.post(form.Encode(), signature) + + s.Equal(http.StatusUnauthorized, status) + s.NotContains(body, "sip:") + }) + } +} + +func (s *TwilioHookSuite) TestABodyThatIsNoFormOrTooLargeIsRefused() { + for name, body := range map[string]string{ + "no form": "To=%zz", + "too large": "To=" + strings.Repeat("1", 64<<10), + } { + s.Run(name, func() { + status, _ := s.post(body, "") + + s.Equal(http.StatusBadRequest, status) + }) + } +} + +// The bench serves the hook at the URL it returns until it is closed, and only with a token. +func (s *TwilioHookSuite) TestTheBenchServesTheHookWhereItSaysUntilClosed() { + bridges := map[string]phone.Bridge{"+15125550100": {URI: "sip:+15125550100@127.0.0.1:5060"}} + host := netip.MustParseAddr("127.0.0.1") + log := slog.New(slog.DiscardHandler) + s.T().Setenv(twiliosig.AuthTokenEnvVar, "") + _, _, err := serveTwilioHook("127.0.0.1:0", host, bridges, log) + s.ErrorContains(err, twiliosig.AuthTokenEnvVar) + + s.T().Setenv(twiliosig.AuthTokenEnvVar, "bench-token") + _, _, err = serveTwilioHook("127.0.0.1", host, bridges, log) + s.ErrorContains(err, "missing port", "an address with no port") + taken, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + defer taken.Close() + _, _, err = serveTwilioHook(taken.Addr().String(), host, bridges, log) + s.ErrorContains(err, "serve twilio's call webhook") + + free, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + address := free.Addr().String() + s.Require().NoError(free.Close()) + publicURL, server, err := serveTwilioHook(address, host, bridges, log) + s.Require().NoError(err) + s.Equal("http://"+address, publicURL) + + form := url.Values{"To": {"+15125550100"}} + request, err := http.NewRequest(http.MethodPost, publicURL+phone.TwilioCallHookPath, strings.NewReader(form.Encode())) + s.Require().NoError(err) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + request.Header.Set(twiliosig.SignatureHeader, twiliosig.Sign("bench-token", publicURL+phone.TwilioCallHookPath, form)) + response, err := http.DefaultClient.Do(request) + s.Require().NoError(err) + body, err := io.ReadAll(response.Body) + s.Require().NoError(err) + s.Require().NoError(response.Body.Close()) + s.Contains(string(body), "sip:+15125550100@127.0.0.1:5060") + + s.Require().NoError(server.Close()) + _, err = http.Post(publicURL+phone.TwilioCallHookPath, "application/x-www-form-urlencoded", strings.NewReader(form.Encode())) + s.Error(err, "nothing serves the hook once it is closed") +} diff --git a/acceleration/evals/telephony-latency/main.go b/acceleration/evals/telephony-latency/main.go index 41d9886425..a37fb3e18b 100644 --- a/acceleration/evals/telephony-latency/main.go +++ b/acceleration/evals/telephony-latency/main.go @@ -38,6 +38,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/phone" "github.com/GetStream/Vision-Agents/acceleration/internal/phone/telnyx" "github.com/GetStream/Vision-Agents/acceleration/internal/phone/twilio" + "github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig" ) // minGap is the shortest time between stamps on a call. The two directions go half a gap @@ -103,6 +104,7 @@ func run(ctx context.Context, arguments []string, log *slog.Logger) error { numbers := flags.String("numbers", "numbers.json", "file of numbers from provision") hostFlag := flags.String("host", "", "public IPv4 address carriers reach this machine at (required)") listen := flags.String("listen", "0.0.0.0:5060", "UDP address to take SIP on") + hookListen := flags.String("hook-listen", "0.0.0.0:8080", "TCP address Twilio's call webhook is served on, over http") rtpRange := flags.String("rtp-ports", "20000-20999", "UDP ports for media, as low-high") region := flags.String("region", "", "where this bench runs, e.g. us-east1; recorded with every call") vendorList := flags.String("vendors", "", "only these vendors' numbers (default: all on file)") @@ -173,10 +175,23 @@ func run(ctx context.Context, arguments []string, log *slog.Logger) error { } defer endpoint.Close() + bridges := map[string]phone.Bridge{} + for _, line := range lines { + bridges[line.E164] = phone.Bridge{URI: fmt.Sprintf("sip:%s@%s:%d", line.E164, host, sipPort)} + } + var hookURL string + if vendorNames["twilio"] { + var hook *http.Server + if hookURL, hook, err = serveTwilioHook(*hookListen, host, bridges, log); err != nil { + return err + } + defer hook.Close() + } + if !*skipInbound { for _, line := range lines { - bridge := phone.Bridge{URI: fmt.Sprintf("sip:%s@%s:%d", line.E164, host, sipPort)} - if err := providers[line.Vendor].ConfigureInbound(ctx, phone.Inbound{E164: line.E164, Bridge: bridge}); err != nil { + inbound := phone.Inbound{E164: line.E164, Bridge: bridges[line.E164], PublicURL: hookURL} + if err := providers[line.Vendor].ConfigureInbound(ctx, inbound); err != nil { return fmt.Errorf("point %s at the bench: %w", line.E164, err) } } @@ -310,7 +325,7 @@ func newProviders(names []string) (map[string]phone.Provider, error) { var err error switch name { case "twilio": - provider, err = twilio.New(twilio.Options{}) + provider, err = twilio.New(twilio.Options{PlainHTTPHook: true}) case "telnyx": provider, err = telnyx.New(telnyx.Options{}) default: @@ -380,6 +395,31 @@ func portRange(text string) (int, int, error) { return low, high, nil } +// serveTwilioHook serves Twilio's call webhook on listen until the server is closed, and returns +// the public URL Twilio reaches it at. +func serveTwilioHook(listen string, host netip.Addr, bridges map[string]phone.Bridge, log *slog.Logger) (string, *http.Server, error) { + token := os.Getenv(twiliosig.AuthTokenEnvVar) + if token == "" { + return "", nil, errors.New(twiliosig.AuthTokenEnvVar + " is required: twilio numbers ask the bench's webhook where calls go") + } + listener, err := net.Listen("tcp", listen) + if err != nil { + return "", nil, fmt.Errorf("serve twilio's call webhook on %s: %w", listen, err) + } + port := listener.Addr().(*net.TCPAddr).Port + publicURL := "http://" + net.JoinHostPort(host.String(), strconv.Itoa(port)) + server := &http.Server{ + Handler: &TwilioHook{Token: token, PublicURL: publicURL, Bridges: bridges, Log: log}, + ReadHeaderTimeout: 10 * time.Second, + } + go func() { + if err := server.Serve(listener); !errors.Is(err, http.ErrServerClosed) { + log.Error("telephony-latency: twilio's call webhook stopped", "error", err) + } + }() + return publicURL, server, nil +} + func listenPort(listen string) (int, error) { _, portText, err := net.SplitHostPort(listen) if err != nil { diff --git a/acceleration/internal/api/router_suite_test.go b/acceleration/internal/api/router_suite_test.go index c19291a604..f8dfe2ec7a 100644 --- a/acceleration/internal/api/router_suite_test.go +++ b/acceleration/internal/api/router_suite_test.go @@ -105,6 +105,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/tts" "github.com/GetStream/Vision-Agents/acceleration/internal/tts/voices" "github.com/GetStream/Vision-Agents/acceleration/internal/ttsrouter" + "github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig" "github.com/GetStream/Vision-Agents/acceleration/internal/usage" "github.com/GetStream/Vision-Agents/acceleration/internal/usage/usagetest" "github.com/GetStream/Vision-Agents/acceleration/prices" @@ -1728,6 +1729,8 @@ func (s *RouterSuite) forgetPhoneVendors() { s.Require().NoError(os.Unsetenv(name)) } } + // The Twilio provider reads it too, to point numbers at the call webhook. + s.Require().NoError(os.Unsetenv(twiliosig.AuthTokenEnvVar)) } // telephony serves the phone paths against the real vendor registry with no credentials diff --git a/acceleration/internal/api/twilioattach_test.go b/acceleration/internal/api/twilioattach_test.go new file mode 100644 index 0000000000..d59aafc8ac --- /dev/null +++ b/acceleration/internal/api/twilioattach_test.go @@ -0,0 +1,259 @@ +//go:build integration + +package api + +import ( + "context" + "encoding/json" + "encoding/xml" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "time" + + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/telnyx" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/twilio" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/vendors" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" + "github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig" +) + +// A number attached at Twilio is pointed at this router's call webhook, by POST, and a call +// Twilio signs over that voice URL is answered there with the number's trunk. +func (s *TwilioHookSuite) TestANumberAttachedAtTwilioIsAnsweredAtTheVoiceURLTwilioWasGiven() { + vendor := newFakeVendor(s.e164) + defer vendor.Close() + service := s.attacher(vendor, attacherSettings{ + token: s.twilioAuthToken, account: s.twilioAccountSID, publicURL: s.publicURL, sealed: true, + }) + s.hold(s.e164, "twilio") + + attached, err := service.Attach(context.Background(), phone.Attachment{CustomerID: s.customerID(), E164: s.e164}) + s.Require().NoError(err) + + configured := vendor.posted() + s.Require().Len(configured, 1) + voiceURL := configured[0].Get("VoiceUrl") + s.Equal(strings.TrimRight(s.publicURL, "/")+"/v1/phone/hooks/twilio", voiceURL) + s.Equal(http.MethodPost, configured[0].Get("VoiceMethod")) + s.NotContains(voiceURL, "#", "no connection overrides: the webhook answers each CallSid once") + s.Require().NotEmpty(attached.Bridge.Password) + for _, value := range configured[0] { + s.NotContains(strings.Join(value, " "), attached.Bridge.Password) + } + + parsed, err := url.Parse(voiceURL) + s.Require().NoError(err) + form := s.line.call(s.e164) + request, err := http.NewRequest(http.MethodPost, s.server.URL+parsed.Path, strings.NewReader(form.Encode())) + s.Require().NoError(err) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + request.Header.Set(twiliosig.SignatureHeader, twiliosig.Sign(s.twilioAuthToken, voiceURL, form)) + response, err := http.DefaultClient.Do(request) + s.Require().NoError(err) + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + s.Require().NoError(err) + s.Require().Equal(http.StatusOK, response.StatusCode, string(body)) + var answer 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(body, &answer), string(body)) + s.Equal(attached.Bridge.URI, answer.Dial.Sip.URI) + s.Equal(attached.Bridge.Username, answer.Dial.Sip.Username) + s.Equal(attached.Bridge.Password, answer.Dial.Sip.Password) +} + +// Without what the router needs to answer the call webhook, a Twilio number is not attached: +// nothing is made at Stream, the app's call hook included, and Twilio is asked nothing. +func (s *TwilioHookSuite) TestATwilioNumberIsNotAttachedWithoutWhatItsCallWebhookNeeds() { + ready := attacherSettings{token: s.twilioAuthToken, account: s.twilioAccountSID, publicURL: s.publicURL, sealed: true} + for name, test := range map[string]struct { + settings attacherSettings + refusal string + }{ + "no webhook token": {settings: ready.without(func(a *attacherSettings) { a.token = "" }), refusal: "TWILIO_WEBHOOK_AUTH_TOKEN"}, + "no public URL": {settings: ready.without(func(a *attacherSettings) { a.publicURL = "" }), refusal: "ROUTER_PUBLIC_URL"}, + "a plain http URL": {settings: ready.without(func(a *attacherSettings) { a.publicURL = "http://router.example.test" }), refusal: "https"}, + "no account SID": {settings: ready.without(func(a *attacherSettings) { a.account = "" }), refusal: "TWILIO_ACCOUNT_SID"}, + "no keyring": {settings: ready.without(func(a *attacherSettings) { a.sealed = false }), refusal: "stored trunk"}, + } { + s.Run(name, func() { + e164 := s.utils.number() + vendor := newFakeVendor(e164) + defer vendor.Close() + service := s.attacher(vendor, test.settings) + s.hold(e164, "twilio") + trunks := s.chat.Trunks() + s.chat.SetEventHooks(s.chat.Key) + + _, err := service.Attach(context.Background(), phone.Attachment{CustomerID: s.customerID(), E164: e164}) + + s.ErrorContains(err, test.refusal) + s.Empty(vendor.asked(), "twilio was asked nothing") + s.Equal(trunks, s.chat.Trunks(), "no trunk was made at Stream") + s.Empty(s.chat.EventHooks(s.chat.Key), "the app's call hook was not written") + number, err := s.store.PhoneNumbers.GetByE164(context.Background(), s.customerID(), e164) + s.Require().NoError(err) + s.Nil(number.AttachedAt) + }) + } +} + +// A number attached already is not pointed anywhere again, so attaching it again still answers +// with what it has where the webhook's settings are gone: programs send it on every start. +func (s *TwilioHookSuite) TestAnAttachedTwilioNumberAttachedAgainWithoutTheWebhookTokenAnswers() { + vendor := newFakeVendor(s.e164) + defer vendor.Close() + ready := attacherSettings{token: s.twilioAuthToken, account: s.twilioAccountSID, publicURL: s.publicURL, sealed: true} + s.hold(s.e164, "twilio") + first, err := s.attacher(vendor, ready).Attach(context.Background(), phone.Attachment{CustomerID: s.customerID(), E164: s.e164}) + s.Require().NoError(err) + asked := len(vendor.asked()) + + unready := s.attacher(vendor, ready.without(func(a *attacherSettings) { a.token, a.publicURL = "", "" })) + again, err := unready.Attach(context.Background(), phone.Attachment{CustomerID: s.customerID(), E164: s.e164}) + + s.Require().NoError(err) + s.Equal(first.TrunkID, again.TrunkID) + s.Len(vendor.asked(), asked, "twilio is not told anything new") +} + +// Telnyx numbers are attached as before: the number is put on the TeXML application, with no +// public URL needed. The requests are those base 52435fe23 sent. +func (s *TwilioHookSuite) TestATelnyxNumberIsAttachedAsBefore() { + vendor := newFakeVendor(s.e164) + defer vendor.Close() + config, err := phone.DefaultConfig() + s.Require().NoError(err) + for i := range config.Vendors { + config.Vendors[i].Credentials = nil + } + registry := vendors.Registry(config) + registry.Register("telnyx", func() (phone.Provider, error) { + return telnyx.New(telnyx.Options{APIKey: "k", ConnectionID: "texml-1", BaseURL: vendor.URL}) + }) + sealer, err := auth.NewSealer(suiteTrunkKEK) + s.Require().NoError(err) + service, err := phone.NewService(phone.ServiceOptions{ + Registry: registry, Store: s.store, Stream: phone.NewStreamFromClient(s.chat.Client), Sealer: sealer, + Logger: slog.New(slog.DiscardHandler), + }) + s.Require().NoError(err) + s.hold(s.e164, "telnyx") + + _, err = service.Attach(context.Background(), phone.Attachment{CustomerID: s.customerID(), E164: s.e164}) + + s.Require().NoError(err) + s.Equal([]string{ + "GET /v2/phone_numbers?filter%5Bphone_number%5D=" + url.QueryEscape(s.e164), + `PATCH /v2/phone_numbers/PN1 {"connection_id":"texml-1"}`, + }, vendor.asked()) +} + +// attacherSettings are what a deployment has for its Twilio numbers. +type attacherSettings struct { + token, account, publicURL string + // sealed is a deployment with a keyring. + sealed bool +} + +// without is the settings with change made to a copy. +func (a attacherSettings) without(change func(*attacherSettings)) attacherSettings { + change(&a) + return a +} + +// attacher is a phone service attaching the suite's numbers in its Stream app, with Twilio at +// vendor and the settings given. +func (s *TwilioHookSuite) attacher(vendor *fakeVendor, settings attacherSettings) *phone.Service { + config, err := phone.DefaultConfig() + s.Require().NoError(err) + // The suites share one process, so the credentials are handed to the provider instead. + for i := range config.Vendors { + config.Vendors[i].Credentials = nil + } + registry := vendors.Registry(config) + registry.Register("twilio", func() (phone.Provider, error) { + return twilio.New(twilio.Options{ + AccountSID: settings.account, AuthToken: "api-secret", WebhookAuthToken: settings.token, BaseURL: vendor.URL, + }) + }) + var sealer *auth.Sealer + if settings.sealed { + sealer, err = auth.NewSealer(suiteTrunkKEK) + s.Require().NoError(err) + } + service, err := phone.NewService(phone.ServiceOptions{ + Registry: registry, Store: s.store, Stream: phone.NewStreamFromClient(s.chat.Client), Sealer: sealer, + PublicURL: settings.publicURL, Logger: slog.New(slog.DiscardHandler), + }) + s.Require().NoError(err) + return service +} + +// hold records the number as the suite's app's, bought from vendor. +func (s *TwilioHookSuite) hold(e164, vendor string) { + s.Require().NoError(s.store.PhoneNumbers.Insert(context.Background(), &store.PhoneNumber{ + E164: e164, Vendor: vendor, Country: "US", CustomerID: s.customerID(), PurchasedAt: time.Now().UTC(), + })) +} + +// fakeVendor is Twilio's and Telnyx's number APIs holding one number, recording every request. +type fakeVendor struct { + *httptest.Server + mu sync.Mutex + requests []string + forms []url.Values +} + +func newFakeVendor(e164 string) *fakeVendor { + vendor := &fakeVendor{} + vendor.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + vendor.mu.Lock() + asked := r.Method + " " + r.URL.RequestURI() + if len(body) > 0 { + asked += " " + string(body) + } + vendor.requests = append(vendor.requests, asked) + if r.Method == http.MethodPost { + form, _ := url.ParseQuery(string(body)) + vendor.forms = append(vendor.forms, form) + } + vendor.mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + listed := []map[string]string{{"sid": "PN1", "id": "PN1", "phone_number": e164}} + _ = json.NewEncoder(w).Encode(map[string]any{ + "incoming_phone_numbers": listed, "data": listed, "sid": "PN1", "phone_number": e164, + }) + })) + return vendor +} + +// asked is every request the vendor got, as method, path and query, then the body. +func (v *fakeVendor) asked() []string { + v.mu.Lock() + defer v.mu.Unlock() + return append([]string(nil), v.requests...) +} + +// posted is the form of every POST the vendor got. +func (v *fakeVendor) posted() []url.Values { + v.mu.Lock() + defer v.mu.Unlock() + return append([]url.Values(nil), v.forms...) +} diff --git a/acceleration/internal/api/twiliohook.go b/acceleration/internal/api/twiliohook.go index fe6c7f6774..3cbb377b0c 100644 --- a/acceleration/internal/api/twiliohook.go +++ b/acceleration/internal/api/twiliohook.go @@ -11,12 +11,13 @@ import ( "github.com/redis/rueidis" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" "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 -// to do with each call to the number. -const twilioCallHookPath = "/v1/phone/hooks/twilio" +// twilioCallHookPath is the voice URL a Twilio number is pointed at. Twilio asks it what to do +// with each call to the number. +const twilioCallHookPath = phone.TwilioCallHookPath // 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"). diff --git a/acceleration/internal/api/twiliohook_test.go b/acceleration/internal/api/twiliohook_test.go index 840874470f..8ee7687f17 100644 --- a/acceleration/internal/api/twiliohook_test.go +++ b/acceleration/internal/api/twiliohook_test.go @@ -27,7 +27,7 @@ import ( // 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/" +const twilioCallPublicURL = "https://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. diff --git a/acceleration/internal/phone/apps_integration_test.go b/acceleration/internal/phone/apps_integration_test.go index a2bb6c0fdf..325b9ccb26 100644 --- a/acceleration/internal/phone/apps_integration_test.go +++ b/acceleration/internal/phone/apps_integration_test.go @@ -122,6 +122,15 @@ func aNumber() string { func (s *AppsSuite) config() Config { config, err := DefaultConfig() s.Require().NoError(err) + // The suite's stub vendor is named twilio but dials the trunk it is given, as Twilio did + // before its numbers asked the router where each call goes, so what the service does with + // no keyring is still exercised. Twilio as declared is attached in the api package's + // TwilioHookSuite. + for i, vendor := range config.Vendors { + if vendor.Vendor == "twilio" { + config.Vendors[i].AsksForTrunk = false + } + } return config } diff --git a/acceleration/internal/phone/hooks.go b/acceleration/internal/phone/hooks.go index 1176a05ed3..af3a5168bf 100644 --- a/acceleration/internal/phone/hooks.go +++ b/acceleration/internal/phone/hooks.go @@ -18,6 +18,11 @@ import ( // cannot disagree about the path. const CallHookPath = "/v1/phone/hooks/stream" +// TwilioCallHookPath is where Twilio asks the router what to do with a call to one of its +// numbers. It is here so the vendor that points a number at it and the server that serves it +// cannot disagree about the path. +const TwilioCallHookPath = "/v1/phone/hooks/twilio" + // callHookEvents are the events the router asks for. // // Only these, deliberately. An app-wide hook asking for everything would deliver every message diff --git a/acceleration/internal/phone/phone.go b/acceleration/internal/phone/phone.go index 4ed2462e56..463d6e40a7 100644 --- a/acceleration/internal/phone/phone.go +++ b/acceleration/internal/phone/phone.go @@ -385,6 +385,9 @@ type Inbound struct { E164 string // Bridge is where the vendor should send the call. Bridge Bridge + // PublicURL is where the router is reachable from the internet. A vendor whose numbers ask + // a webhook of the router's where each call goes (CallHooked) points them there. + PublicURL string } // CallFeature names one of the terms a call can be placed on. @@ -486,6 +489,15 @@ type InboundStopper interface { StopInbound(ctx context.Context, e164 string) error } +// CallHooked is a vendor whose numbers are pointed at a webhook of the router's, which answers +// each of their calls. Attach asks it first, so a number is not pointed at a webhook that +// would refuse its calls. +type CallHooked interface { + // CallHookReady reports which setting the router lacks to answer the vendor's call webhook + // at publicURL, or nil when it lacks none. + CallHookReady(publicURL string) error +} + // NumberFinder is a vendor that can say whether its account holds a number, which settles a // purchase or a release whose outcome was not recorded (Service.SweepOrders). type NumberFinder interface { diff --git a/acceleration/internal/phone/phone.yaml b/acceleration/internal/phone/phone.yaml index 5d640dfca1..4632ac7140 100644 --- a/acceleration/internal/phone/phone.yaml +++ b/acceleration/internal/phone/phone.yaml @@ -22,6 +22,8 @@ vendors: capabilities: [voice, sms, mms] credentials: [TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN] trunk_auth: password + # The number's voice URL asks /v1/phone/hooks/twilio where each call goes. + asks_for_trunk: true - vendor: telnyx implemented: true diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index 7d28d28485..4a22f803fc 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -995,6 +995,14 @@ func (s *Service) Attach(ctx context.Context, attachment Attachment) (Attached, held.Vendor, ErrNoSealer)) } attachedHere := held.AttachedAt != nil && held.StreamTrunkID != "" && held.StreamAppPK == pin + // Refused before anything is made, the app's call hook included, as a number pointed at a + // webhook that refuses its calls would look fine and never answer. A number attached + // already is not pointed anywhere again, so it is not refused. + if hooked, ok := provider.(CallHooked); ok && !attachedHere { + if err := hooked.CallHookReady(s.publicURL); err != nil { + return Attached{}, err + } + } if err := s.pointCallHook(ctx, stream, pin); err != nil { if !attachedHere { return Attached{}, err @@ -1132,7 +1140,7 @@ func (s *Service) finishAttach(ctx context.Context, provider Provider, attachmen ConfigID: held.ConfigID, } - err := provider.ConfigureInbound(ctx, Inbound{E164: attachment.E164, Bridge: attached.Bridge}) + err := provider.ConfigureInbound(ctx, Inbound{E164: attachment.E164, Bridge: attached.Bridge, PublicURL: s.publicURL}) if err != nil { return stack.Wrap(err) } diff --git a/acceleration/internal/phone/twilio/integration_test.go b/acceleration/internal/phone/twilio/integration_test.go index 08587e52f7..ee6523cef6 100644 --- a/acceleration/internal/phone/twilio/integration_test.go +++ b/acceleration/internal/phone/twilio/integration_test.go @@ -30,7 +30,8 @@ func (s *TwilioIntegrationSuite) SetupSuite() { s.T().Skip(accountSIDEnvVar + " and " + authTokenEnvVar + " not set") } - provider, err := New(Options{}) + // No webhook is answered here, but a number is only looked up once a token is set. + provider, err := New(Options{WebhookAuthToken: "not-checked-here"}) s.Require().NoError(err) s.provider = provider } @@ -59,8 +60,9 @@ func (s *TwilioIntegrationSuite) TestANumberThisAccountDoesNotOwnIsReportedAsSuc defer cancel() err := s.provider.ConfigureInbound(ctx, phone.Inbound{ - E164: "+15005550006", - Bridge: phone.Bridge{URI: "sip:nobody@sip.stream-io-api.com"}, + E164: "+15005550006", + Bridge: phone.Bridge{URI: "sip:nobody@sip.stream-io-api.com"}, + PublicURL: "https://router.example.test", }) s.ErrorContains(err, "not one of this account's numbers") diff --git a/acceleration/internal/phone/twilio/twilio.go b/acceleration/internal/phone/twilio/twilio.go index 14332e7f9f..88bd35c05c 100644 --- a/acceleration/internal/phone/twilio/twilio.go +++ b/acceleration/internal/phone/twilio/twilio.go @@ -27,6 +27,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/phone" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" + "github.com/GetStream/Vision-Agents/acceleration/internal/twiliosig" ) const ( @@ -68,6 +69,9 @@ type Options struct { APIKeySID string // AuthToken defaults to TWILIO_AUTH_TOKEN. With APIKeySID set it is that key's secret. AuthToken string + // WebhookAuthToken defaults to TWILIO_WEBHOOK_AUTH_TOKEN, which the router checks its call + // webhook's signatures with. Without it no number is pointed at that webhook. + WebhookAuthToken string // BaseURL defaults to Twilio's API host. BaseURL string // PricingURL defaults to Twilio's pricing host. @@ -76,6 +80,10 @@ type Options struct { Timeout time.Duration // HTTPClient replaces the one built from Timeout. HTTPClient *http.Client + // PlainHTTPHook lets a number's voice URL be an http address. Without it only https is + // taken, as the webhook's answer holds the number's trunk credentials. Only a bench whose + // answer holds none sets it. + PlainHTTPHook bool } // Provider is Twilio. It satisfies phone.Provider. @@ -87,6 +95,10 @@ type Provider struct { baseURL string pricingURL string client *http.Client + // hookSigned is whether the router checks the signature of its call webhook. + hookSigned bool + // plainHTTPHook is whether the voice URL may be an http address. + plainHTTPHook bool mu sync.Mutex prices map[string]countryPrices @@ -109,6 +121,9 @@ func New(options Options) (*Provider, error) { if options.APIKeySID == "" { options.APIKeySID = os.Getenv(apiKeySIDEnvVar) } + if options.WebhookAuthToken == "" { + options.WebhookAuthToken = os.Getenv(twiliosig.AuthTokenEnvVar) + } if options.AccountSID == "" || options.AuthToken == "" { return nil, stack.Wrap(errors.New("twilio: " + accountSIDEnvVar + " and " + authTokenEnvVar + " are required")) } @@ -129,10 +144,13 @@ func New(options Options) (*Provider, error) { accountSID: options.AccountSID, user: cmp.Or(options.APIKeySID, options.AccountSID), authToken: options.AuthToken, - baseURL: strings.TrimSuffix(options.BaseURL, "/"), - pricingURL: strings.TrimSuffix(options.PricingURL, "/"), - client: options.HTTPClient, - prices: map[string]countryPrices{}, + hookSigned: options.WebhookAuthToken != "", + + plainHTTPHook: options.PlainHTTPHook, + baseURL: strings.TrimSuffix(options.BaseURL, "/"), + pricingURL: strings.TrimSuffix(options.PricingURL, "/"), + client: options.HTTPClient, + prices: map[string]countryPrices{}, }, nil } @@ -329,34 +347,62 @@ func (p *Provider) ReleaseNumber(ctx context.Context, e164 string) error { return p.do(ctx, http.MethodDelete, p.baseURL, path, nil, nil, nil) } -// ConfigureInbound points the number's voice webhook at TwiML that dials the Stream trunk, -// so an incoming call is bridged straight to the agent. +// ConfigureInbound points the number's voice webhook at the router's Twilio call webhook, which +// runs the checks a call passes before it is answered and answers one that passes with TwiML +// dialing the number's Stream trunk. The trunk's credentials are only in that answer's body. // -// The TwiML is served inline through Twilio's echo endpoint rather than from a webhook of -// this service's own: the instruction never varies per call, so a server that answers with -// a constant would be one more thing to run and to be down. +// The URL carries no connection overrides (#rp=, #rt=): the webhook answers each CallSid once, +// which holds because Twilio by default sends a call again only when connecting failed +// (https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). func (p *Provider) ConfigureInbound(ctx context.Context, inbound phone.Inbound) error { if err := inbound.Bridge.Validate(); err != nil { return err } - sid, err := p.sidFor(ctx, inbound.E164) + hook, err := p.callHook(inbound.PublicURL) if err != nil { return err } - - instructions, err := dialBridge(inbound.Bridge) + sid, err := p.sidFor(ctx, inbound.E164) if err != nil { return err } form := url.Values{ - "VoiceUrl": {echoURL(instructions)}, - "VoiceMethod": {http.MethodGet}, + "VoiceUrl": {hook}, + "VoiceMethod": {http.MethodPost}, } path := fmt.Sprintf("/2010-04-01/Accounts/%s/IncomingPhoneNumbers/%s.json", p.accountSID, sid) return p.do(ctx, http.MethodPost, p.baseURL, path, nil, form, nil) } +// CallHookReady reports which setting the router lacks to answer calls at its Twilio call +// webhook on publicURL: the token it checks Twilio's signature with, or a public URL. +func (p *Provider) CallHookReady(publicURL string) error { + _, err := p.callHook(publicURL) + return err +} + +// callHook is the router's Twilio call webhook on publicURL. It is only given when the router +// checks the webhook's signature, and publicURL is a bare https address: a query or a +// fragment would reach Twilio as part of the URL, and a user would put a credential in it. +func (p *Provider) callHook(publicURL string) (string, error) { + if !p.hookSigned { + return "", stack.Wrap(phone.NotConfigured(errors.New("twilio: " + twiliosig.AuthTokenEnvVar + + " is required to answer calls to a twilio number"))) + } + if publicURL == "" { + return "", stack.Wrap(phone.NotConfigured(errors.New("twilio: ROUTER_PUBLIC_URL is required, " + + "as twilio asks the router there where each call to a number goes"))) + } + parsed, err := url.Parse(publicURL) + if err != nil || (parsed.Scheme != "https" && !(p.plainHTTPHook && parsed.Scheme == "http")) || + parsed.Host == "" || strings.ContainsAny(publicURL, "?#@") { + return "", stack.Wrap(phone.NotConfigured(errors.New("twilio: ROUTER_PUBLIC_URL must be an https " + + "address with no user, query or fragment"))) + } + return strings.TrimSuffix(publicURL, "/") + phone.TwilioCallHookPath, nil +} + // StopInbound clears the number's voice webhook, so a caller no longer reaches the trunk. func (p *Provider) StopInbound(ctx context.Context, e164 string) error { sid, err := p.sidFor(ctx, e164) @@ -635,12 +681,6 @@ func dialBridge(bridge phone.Bridge) (string, error) { return xml.Header + string(encoded), nil } -// echoURL wraps TwiML in Twilio's echo endpoint, which answers a webhook with whatever -// was put in it. It is what lets a fixed instruction be configured without hosting it. -func echoURL(instructions string) string { - return "https://twimlets.com/echo?Twiml=" + url.QueryEscape(instructions) -} - func dollarsToMicros(dollars string) int64 { if dollars == "" { return 0 diff --git a/acceleration/internal/phone/twilio/twilio_test.go b/acceleration/internal/phone/twilio/twilio_test.go index 4df9e81bb1..1781feba0c 100644 --- a/acceleration/internal/phone/twilio/twilio_test.go +++ b/acceleration/internal/phone/twilio/twilio_test.go @@ -49,6 +49,8 @@ func TestTwilio(t *testing.T) { suite.Run(t, new(TwilioSuite)) } func (s *TwilioSuite) SetupTest() { // A key exported in the shell would sign as the key, not the AC these tests expect. s.T().Setenv("TWILIO_API_KEY_SID", "") + // A webhook token exported in the shell would let a test of a provider without one pass. + s.T().Setenv("TWILIO_WEBHOOK_AUTH_TOKEN", "") s.ctx = context.Background() s.seen = request{} s.seenPricing = request{} @@ -77,10 +79,11 @@ func (s *TwilioSuite) SetupTest() { })) provider, err := New(Options{ - AccountSID: "AC123", - AuthToken: "secret", - BaseURL: s.server.URL, - PricingURL: s.server.URL, + AccountSID: "AC123", + AuthToken: "secret", + WebhookAuthToken: "webhook-secret", + BaseURL: s.server.URL, + PricingURL: s.server.URL, }) s.Require().NoError(err) s.provider = provider @@ -171,11 +174,12 @@ func (s *TwilioSuite) TestTheAPIKeyIsReadFromTheEnvironment() { func (s *TwilioSuite) TestAnAPIKeyLeavesTheAccountInTheCallAndPurchasePaths() { provider, err := New(Options{ - AccountSID: "AC123", - APIKeySID: "SK456", - AuthToken: "key-secret", - BaseURL: s.server.URL, - PricingURL: s.server.URL, + AccountSID: "AC123", + APIKeySID: "SK456", + AuthToken: "key-secret", + WebhookAuthToken: "webhook-secret", + BaseURL: s.server.URL, + PricingURL: s.server.URL, }) s.Require().NoError(err) @@ -211,8 +215,9 @@ func (s *TwilioSuite) TestAnAPIKeyLeavesTheAccountInTheCallAndPurchasePaths() { paths = nil s.Require().NoError(provider.ConfigureInbound(s.ctx, phone.Inbound{ - E164: "+15125551234", - Bridge: phone.Bridge{URI: "sip:trunk-7@sip.stream-io-api.com"}, + E164: "+15125551234", + Bridge: phone.Bridge{URI: "sip:trunk-7@sip.stream-io-api.com"}, + PublicURL: "https://router.example.test", })) s.Equal([]string{ "GET /2010-04-01/Accounts/AC123/IncomingPhoneNumbers.json", @@ -446,26 +451,153 @@ func (s *TwilioSuite) TestANumberThisAccountDoesNotListIsNotHeld() { s.False(held) } -func (s *TwilioSuite) TestConfiguringInboundPointsTheNumberAtTheBridge() { +// The number asks the router's call webhook, by POST, where each call goes, and nothing Twilio +// is told holds the trunk: its credentials are only in the webhook's answer. +func (s *TwilioSuite) TestConfiguringInboundPointsTheNumberAtTheCallWebhook() { s.answer(`{"incoming_phone_numbers":[{"sid":"PN9","phone_number":"+15125551234"}], "sid":"PN9","phone_number":"+15125551234"}`) err := s.provider.ConfigureInbound(s.ctx, phone.Inbound{ E164: "+15125551234", Bridge: phone.Bridge{ - URI: "sip:trunk-7@sip.stream-io-api.com", - Username: "agent", + URI: "sip:+15125551234@trunk-7.sip.stream-io-api.com", + Username: "agent-user", Password: "hunter2", }, + PublicURL: "https://router.example.test/", }) s.Require().NoError(err) - voiceURL := s.seen.form.Get("VoiceUrl") - s.Require().NotEmpty(voiceURL) - instructions := s.twiml(voiceURL) - s.Contains(instructions, "sip:trunk-7@sip.stream-io-api.com") - s.Contains(instructions, `username="agent"`) - s.Contains(instructions, `password="hunter2"`) + s.Equal(http.MethodPost, s.seen.method) + s.Equal("/2010-04-01/Accounts/AC123/IncomingPhoneNumbers/PN9.json", s.seen.path) + s.Equal(url.Values{ + "VoiceUrl": {"https://router.example.test/v1/phone/hooks/twilio"}, + "VoiceMethod": {http.MethodPost}, + }, s.seen.form) + for _, sent := range s.seen.form { + for _, value := range sent { + s.NotContains(value, "hunter2") + s.NotContains(value, "agent-user") + s.NotContains(value, "trunk-7") + } + } +} + +// The voice URL takes no connection overrides (#rp=, #rt=): the webhook answers each CallSid +// once, which holds only with Twilio's default of retrying a connection that failed. +func (s *TwilioSuite) TestTheCallWebhookURLHasNoFragmentQueryOrUser() { + s.answer(`{"incoming_phone_numbers":[{"sid":"PN9","phone_number":"+15125551234"}], + "sid":"PN9","phone_number":"+15125551234"}`) + + s.Require().NoError(s.provider.ConfigureInbound(s.ctx, phone.Inbound{ + E164: "+15125551234", Bridge: phone.Bridge{URI: "sip:trunk-7@sip.stream-io-api.com"}, + PublicURL: "https://10.0.0.7:8080", + })) + + raw := s.seen.form.Get("VoiceUrl") + s.Equal("https://10.0.0.7:8080/v1/phone/hooks/twilio", raw) + parsed, err := url.Parse(raw) + s.Require().NoError(err) + s.NotContains(raw, "#") + s.Empty(parsed.Fragment) + s.Empty(parsed.RawQuery) + s.Nil(parsed.User) +} + +// Without the token the router checks the webhook's signature with, the webhook answers 404, +// so a number pointed at it would never be answered: nothing is asked of Twilio. +func (s *TwilioSuite) TestInboundIsRefusedWithoutTheWebhookToken() { + provider, err := New(Options{AccountSID: "AC123", AuthToken: "secret", BaseURL: s.server.URL}) + s.Require().NoError(err) + + inbound := phone.Inbound{ + E164: "+15125551234", Bridge: phone.Bridge{URI: "sip:trunk-7@sip.stream-io-api.com"}, + PublicURL: "https://router.example.test", + } + err = provider.ConfigureInbound(s.ctx, inbound) + + s.ErrorIs(err, phone.ErrNotConfigured) + s.ErrorContains(err, "TWILIO_WEBHOOK_AUTH_TOKEN") + s.Empty(s.seen.path, "twilio was not asked anything") + s.ErrorIs(provider.CallHookReady(inbound.PublicURL), phone.ErrNotConfigured) +} + +// The token is read from TWILIO_WEBHOOK_AUTH_TOKEN, where the router's config writes it. +func (s *TwilioSuite) TestTheWebhookTokenComesFromTheEnvironment() { + s.T().Setenv("TWILIO_WEBHOOK_AUTH_TOKEN", "from-env") + provider, err := New(Options{AccountSID: "AC123", AuthToken: "secret", BaseURL: s.server.URL}) + s.Require().NoError(err) + + s.NoError(provider.CallHookReady("https://router.example.test")) +} + +// A public URL that is missing, or that would put a query, a fragment or a user into the +// voice URL, is refused before Twilio is asked anything; a bare https address is taken. +func (s *TwilioSuite) TestThePublicURLMustBeABareAddress() { + for name, test := range map[string]struct { + publicURL string + hook string + refusal string + }{ + "missing": {publicURL: "", refusal: "ROUTER_PUBLIC_URL is required"}, + "no scheme": {publicURL: "router.example.test", refusal: "must be an https address"}, + "another scheme": {publicURL: "ftp://router.example.test", refusal: "must be an https address"}, + "no host": {publicURL: "https://", refusal: "must be an https address"}, + "unparseable": {publicURL: "https://router.example.test:port", refusal: "must be an https address"}, + "a user": {publicURL: "https://user:pass@router.example.test", refusal: "no user, query or fragment"}, + "a query": {publicURL: "https://router.example.test/?token=1", refusal: "no user, query or fragment"}, + "an empty query": {publicURL: "https://router.example.test?", refusal: "no user, query or fragment"}, + "a fragment": {publicURL: "https://router.example.test#rp=ct", refusal: "no user, query or fragment"}, + "an empty #": {publicURL: "https://router.example.test#", refusal: "no user, query or fragment"}, + "plain http": {publicURL: "http://router.example.test", refusal: "must be an https address"}, + "https": {publicURL: "https://router.example.test", hook: "https://router.example.test/v1/phone/hooks/twilio"}, + "a slash": {publicURL: "https://router.example.test/", hook: "https://router.example.test/v1/phone/hooks/twilio"}, + "a path": {publicURL: "https://example.test/router", hook: "https://example.test/router/v1/phone/hooks/twilio"}, + "https and port": {publicURL: "https://10.0.0.7:8080", hook: "https://10.0.0.7:8080/v1/phone/hooks/twilio"}, + } { + s.Run(name, func() { + s.seen = request{} + s.answer(`{"incoming_phone_numbers":[{"sid":"PN9","phone_number":"+15125551234"}], + "sid":"PN9","phone_number":"+15125551234"}`) + + err := s.provider.ConfigureInbound(s.ctx, phone.Inbound{ + E164: "+15125551234", Bridge: phone.Bridge{URI: "sip:trunk-7@sip.stream-io-api.com"}, + PublicURL: test.publicURL, + }) + + if test.refusal != "" { + s.ErrorIs(err, phone.ErrNotConfigured) + s.ErrorContains(err, test.refusal) + s.Empty(s.seen.path, "twilio was not asked anything") + s.ErrorIs(s.provider.CallHookReady(test.publicURL), phone.ErrNotConfigured) + return + } + s.Require().NoError(err) + s.Equal(test.hook, s.seen.form.Get("VoiceUrl")) + s.NoError(s.provider.CallHookReady(test.publicURL)) + }) + } +} + +// The webhook's answer holds the trunk's credentials, so an http address is refused for the +// router's numbers; a bench whose answer holds none opts in and is pointed at http. +func (s *TwilioSuite) TestAPlainHTTPVoiceURLIsTakenOnlyWhenOptedIn() { + s.answer(`{"incoming_phone_numbers":[{"sid":"PN9","phone_number":"+15125551234"}], + "sid":"PN9","phone_number":"+15125551234"}`) + inbound := phone.Inbound{ + E164: "+15125551234", Bridge: phone.Bridge{URI: "sip:trunk-7@sip.stream-io-api.com"}, + PublicURL: "http://10.0.0.7:8080", + } + + s.ErrorIs(s.provider.ConfigureInbound(s.ctx, inbound), phone.ErrNotConfigured) + s.Empty(s.seen.path, "twilio was not asked anything") + + bench, err := New(Options{ + AccountSID: "AC123", AuthToken: "secret", WebhookAuthToken: "hook-secret", BaseURL: s.server.URL, PlainHTTPHook: true, + }) + s.Require().NoError(err) + s.Require().NoError(bench.ConfigureInbound(s.ctx, inbound)) + s.Equal("http://10.0.0.7:8080/v1/phone/hooks/twilio", s.seen.form.Get("VoiceUrl")) } func (s *TwilioSuite) TestStoppingInboundClearsTheVoiceURL() { @@ -851,13 +983,6 @@ func (s *TwilioSuite) answerWithPrices(numbers, prices string) { } } -// twiml pulls the instructions back out of the echo url they were configured through. -func (s *TwilioSuite) twiml(voiceURL string) string { - parsed, err := url.Parse(voiceURL) - s.Require().NoError(err) - return parsed.Query().Get("Twiml") -} - // TestTheInstructionsTwilioIsGivenAreValidXML matters because a malformed one would only // be discovered when somebody called the number. func (s *TwilioSuite) TestTheInstructionsTwilioIsGivenAreValidXML() {