-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
232 lines (199 loc) · 6.06 KB
/
request.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package twiml
import (
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/ttacon/libphonenumber"
"go.opencensus.io/trace"
)
// RequestValues hold form values from a validated Request
type RequestValues map[string]string
// CallDuration Parses the duration from the string value
func (r RequestValues) CallDuration() (int, error) {
var duration int
if r["CallDuration"] != "" {
d, err := strconv.Atoi(r["CallDuration"])
if err != nil {
return 0, errors.WithMessage(err, "RequestValues.CallDuration()")
}
duration = d
}
return duration, nil
}
// SequenceNumber Parses the duration rom the string value
func (r RequestValues) SequenceNumber() (int, error) {
var seq int
if r["SequenceNumber"] != "" {
d, err := strconv.Atoi(r["SequenceNumber"])
if err != nil {
return 0, errors.WithMessage(err, "RequestValues.SequenceNumber()")
}
seq = d
}
return seq, nil
}
// TimestampOrNow parses the Timestamp from string. If Timestamp does not exist in the
// current request, time.Now() is returned instead.
func (r RequestValues) TimestampOrNow() time.Time {
t, err := time.Parse(time.RFC1123Z, r["Timestamp"])
if err != nil {
t = time.Now()
}
return t
}
// From returns a Number parsed from the raw From value
func (r RequestValues) From() *ParsedNumber {
return ParseNumber(r["From"])
}
// To returns a Number parsed from the raw To value
func (r RequestValues) To() *ParsedNumber {
return ParseNumber(r["To"])
}
// ParseNumber parses ether a E164 number or a SIP URI returning a ParsedNumber
func ParseNumber(v string) *ParsedNumber {
number := &ParsedNumber{
Number: v,
Raw: v,
}
if err := validPhoneNumber(v, ""); err == nil {
number.Valid = true
return number
}
u, err := parseSipURI(v)
if err != nil {
return number
}
parts := strings.Split(u.Hostname(), ".")
l := len(parts)
if l < 5 || strings.Join(parts[l-2:], ".") != "twilio.com" || parts[l-4] != "sip" {
return number
}
num, err := FormatNumber(u.User.Username())
if err != nil {
return number
}
number.Valid = true
number.Sip = true
number.Number = num
number.SipDomain = strings.Join(parts[:l-4], ".")
number.Region = parts[l-4]
return number
}
type ParsedNumber struct {
Valid bool
Number string
Sip bool
SipDomain string
Region string
Raw string
}
// FormatNumber formates a number to E164 format
func FormatNumber(number string) (string, error) {
num, err := libphonenumber.Parse(number, "US")
if err != nil {
return number, errors.WithMessagef(errors.New("Invalid phone number"), "twiml.FormatNumber(): %s", err)
}
if !libphonenumber.IsValidNumber(num) {
return number, errors.WithMessage(errors.New("Invalid phone number"), "twiml.FormatNumber()")
}
return libphonenumber.Format(num, libphonenumber.E164), nil
}
// Request is a twillio request expecting a TwiML response
type Request struct {
host string
r *http.Request
Values RequestValues
}
// NewRequest returns Request
func NewRequest(host string, r *http.Request) *Request {
return &Request{host: host, r: r, Values: RequestValues{}}
}
// ValidatePost validates the Twilio Signature, requiring that the request is a POST
func (req *Request) ValidatePost(ctx context.Context, authToken string) error {
_, span := trace.StartSpan(ctx, "twiml.Request.ValidatePost()")
defer span.End()
url := req.host + req.r.URL.String()
span.AddAttributes(trace.StringAttribute("url", url))
if req.r.Method != "POST" {
return errors.WithMessage(fmt.Errorf("Expected a POST request, received %s", req.r.Method), "twiml.Request.ValidatePost()")
}
if err := req.r.ParseForm(); err != nil {
return errors.WithMessage(err, "twiml.Request.ValidatePost(): http.Request.ParseForm():")
}
params := make([]string, 0, len(req.r.PostForm))
for p := range req.r.PostForm {
params = append(params, p)
}
sort.Strings(params)
message := url
for _, p := range params {
message += p
if len(req.r.PostForm[p]) > 0 {
message += req.r.PostForm[p][0]
}
}
hash := hmac.New(sha1.New, []byte(authToken))
if n, err := hash.Write([]byte(message)); err != nil {
return errors.WithMessage(err, "twiml.Request.ValidatePost(): hash.Write()")
} else if n != len(message) {
err := fmt.Errorf("expected %d bytes, got %d bytes", len(message), n)
return errors.WithMessage(err, "twiml.Request.ValidatePost(): hash.Write()")
}
sig := base64.StdEncoding.EncodeToString(hash.Sum(nil))
if xTwilioSigHdr := req.r.Header[http.CanonicalHeaderKey("X-Twilio-Signature")]; len(xTwilioSigHdr) != 1 || sig != xTwilioSigHdr[0] {
var xTwilioSig string
if len(xTwilioSigHdr) == 1 {
xTwilioSig = xTwilioSigHdr[0]
}
return errors.WithMessage(fmt.Errorf("Calculated Signature: %s, failed to match X-Twilio-Signature: %s", sig, xTwilioSig), "twiml.Request.ValidatePost()")
}
// Validate data
for _, p := range params {
var val string
if len(req.r.PostForm[p]) > 0 {
val = req.r.PostForm[p][0]
}
if valParam, ok := fieldValidators[p]; ok {
if err := valParam.valFunc(val, valParam.valParam); err != nil {
return errors.WithMessage(fmt.Errorf("Invalid form value: %s=%s, err: %s", p, val, err), "twiml.Request.ValidatePost()")
}
}
req.Values[p] = val
}
return nil
}
type valCfg struct {
valFunc func(interface{}, string) error
valParam string
}
var fieldValidators = map[string]valCfg{
// "CallSid": "CallSid",
// "AccountSid": "AccountSid",
"From": {valFunc: validFromOrTo},
"To": {valFunc: validFromOrTo},
// "CallStatus": "CallStatus",
// "ApiVersion": "ApiVersion",
// "ForwardedFrom": "ForwardedFrom",
// "CallerName": "CallerName",
// "ParentCallSid": "ParentCallSid",
// "FromCity": "FromCity",
// "FromState": "FromState",
// "FromZip": "FromZip",
// "FromCountry": "FromCountry",
// "ToCity": "ToCity",
// "ToZip": "ToZip",
// "ToCountry": "ToCountry",
// "SipDomain": "SipDomain",
// "SipUsername": "SipUsername",
// "SipCallId": "SipCallId",
// "SipSourceIp": "SipSourceIp",
"Digits": {valFunc: validateKeyPadEntry},
}