-
Notifications
You must be signed in to change notification settings - Fork 276
/
options_test.go
776 lines (718 loc) · 24.3 KB
/
options_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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
package config
import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/pem"
"fmt"
"net/url"
"os"
"sync"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pomerium/pomerium/pkg/cryptutil"
"github.com/pomerium/pomerium/pkg/grpc/config"
)
var cmpOptIgnoreUnexported = cmpopts.IgnoreUnexported(Options{}, Policy{})
func Test_Validate(t *testing.T) {
t.Parallel()
testOptions := func() *Options {
o := NewDefaultOptions()
o.SharedKey = "test"
o.Services = "all"
o.CertFile = "./testdata/example-cert.pem"
o.KeyFile = "./testdata/example-key.pem"
return o
}
good := testOptions()
badServices := testOptions()
badServices.Services = "blue"
badSecret := testOptions()
badSecret.SharedKey = ""
badSecret.Services = "authenticate"
badSecretAllServices := testOptions()
badSecretAllServices.SharedKey = ""
badPolicyFile := testOptions()
badPolicyFile.PolicyFile = "file"
invalidStorageType := testOptions()
invalidStorageType.DataBrokerStorageType = "foo"
missingStorageDSN := testOptions()
missingStorageDSN.DataBrokerStorageType = "redis"
badSignoutRedirectURL := testOptions()
badSignoutRedirectURL.SignOutRedirectURLString = "--"
missingSharedSecretWithPersistence := testOptions()
missingSharedSecretWithPersistence.SharedKey = ""
missingSharedSecretWithPersistence.DataBrokerStorageType = StorageRedisName
missingSharedSecretWithPersistence.DataBrokerStorageConnectionString = "redis://somehost:6379"
tests := []struct {
name string
testOpts *Options
wantErr bool
}{
{"good default with no env settings", good, false},
{"invalid service type", badServices, true},
{"missing shared secret", badSecret, true},
{"missing shared secret but all service", badSecretAllServices, false},
{"policy file specified", badPolicyFile, true},
{"invalid databroker storage type", invalidStorageType, true},
{"missing databroker storage dsn", missingStorageDSN, true},
{"invalid signout redirect url", badSignoutRedirectURL, true},
{"no shared key with databroker persistence", missingSharedSecretWithPersistence, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.testOpts.Validate()
if (err != nil) != tt.wantErr {
t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}
func Test_bindEnvs(t *testing.T) {
o := new(Options)
o.viper = viper.New()
v := viper.New()
os.Clearenv()
defer os.Unsetenv("POMERIUM_DEBUG")
defer os.Unsetenv("POLICY")
defer os.Unsetenv("HEADERS")
os.Setenv("POMERIUM_DEBUG", "true")
os.Setenv("POLICY", "LSBmcm9tOiBodHRwczovL2h0dHBiaW4ubG9jYWxob3N0LnBvbWVyaXVtLmlvCiAgdG86IAogICAgLSBodHRwOi8vbG9jYWxob3N0OjgwODEsMQo=")
os.Setenv("HEADERS", `{"X-Custom-1":"foo", "X-Custom-2":"bar"}`)
err := bindEnvs(o, v)
if err != nil {
t.Fatalf("failed to bind options to env vars: %s", err)
}
err = v.Unmarshal(o, ViperPolicyHooks)
if err != nil {
t.Errorf("Could not unmarshal %#v: %s", o, err)
}
o.viper = v
if !o.Debug {
t.Errorf("Failed to load POMERIUM_DEBUG from environment")
}
if len(o.Policies) != 1 {
t.Error("failed to bind POLICY env")
}
if o.Services != "" {
t.Errorf("Somehow got SERVICES from environment without configuring it")
}
if o.HeadersEnv != `{"X-Custom-1":"foo", "X-Custom-2":"bar"}` {
t.Errorf("Failed to bind headers env var to HeadersEnv")
}
}
func Test_parseHeaders(t *testing.T) {
// t.Parallel()
tests := []struct {
name string
want map[string]string
envHeaders string
viperHeaders interface{}
wantErr bool
}{
{
"good env",
map[string]string{"X-Custom-1": "foo", "X-Custom-2": "bar"},
`{"X-Custom-1":"foo", "X-Custom-2":"bar"}`,
map[string]string{"X": "foo"},
false,
},
{
"good env not_json",
map[string]string{"X-Custom-1": "foo", "X-Custom-2": "bar"},
`X-Custom-1:foo,X-Custom-2:bar`,
map[string]string{"X": "foo"},
false,
},
{
"bad env",
map[string]string{},
"xyyyy",
map[string]string{"X": "foo"},
true,
},
{
"bad env not_json",
map[string]string{"X-Custom-1": "foo", "X-Custom-2": "bar"},
`X-Custom-1:foo,X-Custom-2bar`,
map[string]string{"X": "foo"},
true,
},
{
"bad viper",
map[string]string{},
"",
"notaheaderstruct",
true,
},
{
"good viper",
map[string]string{"X-Custom-1": "foo", "X-Custom-2": "bar"},
"",
map[string]string{"X-Custom-1": "foo", "X-Custom-2": "bar"},
false,
},
{
"new field name",
map[string]string{"X-Custom-1": "foo"},
"",
map[string]string{"X-Custom-1": "foo"},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var (
o *Options
mu sync.Mutex
)
mu.Lock()
defer mu.Unlock()
o = NewDefaultOptions()
o.viperSet("set_response_headers", tt.viperHeaders)
o.viperSet("HeadersEnv", tt.envHeaders)
o.HeadersEnv = tt.envHeaders
err := o.parseHeaders(context.Background())
if (err != nil) != tt.wantErr {
t.Errorf("Error condition unexpected: err=%s", err)
}
if !tt.wantErr && !cmp.Equal(tt.want, o.SetResponseHeaders) {
t.Errorf("Did get expected headers: %s", cmp.Diff(tt.want, o.SetResponseHeaders))
}
})
}
}
func Test_parsePolicyFile(t *testing.T) {
t.Parallel()
opts := []cmp.Option{
cmpopts.IgnoreFields(Policy{}, "EnvoyOpts"),
cmpOptIgnoreUnexported,
}
source := "https://pomerium.io"
sourceURL, _ := url.ParseRequestURI(source)
to, err := ParseWeightedURL("https://httpbin.org")
require.NoError(t, err)
tests := []struct {
name string
policyBytes []byte
want []Policy
wantErr bool
}{
{
"simple json",
[]byte(fmt.Sprintf(`{"policy":[{"from": "%s","to":"%s"}]}`, source, to.URL.String())),
[]Policy{{
From: source,
To: []WeightedURL{*to},
Source: &StringURL{sourceURL},
}},
false,
},
{"bad from", []byte(`{"policy":[{"from": "%","to":"httpbin.org"}]}`), nil, true},
{"bad to", []byte(`{"policy":[{"from": "pomerium.io","to":"%"}]}`), nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tempFile, _ := os.CreateTemp("", "*.json")
defer tempFile.Close()
defer os.Remove(tempFile.Name())
tempFile.Write(tt.policyBytes)
var o Options
o.viper = viper.New()
o.viper.SetConfigFile(tempFile.Name())
if err := o.viper.ReadInConfig(); err != nil {
t.Fatal(err)
}
err := o.parsePolicy()
if (err != nil) != tt.wantErr {
t.Errorf("parsePolicyEnv() error = %v, wantErr %v", err, tt.wantErr)
return
}
if err == nil {
if diff := cmp.Diff(o.Policies, tt.want, opts...); diff != "" {
t.Errorf("parsePolicyEnv() = diff:%s", diff)
}
}
})
}
}
func Test_Checksum(t *testing.T) {
o := NewDefaultOptions()
oldChecksum := o.Checksum()
o.SharedKey = "changemeplease"
newChecksum := o.Checksum()
if newChecksum == oldChecksum {
t.Errorf("Checksum() failed to update old = %d, new = %d", oldChecksum, newChecksum)
}
if newChecksum == 0 || oldChecksum == 0 {
t.Error("Checksum() not returning data")
}
if o.Checksum() != newChecksum {
t.Error("Checksum() inconsistent")
}
}
func TestOptionsFromViper(t *testing.T) {
opts := []cmp.Option{
cmpopts.IgnoreFields(Options{}, "CookieSecret", "GRPCInsecure", "GRPCAddr", "DataBrokerURLString", "DataBrokerURLStrings", "AuthorizeURLString", "AuthorizeURLStrings", "DefaultUpstreamTimeout", "CookieExpire", "Services", "Addr", "LogLevel", "KeyFile", "CertFile", "SharedKey", "ReadTimeout", "IdleTimeout", "GRPCClientTimeout", "GRPCClientDNSRoundRobin", "TracingSampleRate", "ProgrammaticRedirectDomainWhitelist"),
cmpopts.IgnoreFields(Policy{}, "Source", "EnvoyOpts"),
cmpOptIgnoreUnexported,
}
tests := []struct {
name string
configBytes []byte
want *Options
wantErr bool
}{
{
"good",
[]byte(`{"autocert_dir":"","insecure_server":true,"policy":[{"from": "https://from.example","to":"https://to.example"}]}`),
&Options{
Policies: []Policy{{From: "https://from.example", To: mustParseWeightedURLs(t, "https://to.example")}},
CookieName: "_pomerium",
CookieSecure: true,
InsecureServer: true,
CookieHTTPOnly: true,
AuthenticateCallbackPath: "/oauth2/callback",
SetResponseHeaders: map[string]string{
"Strict-Transport-Security": "max-age=31536000; includeSubDomains; preload",
"X-Frame-Options": "SAMEORIGIN",
"X-XSS-Protection": "1; mode=block",
},
RefreshDirectoryTimeout: 1 * time.Minute,
RefreshDirectoryInterval: 10 * time.Minute,
QPS: 1.0,
DataBrokerStorageType: "memory",
EnvoyAdminAccessLogPath: os.DevNull,
EnvoyAdminProfilePath: os.DevNull,
},
false,
},
{
"good disable header",
[]byte(`{"autocert_dir":"","insecure_server":true,"set_response_headers": {"disable":"true"},"policy":[{"from": "https://from.example","to":"https://to.example"}]}`),
&Options{
Policies: []Policy{{From: "https://from.example", To: mustParseWeightedURLs(t, "https://to.example")}},
CookieName: "_pomerium",
AuthenticateCallbackPath: "/oauth2/callback",
CookieSecure: true,
CookieHTTPOnly: true,
InsecureServer: true,
SetResponseHeaders: map[string]string{"disable": "true"},
RefreshDirectoryTimeout: 1 * time.Minute,
RefreshDirectoryInterval: 10 * time.Minute,
QPS: 1.0,
DataBrokerStorageType: "memory",
EnvoyAdminAccessLogPath: os.DevNull,
EnvoyAdminProfilePath: os.DevNull,
},
false,
},
{"bad url", []byte(`{"policy":[{"from": "https://","to":"https://to.example"}]}`), nil, true},
{"bad policy", []byte(`{"policy":[{"allow_public_unauthenticated_access": "dog","to":"https://to.example"}]}`), nil, true},
{"bad file", []byte(`{''''}`), nil, true},
{"allowed_groups without idp_service_account should fail", []byte(`{"autocert_dir":"","insecure_server":true,"policy":[{"from": "https://from.example","to":"https://to.example","allowed_groups": "['group1']"}]}`), nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tempFile, _ := os.CreateTemp("", "*.json")
defer tempFile.Close()
defer os.Remove(tempFile.Name())
tempFile.Write(tt.configBytes)
got, err := optionsFromViper(tempFile.Name())
if (err != nil) != tt.wantErr {
t.Errorf("optionsFromViper() error = %v, wantErr %v", err, tt.wantErr)
return
}
if diff := cmp.Diff(got, tt.want, opts...); diff != "" {
t.Errorf("newOptionsFromConfig() = %s", diff)
}
})
}
}
func Test_NewOptionsFromConfigEnvVar(t *testing.T) {
tests := []struct {
name string
envKeyPairs map[string]string
wantErr bool
}{
{"good", map[string]string{"INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, false},
{"bad no shared secret", map[string]string{"INSECURE_SERVER": "true", "SERVICES": "authenticate"}, true},
{"good no shared secret in all mode", map[string]string{"INSECURE_SERVER": "true"}, false},
{"bad header", map[string]string{"HEADERS": "x;y;z", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, true},
{"bad authenticate url", map[string]string{"AUTHENTICATE_SERVICE_URL": "authenticate.example", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, true},
{"bad authorize url", map[string]string{"AUTHORIZE_SERVICE_URL": "authorize.example", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, true},
{"bad cert base64", map[string]string{"CERTIFICATE": "bad cert", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, true},
{"bad cert key base64", map[string]string{"CERTIFICATE_KEY": "bad cert", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, true},
{"no certs no insecure mode set", map[string]string{"SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, false},
{"good disable headers ", map[string]string{"HEADERS": "disable:true", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, false},
{"bad whitespace in secret", map[string]string{"INSECURE_SERVER": "true", "SERVICES": "authenticate", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM=\n"}, true},
{"good forward auth url", map[string]string{"FORWARD_AUTH_URL": "https://databroker.example", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, false},
{"bad forward auth url", map[string]string{"FORWARD_AUTH_URL": "databroker.example", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, true},
{"same addr and grpc addr", map[string]string{"SERVICES": "databroker", "ADDRESS": "0", "GRPC_ADDRESS": "0", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, false},
{"bad cert files", map[string]string{"INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM=", "CERTIFICATES": "./test-data/example-cert.pem"}, true},
{"good cert file", map[string]string{"CERTIFICATE_FILE": "./testdata/example-cert.pem", "CERTIFICATE_KEY_FILE": "./testdata/example-key.pem", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, false},
{"bad cert file", map[string]string{"CERTIFICATE_FILE": "./testdata/example-cert-bad.pem", "CERTIFICATE_KEY_FILE": "./testdata/example-key-bad.pem", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, true},
{"good client ca file", map[string]string{"CLIENT_CA_FILE": "./testdata/ca.pem", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, false},
{"bad client ca file", map[string]string{"CLIENT_CA_FILE": "./testdata/bad-ca.pem", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, true},
{"bad client ca b64", map[string]string{"CLIENT_CA": "bad cert", "INSECURE_SERVER": "true", "SHARED_SECRET": "YixWi1MYh77NMECGGIJQevoonYtVF+ZPRkQZrrmeRqM="}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for k, v := range tt.envKeyPairs {
os.Setenv(k, v)
defer os.Unsetenv(k)
}
_, err := newOptionsFromConfig("")
if (err != nil) != tt.wantErr {
t.Errorf("newOptionsFromConfig() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}
func Test_AutoCertOptionsFromEnvVar(t *testing.T) {
type test struct {
envs map[string]string
expected AutocertOptions
wantErr bool
cleanup func()
}
tests := map[string]func(t *testing.T) test{
"ok/simple": func(t *testing.T) test {
envs := map[string]string{
"AUTOCERT": "true",
"AUTOCERT_DIR": "/test",
"AUTOCERT_MUST_STAPLE": "true",
"INSECURE_SERVER": "true",
}
return test{
envs: envs,
expected: AutocertOptions{
Enable: true,
Folder: "/test",
MustStaple: true,
},
wantErr: false,
}
},
"ok/custom-ca": func(t *testing.T) test {
certPEM, err := newCACertPEM()
require.NoError(t, err)
envs := map[string]string{
"AUTOCERT": "true",
"AUTOCERT_CA": "test-ca.example.com/directory",
"AUTOCERT_EMAIL": "test@example.com",
"AUTOCERT_EAB_KEY_ID": "keyID",
"AUTOCERT_EAB_MAC_KEY": "fake-key",
"AUTOCERT_TRUSTED_CA": base64.StdEncoding.EncodeToString(certPEM),
"AUTOCERT_DIR": "/test",
"AUTOCERT_MUST_STAPLE": "true",
"INSECURE_SERVER": "true",
}
return test{
envs: envs,
wantErr: false,
expected: AutocertOptions{
Enable: true,
CA: "test-ca.example.com/directory",
Email: "test@example.com",
EABKeyID: "keyID",
EABMACKey: "fake-key",
TrustedCA: base64.StdEncoding.EncodeToString(certPEM),
Folder: "/test",
MustStaple: true,
},
}
},
"ok/custom-ca-file": func(t *testing.T) test {
certPEM, err := newCACertPEM()
require.NoError(t, err)
f, err := os.CreateTemp("", "pomerium-test-ca")
require.NoError(t, err)
n, err := f.Write(certPEM)
require.NoError(t, err)
require.Equal(t, len(certPEM), n)
envs := map[string]string{
"AUTOCERT": "true",
"AUTOCERT_CA": "test-ca.example.com/directory",
"AUTOCERT_EMAIL": "test@example.com",
"AUTOCERT_EAB_KEY_ID": "keyID",
"AUTOCERT_EAB_MAC_KEY": "fake-key",
"AUTOCERT_TRUSTED_CA_FILE": f.Name(),
"AUTOCERT_DIR": "/test",
"AUTOCERT_MUST_STAPLE": "true",
"INSECURE_SERVER": "true",
}
return test{
envs: envs,
wantErr: false,
expected: AutocertOptions{
Enable: true,
CA: "test-ca.example.com/directory",
Email: "test@example.com",
EABKeyID: "keyID",
EABMACKey: "fake-key",
TrustedCAFile: f.Name(),
Folder: "/test",
MustStaple: true,
},
cleanup: func() { os.Remove(f.Name()) },
}
},
}
for name, run := range tests {
tc := run(t)
t.Run(name, func(t *testing.T) {
for k, v := range tc.envs {
os.Setenv(k, v)
defer os.Unsetenv(k)
}
o, err := newOptionsFromConfig("")
if err != nil {
t.Fatal(err)
}
if !cmp.Equal(tc.expected, o.AutocertOptions) {
t.Errorf("AutoCertOptionsFromEnvVar() diff = %s", cmp.Diff(tc.expected, o.AutocertOptions))
}
if tc.cleanup != nil {
tc.cleanup()
}
})
}
}
func TestHTTPRedirectAddressStripQuotes(t *testing.T) {
o := NewDefaultOptions()
o.InsecureServer = true
o.HTTPRedirectAddr = `":80"`
assert.NoError(t, o.Validate())
assert.Equal(t, ":80", o.HTTPRedirectAddr)
}
func TestCertificatesArrayParsing(t *testing.T) {
t.Parallel()
testCertFileRef := "./testdata/example-cert.pem"
testKeyFileRef := "./testdata/example-key.pem"
testCertFile, _ := os.ReadFile(testCertFileRef)
testKeyFile, _ := os.ReadFile(testKeyFileRef)
testCertAsBase64 := base64.StdEncoding.EncodeToString(testCertFile)
testKeyAsBase64 := base64.StdEncoding.EncodeToString(testKeyFile)
tests := []struct {
name string
certificateFiles []certificateFilePair
wantErr bool
}{
{"Handles base64 string as params", []certificateFilePair{{KeyFile: testKeyAsBase64, CertFile: testCertAsBase64}}, false},
{"Handles file reference as params", []certificateFilePair{{KeyFile: testKeyFileRef, CertFile: testCertFileRef}}, false},
{"Returns an error otherwise", []certificateFilePair{{KeyFile: "abc", CertFile: "abc"}}, true},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
o := NewDefaultOptions()
o.CertificateFiles = tt.certificateFiles
err := o.Validate()
if err != nil && tt.wantErr == false {
t.Fatal(err)
}
})
}
}
func TestCompareByteSliceSlice(t *testing.T) {
type Bytes = [][]byte
tests := []struct {
expect int
a Bytes
b Bytes
}{
{
0,
Bytes{
{0, 1, 2, 3},
},
Bytes{
{0, 1, 2, 3},
},
},
{
-1,
Bytes{
{0, 1, 2, 3},
},
Bytes{
{0, 1, 2, 4},
},
},
{
1,
Bytes{
{0, 1, 2, 4},
},
Bytes{
{0, 1, 2, 3},
},
},
{
-1,
Bytes{
{0, 1, 2, 3},
},
Bytes{
{0, 1, 2, 3},
{4, 5, 6, 7},
},
},
{
1,
Bytes{
{0, 1, 2, 3},
{4, 5, 6, 7},
},
Bytes{
{0, 1, 2, 3},
},
},
}
for _, tt := range tests {
actual := compareByteSliceSlice(tt.a, tt.b)
if tt.expect != actual {
t.Errorf("expected compare(%v, %v) to be %v but got %v",
tt.a, tt.b, tt.expect, actual)
}
}
}
func TestOptions_DefaultURL(t *testing.T) {
t.Parallel()
firstURL := func(f func() ([]*url.URL, error)) func() (*url.URL, error) {
return func() (*url.URL, error) {
urls, err := f()
if err != nil {
return nil, err
} else if len(urls) == 0 {
return nil, fmt.Errorf("no url defined")
}
return urls[0], nil
}
}
defaultOptions := &Options{}
opts := &Options{
AuthenticateURLString: "https://authenticate.example.com",
AuthorizeURLString: "https://authorize.example.com",
DataBrokerURLString: "https://databroker.example.com",
ForwardAuthURLString: "https://forwardauth.example.com",
}
tests := []struct {
name string
f func() (*url.URL, error)
expectedURLStr string
}{
{"default authenticate url", defaultOptions.GetAuthenticateURL, "https://127.0.0.1"},
{"default authorize url", defaultOptions.GetAuthenticateURL, "https://127.0.0.1"},
{"default databroker url", defaultOptions.GetAuthenticateURL, "https://127.0.0.1"},
{"default forward auth url", defaultOptions.GetAuthenticateURL, "https://127.0.0.1"},
{"good authenticate url", opts.GetAuthenticateURL, "https://authenticate.example.com"},
{"good authorize url", firstURL(opts.GetAuthorizeURLs), "https://authorize.example.com"},
{"good databroker url", firstURL(opts.GetDataBrokerURLs), "https://databroker.example.com"},
{"good forward auth url", opts.GetForwardAuthURL, "https://forwardauth.example.com"},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
u, err := tc.f()
require.NoError(t, err)
assert.Equal(t, tc.expectedURLStr, u.String())
})
}
}
func TestOptions_GetOauthOptions(t *testing.T) {
opts := &Options{AuthenticateURLString: "https://authenticate.example.com"}
oauthOptions, err := opts.GetOauthOptions()
require.NoError(t, err)
// Test that oauth redirect url hostname must point to authenticate url hostname.
u, err := opts.GetAuthenticateURL()
require.NoError(t, err)
assert.Equal(t, u.Hostname(), oauthOptions.RedirectURL.Hostname())
}
func TestOptions_GetAllRouteableGRPCDomains(t *testing.T) {
opts := &Options{
AuthenticateURLString: "https://authenticate.example.com",
AuthorizeURLString: "https://authorize.example.com",
DataBrokerURLString: "https://databroker.example.com",
Services: "all",
}
domains, err := opts.GetAllRouteableGRPCDomains()
assert.NoError(t, err)
assert.Equal(t, []string{
"authorize.example.com",
"authorize.example.com:443",
"databroker.example.com",
"databroker.example.com:443",
}, domains)
}
func TestOptions_GetAllRouteableHTTPDomains(t *testing.T) {
p1 := Policy{From: "https://from1.example.com"}
p1.Validate()
p2 := Policy{From: "https://from2.example.com"}
p2.Validate()
p3 := Policy{From: "https://from3.example.com", TLSDownstreamServerName: "from.example.com"}
p3.Validate()
opts := &Options{
AuthenticateURLString: "https://authenticate.example.com",
AuthorizeURLString: "https://authorize.example.com",
DataBrokerURLString: "https://databroker.example.com",
Policies: []Policy{p1, p2, p3},
Services: "all",
}
domains, err := opts.GetAllRouteableHTTPDomains()
assert.NoError(t, err)
assert.Equal(t, []string{
"authenticate.example.com",
"authenticate.example.com:443",
"from.example.com",
"from.example.com:443",
"from1.example.com",
"from1.example.com:443",
"from2.example.com",
"from2.example.com:443",
"from3.example.com",
"from3.example.com:443",
}, domains)
}
func TestOptions_ApplySettings(t *testing.T) {
ctx, clearTimeout := context.WithTimeout(context.Background(), time.Second)
defer clearTimeout()
t.Run("certificates", func(t *testing.T) {
options := NewDefaultOptions()
cert1, err := cryptutil.GenerateSelfSignedCertificate("example.com")
require.NoError(t, err)
options.CertificateFiles = append(options.CertificateFiles, certificateFilePair{
CertFile: base64.StdEncoding.EncodeToString(encodeCert(cert1)),
})
cert2, err := cryptutil.GenerateSelfSignedCertificate("example.com")
require.NoError(t, err)
cert3, err := cryptutil.GenerateSelfSignedCertificate("not.example.com")
require.NoError(t, err)
settings := &config.Settings{
Certificates: []*config.Settings_Certificate{
{CertBytes: encodeCert(cert2)},
{CertBytes: encodeCert(cert3)},
},
}
options.ApplySettings(ctx, settings)
assert.Len(t, options.CertificateFiles, 2, "should prevent adding duplicate certificates")
})
}
func encodeCert(cert *tls.Certificate) []byte {
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Certificate[0]})
}
func mustParseWeightedURLs(t *testing.T, urls ...string) []WeightedURL {
wu, err := ParseWeightedUrls(urls...)
require.NoError(t, err)
return wu
}