Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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<n>_WRAPPED` hosted): without one they cannot be attached |
Expand Down
23 changes: 23 additions & 0 deletions acceleration/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24493,6 +24493,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.'
Expand Down
1 change: 1 addition & 0 deletions acceleration/cmd/router/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1499,6 +1499,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,
Expand Down
33 changes: 33 additions & 0 deletions acceleration/cmd/router/startup_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand Down
30 changes: 29 additions & 1 deletion acceleration/internal/api/admission_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -647,6 +651,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, `<Response><Reject reason="rejected"/></Response>`)
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() {
Expand Down
93 changes: 93 additions & 0 deletions acceleration/internal/api/callhook.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
21 changes: 21 additions & 0 deletions acceleration/internal/api/handwritten.go
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,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,
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/hookbody.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions acceleration/internal/api/router_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,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.
Expand Down Expand Up @@ -815,6 +818,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,
Expand Down
Loading
Loading