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
|
package config // import "github.com/docker/docker/daemon/config"
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/docker/docker/libnetwork/ipamutils"
"github.com/docker/docker/opts"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/imdario/mergo"
"github.com/spf13/pflag"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/unicode"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/skip"
)
func makeConfigFile(t *testing.T, content string) string {
t.Helper()
name := filepath.Join(t.TempDir(), "daemon.json")
err := os.WriteFile(name, []byte(content), 0666)
assert.NilError(t, err)
return name
}
func TestDaemonConfigurationNotFound(t *testing.T) {
_, err := MergeDaemonConfigurations(&Config{}, nil, "/tmp/foo-bar-baz-docker")
assert.Check(t, os.IsNotExist(err), "got: %[1]T: %[1]v", err)
}
func TestDaemonBrokenConfiguration(t *testing.T) {
configFile := makeConfigFile(t, `{"Debug": tru`)
_, err := MergeDaemonConfigurations(&Config{}, nil, configFile)
assert.ErrorContains(t, err, `invalid character ' ' in literal true`)
}
// TestDaemonConfigurationUnicodeVariations feeds various variations of Unicode into the JSON parser, ensuring that we
// respect a BOM and otherwise default to UTF-8.
func TestDaemonConfigurationUnicodeVariations(t *testing.T) {
jsonData := `{"debug": true}`
testCases := []struct {
name string
encoding encoding.Encoding
}{
{
name: "UTF-8",
encoding: unicode.UTF8,
},
{
name: "UTF-8 (with BOM)",
encoding: unicode.UTF8BOM,
},
{
name: "UTF-16 (BE with BOM)",
encoding: unicode.UTF16(unicode.BigEndian, unicode.UseBOM),
},
{
name: "UTF-16 (LE with BOM)",
encoding: unicode.UTF16(unicode.LittleEndian, unicode.UseBOM),
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
encodedJson, err := tc.encoding.NewEncoder().String(jsonData)
assert.NilError(t, err)
configFile := makeConfigFile(t, encodedJson)
_, err = MergeDaemonConfigurations(&Config{}, nil, configFile)
assert.NilError(t, err)
})
}
}
// TestDaemonConfigurationInvalidUnicode ensures that the JSON parser returns a useful error message if malformed UTF-8
// is provided.
func TestDaemonConfigurationInvalidUnicode(t *testing.T) {
configFileBOM := makeConfigFile(t, "\xef\xbb\xbf{\"debug\": true}\xff")
_, err := MergeDaemonConfigurations(&Config{}, nil, configFileBOM)
assert.ErrorIs(t, err, encoding.ErrInvalidUTF8)
configFileNoBOM := makeConfigFile(t, "{\"debug\": true}\xff")
_, err = MergeDaemonConfigurations(&Config{}, nil, configFileNoBOM)
assert.ErrorIs(t, err, encoding.ErrInvalidUTF8)
}
func TestFindConfigurationConflicts(t *testing.T) {
config := map[string]interface{}{"authorization-plugins": "foobar"}
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("authorization-plugins", "", "")
assert.Check(t, flags.Set("authorization-plugins", "asdf"))
assert.Check(t, is.ErrorContains(findConfigurationConflicts(config, flags), "authorization-plugins: (from flag: asdf, from file: foobar)"))
}
func TestFindConfigurationConflictsWithNamedOptions(t *testing.T) {
config := map[string]interface{}{"hosts": []string{"qwer"}}
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
var hosts []string
flags.VarP(opts.NewNamedListOptsRef("hosts", &hosts, opts.ValidateHost), "host", "H", "Daemon socket(s) to connect to")
assert.Check(t, flags.Set("host", "tcp://127.0.0.1:4444"))
assert.Check(t, flags.Set("host", "unix:///var/run/docker.sock"))
assert.Check(t, is.ErrorContains(findConfigurationConflicts(config, flags), "hosts"))
}
func TestDaemonConfigurationMergeConflicts(t *testing.T) {
configFile := makeConfigFile(t, `{"debug": true}`)
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.Bool("debug", false, "")
assert.Check(t, flags.Set("debug", "false"))
_, err := MergeDaemonConfigurations(&Config{}, flags, configFile)
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "debug") {
t.Fatalf("expected debug conflict, got %v", err)
}
}
func TestDaemonConfigurationMergeConcurrent(t *testing.T) {
configFile := makeConfigFile(t, `{"max-concurrent-downloads": 1}`)
_, err := MergeDaemonConfigurations(&Config{}, nil, configFile)
assert.NilError(t, err)
}
func TestDaemonConfigurationMergeConcurrentError(t *testing.T) {
configFile := makeConfigFile(t, `{"max-concurrent-downloads": -1}`)
_, err := MergeDaemonConfigurations(&Config{}, nil, configFile)
assert.ErrorContains(t, err, `invalid max concurrent downloads: -1`)
}
func TestDaemonConfigurationMergeConflictsWithInnerStructs(t *testing.T) {
configFile := makeConfigFile(t, `{"tlscacert": "/etc/certificates/ca.pem"}`)
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("tlscacert", "", "")
assert.Check(t, flags.Set("tlscacert", "~/.docker/ca.pem"))
_, err := MergeDaemonConfigurations(&Config{}, flags, configFile)
assert.ErrorContains(t, err, `the following directives are specified both as a flag and in the configuration file: tlscacert`)
}
// TestDaemonConfigurationMergeDefaultAddressPools is a regression test for #40711.
func TestDaemonConfigurationMergeDefaultAddressPools(t *testing.T) {
emptyConfigFile := makeConfigFile(t, `{}`)
configFile := makeConfigFile(t, `{"default-address-pools":[{"base": "10.123.0.0/16", "size": 24 }]}`)
expected := []*ipamutils.NetworkToSplit{{Base: "10.123.0.0/16", Size: 24}}
t.Run("empty config file", func(t *testing.T) {
var conf = Config{}
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.Var(&conf.NetworkConfig.DefaultAddressPools, "default-address-pool", "")
assert.Check(t, flags.Set("default-address-pool", "base=10.123.0.0/16,size=24"))
config, err := MergeDaemonConfigurations(&conf, flags, emptyConfigFile)
assert.NilError(t, err)
assert.DeepEqual(t, config.DefaultAddressPools.Value(), expected)
})
t.Run("config file", func(t *testing.T) {
var conf = Config{}
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.Var(&conf.NetworkConfig.DefaultAddressPools, "default-address-pool", "")
config, err := MergeDaemonConfigurations(&conf, flags, configFile)
assert.NilError(t, err)
assert.DeepEqual(t, config.DefaultAddressPools.Value(), expected)
})
t.Run("with conflicting options", func(t *testing.T) {
var conf = Config{}
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.Var(&conf.NetworkConfig.DefaultAddressPools, "default-address-pool", "")
assert.Check(t, flags.Set("default-address-pool", "base=10.123.0.0/16,size=24"))
_, err := MergeDaemonConfigurations(&conf, flags, configFile)
assert.ErrorContains(t, err, "the following directives are specified both as a flag and in the configuration file")
assert.ErrorContains(t, err, "default-address-pools")
})
}
func TestFindConfigurationConflictsWithUnknownKeys(t *testing.T) {
config := map[string]interface{}{"tls-verify": "true"}
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.Bool("tlsverify", false, "")
err := findConfigurationConflicts(config, flags)
assert.ErrorContains(t, err, "the following directives don't match any configuration option: tls-verify")
}
func TestFindConfigurationConflictsWithMergedValues(t *testing.T) {
var hosts []string
config := map[string]interface{}{"hosts": "tcp://127.0.0.1:2345"}
flags := pflag.NewFlagSet("base", pflag.ContinueOnError)
flags.VarP(opts.NewNamedListOptsRef("hosts", &hosts, nil), "host", "H", "")
err := findConfigurationConflicts(config, flags)
assert.NilError(t, err)
assert.Check(t, flags.Set("host", "unix:///var/run/docker.sock"))
err = findConfigurationConflicts(config, flags)
assert.ErrorContains(t, err, "hosts: (from flag: [unix:///var/run/docker.sock], from file: tcp://127.0.0.1:2345)")
}
func TestValidateConfigurationErrors(t *testing.T) {
testCases := []struct {
name string
field string
config *Config
expectedErr string
}{
{
name: "single label without value",
config: &Config{
CommonConfig: CommonConfig{
Labels: []string{"one"},
},
},
expectedErr: "bad attribute format: one",
},
{
name: "multiple label without value",
config: &Config{
CommonConfig: CommonConfig{
Labels: []string{"foo=bar", "one"},
},
},
expectedErr: "bad attribute format: one",
},
{
name: "single DNS, invalid IP-address",
config: &Config{
CommonConfig: CommonConfig{
DNSConfig: DNSConfig{
DNS: []string{"1.1.1.1o"},
},
},
},
expectedErr: "1.1.1.1o is not an ip address",
},
{
name: "multiple DNS, invalid IP-address",
config: &Config{
CommonConfig: CommonConfig{
DNSConfig: DNSConfig{
DNS: []string{"2.2.2.2", "1.1.1.1o"},
},
},
},
expectedErr: "1.1.1.1o is not an ip address",
},
{
name: "single DNSSearch",
config: &Config{
CommonConfig: CommonConfig{
DNSConfig: DNSConfig{
DNSSearch: []string{"123456"},
},
},
},
expectedErr: "123456 is not a valid domain",
},
{
name: "multiple DNSSearch",
config: &Config{
CommonConfig: CommonConfig{
DNSConfig: DNSConfig{
DNSSearch: []string{"a.b.c", "123456"},
},
},
},
expectedErr: "123456 is not a valid domain",
},
{
name: "negative MTU",
config: &Config{
CommonConfig: CommonConfig{
Mtu: -10,
},
},
expectedErr: "invalid default MTU: -10",
},
{
name: "negative max-concurrent-downloads",
config: &Config{
CommonConfig: CommonConfig{
MaxConcurrentDownloads: -10,
},
},
expectedErr: "invalid max concurrent downloads: -10",
},
{
name: "negative max-concurrent-uploads",
config: &Config{
CommonConfig: CommonConfig{
MaxConcurrentUploads: -10,
},
},
expectedErr: "invalid max concurrent uploads: -10",
},
{
name: "negative max-download-attempts",
config: &Config{
CommonConfig: CommonConfig{
MaxDownloadAttempts: -10,
},
},
expectedErr: "invalid max download attempts: -10",
},
// TODO(thaJeztah) temporarily excluding this test as it assumes defaults are set before validating and applying updated configs
/*
{
name: "zero max-download-attempts",
field: "MaxDownloadAttempts",
config: &Config{
CommonConfig: CommonConfig{
MaxDownloadAttempts: 0,
},
},
expectedErr: "invalid max download attempts: 0",
},
*/
{
name: "generic resource without =",
config: &Config{
CommonConfig: CommonConfig{
NodeGenericResources: []string{"foo"},
},
},
expectedErr: "could not parse GenericResource: incorrect term foo, missing '=' or malformed expression",
},
{
name: "generic resource mixed named and discrete",
config: &Config{
CommonConfig: CommonConfig{
NodeGenericResources: []string{"foo=bar", "foo=1"},
},
},
expectedErr: "could not parse GenericResource: mixed discrete and named resources in expression 'foo=[bar 1]'",
},
{
name: "with invalid hosts",
config: &Config{
CommonConfig: CommonConfig{
Hosts: []string{"127.0.0.1:2375/path"},
},
},
expectedErr: "invalid bind address (127.0.0.1:2375/path): should not contain a path element",
},
{
name: "with invalid log-level",
config: &Config{
CommonConfig: CommonConfig{
LogLevel: "foobar",
},
},
expectedErr: "invalid logging level: foobar",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
cfg, err := New()
assert.NilError(t, err)
if tc.field != "" {
assert.Check(t, mergo.Merge(cfg, tc.config, mergo.WithOverride, withForceOverwrite(tc.field)))
} else {
assert.Check(t, mergo.Merge(cfg, tc.config, mergo.WithOverride))
}
err = Validate(cfg)
assert.Error(t, err, tc.expectedErr)
})
}
}
func withForceOverwrite(fieldName string) func(config *mergo.Config) {
return mergo.WithTransformers(overwriteTransformer{fieldName: fieldName})
}
type overwriteTransformer struct {
fieldName string
}
func (tf overwriteTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
if typ == reflect.TypeOf(CommonConfig{}) {
return func(dst, src reflect.Value) error {
dst.FieldByName(tf.fieldName).Set(src.FieldByName(tf.fieldName))
return nil
}
}
return nil
}
func TestValidateConfiguration(t *testing.T) {
testCases := []struct {
name string
field string
config *Config
}{
{
name: "with label",
field: "Labels",
config: &Config{
CommonConfig: CommonConfig{
Labels: []string{"one=two"},
},
},
},
{
name: "with dns",
field: "DNSConfig",
config: &Config{
CommonConfig: CommonConfig{
DNSConfig: DNSConfig{
DNS: []string{"1.1.1.1"},
},
},
},
},
{
name: "with dns-search",
field: "DNSConfig",
config: &Config{
CommonConfig: CommonConfig{
DNSConfig: DNSConfig{
DNSSearch: []string{"a.b.c"},
},
},
},
},
{
name: "with mtu",
field: "Mtu",
config: &Config{
CommonConfig: CommonConfig{
Mtu: 1234,
},
},
},
{
name: "with max-concurrent-downloads",
field: "MaxConcurrentDownloads",
config: &Config{
CommonConfig: CommonConfig{
MaxConcurrentDownloads: 4,
},
},
},
{
name: "with max-concurrent-uploads",
field: "MaxConcurrentUploads",
config: &Config{
CommonConfig: CommonConfig{
MaxConcurrentUploads: 4,
},
},
},
{
name: "with max-download-attempts",
field: "MaxDownloadAttempts",
config: &Config{
CommonConfig: CommonConfig{
MaxDownloadAttempts: 4,
},
},
},
{
name: "with multiple node generic resources",
field: "NodeGenericResources",
config: &Config{
CommonConfig: CommonConfig{
NodeGenericResources: []string{"foo=bar", "foo=baz"},
},
},
},
{
name: "with node generic resources",
field: "NodeGenericResources",
config: &Config{
CommonConfig: CommonConfig{
NodeGenericResources: []string{"foo=1"},
},
},
},
{
name: "with hosts",
field: "Hosts",
config: &Config{
CommonConfig: CommonConfig{
Hosts: []string{"tcp://127.0.0.1:2375"},
},
},
},
{
name: "with log-level warn",
field: "LogLevel",
config: &Config{
CommonConfig: CommonConfig{
LogLevel: "warn",
},
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Start with a config with all defaults set, so that we only
cfg, err := New()
assert.NilError(t, err)
assert.Check(t, mergo.Merge(cfg, tc.config, mergo.WithOverride))
// Check that the override happened :)
assert.Check(t, is.DeepEqual(cfg, tc.config, field(tc.field)))
err = Validate(cfg)
assert.NilError(t, err)
})
}
}
func field(field string) cmp.Option {
tmp := reflect.TypeOf(Config{})
ignoreFields := make([]string, 0, tmp.NumField())
for i := 0; i < tmp.NumField(); i++ {
if tmp.Field(i).Name != field {
ignoreFields = append(ignoreFields, tmp.Field(i).Name)
}
}
return cmpopts.IgnoreFields(Config{}, ignoreFields...)
}
// TestReloadSetConfigFileNotExist tests that when `--config-file` is set, and it doesn't exist the `Reload` function
// returns an error.
func TestReloadSetConfigFileNotExist(t *testing.T) {
configFile := "/tmp/blabla/not/exists/config.json"
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("config-file", "", "")
assert.Check(t, flags.Set("config-file", configFile))
err := Reload(configFile, flags, func(c *Config) {})
assert.Check(t, is.ErrorContains(err, "unable to configure the Docker daemon with file"))
}
// TestReloadDefaultConfigNotExist tests that if the default configuration file doesn't exist the daemon still will
// still be reloaded.
func TestReloadDefaultConfigNotExist(t *testing.T) {
skip.If(t, os.Getuid() != 0, "skipping test that requires root")
defaultConfigFile := "/tmp/blabla/not/exists/daemon.json"
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("config-file", defaultConfigFile, "")
reloaded := false
err := Reload(defaultConfigFile, flags, func(c *Config) {
reloaded = true
})
assert.Check(t, err)
assert.Check(t, reloaded)
}
// TestReloadBadDefaultConfig tests that when `--config-file` is not set and the default configuration file exists and
// is bad, an error is returned.
func TestReloadBadDefaultConfig(t *testing.T) {
configFile := makeConfigFile(t, `{wrong: "configuration"}`)
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("config-file", configFile, "")
reloaded := false
err := Reload(configFile, flags, func(c *Config) {
reloaded = true
})
assert.Check(t, is.ErrorContains(err, "unable to configure the Docker daemon with file"))
assert.Check(t, reloaded == false)
}
func TestReloadWithConflictingLabels(t *testing.T) {
configFile := makeConfigFile(t, `{"labels": ["foo=bar", "foo=baz"]}`)
var lbls []string
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("config-file", configFile, "")
flags.StringSlice("labels", lbls, "")
reloaded := false
err := Reload(configFile, flags, func(c *Config) {
reloaded = true
})
assert.Check(t, is.ErrorContains(err, "conflict labels for foo=baz and foo=bar"))
assert.Check(t, reloaded == false)
}
func TestReloadWithDuplicateLabels(t *testing.T) {
configFile := makeConfigFile(t, `{"labels": ["foo=the-same", "foo=the-same"]}`)
var lbls []string
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("config-file", configFile, "")
flags.StringSlice("labels", lbls, "")
reloaded := false
err := Reload(configFile, flags, func(c *Config) {
reloaded = true
assert.Check(t, is.DeepEqual(c.Labels, []string{"foo=the-same"}))
})
assert.Check(t, err)
assert.Check(t, reloaded)
}
func TestMaskURLCredentials(t *testing.T) {
tests := []struct {
rawURL string
maskedURL string
}{
{
rawURL: "",
maskedURL: "",
}, {
rawURL: "invalidURL",
maskedURL: "invalidURL",
}, {
rawURL: "http://proxy.example.com:80/",
maskedURL: "http://proxy.example.com:80/",
}, {
rawURL: "http://USER:PASSWORD@proxy.example.com:80/",
maskedURL: "http://xxxxx:xxxxx@proxy.example.com:80/",
}, {
rawURL: "http://PASSWORD:PASSWORD@proxy.example.com:80/",
maskedURL: "http://xxxxx:xxxxx@proxy.example.com:80/",
}, {
rawURL: "http://USER:@proxy.example.com:80/",
maskedURL: "http://xxxxx:xxxxx@proxy.example.com:80/",
}, {
rawURL: "http://:PASSWORD@proxy.example.com:80/",
maskedURL: "http://xxxxx:xxxxx@proxy.example.com:80/",
}, {
rawURL: "http://USER@docker:password@proxy.example.com:80/",
maskedURL: "http://xxxxx:xxxxx@proxy.example.com:80/",
}, {
rawURL: "http://USER%40docker:password@proxy.example.com:80/",
maskedURL: "http://xxxxx:xxxxx@proxy.example.com:80/",
}, {
rawURL: "http://USER%40docker:pa%3Fsword@proxy.example.com:80/",
maskedURL: "http://xxxxx:xxxxx@proxy.example.com:80/",
}, {
rawURL: "http://USER%40docker:pa%3Fsword@proxy.example.com:80/hello%20world",
maskedURL: "http://xxxxx:xxxxx@proxy.example.com:80/hello%20world",
},
}
for _, test := range tests {
maskedURL := MaskCredentials(test.rawURL)
assert.Equal(t, maskedURL, test.maskedURL)
}
}
|