This repository has been archived by the owner on Dec 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 349
/
utils_test.go
596 lines (547 loc) · 13.9 KB
/
utils_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
/*
Copyright 2015 All rights reserved.
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 main
import (
"bytes"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"reflect"
"testing"
"time"
uuid "github.com/gofrs/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDecodeKeyPairs(t *testing.T) {
testCases := []struct {
List []string
KeyPairs map[string]string
Ok bool
}{
{
List: []string{"a=b", "b=3"},
KeyPairs: map[string]string{
"a": "b",
"b": "3",
},
Ok: true,
},
{
List: []string{"add", "b=3"},
},
}
for i, c := range testCases {
kp, err := decodeKeyPairs(c.List)
if err != nil && c.Ok {
t.Errorf("test case %d should not have failed", i)
continue
}
if !c.Ok {
continue
}
if !reflect.DeepEqual(kp, c.KeyPairs) {
t.Errorf("test case %d are not equal %v <-> %v", i, kp, c.KeyPairs)
}
}
}
func TestGetRequestHostURL(t *testing.T) {
cs := []struct {
Expected string
HostHeader string
Hostname string
TLS *tls.ConnectionState
}{
{
Expected: "http://www.test.com",
Hostname: "www.test.com",
},
{
Expected: "http://",
},
{
Expected: "http://www.override.com",
HostHeader: "www.override.com",
Hostname: "www.test.com",
},
{
Expected: "https://www.test.com",
Hostname: "www.test.com",
TLS: &tls.ConnectionState{},
},
{
Expected: "https://www.override.com",
HostHeader: "www.override.com",
Hostname: "www.test.com",
TLS: &tls.ConnectionState{},
},
}
for i, c := range cs {
request := &http.Request{
Method: http.MethodGet,
Host: c.Hostname,
TLS: c.TLS,
}
if c.HostHeader != "" {
request.Header = make(http.Header)
request.Header.Set("X-Forwarded-Host", c.HostHeader)
}
assert.Equal(t, c.Expected, getRequestHostURL(request), "case %d, expected: %s, got: %s", i, c.Expected, getRequestHostURL(request))
}
}
func BenchmarkUUID(b *testing.B) {
for n := 0; n < b.N; n++ {
s, err := uuid.NewV1()
if err != nil {
b.Errorf("test case should not have failed")
}
_ = s.String()
}
}
func TestDefaultTo(t *testing.T) {
cs := []struct {
Value string
Default string
Expected string
}{
{
Value: "",
Default: "hello",
Expected: "hello",
},
{
Value: "world",
Default: "hello",
Expected: "world",
},
}
for _, c := range cs {
assert.Equal(t, c.Expected, defaultTo(c.Value, c.Default))
}
}
func TestEncryptDataBlock(t *testing.T) {
testCase := []struct {
Text string
Key string
Ok bool
}{
{
Text: "hello world, my name is Louketo proxy",
Key: "DtNMS2eO7Fi5vsuLrW55nrRbir2kPfTw",
Ok: true,
},
{
Text: "hello world, my name is Louketo proxy",
Key: "DtNMS2eO7Fi5vsu",
},
{
Text: "h",
Key: "DtNMS2eO7Fi5vsuLrW55nrRbir2kPfTwtr",
},
}
for i, test := range testCase {
_, err := encryptDataBlock(bytes.NewBufferString(test.Text).Bytes(), bytes.NewBufferString(test.Key).Bytes())
if err != nil && test.Ok {
t.Errorf("test case: %d should not have failed, %s", i, err)
}
}
}
func TestEncodeText(t *testing.T) {
session, err := encodeText("12245325632323263762", "1gjrlcjQ8RyKANngp9607txr5fF5fhf1")
assert.NotEmpty(t, session)
assert.NoError(t, err)
}
var (
fakePlainText = []byte(`nFlhnhwRzC9uJ9mjhR0PQezUpIiDlU9ASLqH1KIKFhBZZrMZfnAAdHdgKs2OJoni8cTSQ
JxkaNpboZ6hnrMytlw5kf0biF7dLTU885uHIGkUIRy75hx6BaTEEhbN36qVTxediEHd6xeBPS3qpJ7riO6J
EeaQr1rroDL0LvmDyB6Zds4LdVQEmtUueusc7jkBz7gJ12vnTHIxviZM5rzcq4tyCbZO7Kb37RqZg5kbYGK
PfErhUwUIin7jsNVE7coB`)
fakeCipherText = []byte("lfQPTa6jwMTABaJhcrfVkoqcdyMVAettMsqgKXIALSKG5UpoYKbT/WgZjOiuCmEI0E/7piP8VATLOAHKDBNF2WrQOKSYF+gdHkh4NLv0cW0NZ2qyZeWhknywE6063ylhCYjJOrJA1z12i2bHHbjZZGfqkwfzyxxFLTv6jSbalpZ4oZcUcNY/DrtVk/K01qZw6o4l1f0FUL6UZVSirn+B3YDWLeVQ0FGr6jlhCpN203Rf688nqdBvhw4bUEQiykCMxWm2/rJBNWm2SzZgw65kb4W0ph1qjcoUjXBwNakK+E0Lw/fwi8+bUC1lkT8+hJpMLKZkzb07rbGAnmljQo0NkqJh4kl+aycsEhm9bZj+b6w0r795YugyNsyca5CnUvkB1Dg")
fakeKey = []byte("u3K0eKsmGl76jY1buzexwYoRRLLQrQck")
)
/*
func TestEncryptedText(t *testing.T) {
s, err := encodeText(string(fakePlainText), string(fakeKey))
require.NoError(t, err)
require.NotEmpty(t, s)
d, err := decodeText(s, string(fakeKey))
require.NoError(t, err)
require.NotEmpty(t, d)
assert.Equal(t, string(fakePlainText), d)
fmt.Printf("Encoded: '%s'\n", s)
fmt.Printf("Decoded: '%s'\n", d)
}
*/
func BenchmarkEncryptDataBlock(b *testing.B) {
for n := 0; n < b.N; n++ {
_, _ = encryptDataBlock(fakePlainText, fakeKey)
}
}
func BenchmarkEncodeText(b *testing.B) {
text := string(fakePlainText)
key := string(fakeKey)
for n := 0; n < b.N; n++ {
_, _ = encodeText(text, key)
}
}
func BenchmarkDecodeText(b *testing.B) {
t := string(fakeCipherText)
k := string(fakeKey)
for n := 0; n < b.N; n++ {
if _, err := decodeText(t, k); err != nil {
b.FailNow()
}
}
}
func TestDecodeText(t *testing.T) {
fakeKey := "HYLNt2JSzD7Lpz0djTRudmlOpbwx1oHB"
fakeText := "12245325632323263762"
encrypted, err := encodeText(fakeText, fakeKey)
require.NoError(t, err)
assert.NotEmpty(t, encrypted)
decoded, _ := decodeText(encrypted, fakeKey)
assert.NotNil(t, decoded, "the session should not have been nil")
assert.Equal(t, decoded, fakeText, "the decoded text is not the same")
}
func TestFindCookie(t *testing.T) {
cookies := []*http.Cookie{
{Name: "cookie_there"},
}
assert.NotNil(t, findCookie("cookie_there", cookies))
assert.Nil(t, findCookie("not_there", cookies))
}
func TestDecryptDataBlock(t *testing.T) {
testCase := []struct {
Text string
Key string
Ok bool
}{
{
Text: "hello world, my name is Louketo proxy",
Key: "DtNMS2eO7Fi5vsuLrW55nrRbir2kPfss",
Ok: true,
},
{
Text: "h",
Key: "DtNMS2eO7Fi5vsuLrW55nrRbir2kPfTw",
Ok: true,
},
}
for i, test := range testCase {
cipher, err := encryptDataBlock(bytes.NewBufferString(test.Text).Bytes(), bytes.NewBufferString(test.Key).Bytes())
if err != nil && test.Ok {
t.Errorf("test case: %d should not have failed, %s", i, err)
}
plain, err := decryptDataBlock(cipher, bytes.NewBufferString(test.Key).Bytes())
if err != nil {
t.Errorf("test case: %d should not have failed, %s", i, err)
}
if string(plain) != test.Text {
t.Errorf("test case: %d are not the same", i)
}
}
}
func TestHasAccessOK(t *testing.T) {
cs := []struct {
Have []string
Need []string
Required bool
}{
{},
{
Have: []string{"a", "b"},
},
{
Have: []string{"a", "b", "c"},
Need: []string{"a", "b"},
Required: true,
},
{
Have: []string{"a", "b", "c"},
Need: []string{"a", "c"},
},
{
Have: []string{"a", "b", "c"},
Need: []string{"c"},
},
{
Have: []string{"a", "b", "c"},
Need: []string{"b"},
},
{
Have: []string{"a", "b", "c"},
Need: []string{"b"},
},
{
Have: []string{"a", "b"},
Need: []string{"a"},
},
{
Have: []string{"a", "b"},
Need: []string{"a"},
Required: true,
},
{
Have: []string{"b", "a"},
Need: []string{"a"},
Required: true,
},
}
for i, x := range cs {
assert.True(t, hasAccess(x.Need, x.Have, x.Required), "case: %d should be true, have: %v, need: %v, require: %t ", i, x.Have, x.Need, x.Required)
}
}
func TestHasAccessBad(t *testing.T) {
cs := []struct {
Have []string
Need []string
Required bool
}{
{
Have: []string{"a", "b"},
Need: []string{"c"},
},
{
Have: []string{"a", "b"},
Need: []string{"c"},
Required: true,
},
{
Have: []string{"a", "c"},
Need: []string{"a", "b"},
Required: true,
},
{
Have: []string{"a", "b", "c"},
Need: []string{"b", "j"},
Required: true,
},
{
Have: []string{"a", "b", "c"},
Need: []string{"a", "d"},
Required: true,
},
}
for i, x := range cs {
assert.False(t, hasAccess(x.Need, x.Have, x.Required), "case: %d should be false, have: %v, need: %v, require: %t ", i, x.Have, x.Need, x.Required)
}
}
func TestContainedIn(t *testing.T) {
assert.False(t, containedIn("1", []string{"2", "3", "4"}))
assert.True(t, containedIn("1", []string{"1", "2", "3", "4"}))
}
func TestContainsSubString(t *testing.T) {
assert.False(t, containsSubString("bar.com", []string{"foo.bar.com"}))
assert.True(t, containsSubString("www.foo.bar.com", []string{"foo.bar.com"}))
assert.True(t, containsSubString("foo.bar.com", []string{"bar.com"}))
assert.True(t, containsSubString("star.domain.com", []string{"domain.com", "domain1.com"}))
assert.True(t, containsSubString("star.domain1.com", []string{"domain.com", "domain1.com"}))
assert.True(t, containsSubString("test.test.svc.cluster.local", []string{"svc.cluster.local"}))
assert.False(t, containsSubString("star.domain1.com", []string{"domain.com", "sub.domain1.com"}))
assert.False(t, containsSubString("svc.cluster.local", []string{"nginx.pr1.svc.cluster.local"}))
assert.False(t, containsSubString("cluster.local", []string{"nginx.pr1.svc.cluster.local"}))
assert.False(t, containsSubString("pr1", []string{"nginx.pr1.svc.cluster.local"}))
}
func BenchmarkContainsSubString(t *testing.B) {
for n := 0; n < t.N; n++ {
containsSubString("svc.cluster.local", []string{"nginx.pr1.svc.cluster.local"})
}
}
func TestDialAddress(t *testing.T) {
assert.Equal(t, dialAddress(getFakeURL("http://127.0.0.1")), "127.0.0.1:80")
assert.Equal(t, dialAddress(getFakeURL("https://127.0.0.1")), "127.0.0.1:443")
assert.Equal(t, dialAddress(getFakeURL("http://127.0.0.1:8080")), "127.0.0.1:8080")
}
func TestIsUpgradedConnection(t *testing.T) {
header := http.Header{}
header.Add(headerUpgrade, "")
assert.False(t, isUpgradedConnection(&http.Request{Header: header}))
header.Set(headerUpgrade, "set")
assert.True(t, isUpgradedConnection(&http.Request{Header: header}))
}
func TestIdValidHTTPMethod(t *testing.T) {
cs := []struct {
Method string
Ok bool
}{
{Method: "GET", Ok: true},
{Method: "GETT"},
{Method: "CONNECT", Ok: false},
{Method: "PUT", Ok: true},
{Method: "PATCH", Ok: true},
}
for _, x := range cs {
assert.Equal(t, x.Ok, isValidHTTPMethod(x.Method))
}
}
func TestFileExists(t *testing.T) {
if fileExists("no_such_file_exsit_32323232") {
t.Error("we should have received false")
}
tmpfile, err := ioutil.TempFile("/tmp", fmt.Sprintf("test_file_%d", os.Getpid()))
if err != nil {
t.Fatalf("failed to create the temporary file, %s", err)
}
defer os.Remove(tmpfile.Name())
if !fileExists(tmpfile.Name()) {
t.Error("we should have received a true")
}
}
func TestGetWithin(t *testing.T) {
cs := []struct {
Expires time.Time
Percent float64
Expected time.Duration
}{
{
Expires: time.Now().Add(time.Duration(1) * time.Hour),
Percent: 0.10,
Expected: 359000000000,
},
{
Expires: time.Now().Add(time.Duration(1) * time.Hour),
Percent: 0.20,
Expected: 719000000000,
},
}
for _, x := range cs {
assert.InDelta(t, x.Expected, getWithin(x.Expires, x.Percent), 1000000001)
}
}
func TestToHeader(t *testing.T) {
cases := []struct {
Word string
Expected string
}{
{
Word: "given_name",
Expected: "Given-Name",
},
{
Word: "family%name",
Expected: "Family-Name",
},
{
Word: "perferredname",
Expected: "Perferredname",
},
}
for i, x := range cases {
assert.Equal(t, x.Expected, toHeader(x.Word), "case %d, expected: %s but got: %s",
i, x.Expected, toHeader(x.Word))
}
}
func TestCapitalize(t *testing.T) {
cases := []struct {
Word string
Expected string
}{
{
Word: "given",
Expected: "Given",
},
{
Word: "1iven",
Expected: "1iven",
},
{
Word: "Test this",
Expected: "Test this",
},
}
for i, x := range cases {
assert.Equal(t, x.Expected, capitalize(x.Word), "case %d, expected: %s but got: %s", i, x.Expected,
capitalize(x.Word))
}
}
func TestMergeMaps(t *testing.T) {
cases := []struct {
Source map[string]string
Dest map[string]string
Expected map[string]string
}{
{
Source: map[string]string{
"a": "b",
"b": "b",
},
Dest: map[string]string{
"c": "c",
},
Expected: map[string]string{
"a": "b",
"b": "b",
"c": "c",
},
},
}
for i, x := range cases {
merged := mergeMaps(x.Dest, x.Source)
if !reflect.DeepEqual(x.Expected, merged) {
t.Errorf("case %d, expected: %v but got: %v", i, x.Expected, merged)
}
}
}
func TestReadConfiguration(t *testing.T) {
testCases := []struct {
Content string
Ok bool
}{
{
Content: `
discovery_url: https://keyclock.domain.com/
client-id: <client_id>
secret: <secret>
`,
},
{
Content: `
discovery_url: https://keyclock.domain.com
client-id: <client_id>
secret: <secret>
upstream-url: http://127.0.0.1:8080
redirection_url: http://127.0.0.1:3000
`,
Ok: true,
},
}
for i, test := range testCases {
// step: write the fake config file
file := writeFakeConfigFile(t, test.Content)
config := new(Config)
err := readConfigFile(file.Name(), config)
if test.Ok && err != nil {
os.Remove(file.Name())
t.Errorf("test case %d should not have failed, config: %v, error: %s", i, config, err)
}
os.Remove(file.Name())
}
}
func getFakeURL(location string) *url.URL {
u, _ := url.Parse(location)
return u
}
func writeFakeConfigFile(t *testing.T, content string) *os.File {
f, err := ioutil.TempFile("", "node_label_file")
if err != nil {
t.Fatalf("unexpected error creating node_label_file: %v", err)
}
f.Close()
if err := ioutil.WriteFile(f.Name(), []byte(content), 0600); err != nil {
t.Fatalf("unexpected error writing node label file: %v", err)
}
return f
}