-
Notifications
You must be signed in to change notification settings - Fork 0
/
authmeter_test.go
488 lines (411 loc) · 13.6 KB
/
authmeter_test.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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package authmeter
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
const CorrectKey = "specials: !$%,.#\"!?~`<>@$^*(){}[]|/\\123"
func TestAuthSources(t *testing.T) {
t.Parallel()
// define test cases
testSources := []string{"header", "cookie", "query", "param", "form"}
tests := []struct {
route string
authTokenName string
description string
APIKey string
expectedCode int
expectedBody string
}{
{
route: "/",
authTokenName: "access_token",
description: "auth with correct key",
APIKey: CorrectKey,
expectedCode: fiber.StatusOK,
expectedBody: "Success!",
},
{
route: "/",
authTokenName: "access_token",
description: "auth with no key",
APIKey: "",
expectedCode: fiber.StatusUnauthorized, // fiber.StatusNotFound in case of param authentication
expectedBody: "missing or malformed API Key",
},
{
route: "/",
authTokenName: "access_token",
description: "auth with wrong key",
APIKey: "WRONGKEY",
expectedCode: fiber.StatusUnauthorized,
expectedBody: "missing or malformed API Key",
},
}
for _, authSource := range testSources {
t.Run(authSource, func(t *testing.T) {
t.Parallel()
for _, test := range tests {
// setup the fiber endpoint
// note that if UnescapePath: false (the default)
// escaped characters (such as `\"`) will not be handled correctly in the tests
app := fiber.New(fiber.Config{UnescapePath: true})
authMiddleware := New(Config{
KeyAuthConfig: KeyAuthConfig{
KeyLookup: authSource + ":" + test.authTokenName,
Validator: func(c *fiber.Ctx, key string) (bool, error) {
if key == CorrectKey {
return true, nil
}
return false, ErrMissingOrMalformedAPIKey
},
},
})
var route string
if authSource == param {
route = test.route + ":" + test.authTokenName
app.Use(route, authMiddleware)
} else {
route = test.route
app.Use(authMiddleware)
}
app.Get(route, func(c *fiber.Ctx) error {
return c.SendString("Success!")
})
// construct the test HTTP request
var req *http.Request
req, err := http.NewRequestWithContext(context.Background(), fiber.MethodGet, test.route, nil)
utils.AssertEqual(t, err, nil)
// setup the apikey for the different auth schemes
if authSource == "header" {
req.Header.Set(test.authTokenName, test.APIKey)
} else if authSource == "cookie" {
req.Header.Set("Cookie", test.authTokenName+"="+test.APIKey)
} else if authSource == "query" || authSource == "form" {
q := req.URL.Query()
q.Add(test.authTokenName, test.APIKey)
req.URL.RawQuery = q.Encode()
} else if authSource == "param" {
r := req.URL.Path
r += url.PathEscape(test.APIKey)
req.URL.Path = r
}
res, err := app.Test(req, -1)
utils.AssertEqual(t, nil, err, test.description)
// test the body of the request
body, err := io.ReadAll(res.Body)
// for param authentication, the route would be /:access_token
// when the access_token is empty, it leads to a fiber.StatusNotFound (not found)
// not a fiber.StatusUnauthorized (auth error)
if authSource == "param" && test.APIKey == "" {
test.expectedCode = fiber.StatusNotFound
test.expectedBody = "Cannot GET /"
}
utils.AssertEqual(t, test.expectedCode, res.StatusCode, test.description)
// body
utils.AssertEqual(t, nil, err, test.description)
utils.AssertEqual(t, test.expectedBody, string(body), test.description)
err = res.Body.Close()
utils.AssertEqual(t, err, nil)
}
})
}
}
func TestMultipleKeyAuth(t *testing.T) {
t.Parallel()
// setup the fiber endpoint
app := fiber.New()
// setup keyauth for /auth1
app.Use(New(Config{
Next: func(c *fiber.Ctx) bool {
return c.OriginalURL() != "/auth1"
},
KeyAuthConfig: KeyAuthConfig{
KeyLookup: "header:key",
Validator: func(c *fiber.Ctx, key string) (bool, error) {
if key == "password1" {
return true, nil
}
return false, ErrMissingOrMalformedAPIKey
},
},
}))
// setup keyauth for /auth2
app.Use(New(Config{
Next: func(c *fiber.Ctx) bool {
return c.OriginalURL() != "/auth2"
},
KeyAuthConfig: KeyAuthConfig{
KeyLookup: "header:key",
Validator: func(c *fiber.Ctx, key string) (bool, error) {
if key == "password2" {
return true, nil
}
return false, ErrMissingOrMalformedAPIKey
},
},
}))
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("No auth needed!")
})
app.Get("/auth1", func(c *fiber.Ctx) error {
return c.SendString("Successfully authenticated for auth1!")
})
app.Get("/auth2", func(c *fiber.Ctx) error {
return c.SendString("Successfully authenticated for auth2!")
})
// define test cases
tests := []struct {
route string
description string
APIKey string
expectedCode int
expectedBody string
}{
// No auth needed for /
{
route: "/",
description: "No password needed",
APIKey: "",
expectedCode: fiber.StatusOK,
expectedBody: "No auth needed!",
},
// auth needed for auth1
{
route: "/auth1",
description: "Normal Authentication Case",
APIKey: "password1",
expectedCode: fiber.StatusOK,
expectedBody: "Successfully authenticated for auth1!",
},
{
route: "/auth1",
description: "Wrong API Key",
APIKey: "WRONG KEY",
expectedCode: fiber.StatusUnauthorized,
expectedBody: "missing or malformed API Key",
},
{
route: "/auth1",
description: "Wrong API Key",
APIKey: "", // NO KEY
expectedCode: fiber.StatusUnauthorized,
expectedBody: "missing or malformed API Key",
},
// Auth 2 has a different password
{
route: "/auth2",
description: "Normal Authentication Case for auth2",
APIKey: "password2",
expectedCode: fiber.StatusOK,
expectedBody: "Successfully authenticated for auth2!",
},
{
route: "/auth2",
description: "Wrong API Key",
APIKey: "WRONG KEY",
expectedCode: fiber.StatusUnauthorized,
expectedBody: "missing or malformed API Key",
},
{
route: "/auth2",
description: "Wrong API Key",
APIKey: "", // NO KEY
expectedCode: fiber.StatusUnauthorized,
expectedBody: "missing or malformed API Key",
},
}
// run the tests
for _, test := range tests {
var req *http.Request
req, err := http.NewRequestWithContext(context.Background(), fiber.MethodGet, test.route, nil)
utils.AssertEqual(t, err, nil)
if test.APIKey != "" {
req.Header.Set("key", test.APIKey)
}
res, err := app.Test(req, -1)
utils.AssertEqual(t, nil, err, test.description)
// test the body of the request
body, err := io.ReadAll(res.Body)
utils.AssertEqual(t, test.expectedCode, res.StatusCode, test.description)
// body
utils.AssertEqual(t, nil, err, test.description)
utils.AssertEqual(t, test.expectedBody, string(body), test.description)
}
}
func TestCustomSuccessAndFailureHandlers(t *testing.T) {
t.Parallel()
app := fiber.New()
app.Use(New(Config{
KeyAuthConfig: KeyAuthConfig{
SuccessHandler: func(c *fiber.Ctx) error {
return c.Status(fiber.StatusOK).SendString("API key is valid and request was handled by custom success handler")
},
ErrorHandler: func(c *fiber.Ctx, err error) error {
return c.Status(fiber.StatusUnauthorized).SendString("API key is invalid and request was handled by custom error handler")
},
Validator: func(c *fiber.Ctx, key string) (bool, error) {
if key == CorrectKey {
return true, nil
}
return false, ErrMissingOrMalformedAPIKey
},
},
}))
// Define a test handler that should not be called
app.Get("/", func(c *fiber.Ctx) error {
t.Error("Test handler should not be called")
return nil
})
// Create a request without an API key and send it to the app
res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
utils.AssertEqual(t, err, nil)
// Read the response body into a string
body, err := io.ReadAll(res.Body)
utils.AssertEqual(t, err, nil)
// Check that the response has the expected status code and body
utils.AssertEqual(t, res.StatusCode, http.StatusUnauthorized)
utils.AssertEqual(t, string(body), "API key is invalid and request was handled by custom error handler")
// Create a request with a valid API key in the Authorization header
req := httptest.NewRequest(fiber.MethodGet, "/", nil)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", CorrectKey))
// Send the request to the app
res, err = app.Test(req)
utils.AssertEqual(t, err, nil)
// Read the response body into a string
body, err = io.ReadAll(res.Body)
utils.AssertEqual(t, err, nil)
// Check that the response has the expected status code and body
utils.AssertEqual(t, res.StatusCode, http.StatusOK)
utils.AssertEqual(t, string(body), "API key is valid and request was handled by custom success handler")
}
func TestCustomNextFunc(t *testing.T) {
t.Parallel()
app := fiber.New()
app.Use(New(Config{
Next: func(c *fiber.Ctx) bool {
return c.Path() == "/allowed"
},
KeyAuthConfig: KeyAuthConfig{
Validator: func(c *fiber.Ctx, key string) (bool, error) {
if key == CorrectKey {
return true, nil
}
return false, ErrMissingOrMalformedAPIKey
},
},
}))
// Define a test handler
app.Get("/allowed", func(c *fiber.Ctx) error {
return c.SendString("API key is valid and request was allowed by custom filter")
})
// Create a request with the "/allowed" path and send it to the app
req := httptest.NewRequest(fiber.MethodGet, "/allowed", nil)
res, err := app.Test(req)
utils.AssertEqual(t, err, nil)
// Read the response body into a string
body, err := io.ReadAll(res.Body)
utils.AssertEqual(t, err, nil)
// Check that the response has the expected status code and body
utils.AssertEqual(t, res.StatusCode, http.StatusOK)
utils.AssertEqual(t, string(body), "API key is valid and request was allowed by custom filter")
// Create a request with a different path and send it to the app without correct key
req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", nil)
res, err = app.Test(req)
utils.AssertEqual(t, err, nil)
// Read the response body into a string
body, err = io.ReadAll(res.Body)
utils.AssertEqual(t, err, nil)
// Check that the response has the expected status code and body
utils.AssertEqual(t, res.StatusCode, http.StatusUnauthorized)
utils.AssertEqual(t, string(body), ErrMissingOrMalformedAPIKey.Error())
// Create a request with a different path and send it to the app with correct key
req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", nil)
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", CorrectKey))
res, err = app.Test(req)
utils.AssertEqual(t, err, nil)
// Read the response body into a string
body, err = io.ReadAll(res.Body)
utils.AssertEqual(t, err, nil)
// Check that the response has the expected status code and body
utils.AssertEqual(t, res.StatusCode, http.StatusUnauthorized)
utils.AssertEqual(t, string(body), ErrMissingOrMalformedAPIKey.Error())
}
func TestAuthSchemeToken(t *testing.T) {
t.Parallel()
app := fiber.New()
app.Use(New(Config{
KeyAuthConfig: KeyAuthConfig{
AuthScheme: "Token",
Validator: func(c *fiber.Ctx, key string) (bool, error) {
if key == CorrectKey {
return true, nil
}
return false, ErrMissingOrMalformedAPIKey
},
},
}))
// Define a test handler
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("API key is valid")
})
// Create a request with a valid API key in the "Token" Authorization header
req := httptest.NewRequest(fiber.MethodGet, "/", nil)
req.Header.Add("Authorization", fmt.Sprintf("Token %s", CorrectKey))
// Send the request to the app
res, err := app.Test(req)
utils.AssertEqual(t, err, nil)
// Read the response body into a string
body, err := io.ReadAll(res.Body)
utils.AssertEqual(t, err, nil)
// Check that the response has the expected status code and body
utils.AssertEqual(t, res.StatusCode, http.StatusOK)
utils.AssertEqual(t, string(body), "API key is valid")
}
func TestAuthSchemeBasic(t *testing.T) {
t.Parallel()
app := fiber.New()
app.Use(New(Config{
KeyAuthConfig: KeyAuthConfig{
KeyLookup: "header:Authorization",
AuthScheme: "Basic",
Validator: func(c *fiber.Ctx, key string) (bool, error) {
if key == CorrectKey {
return true, nil
}
return false, ErrMissingOrMalformedAPIKey
},
},
}))
// Define a test handler
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("API key is valid")
})
// Create a request without an API key and Send the request to the app
res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
utils.AssertEqual(t, err, nil)
// Read the response body into a string
body, err := io.ReadAll(res.Body)
utils.AssertEqual(t, err, nil)
// Check that the response has the expected status code and body
utils.AssertEqual(t, res.StatusCode, http.StatusUnauthorized)
utils.AssertEqual(t, string(body), ErrMissingOrMalformedAPIKey.Error())
// Create a request with a valid API key in the "Authorization" header using the "Basic" scheme
req := httptest.NewRequest(fiber.MethodGet, "/", nil)
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", CorrectKey))
// Send the request to the app
res, err = app.Test(req)
utils.AssertEqual(t, err, nil)
// Read the response body into a string
body, err = io.ReadAll(res.Body)
utils.AssertEqual(t, err, nil)
// Check that the response has the expected status code and body
utils.AssertEqual(t, res.StatusCode, http.StatusOK)
utils.AssertEqual(t, string(body), "API key is valid")
}