forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_test.go
671 lines (618 loc) · 16.1 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
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
/*
Copyright 2015-2019 Gravitational, Inc.
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 utils
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gravitational/teleport/lib/fixtures"
"github.com/gravitational/teleport/lib/utils/cert"
)
func TestMain(m *testing.M) {
InitLoggerForTests()
os.Exit(m.Run())
}
func TestHostUUIDIdempotent(t *testing.T) {
t.Parallel()
// call twice, get same result
dir := t.TempDir()
id, err := ReadOrMakeHostUUID(dir)
require.Len(t, id, 36)
require.NoError(t, err)
uuidCopy, err := ReadOrMakeHostUUID(dir)
require.NoError(t, err)
require.Equal(t, id, uuidCopy)
}
func TestHostUUIDBadLocation(t *testing.T) {
t.Parallel()
// call with a read-only dir, make sure to get an error
id, err := ReadOrMakeHostUUID("/bad-location")
require.Equal(t, id, "")
require.Error(t, err)
require.Regexp(t, "^.*no such file or directory.*$", err.Error())
}
func TestHostUUIDIgnoreWhitespace(t *testing.T) {
t.Parallel()
// newlines are getting ignored
dir := t.TempDir()
id := fmt.Sprintf("%s\n", uuid.NewString())
err := os.WriteFile(filepath.Join(dir, HostUUIDFile), []byte(id), 0666)
require.NoError(t, err)
out, err := ReadHostUUID(dir)
require.NoError(t, err)
require.Equal(t, strings.TrimSpace(id), out)
}
func TestHostUUIDRegenerateEmpty(t *testing.T) {
t.Parallel()
// empty UUID in file is regenerated
dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, HostUUIDFile), nil, 0666)
require.NoError(t, err)
out, err := ReadOrMakeHostUUID(dir)
require.NoError(t, err)
require.Len(t, out, 36)
}
func TestSelfSignedCert(t *testing.T) {
t.Parallel()
creds, err := cert.GenerateSelfSignedCert([]string{"example.com"})
require.NoError(t, err)
require.NotNil(t, creds)
require.Equal(t, 4, len(creds.PublicKey)/100)
require.Equal(t, 16, len(creds.PrivateKey)/100)
}
func TestRandomDuration(t *testing.T) {
t.Parallel()
expectedMin := time.Duration(0)
expectedMax := time.Second * 10
for i := 0; i < 50; i++ {
dur := RandomDuration(expectedMax)
require.True(t, dur >= expectedMin)
require.True(t, dur < expectedMax)
}
}
func TestRemoveFromSlice(t *testing.T) {
t.Parallel()
tests := []struct {
name string
slice []string
target string
expected []string
}{
{name: "remove from empty", slice: []string{}, target: "a", expected: []string{}},
{name: "remove only element", slice: []string{"a"}, target: "a", expected: []string{}},
{name: "remove a", slice: []string{"a", "b"}, target: "a", expected: []string{"b"}},
{name: "remove b", slice: []string{"a", "b"}, target: "b", expected: []string{"a"}},
{name: "remove duplicate elements", slice: []string{"a", "a", "b"}, target: "a", expected: []string{"b"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.expected, RemoveFromSlice(tc.slice, tc.target))
})
}
}
// TestVersions tests versions compatibility checking
func TestVersions(t *testing.T) {
t.Parallel()
type tc struct {
info string
client string
minClient string
}
successTestCases := []tc{
{info: "client same as min version", client: "1.0.0", minClient: "1.0.0"},
{info: "client newer than min version", client: "1.1.0", minClient: "1.0.0"},
{info: "pre-releases clients are ok", client: "1.1.0-alpha.1", minClient: "1.0.0"},
}
for _, testCase := range successTestCases {
t.Run(testCase.info, func(t *testing.T) {
require.NoError(t, CheckVersion(testCase.client, testCase.minClient))
})
}
failTestCases := []tc{
{info: "client older than min version", client: "1.0.0", minClient: "1.1.0"},
{info: "older pre-releases are no ok", client: "1.1.0-alpha.1", minClient: "1.1.0"},
}
for _, testCase := range failTestCases {
t.Run(testCase.info, func(t *testing.T) {
fixtures.AssertBadParameter(t, CheckVersion(testCase.client, testCase.minClient))
})
}
}
// TestClickableURL tests clickable URL conversions
func TestClickableURL(t *testing.T) {
t.Parallel()
testCases := []struct {
info string
in string
out string
}{
{info: "original URL is OK", in: "http://127.0.0.1:3000/hello", out: "http://127.0.0.1:3000/hello"},
{info: "unspecified IPV6", in: "http://[::]:5050/howdy", out: "http://127.0.0.1:5050/howdy"},
{info: "unspecified IPV4", in: "http://0.0.0.0:5050/howdy", out: "http://127.0.0.1:5050/howdy"},
{info: "specified IPV4", in: "http://192.168.1.1:5050/howdy", out: "http://192.168.1.1:5050/howdy"},
{info: "specified IPV6", in: "http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:5050/howdy", out: "http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:5050/howdy"},
}
for _, testCase := range testCases {
t.Run(testCase.info, func(t *testing.T) {
out := ClickableURL(testCase.in)
require.Equal(t, testCase.out, out)
})
}
}
// TestParseAdvertiseAddr tests parsing of advertise address
func TestParseAdvertiseAddr(t *testing.T) {
t.Parallel()
type tc struct {
info string
in string
host string
port string
}
successTestCases := []tc{
{info: "ok address", in: "192.168.1.1", host: "192.168.1.1"},
{info: "trim space", in: " 192.168.1.1 ", host: "192.168.1.1"},
{info: "ok address and port", in: "192.168.1.1:22", host: "192.168.1.1", port: "22"},
{info: "ok host", in: "localhost", host: "localhost"},
{info: "ok host and port", in: "localhost:33", host: "localhost", port: "33"},
{info: "ipv6 address", in: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", host: "2001:0db8:85a3:0000:0000:8a2e:0370:7334"},
{info: "ipv6 address and port", in: "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:443", host: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", port: "443"},
}
for _, testCase := range successTestCases {
t.Run(testCase.info, func(t *testing.T) {
host, port, err := ParseAdvertiseAddr(testCase.in)
require.NoError(t, err)
require.Equal(t, testCase.host, host)
require.Equal(t, testCase.port, port)
})
}
failTestCases := []tc{
{info: "multicast address", in: "224.0.0.0"},
{info: "multicast address", in: " 224.0.0.0 "},
{info: "ok address and bad port", in: "192.168.1.1:b"},
{info: "missing host ", in: ":33"},
{info: "missing port", in: "localhost:"},
}
for _, testCase := range failTestCases {
t.Run(testCase.info, func(t *testing.T) {
_, _, err := ParseAdvertiseAddr(testCase.in)
fixtures.AssertBadParameter(t, err)
})
}
}
// TestGlobToRegexp tests replacement of glob-style wildcard values
// with regular expression compatible value
func TestGlobToRegexp(t *testing.T) {
t.Parallel()
testCases := []struct {
comment string
in string
out string
}{
{
comment: "simple values are not replaced",
in: "value-value",
out: "value-value",
},
{
comment: "wildcard and start of string is replaced with regexp wildcard expression",
in: "*",
out: "(.*)",
},
{
comment: "wildcard is replaced with regexp wildcard expression",
in: "a-*-b-*",
out: "a-(.*)-b-(.*)",
},
{
comment: "special chars are quoted",
in: "a-.*-b-*$",
out: `a-\.(.*)-b-(.*)\$`,
},
}
for _, testCase := range testCases {
t.Run(testCase.comment, func(t *testing.T) {
out := GlobToRegexp(testCase.in)
require.Equal(t, testCase.out, out)
})
}
}
func TestIsValidHostname(t *testing.T) {
t.Parallel()
tests := []struct {
name string
hostname string
assert require.BoolAssertionFunc
}{
{
name: "normal hostname",
hostname: "some-host-1.example.com",
assert: require.True,
},
{
name: "one component",
hostname: "example",
assert: require.True,
},
{
name: "empty",
hostname: "",
assert: require.False,
},
{
name: "invalid characters",
hostname: "some spaces.example.com",
assert: require.False,
},
{
name: "empty label",
hostname: "somewhere..example.com",
assert: require.False,
},
{
name: "label too long",
hostname: strings.Repeat("x", 64) + ".example.com",
assert: require.False,
},
{
name: "hostname too long",
hostname: strings.Repeat("x.", 256) + ".example.com",
assert: require.False,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
tc.assert(t, IsValidHostname(tc.hostname))
})
}
}
// TestReplaceRegexp tests regexp-style replacement of values
func TestReplaceRegexp(t *testing.T) {
t.Parallel()
testCases := []struct {
comment string
expr string
replace string
in string
out string
err error
}{
{
comment: "simple values are replaced directly",
expr: "value",
replace: "value",
in: "value",
out: "value",
},
{
comment: "no match returns explicit not found error",
expr: "value",
replace: "value",
in: "val",
err: trace.NotFound(""),
},
{
comment: "empty value is no match",
expr: "",
replace: "value",
in: "value",
err: trace.NotFound(""),
},
{
comment: "bad regexp results in bad parameter error",
expr: "^(($",
replace: "value",
in: "val",
err: trace.BadParameter(""),
},
{
comment: "full match is supported",
expr: "^value$",
replace: "value",
in: "value",
out: "value",
},
{
comment: "wildcard replaces to itself",
expr: "^(.*)$",
replace: "$1",
in: "value",
out: "value",
},
{
comment: "wildcard replaces to predefined value",
expr: "*",
replace: "boo",
in: "different",
out: "boo",
},
{
comment: "wildcard replaces empty string to predefined value",
expr: "*",
replace: "boo",
in: "",
out: "boo",
},
{
comment: "regexp wildcard replaces to itself",
expr: "^(.*)$",
replace: "$1",
in: "value",
out: "value",
},
{
comment: "partial conversions are supported",
expr: "^test-(.*)$",
replace: "replace-$1",
in: "test-hello",
out: "replace-hello",
},
{
comment: "partial conversions are supported",
expr: "^test-(.*)$",
replace: "replace-$1",
in: "test-hello",
out: "replace-hello",
},
}
for _, testCase := range testCases {
t.Run(testCase.comment, func(t *testing.T) {
out, err := ReplaceRegexp(testCase.expr, testCase.replace, testCase.in)
if testCase.err == nil {
require.NoError(t, err)
require.Equal(t, testCase.out, out)
} else {
require.IsType(t, testCase.err, err)
}
})
}
}
// TestContainsExpansion tests whether string contains expansion value
func TestContainsExpansion(t *testing.T) {
t.Parallel()
testCases := []struct {
comment string
val string
contains bool
}{
{
comment: "detect simple expansion",
val: "$1",
contains: true,
},
{
comment: "escaping is honored",
val: "$$",
contains: false,
},
{
comment: "escaping is honored",
val: "$$$$",
contains: false,
},
{
comment: "escaping is honored",
val: "$$$$$",
contains: false,
},
{
comment: "escaping and expansion",
val: "$$$$$1",
contains: true,
},
{
comment: "expansion with brackets",
val: "${100}",
contains: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.comment, func(t *testing.T) {
contains := ContainsExpansion(testCase.val)
require.Equal(t, testCase.contains, contains)
})
}
}
// TestMarshalYAML tests marshal/unmarshal of elements
func TestMarshalYAML(t *testing.T) {
t.Parallel()
type kv struct {
Key string
}
testCases := []struct {
comment string
val interface{}
expected interface{}
isDoc bool
}{
{
comment: "simple yaml value",
val: "hello",
},
{
comment: "list of yaml types",
val: []interface{}{"hello", "there"},
},
{
comment: "list of yaml documents",
val: []interface{}{kv{Key: "a"}, kv{Key: "b"}},
expected: []interface{}{map[string]interface{}{"Key": "a"}, map[string]interface{}{"Key": "b"}},
isDoc: true,
},
{
comment: "list of pointers to yaml docs",
val: []interface{}{kv{Key: "a"}, &kv{Key: "b"}},
expected: []interface{}{map[string]interface{}{"Key": "a"}, map[string]interface{}{"Key": "b"}},
isDoc: true,
},
{
comment: "list of maps",
val: []interface{}{map[string]interface{}{"Key": "a"}, map[string]interface{}{"Key": "b"}},
isDoc: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.comment, func(t *testing.T) {
buf := &bytes.Buffer{}
err := WriteYAML(buf, testCase.val)
require.NoError(t, err)
if testCase.isDoc {
require.Contains(t, buf.String(), yamlDocDelimiter)
}
out, err := ReadYAML(bytes.NewReader(buf.Bytes()))
require.NoError(t, err)
if testCase.expected != nil {
require.Equal(t, testCase.expected, out)
} else {
require.Equal(t, testCase.val, out)
}
})
}
}
// TestReadToken tests reading token from file and as is
func TestTryReadValueAsFile(t *testing.T) {
t.Parallel()
tok, err := TryReadValueAsFile("token")
require.Equal(t, "token", tok)
require.NoError(t, err)
_, err = TryReadValueAsFile("/tmp/non-existent-token-for-teleport-tests-not-found")
fixtures.AssertNotFound(t, err)
dir := t.TempDir()
tokenPath := filepath.Join(dir, "token")
err = os.WriteFile(tokenPath, []byte("shmoken"), 0644)
require.NoError(t, err)
tok, err = TryReadValueAsFile(tokenPath)
require.NoError(t, err)
require.Equal(t, "shmoken", tok)
}
// TestStringsSet makes sure that nil slice returns empty set (less error prone)
func TestStringsSet(t *testing.T) {
t.Parallel()
out := StringsSet(nil)
require.Len(t, out, 0)
require.NotNil(t, out)
}
// TestRepeatReader tests repeat reader
func TestRepeatReader(t *testing.T) {
t.Parallel()
type tc struct {
name string
repeat byte
count int
expected string
}
tcs := []tc{
{
name: "repeat once",
repeat: byte('a'),
count: 1,
expected: "a",
},
{
name: "repeat zero times",
repeat: byte('a'),
count: 0,
expected: "",
},
{
name: "repeat multiple times",
repeat: byte('a'),
count: 3,
expected: "aaa",
},
}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
data, err := io.ReadAll(NewRepeatReader(tc.repeat, tc.count))
require.NoError(t, err)
require.Equal(t, tc.expected, string(data))
})
}
}
func TestReadAtMost(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
limit int64
data string
err error
}{
{name: "limit reached at 4", limit: 4, data: "hell", err: ErrLimitReached},
{name: "limit reached at 5", limit: 5, data: "hello", err: ErrLimitReached},
{name: "limit not reached", limit: 6, data: "hello", err: nil},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
r := strings.NewReader("hello")
data, err := ReadAtMost(r, tc.limit)
require.Equal(t, []byte(tc.data), data)
require.ErrorIs(t, err, tc.err)
})
}
}
func TestByteCount(t *testing.T) {
tt := []struct {
name string
size int64
expected string
}{
{
name: "1 byte",
size: 1,
expected: "1 B",
},
{
name: "2 byte2",
size: 2,
expected: "2 B",
},
{
name: "1kb",
size: 1000,
expected: "1.0 kB",
},
{
name: "1mb",
size: 1000_000,
expected: "1.0 MB",
},
{
name: "1gb",
size: 1000_000_000,
expected: "1.0 GB",
},
{
name: "1tb",
size: 1000_000_000_000,
expected: "1.0 TB",
},
{
name: "1.6 kb",
size: 1600,
expected: "1.6 kB",
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, ByteCount(tc.size), tc.expected)
})
}
}