forked from nats-io/nats-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse_test.go
742 lines (690 loc) · 16.8 KB
/
parse_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
package conf
import (
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)
// Test to make sure we get what we expect.
func test(t *testing.T, data string, ex map[string]interface{}) {
t.Helper()
m, err := Parse(data)
if err != nil {
t.Fatalf("Received err: %v\n", err)
}
if m == nil {
t.Fatal("Received nil map")
}
if !reflect.DeepEqual(m, ex) {
t.Fatalf("Not Equal:\nReceived: '%+v'\nExpected: '%+v'\n", m, ex)
}
}
func TestSimpleTopLevel(t *testing.T) {
ex := map[string]interface{}{
"foo": "1",
"bar": float64(2.2),
"baz": true,
"boo": int64(22),
}
test(t, "foo='1'; bar=2.2; baz=true; boo=22", ex)
}
func TestBools(t *testing.T) {
ex := map[string]interface{}{
"foo": true,
}
test(t, "foo=true", ex)
test(t, "foo=TRUE", ex)
test(t, "foo=true", ex)
test(t, "foo=yes", ex)
test(t, "foo=on", ex)
}
var varSample = `
index = 22
foo = $index
`
func TestSimpleVariable(t *testing.T) {
ex := map[string]interface{}{
"index": int64(22),
"foo": int64(22),
}
test(t, varSample, ex)
}
var varNestedSample = `
index = 22
nest {
index = 11
foo = $index
}
bar = $index
`
func TestNestedVariable(t *testing.T) {
ex := map[string]interface{}{
"index": int64(22),
"nest": map[string]interface{}{
"index": int64(11),
"foo": int64(11),
},
"bar": int64(22),
}
test(t, varNestedSample, ex)
}
func TestMissingVariable(t *testing.T) {
_, err := Parse("foo=$index")
if err == nil {
t.Fatalf("Expected an error for a missing variable, got none")
}
if !strings.HasPrefix(err.Error(), "variable reference") {
t.Fatalf("Wanted a variable reference err, got %q\n", err)
}
}
func TestEnvVariable(t *testing.T) {
ex := map[string]interface{}{
"foo": int64(22),
}
evar := "__UNIQ22__"
os.Setenv(evar, "22")
defer os.Unsetenv(evar)
test(t, fmt.Sprintf("foo = $%s", evar), ex)
}
func TestEnvVariableString(t *testing.T) {
ex := map[string]interface{}{
"foo": "xyz",
}
evar := "__UNIQ22__"
os.Setenv(evar, "xyz")
defer os.Unsetenv(evar)
test(t, fmt.Sprintf("foo = $%s", evar), ex)
}
func TestEnvVariableStringStartingWithNumber(t *testing.T) {
evar := "__UNIQ22__"
os.Setenv(evar, "3xyz")
defer os.Unsetenv(evar)
_, err := Parse("foo = $%s")
if err == nil {
t.Fatalf("Expected err not being able to process string: %v\n", err)
}
}
func TestEnvVariableStringStartingWithNumberAndSizeUnit(t *testing.T) {
ex := map[string]interface{}{
"foo": "3Gyz",
}
evar := "__UNIQ22__"
os.Setenv(evar, "3Gyz")
defer os.Unsetenv(evar)
test(t, fmt.Sprintf("foo = $%s", evar), ex)
}
func TestEnvVariableStringStartingWithNumberUsingQuotes(t *testing.T) {
ex := map[string]interface{}{
"foo": "3xyz",
}
evar := "__UNIQ22__"
os.Setenv(evar, "'3xyz'")
defer os.Unsetenv(evar)
test(t, fmt.Sprintf("foo = $%s", evar), ex)
}
func TestBcryptVariable(t *testing.T) {
ex := map[string]interface{}{
"password": "$2a$11$ooo",
}
test(t, "password: $2a$11$ooo", ex)
}
var easynum = `
k = 8k
kb = 4kb
ki = 3ki
kib = 4ki
m = 1m
mb = 2MB
mi = 2Mi
mib = 64MiB
g = 2g
gb = 22GB
gi = 22Gi
gib = 22GiB
tb = 22TB
ti = 22Ti
tib = 22TiB
pb = 22PB
pi = 22Pi
pib = 22PiB
`
func TestConvenientNumbers(t *testing.T) {
ex := map[string]interface{}{
"k": int64(8 * 1000),
"kb": int64(4 * 1024),
"ki": int64(3 * 1024),
"kib": int64(4 * 1024),
"m": int64(1000 * 1000),
"mb": int64(2 * 1024 * 1024),
"mi": int64(2 * 1024 * 1024),
"mib": int64(64 * 1024 * 1024),
"g": int64(2 * 1000 * 1000 * 1000),
"gb": int64(22 * 1024 * 1024 * 1024),
"gi": int64(22 * 1024 * 1024 * 1024),
"gib": int64(22 * 1024 * 1024 * 1024),
"tb": int64(22 * 1024 * 1024 * 1024 * 1024),
"ti": int64(22 * 1024 * 1024 * 1024 * 1024),
"tib": int64(22 * 1024 * 1024 * 1024 * 1024),
"pb": int64(22 * 1024 * 1024 * 1024 * 1024 * 1024),
"pi": int64(22 * 1024 * 1024 * 1024 * 1024 * 1024),
"pib": int64(22 * 1024 * 1024 * 1024 * 1024 * 1024),
}
test(t, easynum, ex)
}
var sample1 = `
foo {
host {
ip = '127.0.0.1'
port = 4242
}
servers = [ "a.com", "b.com", "c.com"]
}
`
func TestSample1(t *testing.T) {
ex := map[string]interface{}{
"foo": map[string]interface{}{
"host": map[string]interface{}{
"ip": "127.0.0.1",
"port": int64(4242),
},
"servers": []interface{}{"a.com", "b.com", "c.com"},
},
}
test(t, sample1, ex)
}
var cluster = `
cluster {
port: 4244
authorization {
user: route_user
password: top_secret
timeout: 1
}
# Routes are actively solicited and connected to from this server.
# Other servers can connect to us if they supply the correct credentials
# in their routes definitions from above.
// Test both styles of comments
routes = [
nats-route://foo:[email protected]:4245
nats-route://foo:[email protected]:4246
]
}
`
func TestSample2(t *testing.T) {
ex := map[string]interface{}{
"cluster": map[string]interface{}{
"port": int64(4244),
"authorization": map[string]interface{}{
"user": "route_user",
"password": "top_secret",
"timeout": int64(1),
},
"routes": []interface{}{
"nats-route://foo:[email protected]:4245",
"nats-route://foo:[email protected]:4246",
},
},
}
test(t, cluster, ex)
}
var sample3 = `
foo {
expr = '(true == "false")'
text = 'This is a multi-line
text block.'
}
`
func TestSample3(t *testing.T) {
ex := map[string]interface{}{
"foo": map[string]interface{}{
"expr": "(true == \"false\")",
"text": "This is a multi-line\ntext block.",
},
}
test(t, sample3, ex)
}
var sample4 = `
array [
{ abc: 123 }
{ xyz: "word" }
]
`
func TestSample4(t *testing.T) {
ex := map[string]interface{}{
"array": []interface{}{
map[string]interface{}{"abc": int64(123)},
map[string]interface{}{"xyz": "word"},
},
}
test(t, sample4, ex)
}
var sample5 = `
now = 2016-05-04T18:53:41Z
gmt = false
`
func TestSample5(t *testing.T) {
dt, _ := time.Parse("2006-01-02T15:04:05Z", "2016-05-04T18:53:41Z")
ex := map[string]interface{}{
"now": dt,
"gmt": false,
}
test(t, sample5, ex)
}
func TestIncludes(t *testing.T) {
ex := map[string]interface{}{
"listen": "127.0.0.1:4222",
"authorization": map[string]interface{}{
"ALICE_PASS": "$2a$10$UHR6GhotWhpLsKtVP0/i6.Nh9.fuY73cWjLoJjb2sKT8KISBcUW5q",
"BOB_PASS": "$2a$11$dZM98SpGeI7dCFFGSpt.JObQcix8YHml4TBUZoge9R1uxnMIln5ly",
"users": []interface{}{
map[string]interface{}{
"user": "alice",
"password": "$2a$10$UHR6GhotWhpLsKtVP0/i6.Nh9.fuY73cWjLoJjb2sKT8KISBcUW5q"},
map[string]interface{}{
"user": "bob",
"password": "$2a$11$dZM98SpGeI7dCFFGSpt.JObQcix8YHml4TBUZoge9R1uxnMIln5ly"},
},
"timeout": float64(0.5),
},
}
m, err := ParseFile("simple.conf")
if err != nil {
t.Fatalf("Received err: %v\n", err)
}
if m == nil {
t.Fatal("Received nil map")
}
if !reflect.DeepEqual(m, ex) {
t.Fatalf("Not Equal:\nReceived: '%+v'\nExpected: '%+v'\n", m, ex)
}
}
var varIncludedVariablesSample = `
authorization {
include "./includes/passwords.conf"
CAROL_PASS: foo
users = [
{user: alice, password: $ALICE_PASS}
{user: bob, password: $BOB_PASS}
{user: carol, password: $CAROL_PASS}
]
}
`
func TestIncludeVariablesWithChecks(t *testing.T) {
p, err := parse(varIncludedVariablesSample, "", true)
if err != nil {
t.Fatalf("Received err: %v\n", err)
}
key := "authorization"
m, ok := p.mapping[key]
if !ok {
t.Errorf("Expected %q to be in the config", key)
}
expectKeyVal := func(t *testing.T, m interface{}, expectedKey string, expectedVal string, expectedLine, expectedPos int) {
t.Helper()
tk := m.(*token)
v := tk.Value()
vv := v.(map[string]interface{})
value, ok := vv[expectedKey]
if !ok {
t.Errorf("Expected key %q", expectedKey)
}
tk, ok = value.(*token)
if !ok {
t.Fatalf("Expected token %v", value)
}
if tk.Line() != expectedLine {
t.Errorf("Expected token to be at line %d, got: %d", expectedLine, tk.Line())
}
if tk.Position() != expectedPos {
t.Errorf("Expected token to be at position %d, got: %d", expectedPos, tk.Position())
}
v = tk.Value()
if v != expectedVal {
t.Errorf("Expected %q, got: %s", expectedVal, v)
}
}
expectKeyVal(t, m, "ALICE_PASS", "$2a$10$UHR6GhotWhpLsKtVP0/i6.Nh9.fuY73cWjLoJjb2sKT8KISBcUW5q", 2, 1)
expectKeyVal(t, m, "BOB_PASS", "$2a$11$dZM98SpGeI7dCFFGSpt.JObQcix8YHml4TBUZoge9R1uxnMIln5ly", 3, 1)
expectKeyVal(t, m, "CAROL_PASS", "foo", 6, 3)
}
func TestParserNoInfiniteLoop(t *testing.T) {
for _, test := range []string{`A@@Føøøø?˛ø:{øøøø˙˙`, `include "9/�`} {
if _, err := Parse(test); err == nil {
t.Fatal("expected an error")
} else if !strings.Contains(err.Error(), "Unexpected EOF") {
t.Fatal("expected unexpected eof error")
}
}
}
func TestParseWithNoValuesAreInvalid(t *testing.T) {
for _, test := range []struct {
name string
conf string
err string
}{
{
"invalid key without values",
`aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`,
"config is invalid (:1:41)",
},
{
"invalid untrimmed key without values",
` aaaaaaaaaaaaaaaaaaaaaaaaaaa`,
"config is invalid (:1:41)",
},
{
"invalid untrimmed key without values",
` aaaaaaaaaaaaaaaaaaaaaaaaaaa `,
"config is invalid (:1:41)",
},
{
"invalid keys after comments",
`
# with comments and no spaces to create key values
# is also an invalid config.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
`,
"config is invalid (:5:25)",
},
{
"comma separated without values are invalid",
`
a,a,a,a,a,a,a,a,a,a,a
`,
"config is invalid (:3:25)",
},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := parse(test.conf, "", true); err == nil {
t.Error("expected an error")
} else if !strings.Contains(err.Error(), test.err) {
t.Errorf("expected invalid conf error, got: %v", err)
}
})
}
}
func TestParseWithNoValuesEmptyConfigsAreValid(t *testing.T) {
for _, test := range []struct {
name string
conf string
}{
{
"empty conf",
"",
},
{
"empty conf with line breaks",
`
`,
},
{
"just comments with no values",
`
# just comments with no values
# is still valid.
`,
},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := parse(test.conf, "", true); err != nil {
t.Errorf("unexpected error: %v", err)
}
})
}
}
func TestParseWithTrailingBracketsAreValid(t *testing.T) {
for _, test := range []struct {
name string
conf string
}{
{
"empty conf",
"{}",
},
{
"just comments with no values",
`
{
# comments in the body
}
`,
},
{
// trailing brackets accidentally can become keys,
// this is valid since needed to support JSON like configs..
"trailing brackets after config",
`
accounts { users = [{}]}
}
`,
},
{
"wrapped in brackets",
`{
accounts { users = [{}]}
}
`,
},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := parse(test.conf, "", true); err != nil {
t.Errorf("unexpected error: %v", err)
}
})
}
}
func TestParseWithNoValuesIncludes(t *testing.T) {
for _, test := range []struct {
input string
includes map[string]string
err string
linepos string
}{
{
`# includes
accounts {
foo { include 'foo.conf'}
bar { users = [{user = "bar"}] }
quux { include 'quux.conf'}
}
`,
map[string]string{
"foo.conf": ``,
"quux.conf": `?????????????`,
},
"error parsing include file 'quux.conf', config is invalid",
"quux.conf:1:1",
},
{
`# includes
accounts {
foo { include 'foo.conf'}
bar { include 'bar.conf'}
quux { include 'quux.conf'}
}
`,
map[string]string{
"foo.conf": ``, // Empty configs are ok
"bar.conf": `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`,
"quux.conf": `
# just some comments,
# and no key values also ok.
`,
},
"error parsing include file 'bar.conf', config is invalid",
"bar.conf:1:34",
},
} {
t.Run("", func(t *testing.T) {
sdir := t.TempDir()
f, err := os.CreateTemp(sdir, "nats.conf-")
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(f.Name(), []byte(test.input), 066); err != nil {
t.Error(err)
}
if test.includes != nil {
for includeFile, contents := range test.includes {
inf, err := os.Create(filepath.Join(sdir, includeFile))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(inf.Name(), []byte(contents), 066); err != nil {
t.Error(err)
}
}
}
if _, err := parse(test.input, f.Name(), true); err == nil {
t.Error("expected an error")
} else if !strings.Contains(err.Error(), test.err) || !strings.Contains(err.Error(), test.linepos) {
t.Errorf("expected invalid conf error, got: %v", err)
}
})
}
}
func TestJSONParseCompat(t *testing.T) {
for _, test := range []struct {
name string
input string
includes map[string]string
expected map[string]interface{}
}{
{
"JSON with nested blocks",
`
{
"http_port": 8227,
"port": 4227,
"write_deadline": "1h",
"cluster": {
"port": 6222,
"routes": [
"nats://127.0.0.1:4222",
"nats://127.0.0.1:4223",
"nats://127.0.0.1:4224"
]
}
}
`,
nil,
map[string]interface{}{
"http_port": int64(8227),
"port": int64(4227),
"write_deadline": "1h",
"cluster": map[string]interface{}{
"port": int64(6222),
"routes": []interface{}{
"nats://127.0.0.1:4222",
"nats://127.0.0.1:4223",
"nats://127.0.0.1:4224",
},
},
},
},
{
"JSON with nested blocks",
`{
"jetstream": {
"store_dir": "/tmp/nats"
"max_mem": 1000000,
},
"port": 4222,
"server_name": "nats1"
}
`,
nil,
map[string]interface{}{
"jetstream": map[string]interface{}{
"store_dir": "/tmp/nats",
"max_mem": int64(1_000_000),
},
"port": int64(4222),
"server_name": "nats1",
},
},
{
"JSON empty object in one line",
`{}`,
nil,
map[string]interface{}{},
},
{
"JSON empty object with line breaks",
`
{
}
`,
nil,
map[string]interface{}{},
},
{
"JSON includes",
`
accounts {
foo { include 'foo.json' }
bar { include 'bar.json' }
quux { include 'quux.json' }
}
`,
map[string]string{
"foo.json": `{ "users": [ {"user": "foo"} ] }`,
"bar.json": `{
"users": [ {"user": "bar"} ]
}`,
"quux.json": `{}`,
},
map[string]interface{}{
"accounts": map[string]interface{}{
"foo": map[string]interface{}{
"users": []interface{}{
map[string]interface{}{
"user": "foo",
},
},
},
"bar": map[string]interface{}{
"users": []interface{}{
map[string]interface{}{
"user": "bar",
},
},
},
"quux": map[string]interface{}{},
},
},
},
} {
t.Run(test.name, func(t *testing.T) {
sdir := t.TempDir()
f, err := os.CreateTemp(sdir, "nats.conf-")
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(f.Name(), []byte(test.input), 066); err != nil {
t.Error(err)
}
if test.includes != nil {
for includeFile, contents := range test.includes {
inf, err := os.Create(filepath.Join(sdir, includeFile))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(inf.Name(), []byte(contents), 066); err != nil {
t.Error(err)
}
}
}
m, err := ParseFile(f.Name())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if !reflect.DeepEqual(m, test.expected) {
t.Fatalf("Not Equal:\nReceived: '%+v'\nExpected: '%+v'\n", m, test.expected)
}
})
}
}