17803: Warn when config keys are ignored due to case mismatch.
[arvados.git] / lib / config / load_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package config
6
7 import (
8         "bytes"
9         "fmt"
10         "io"
11         "io/ioutil"
12         "os"
13         "os/exec"
14         "reflect"
15         "strings"
16         "testing"
17
18         "git.arvados.org/arvados.git/sdk/go/arvados"
19         "git.arvados.org/arvados.git/sdk/go/ctxlog"
20         "github.com/ghodss/yaml"
21         "github.com/sirupsen/logrus"
22         check "gopkg.in/check.v1"
23 )
24
25 // Gocheck boilerplate
26 func Test(t *testing.T) {
27         check.TestingT(t)
28 }
29
30 var _ = check.Suite(&LoadSuite{})
31
32 // Return a new Loader that reads cluster config from configdata
33 // (instead of the usual default /etc/arvados/config.yml), and logs to
34 // logdst or (if that's nil) c.Log.
35 func testLoader(c *check.C, configdata string, logdst io.Writer) *Loader {
36         logger := ctxlog.TestLogger(c)
37         if logdst != nil {
38                 lgr := logrus.New()
39                 lgr.Out = logdst
40                 logger = lgr
41         }
42         ldr := NewLoader(bytes.NewBufferString(configdata), logger)
43         ldr.Path = "-"
44         return ldr
45 }
46
47 type LoadSuite struct{}
48
49 func (s *LoadSuite) SetUpSuite(c *check.C) {
50         os.Unsetenv("ARVADOS_API_HOST")
51         os.Unsetenv("ARVADOS_API_HOST_INSECURE")
52         os.Unsetenv("ARVADOS_API_TOKEN")
53 }
54
55 func (s *LoadSuite) TestEmpty(c *check.C) {
56         cfg, err := testLoader(c, "", nil).Load()
57         c.Check(cfg, check.IsNil)
58         c.Assert(err, check.ErrorMatches, `config does not define any clusters`)
59 }
60
61 func (s *LoadSuite) TestNoConfigs(c *check.C) {
62         cfg, err := testLoader(c, `Clusters: {"z1111": {}}`, nil).Load()
63         c.Assert(err, check.IsNil)
64         c.Assert(cfg.Clusters, check.HasLen, 1)
65         cc, err := cfg.GetCluster("z1111")
66         c.Assert(err, check.IsNil)
67         c.Check(cc.ClusterID, check.Equals, "z1111")
68         c.Check(cc.API.MaxRequestAmplification, check.Equals, 4)
69         c.Check(cc.API.MaxItemsPerResponse, check.Equals, 1000)
70 }
71
72 func (s *LoadSuite) TestMungeLegacyConfigArgs(c *check.C) {
73         f, err := ioutil.TempFile("", "")
74         c.Check(err, check.IsNil)
75         defer os.Remove(f.Name())
76         io.WriteString(f, "Debug: true\n")
77         oldfile := f.Name()
78
79         f, err = ioutil.TempFile("", "")
80         c.Check(err, check.IsNil)
81         defer os.Remove(f.Name())
82         io.WriteString(f, "Clusters: {aaaaa: {}}\n")
83         newfile := f.Name()
84
85         for _, trial := range []struct {
86                 argsIn  []string
87                 argsOut []string
88         }{
89                 {
90                         []string{"-config", oldfile},
91                         []string{"-old-config", oldfile},
92                 },
93                 {
94                         []string{"-config=" + oldfile},
95                         []string{"-old-config=" + oldfile},
96                 },
97                 {
98                         []string{"-config", newfile},
99                         []string{"-config", newfile},
100                 },
101                 {
102                         []string{"-config=" + newfile},
103                         []string{"-config=" + newfile},
104                 },
105                 {
106                         []string{"-foo", oldfile},
107                         []string{"-foo", oldfile},
108                 },
109                 {
110                         []string{"-foo=" + oldfile},
111                         []string{"-foo=" + oldfile},
112                 },
113                 {
114                         []string{"-foo", "-config=" + oldfile},
115                         []string{"-foo", "-old-config=" + oldfile},
116                 },
117                 {
118                         []string{"-foo", "bar", "-config=" + oldfile},
119                         []string{"-foo", "bar", "-old-config=" + oldfile},
120                 },
121                 {
122                         []string{"-foo=bar", "baz", "-config=" + oldfile},
123                         []string{"-foo=bar", "baz", "-old-config=" + oldfile},
124                 },
125                 {
126                         []string{"-config=/dev/null"},
127                         []string{"-config=/dev/null"},
128                 },
129                 {
130                         []string{"-config=-"},
131                         []string{"-config=-"},
132                 },
133                 {
134                         []string{"-config="},
135                         []string{"-config="},
136                 },
137                 {
138                         []string{"-foo=bar", "baz", "-config"},
139                         []string{"-foo=bar", "baz", "-config"},
140                 },
141                 {
142                         []string{},
143                         nil,
144                 },
145         } {
146                 var logbuf bytes.Buffer
147                 logger := logrus.New()
148                 logger.Out = &logbuf
149
150                 var ldr Loader
151                 args := ldr.MungeLegacyConfigArgs(logger, trial.argsIn, "-old-config")
152                 c.Check(args, check.DeepEquals, trial.argsOut)
153                 if fmt.Sprintf("%v", trial.argsIn) != fmt.Sprintf("%v", trial.argsOut) {
154                         c.Check(logbuf.String(), check.Matches, `.*`+oldfile+` is not a cluster config file -- interpreting -config as -old-config.*\n`)
155                 }
156         }
157 }
158
159 func (s *LoadSuite) TestSampleKeys(c *check.C) {
160         for _, yaml := range []string{
161                 `{"Clusters":{"z1111":{}}}`,
162                 `{"Clusters":{"z1111":{"InstanceTypes":{"Foo":{"RAM": "12345M"}}}}}`,
163         } {
164                 cfg, err := testLoader(c, yaml, nil).Load()
165                 c.Assert(err, check.IsNil)
166                 cc, err := cfg.GetCluster("z1111")
167                 c.Assert(err, check.IsNil)
168                 _, hasSample := cc.InstanceTypes["SAMPLE"]
169                 c.Check(hasSample, check.Equals, false)
170                 if strings.Contains(yaml, "Foo") {
171                         c.Check(cc.InstanceTypes["Foo"].RAM, check.Equals, arvados.ByteSize(12345000000))
172                         c.Check(cc.InstanceTypes["Foo"].Price, check.Equals, 0.0)
173                 }
174         }
175 }
176
177 func (s *LoadSuite) TestMultipleClusters(c *check.C) {
178         ldr := testLoader(c, `{"Clusters":{"z1111":{},"z2222":{}}}`, nil)
179         ldr.SkipDeprecated = true
180         cfg, err := ldr.Load()
181         c.Assert(err, check.IsNil)
182         c1, err := cfg.GetCluster("z1111")
183         c.Assert(err, check.IsNil)
184         c.Check(c1.ClusterID, check.Equals, "z1111")
185         c2, err := cfg.GetCluster("z2222")
186         c.Assert(err, check.IsNil)
187         c.Check(c2.ClusterID, check.Equals, "z2222")
188 }
189
190 func (s *LoadSuite) TestDeprecatedOrUnknownWarning(c *check.C) {
191         var logbuf bytes.Buffer
192         _, err := testLoader(c, `
193 Clusters:
194   zzzzz:
195     ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
196     SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
197     Collections:
198      BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
199     PostgreSQL: {}
200     BadKey: {}
201     Containers:
202       RunTimeEngine: abc
203     RemoteClusters:
204       z2222:
205         Host: z2222.arvadosapi.com
206         Proxy: true
207         BadKey: badValue
208 `, &logbuf).Load()
209         c.Assert(err, check.IsNil)
210         c.Log(logbuf.String())
211         logs := strings.Split(strings.TrimSuffix(logbuf.String(), "\n"), "\n")
212         for _, log := range logs {
213                 c.Check(log, check.Matches, `.*deprecated or unknown config entry:.*(RunTimeEngine.*RuntimeEngine|BadKey).*`)
214         }
215         c.Check(logs, check.HasLen, 3)
216 }
217
218 func (s *LoadSuite) checkSAMPLEKeys(c *check.C, path string, x interface{}) {
219         v := reflect.Indirect(reflect.ValueOf(x))
220         switch v.Kind() {
221         case reflect.Map:
222                 var stringKeys, sampleKey bool
223                 iter := v.MapRange()
224                 for iter.Next() {
225                         k := iter.Key()
226                         if k.Kind() == reflect.String {
227                                 stringKeys = true
228                                 if k.String() == "SAMPLE" || k.String() == "xxxxx" {
229                                         sampleKey = true
230                                         s.checkSAMPLEKeys(c, path+"."+k.String(), iter.Value().Interface())
231                                 }
232                         }
233                 }
234                 if stringKeys && !sampleKey {
235                         c.Errorf("%s is a map with string keys (type %T) but config.default.yml has no SAMPLE key", path, x)
236                 }
237                 return
238         case reflect.Struct:
239                 for i := 0; i < v.NumField(); i++ {
240                         val := v.Field(i)
241                         if val.CanInterface() {
242                                 s.checkSAMPLEKeys(c, path+"."+v.Type().Field(i).Name, val.Interface())
243                         }
244                 }
245         }
246 }
247
248 func (s *LoadSuite) TestDefaultConfigHasAllSAMPLEKeys(c *check.C) {
249         var logbuf bytes.Buffer
250         loader := testLoader(c, string(DefaultYAML), &logbuf)
251         cfg, err := loader.Load()
252         c.Assert(err, check.IsNil)
253         s.checkSAMPLEKeys(c, "", cfg)
254 }
255
256 func (s *LoadSuite) TestNoUnrecognizedKeysInDefaultConfig(c *check.C) {
257         var logbuf bytes.Buffer
258         var supplied map[string]interface{}
259         yaml.Unmarshal(DefaultYAML, &supplied)
260
261         loader := testLoader(c, string(DefaultYAML), &logbuf)
262         cfg, err := loader.Load()
263         c.Assert(err, check.IsNil)
264         var loaded map[string]interface{}
265         buf, err := yaml.Marshal(cfg)
266         c.Assert(err, check.IsNil)
267         err = yaml.Unmarshal(buf, &loaded)
268         c.Assert(err, check.IsNil)
269
270         c.Check(logbuf.String(), check.Matches, `(?ms).*SystemRootToken: secret token is not set.*`)
271         c.Check(logbuf.String(), check.Matches, `(?ms).*ManagementToken: secret token is not set.*`)
272         c.Check(logbuf.String(), check.Matches, `(?ms).*Collections.BlobSigningKey: secret token is not set.*`)
273         logbuf.Reset()
274         loader.logExtraKeys(loaded, supplied, "")
275         c.Check(logbuf.String(), check.Equals, "")
276 }
277
278 func (s *LoadSuite) TestNoWarningsForDumpedConfig(c *check.C) {
279         var logbuf bytes.Buffer
280         logger := logrus.New()
281         logger.Out = &logbuf
282         cfg, err := testLoader(c, `
283 Clusters:
284  zzzzz:
285   ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
286   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
287   Collections:
288    BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`, &logbuf).Load()
289         c.Assert(err, check.IsNil)
290         yaml, err := yaml.Marshal(cfg)
291         c.Assert(err, check.IsNil)
292         cfgDumped, err := testLoader(c, string(yaml), &logbuf).Load()
293         c.Assert(err, check.IsNil)
294         c.Check(cfg, check.DeepEquals, cfgDumped)
295         c.Check(logbuf.String(), check.Equals, "")
296 }
297
298 func (s *LoadSuite) TestUnacceptableTokens(c *check.C) {
299         for _, trial := range []struct {
300                 short      bool
301                 configPath string
302                 example    string
303         }{
304                 {false, "SystemRootToken", "SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_b_c"},
305                 {false, "ManagementToken", "ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa b c"},
306                 {false, "ManagementToken", "ManagementToken: \"$aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabc\""},
307                 {false, "Collections.BlobSigningKey", "Collections: {BlobSigningKey: \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa⛵\"}"},
308                 {true, "SystemRootToken", "SystemRootToken: a_b_c"},
309                 {true, "ManagementToken", "ManagementToken: a b c"},
310                 {true, "ManagementToken", "ManagementToken: \"$abc\""},
311                 {true, "Collections.BlobSigningKey", "Collections: {BlobSigningKey: \"⛵\"}"},
312         } {
313                 c.Logf("trying bogus config: %s", trial.example)
314                 _, err := testLoader(c, "Clusters:\n zzzzz:\n  "+trial.example, nil).Load()
315                 if trial.short {
316                         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.`+trial.configPath+`: unacceptable characters in token.*`)
317                 } else {
318                         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.`+trial.configPath+`: unacceptable characters in token.*`)
319                 }
320         }
321 }
322
323 func (s *LoadSuite) TestPostgreSQLKeyConflict(c *check.C) {
324         _, err := testLoader(c, `
325 Clusters:
326  zzzzz:
327   PostgreSQL:
328    connection:
329      DBName: dbname
330      Host: host
331 `, nil).Load()
332         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.PostgreSQL.Connection: multiple entries for "(dbname|host)".*`)
333 }
334
335 func (s *LoadSuite) TestBadClusterIDs(c *check.C) {
336         for _, data := range []string{`
337 Clusters:
338  123456:
339   ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
340   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
341   Collections:
342    BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
343 `, `
344 Clusters:
345  12345:
346   ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
347   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
348   Collections:
349    BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
350   RemoteClusters:
351    Zzzzz:
352     Host: Zzzzz.arvadosapi.com
353     Proxy: true
354 `, `
355 Clusters:
356  abcde:
357   ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
358   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
359   Collections:
360    BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
361   Login:
362    LoginCluster: zz-zz
363 `,
364         } {
365                 c.Log(data)
366                 v, err := testLoader(c, data, nil).Load()
367                 if v != nil {
368                         c.Logf("%#v", v.Clusters)
369                 }
370                 c.Check(err, check.ErrorMatches, `.*cluster ID should be 5 alphanumeric characters.*`)
371         }
372 }
373
374 func (s *LoadSuite) TestBadType(c *check.C) {
375         for _, data := range []string{`
376 Clusters:
377  zzzzz:
378   PostgreSQL: true
379 `, `
380 Clusters:
381  zzzzz:
382   PostgreSQL:
383    ConnectionPool: true
384 `, `
385 Clusters:
386  zzzzz:
387   PostgreSQL:
388    ConnectionPool: "foo"
389 `, `
390 Clusters:
391  zzzzz:
392   PostgreSQL:
393    ConnectionPool: []
394 `, `
395 Clusters:
396  zzzzz:
397   PostgreSQL:
398    ConnectionPool: [] # {foo: bar} isn't caught here; we rely on config-check
399 `,
400         } {
401                 c.Log(data)
402                 v, err := testLoader(c, data, nil).Load()
403                 if v != nil {
404                         c.Logf("%#v", v.Clusters["zzzzz"].PostgreSQL.ConnectionPool)
405                 }
406                 c.Check(err, check.ErrorMatches, `.*cannot unmarshal .*PostgreSQL.*`)
407         }
408 }
409
410 func (s *LoadSuite) TestMovedKeys(c *check.C) {
411         checkEquivalent(c, `# config has old keys only
412 Clusters:
413  zzzzz:
414   RequestLimits:
415    MultiClusterRequestConcurrency: 3
416    MaxItemsPerResponse: 999
417 `, `
418 Clusters:
419  zzzzz:
420   API:
421    MaxRequestAmplification: 3
422    MaxItemsPerResponse: 999
423 `)
424         checkEquivalent(c, `# config has both old and new keys; old values win
425 Clusters:
426  zzzzz:
427   RequestLimits:
428    MultiClusterRequestConcurrency: 0
429    MaxItemsPerResponse: 555
430   API:
431    MaxRequestAmplification: 3
432    MaxItemsPerResponse: 999
433 `, `
434 Clusters:
435  zzzzz:
436   API:
437    MaxRequestAmplification: 0
438    MaxItemsPerResponse: 555
439 `)
440 }
441
442 func checkEquivalent(c *check.C, goty, expectedy string) string {
443         var logbuf bytes.Buffer
444         gotldr := testLoader(c, goty, &logbuf)
445         expectedldr := testLoader(c, expectedy, nil)
446         checkEquivalentLoaders(c, gotldr, expectedldr)
447         return logbuf.String()
448 }
449
450 func checkEqualYAML(c *check.C, got, expected interface{}) {
451         expectedyaml, err := yaml.Marshal(expected)
452         c.Assert(err, check.IsNil)
453         gotyaml, err := yaml.Marshal(got)
454         c.Assert(err, check.IsNil)
455         if !bytes.Equal(gotyaml, expectedyaml) {
456                 cmd := exec.Command("diff", "-u", "--label", "expected", "--label", "got", "/dev/fd/3", "/dev/fd/4")
457                 for _, y := range [][]byte{expectedyaml, gotyaml} {
458                         pr, pw, err := os.Pipe()
459                         c.Assert(err, check.IsNil)
460                         defer pr.Close()
461                         go func(data []byte) {
462                                 pw.Write(data)
463                                 pw.Close()
464                         }(y)
465                         cmd.ExtraFiles = append(cmd.ExtraFiles, pr)
466                 }
467                 diff, err := cmd.CombinedOutput()
468                 // diff should report differences and exit non-zero.
469                 c.Check(err, check.NotNil)
470                 c.Log(string(diff))
471                 c.Error("got != expected; see diff (-expected +got) above")
472         }
473 }
474
475 func checkEquivalentLoaders(c *check.C, gotldr, expectedldr *Loader) {
476         got, err := gotldr.Load()
477         c.Assert(err, check.IsNil)
478         expected, err := expectedldr.Load()
479         c.Assert(err, check.IsNil)
480         checkEqualYAML(c, got, expected)
481 }
482
483 func checkListKeys(path string, x interface{}) (err error) {
484         v := reflect.Indirect(reflect.ValueOf(x))
485         switch v.Kind() {
486         case reflect.Map:
487                 iter := v.MapRange()
488                 for iter.Next() {
489                         k := iter.Key()
490                         if k.Kind() == reflect.String {
491                                 if err = checkListKeys(path+"."+k.String(), iter.Value().Interface()); err != nil {
492                                         return
493                                 }
494                         }
495                 }
496                 return
497
498         case reflect.Struct:
499                 for i := 0; i < v.NumField(); i++ {
500                         val := v.Field(i)
501                         structField := v.Type().Field(i)
502                         fieldname := structField.Name
503                         endsWithList := strings.HasSuffix(fieldname, "List")
504                         isAnArray := structField.Type.Kind() == reflect.Slice
505                         if endsWithList != isAnArray {
506                                 if endsWithList {
507                                         err = fmt.Errorf("%s.%s ends with 'List' but field is not an array (type %v)", path, fieldname, val.Kind())
508                                         return
509                                 }
510                                 if isAnArray && structField.Type.Elem().Kind() != reflect.Uint8 {
511                                         err = fmt.Errorf("%s.%s is an array but field name does not end in 'List' (slice of %v)", path, fieldname, structField.Type.Elem().Kind())
512                                         return
513                                 }
514                         }
515                         if val.CanInterface() {
516                                 checkListKeys(path+"."+fieldname, val.Interface())
517                         }
518                 }
519         }
520         return
521 }
522
523 func (s *LoadSuite) TestListKeys(c *check.C) {
524         v1 := struct {
525                 EndInList []string
526         }{[]string{"a", "b"}}
527         var m1 = make(map[string]interface{})
528         m1["c"] = &v1
529         if err := checkListKeys("", m1); err != nil {
530                 c.Error(err)
531         }
532
533         v2 := struct {
534                 DoesNot []string
535         }{[]string{"a", "b"}}
536         var m2 = make(map[string]interface{})
537         m2["c"] = &v2
538         if err := checkListKeys("", m2); err == nil {
539                 c.Errorf("Should have produced an error")
540         }
541
542         v3 := struct {
543                 EndInList string
544         }{"a"}
545         var m3 = make(map[string]interface{})
546         m3["c"] = &v3
547         if err := checkListKeys("", m3); err == nil {
548                 c.Errorf("Should have produced an error")
549         }
550
551         var logbuf bytes.Buffer
552         loader := testLoader(c, string(DefaultYAML), &logbuf)
553         cfg, err := loader.Load()
554         c.Assert(err, check.IsNil)
555         if err := checkListKeys("", cfg); err != nil {
556                 c.Error(err)
557         }
558 }