Repository navigation
[AI-3805] Point new Twilio numbers at the signed call webhook #2474
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
74ec5c8
AI-3805: Twilio numbers point at the signed call webhook (WIP)
kanat 366e531
AI-3805: the latency bench serves the Twilio call webhook (WIP)
kanat faed4eb
AI-3805: tests for numbers pointed at the call webhook; docs
kanat 68b2de1
AI-3805: test the bench's hook server
kanat f13631e
AI-3805: the bench takes the hook's port from its listener
kanat 8622ecd
AI-3805: wording
kanat b1e097c
Merge origin/main into kanat/ai-3805-twilio-numbers-use-hook
kanat 68526a4
AI-3805: a Twilio number's voice URL must be https unless the bench o…
kanat 09abdcb
AI-3805: a refused Twilio attach no longer writes the app's call hook
kanat 215abc0
AI-3805: phonecheck restarts the router on the tunnel URL before a Tw…
kanat 5cdb72c
AI-3805: name the https public URL rule in the Twilio token row and t…
kanat 761ab5c
Merge remote-tracking branch 'origin/main' into HEAD
kanat File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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, "<Dial><Sip>sip:+15125550100@203.0.113.7:5060</Sip></Dial>") | ||
| } | ||
|
|
||
| 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, "<Hangup/>") | ||
| s.NotContains(body, "<Dial>") | ||
| } | ||
|
|
||
| // 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, "<Hangup/>") | ||
| } | ||
|
|
||
| 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>sip:+15125550100@127.0.0.1:5060</Sip>") | ||
|
|
||
| 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") | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.