forked from greenpau/caddy-authorize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
caddyfile_test.go
706 lines (684 loc) · 18.9 KB
/
caddyfile_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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
// Copyright 2020 Paul Greenberg [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package authorize
import (
"fmt"
"github.com/betrybe/caddy-authorize/internal/tests"
"github.com/betrybe/caddy-authorize/internal/testutils"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/caddytest"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"testing"
"time"
)
func TestParser(t *testing.T) {
var testcases = []struct {
name string
config string
shouldErr bool
err error
}{
{
name: "auto generate crypto key",
config: `
authorize {
primary yes
}`,
},
{
name: "default shared key in default context",
config: `
authorize {
context default
primary yes
crypto key token name "foobar token"
crypto key verify foobar
allow roles viewer editor with get to /internal/dashboard
allow roles viewer editor with post
allow audience https://localhost/ https://example.com/
allow origin any
}`,
},
{
name: "multiple shared keys in default context",
config: `
authorize {
context default
primary yes
crypto key token name "foobar token"
crypto key verify foobar
crypto key abc123 token name foobar_token
crypto key abc123 verify foobar
}`,
},
{
name: "multiple shared keys in with implicit token name config",
config: `
authorize {
context default
primary yes
crypto key verify foobar
crypto key abc123 verify foobar
}`,
},
{
name: "multiple shared keys in with explicit default token name config",
config: `
authorize {
context default
primary yes
crypto default token name jwt_token
crypto key verify foobar
crypto key abc123 verify foobar
crypto key abc123 token name foobar_token
}`,
},
{
name: "enable valid request handling parameters",
config: `
authorize {
context default
primary yes
crypto key verify foobar
enable js redirect
enable strip token
}`,
},
{
name: "enable invalid request handling parameters",
config: `
authorize {
enable foobar
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: unsupported directive for enable: foobar"),
},
{
name: "configure header claim injection",
config: `
authorize {
primary yes
crypto key verify foobar
inject headers with claims
}`,
},
{
name: "invalid crypto key config",
config: `
authorize {
crypto default barfoo foobar
}`,
shouldErr: true,
err: fmt.Errorf(`Testfile:4 - Error during parsing: crypto key store config error: key config entry "default barfoo foobar" is invalid: too few arguments`),
},
{
name: "crypto directive too short",
config: `
authorize {
crypto foobar
}`,
shouldErr: true,
err: fmt.Errorf(`Testfile:3 - Error during parsing: crypto directive "foobar" is too short`),
},
{
name: "crypto directive throws error",
config: `
authorize {
crypto default foobar
}`,
shouldErr: true,
err: fmt.Errorf(`Testfile:3 - Error during parsing: crypto directive "default foobar" is too short`),
},
{
name: "crypto directive throws unsupported error",
config: `
authorize {
crypto foobar barfoo foobar
}`,
shouldErr: true,
err: fmt.Errorf(`Testfile:3 - Error during parsing: crypto directive value of "foobar barfoo foobar" is unsupported`),
},
{
name: "configure invalid header claim injection",
config: `
authorize {
inject foobar
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: unsupported directive for inject: foobar"),
},
{
name: "configure invalid top level keyword",
config: `
authorize {
primary no
foobar barfoo
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:4 - Error during parsing: unsupported root directive: foobar"),
},
{
name: "configure empty context",
config: `
authorize {
context ""
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:4 - Error during parsing: context directive must not be empty"),
},
{
name: "configure context without args",
config: `
authorize {
context
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: context directive has no value"),
},
{
name: "configure context with invalid args",
config: `
authorize {
context foobar foobar
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: context directive value of foobar is unsupported"),
},
{
name: "configure empty primary context indicator",
config: `
authorize {
primary ""
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: primary directive error: empty switch"),
},
{
name: "configure invalid primary context indicator",
config: `
authorize {
primary foobar
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: primary directive error: invalid switch: foobar"),
},
{
name: "set disable settings",
config: `
authorize {
primary yes
disable auth redirect query
disable auth redirect
}`,
},
{
name: "set empty disable settings",
config: `
authorize {
disable ""
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: disable directive has no value"),
},
{
name: "set invalid disable settings",
config: `
authorize {
disable "foobar"
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: disable directive \"foobar\" is unsupported"),
},
{
name: "validate token parameters",
config: `
authorize {
primary yes
validate path acl
validate source address
validate bearer header
}`,
},
{
name: "empty validate token settings",
config: `
authorize {
validate ""
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: validate directive has no value"),
},
{
name: "set invalid disable settings",
config: `
authorize {
validate foobar
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: validate directive \"foobar\" is unsupported"),
},
{
name: "set general settings",
config: `
authorize {
primary yes
set token sources header
set auth url /xauth
set forbidden url /forbidden.html
set user identity mail
}`,
},
{
name: "empty validate set settings",
config: `
authorize {
set ""
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: set directive has no value"),
},
{
name: "set invalid settings",
config: `
authorize {
set foobar
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: set directive \"foobar\" is unsupported"),
},
{
name: "empty acl shortcut",
config: `
authorize {
allow
}`,
shouldErr: true,
err: fmt.Errorf("Testfile:3 - Error during parsing: allow directive has no value"),
},
{
name: "invalid acl shortcut",
config: `
authorize {
allow roles
}`,
shouldErr: true,
err: fmt.Errorf(`Testfile:3 - Error during parsing: allow directive "roles" is too short`),
},
{
name: "invalid acl shortcut args",
config: `
authorize {
allow roles foobar with post to /foobar foobar
}`,
shouldErr: true,
err: fmt.Errorf(`Testfile:3 - Error during parsing: allow directive value of "roles foobar with post to /foobar foobar" is unsupported`),
},
{
name: "acl with a single rule",
config: `
authorize {
primary yes
crypto key verify foobar
acl rule {
comment rule 1
match origin local
allow
}
}`,
},
{
name: "with basic auth in local realm",
config: `
authorize {
primary yes
crypto key verify foobar
with basic auth realm local
}`,
},
{
name: "with api key auth in local realm",
config: `
authorize {
primary yes
crypto key verify foobar
with api key auth realm local
}`,
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
msgs := []string{fmt.Sprintf("test name: %s", tc.name)}
msgs = append(msgs, fmt.Sprintf("config: %s", tc.config))
h := httpcaddyfile.Helper{
Dispenser: caddyfile.NewTestDispenser(tc.config),
}
handler, err := parseCaddyfile(h)
if tests.EvalErrWithLog(t, err, nil, tc.shouldErr, tc.err, msgs) {
return
}
if handler == nil {
t.Fatalf("handler is nil")
}
})
}
}
func TestCaddyfile(t *testing.T) {
scheme := "https"
host := "127.0.0.1"
port := "8080"
securePort := "8443"
hostPort := host + ":" + securePort
baseURL := scheme + "://" + hostPort
tokenName := "access_token"
localhost, _ := url.Parse(baseURL)
tester := caddytest.NewTester(t)
tester.InitServer(`
{
debug
http_port `+port+`
https_port `+securePort+`
local_certs
}
`+host+`, localhost {
route /dummy/jwt* {
authorize {
primary yes
crypto key token name `+tokenName+`
crypto key verify `+testutils.GetSharedKey()+`
crypto key foobar1 token name `+tokenName+`
crypto key foobar1 verify `+testutils.GetSharedKey()+`
set auth url /auth
disable auth redirect query
allow roles *
inject headers with claims
set token sources header query cookie
}
respond * "caddy jwt plugin" 200
}
route /protected/viewer* {
authorize {
allow roles admin editor viewer
disable auth redirect query
}
respond * "viewers, editors, and administrators" 200
}
route /protected/editor* {
authorize {
deny roles admin with get to editor/blocked
allow roles admin editor
disable auth redirect query
}
respond * "editors and administrators" 200
}
route /protected/admin* {
authorize {
allow roles admin
disable auth redirect query
}
respond * "administrators only" 200
}
route /protected/authenticated* {
authorize {
allow roles admin editor viewer anonymous guest
set auth url https://auth.google.com/oauth2
}
respond * "authenticated users only" 200
}
route /protected/guest* {
authorize {
allow roles anonymous guest
}
respond * "guests only" 200
}
route /protected/unauth* {
authorize {
allow scope read:books
}
}
route /protected/api* {
authorize {
allow scope read:books
disable auth redirect
}
}
route /auth* {
respond * "caddy auth portal plugin" 200
}
route /version* {
respond * "1.0.0" 200
}
}
`, "caddyfile")
expectedResponse := map[string]string{
"/version": "1.0.0",
"/auth": "caddy auth portal plugin",
"/dummy/jwt": "caddy jwt plugin",
"/protected/viewer": "viewers, editors, and administrators",
"/protected/editor": "editors and administrators",
"/protected/admin": "administrators only",
"/protected/authenticated": "authenticated users only",
"/protected/guest": "guests only",
"/protected/editor/allowed": "editors and administrators",
"/protected/api": "",
}
var testcases = []struct {
name string
roles []string
accessGrantedPath []string
accessDeniedPath []string
unauthorizedPath []string
headers map[string]string
}{
{
name: "access with admin role",
roles: []string{"admin"},
accessGrantedPath: []string{
"/version",
"/dummy/jwt",
"/protected/viewer",
"/protected/admin",
"/protected/editor/allowed",
"/protected/authenticated",
},
accessDeniedPath: []string{
"/protected/guest",
"/protected/editor/blocked",
},
},
{
name: "access with editor role",
roles: []string{"editor"},
accessGrantedPath: []string{
"/version",
"/dummy/jwt",
"/protected/viewer",
"/protected/editor",
"/protected/authenticated",
},
accessDeniedPath: []string{
"/protected/guest",
"/protected/admin",
},
},
{
name: "access with viewer role",
roles: []string{"viewer"},
accessGrantedPath: []string{
"/version",
"/dummy/jwt",
"/protected/viewer",
"/protected/authenticated",
},
accessDeniedPath: []string{
"/protected/guest",
"/protected/admin",
"/protected/editor",
},
},
{
name: "access with guest role",
roles: []string{"guest", "anonymous"},
accessGrantedPath: []string{
"/version",
"/dummy/jwt",
"/protected/authenticated",
"/protected/guest",
},
accessDeniedPath: []string{
"/protected/viewer",
"/protected/admin",
"/protected/editor",
},
},
{
name: "access as unauthenticated user",
roles: []string{},
accessGrantedPath: []string{
"/version",
},
accessDeniedPath: []string{
"/protected/viewer",
"/protected/guest",
"/protected/admin",
"/protected/editor",
"/protected/authenticated",
"/dummy/jwt",
},
headers: map[string]string{
"X-Forwarded-Host": "app.contoso.com",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
"X-Real-Ip": "10.11.12.14",
"X-Request-Id": "7a37b3b708b1497c95be8a6bf2a8274c",
},
},
{
name: "access as unauthorized user no redirect",
roles: []string{},
unauthorizedPath: []string{
"/protected/api",
},
},
{
name: "access as unauthorized user with redirect",
roles: []string{},
unauthorizedPath: []string{
"/protected/unauth",
},
},
}
tester.AssertGetResponse(baseURL+"/version", 200, "1.0.0")
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
var msgs []string
msgs = append(msgs, fmt.Sprintf("test name: %s", tc.name))
got := make(map[string]interface{})
want := make(map[string]interface{})
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatalf("failed to create cookiejar: %s", err)
}
tester.Client.Jar = jar
cookies := []*http.Cookie{}
if len(tc.roles) > 0 {
if len(tc.unauthorizedPath) == 0 {
usr := testutils.NewTestUser()
usr.SetRolesClaim(tc.roles)
msgs = append(msgs, fmt.Sprintf("roles: %s", tc.roles))
ks := testutils.NewTestCryptoKeyStore()
if err := ks.SignToken("access_token", "HS512", usr); err != nil {
t.Fatalf("Failed to get JWT token for %v: %v", usr.AsMap(), err)
}
msgs = append(msgs, fmt.Sprintf("token: %s", usr.Token))
cookies = append(cookies, &http.Cookie{Name: "access_token", Value: usr.Token})
}
tester.Client.Jar.SetCookies(localhost, cookies)
}
for _, p := range tc.accessGrantedPath {
msgs = append(msgs, fmt.Sprintf("accessing %s", p))
want[p] = map[string]interface{}{
"status_code": 200,
"response": expectedResponse[p],
}
resp, respBody := tester.AssertGetResponse(baseURL+p, 200, expectedResponse[p])
got[p] = map[string]interface{}{
"status_code": resp.StatusCode,
"response": respBody,
}
}
for _, p := range tc.accessDeniedPath {
msgs = append(msgs, fmt.Sprintf("accessing %s", p))
var redirectURL string
var redirectEnabled bool
if !strings.Contains(tc.name, "role") {
redirectEnabled = true
}
switch p {
case "/protected/guest":
redirectURL = baseURL + "/auth?redirect_url=" + url.QueryEscape(scheme+"://"+host+":"+securePort+p)
case "/protected/authenticated":
redirectURL = "https://auth.google.com/oauth2?redirect_url=" + url.QueryEscape(scheme+"://"+host+":"+securePort+p)
default:
redirectURL = baseURL + "/auth"
}
if redirectEnabled {
want[p] = map[string]interface{}{
"status_code": 302,
}
resp := tester.AssertRedirect(baseURL+p, redirectURL, 302)
got[p] = map[string]interface{}{
"status_code": resp.StatusCode,
}
} else {
want[p] = map[string]interface{}{
"status_code": 403,
}
resp, _ := tester.AssertGetResponse(baseURL+p, 403, "Forbidden")
got[p] = map[string]interface{}{
"status_code": resp.StatusCode,
}
}
}
for _, p := range tc.unauthorizedPath {
msgs = append(msgs, fmt.Sprintf("accessing %s", p))
if p == "/protected/api" {
want[p] = map[string]interface{}{
"status_code": 401,
"response": expectedResponse[p],
}
resp, respBody := tester.AssertGetResponse(baseURL+p, 401, expectedResponse[p])
got[p] = map[string]interface{}{
"status_code": resp.StatusCode,
"response": respBody,
}
} else {
want[p] = map[string]interface{}{
"status_code": 302,
}
var redirectURL = baseURL + "/auth?redirect_url=" + url.QueryEscape(scheme+"://"+host+":"+securePort+p)
resp := tester.AssertRedirect(baseURL+p, redirectURL, 302)
got[p] = map[string]interface{}{
"status_code": resp.StatusCode,
}
}
}
tests.EvalObjectsWithLog(t, "responses", want, got, msgs)
})
}
time.Sleep(1 * time.Second)
}