-
Notifications
You must be signed in to change notification settings - Fork 20
/
webhook.go
214 lines (178 loc) · 6.51 KB
/
webhook.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
package flows
import (
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"net/http/httputil"
"strings"
"time"
"github.com/nyaruka/goflow/utils"
)
var DefaultWebhookPayload = `{
"contact": {"uuid": "@contact.uuid", "name": @(json(contact.name)), "urn": @(json(if(default(run.input.urn, default(contact.urns.0, null)), text(default(run.input.urn, default(contact.urns.0, null))), null)))},
"flow": @(json(run.flow)),
"path": @(json(run.path)),
"results": @(json(run.results)),
"run": {"uuid": "@run.uuid", "created_on": "@run.created_on"},
"input": @(json(run.input)),
"channel": @(json(if(run.input, run.input.channel, null)))
}`
// response content-types that we'll fetch
var fetchResponseContentTypes = map[string]bool{
"application/json": true,
"application/javascript": true,
"application/xml": true,
"text/html": true,
"text/plain": true,
"text/xml": true,
}
// WebhookStatus represents the status of a WebhookRequest
type WebhookStatus string
const (
// WebhookStatusSuccess represents that the webhook was successful
WebhookStatusSuccess WebhookStatus = "success"
// WebhookStatusConnectionError represents that the webhook had a connection error
WebhookStatusConnectionError WebhookStatus = "connection_error"
// WebhookStatusResponseError represents that the webhook response had a non 2xx status code
WebhookStatusResponseError WebhookStatus = "response_error"
)
func WebhookStatusFromCode(code int) WebhookStatus {
if code/100 == 2 {
return WebhookStatusSuccess
}
return WebhookStatusResponseError
}
func (r WebhookStatus) String() string {
return string(r)
}
// WebhookCall is a call made to an external service
type WebhookCall struct {
url string
request *http.Request
response *http.Response
status WebhookStatus
timeTaken time.Duration
requestTrace string
responseTrace string
}
// MakeWebhookCall fires the passed in http request, returning any errors encountered. RequestResponse is always set
// regardless of any errors being set
func MakeWebhookCall(session Session, request *http.Request) (*WebhookCall, error) {
var response *http.Response
var requestDump string
var err error
var timeTaken time.Duration
// if our config has mocks, look for a matching one
mock := findMockedRequest(session, request)
if mock != nil {
response, requestDump, err = session.HTTPClient().MockWithDump(request, mock.Status, mock.Body)
} else {
if session.EngineConfig().DisableWebhooks() {
response, requestDump, err = session.HTTPClient().MockWithDump(request, 200, "DISABLED")
} else {
start := utils.Now()
response, requestDump, err = session.HTTPClient().DoWithDump(request)
timeTaken = utils.Now().Sub(start)
}
}
if err != nil {
return newWebhookCallFromError(request, requestDump, err), err
}
return newWebhookCallFromResponse(requestDump, response, session.EngineConfig().MaxWebhookResponseBytes(), timeTaken)
}
// URL returns the full URL
func (w *WebhookCall) URL() string { return w.url }
// Method returns the full HTTP method
func (w *WebhookCall) Method() string { return w.request.Method }
// Status returns the response status message
func (w *WebhookCall) Status() WebhookStatus { return w.status }
// StatusCode returns the response status code
func (w *WebhookCall) StatusCode() int {
if w.response != nil {
return w.response.StatusCode
}
return 0
}
// TimeTaken returns the time taken to make the request
func (w *WebhookCall) TimeTaken() time.Duration { return w.timeTaken }
// Request returns the request trace
func (w *WebhookCall) Request() string { return w.requestTrace }
// Response returns the response trace
func (w *WebhookCall) Response() string { return w.responseTrace }
// Body returns the response body
func (w *WebhookCall) Body() string {
parts := strings.SplitN(w.responseTrace, "\r\n\r\n", 2)
if len(parts) == 2 {
return parts[1]
}
return ""
}
// newWebhookCallFromError creates a new webhook call based on the passed in http request and error (when we received no response)
func newWebhookCallFromError(request *http.Request, requestTrace string, requestError error) *WebhookCall {
return &WebhookCall{
url: request.URL.String(),
request: request,
response: nil,
status: WebhookStatusConnectionError,
requestTrace: requestTrace,
responseTrace: requestError.Error(),
}
}
// newWebhookCallFromResponse creates a new RequestResponse based on the passed in http Response
func newWebhookCallFromResponse(requestTrace string, response *http.Response, maxBodyBytes int, timeTaken time.Duration) (*WebhookCall, error) {
defer response.Body.Close()
// save response trace without body which will be parsed separately
responseTrace, err := httputil.DumpResponse(response, false)
if err != nil {
return nil, err
}
w := &WebhookCall{
url: response.Request.URL.String(),
request: response.Request,
response: response,
status: WebhookStatusFromCode(response.StatusCode),
requestTrace: requestTrace,
responseTrace: string(responseTrace),
timeTaken: timeTaken,
}
// only save response body's if we have a supported content-type
contentType := response.Header.Get("Content-Type")
mediaType, _, _ := mime.ParseMediaType(contentType)
saveBody := fetchResponseContentTypes[mediaType]
if saveBody {
// only read up to our max body bytes limit
bodyReader := io.LimitReader(response.Body, int64(maxBodyBytes)+1)
bodyBytes, err := ioutil.ReadAll(bodyReader)
if err != nil {
return nil, err
}
// if we have no remaining bytes, error because the body was too big
if bodyReader.(*io.LimitedReader).N <= 0 {
return nil, fmt.Errorf("webhook response body exceeds %d bytes limit", maxBodyBytes)
}
w.responseTrace += string(bodyBytes)
} else {
// no body for non-text responses but add it to our Response log so users know why
w.responseTrace += "Non-text body, ignoring"
}
return w, nil
}
//------------------------------------------------------------------------------------------
// Request Mocking
//------------------------------------------------------------------------------------------
type WebhookMock struct {
Method string `json:"method"`
URL string `json:"url"`
Status int `json:"status"`
Body string `json:"body"`
}
func findMockedRequest(session Session, request *http.Request) *WebhookMock {
for _, mock := range session.EngineConfig().WebhookMocks() {
if strings.EqualFold(mock.Method, request.Method) && strings.EqualFold(mock.URL, request.URL.String()) {
return mock
}
}
return nil
}