-
Notifications
You must be signed in to change notification settings - Fork 654
Expand file tree
/
Copy pathhookshttp_test.go
More file actions
355 lines (318 loc) · 8.31 KB
/
hookshttp_test.go
File metadata and controls
355 lines (318 loc) · 8.31 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package hookshttp
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gofrs/uuid"
"github.com/stretchr/testify/require"
"github.com/supabase/auth/internal/api/apierrors"
"github.com/supabase/auth/internal/conf"
"github.com/supabase/auth/internal/reloader"
)
type M = map[string]any
func TestDispatch(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
ah := reloader.NewAtomicHandler(nil)
ts := httptest.NewServer(ah)
defer ts.Close()
type testCase struct {
desc string
ctx context.Context
dr *Dispatcher
cfg conf.ExtensibilityPointConfiguration
hr http.Handler
req any
exp any
err error
errStr string
}
cases := []testCase{
{
desc: "pass - basic success",
req: M{
"user": M{
"ID": uuid.Must(uuid.NewV4()),
},
},
exp: M{"success": true},
hr: &mockHandler{
status: http.StatusOK,
ctype: "application/json",
data: M{"success": true},
},
},
{
desc: "pass - email with apostrophe in payload",
req: M{
"user": M{
"email": "joe.o'sullivan@example.com",
},
},
exp: M{"success": true},
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Verify the apostrophe email is correctly received in the JSON payload
var body M
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
user, _ := body["user"].(map[string]any)
email, _ := user["email"].(string)
if email != "joe.o'sullivan@example.com" {
http.Error(w, fmt.Sprintf("unexpected email: %q", email), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(M{"success": true})
}),
},
{
desc: "pass - empty content type should not error 204 status",
exp: M{},
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "")
w.WriteHeader(http.StatusNoContent)
}),
},
{
desc: "fail - invalid input",
req: make(chan int),
errStr: "500: Error marshaling JSON input.",
},
{
desc: "fail - invalid format in secret",
cfg: conf.ExtensibilityPointConfiguration{
HTTPHookSecrets: conf.HTTPHookSecrets{
"invalid",
},
},
errStr: "invalid signature format",
},
{
desc: "fail - invalid base64 in secret",
cfg: conf.ExtensibilityPointConfiguration{
HTTPHookSecrets: conf.HTTPHookSecrets{
"v1,aaaaaaaaaa",
},
},
errStr: "unable to create webhook, err: illegal base64 dat",
},
{
desc: "fail - unable to make request object",
cfg: conf.ExtensibilityPointConfiguration{
URI: string([]byte{0}),
},
errStr: "Hook failed to make request object",
},
{
desc: "fail - ctx timeout",
dr: New(WithTimeout(1)),
errStr: "422: Failed to reach hook within maximum time",
},
{
desc: "fail - net timeout",
cfg: conf.ExtensibilityPointConfiguration{
URI: "http://0.0.0.0:8000",
},
errStr: "422: Failed to reach hook after maximum retries",
},
{
desc: "fail - net timeout > ctx timeout",
dr: New(
WithTimeout(time.Second/10),
WithBackoff(time.Minute),
),
cfg: conf.ExtensibilityPointConfiguration{
URI: "http://0.0.0.0:8000",
},
errStr: "422: Failed to reach hook within maximum time of 0.100000 seconds",
},
{
desc: "fail - retry after header pushes to fallback",
errStr: "Service currently unavailable due to hook",
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("retry-after", "not-read")
w.WriteHeader(http.StatusTooManyRequests)
}),
},
{
desc: "fail - empty content type",
errStr: "Invalid Content-Type: Missing Content-Type header",
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "")
w.WriteHeader(http.StatusOK)
}),
},
{
desc: "fail - malformed content type",
errStr: "400: Invalid Content-Type header: mime: no media type",
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", ";/")
w.WriteHeader(http.StatusOK)
}),
},
{
desc: "fail - content type is not application/json",
errStr: "400: Invalid JSON response. Received content-type: app/js",
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "app/js")
w.WriteHeader(http.StatusOK)
}),
},
{
desc: "fail - limit reader exceeeded",
dr: New(
WithResponseLimit(1),
),
errStr: "422: Payload size exceeded size limit of 1 bytes",
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(bytes.Repeat([]byte("a"), 1024*64))
}),
},
{
desc: "fail - unmarshal error",
dr: New(),
errStr: "500: Error unmarshaling JSON output.",
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
io.WriteString(w, "12345")
}),
},
{
desc: "fail - returning error objects",
errStr: "500: failed to verify ip addres",
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
io.WriteString(w, `{"error": {"message": "failed to verify ip addres"}}`)
}),
},
{
desc: "fail - returning error objects with status",
errStr: "400: failed to verify ip addres",
hr: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
io.WriteString(w, `{"error": {"message": "failed to verify ip addres", "http_code": 400}}`)
}),
},
}
// error status codes
{
addCase := func(statusIn, statusOut int, msg string) {
cases = append(cases, testCase{
desc: fmt.Sprintf("fail - invalid status code %d", statusIn),
req: M{"empty": true},
err: &apierrors.HTTPError{
HTTPStatus: statusOut,
ErrorCode: apierrors.ErrorCodeUnexpectedFailure,
Message: msg,
},
hr: &mockHandler{
status: statusIn,
ctype: "application/json",
data: M{
"error": M{
// This is not propagated in current implementation
"http_code": 500,
"message": "sentinel error",
},
},
},
})
}
addCase(
http.StatusServiceUnavailable,
http.StatusInternalServerError,
"Service currently unavailable due to hook",
)
addCase(
http.StatusTooManyRequests,
http.StatusInternalServerError,
"Service currently unavailable due to hook",
)
addCase(
http.StatusBadRequest,
http.StatusInternalServerError,
"Invalid payload sent to hook",
)
addCase(
http.StatusUnauthorized,
http.StatusInternalServerError,
"Hook requires authorization token",
)
addCase(
http.StatusTeapot,
http.StatusInternalServerError,
"Unexpected status code returned from hook: 418",
)
}
for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
testCtx := tc.ctx
if testCtx == nil {
testCtx = ctx
}
dr := tc.dr
if dr == nil {
dr = New(
WithTimeout(time.Second/10),
WithRetries(3),
WithBackoff(time.Second/50),
)
}
hr := tc.hr
if hr == nil {
hr = &mockHandler{}
}
ah.Store(hr)
cfg := tc.cfg
if cfg.URI == "" {
cfg.URI = ts.URL
}
res := M{}
err := dr.Dispatch(testCtx, &cfg, tc.req, &res)
if tc.err != nil {
require.Error(t, err)
require.Equal(t, tc.err, err)
return
}
if tc.errStr != "" {
require.Error(t, err)
require.Contains(t, err.Error(), tc.errStr)
return
}
require.NoError(t, err)
require.Equal(t, tc.exp, res)
})
}
}
type mockHandler struct {
status int
ctype string
data any
}
func (o *mockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if o.ctype != "" {
w.Header().Set("content-type", o.ctype)
}
if o.status > 0 {
w.WriteHeader(o.status)
}
err := json.NewEncoder(w).Encode(o.data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}