Skip to content

Commit

Permalink
Fix bug in Config.Update
Browse files Browse the repository at this point in the history
Incoming config updates with slices smaller than the current slice
didn't resize the current slice, resulting in undesirable values
in the tail of the slice.
  • Loading branch information
yashtewari committed May 16, 2022
1 parent 0d2061b commit f77bf0b
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 4 deletions.
13 changes: 13 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,23 @@ func New(cfg *common.Config) (Config, error) {
}

func (c *Config) Update(cfg *common.Config) error {
// Overwrite the parts of the config received in the update body.
if err := cfg.Unpack(&c); err != nil {
return err
}

// Shorter slices in the incoming config won't resize the corresponding slice
// in the current config, leaving undesirable values in the tail of the slice.
// This needs to be handled.
uc, err := New(cfg)
if err != nil {
return err
}

for i := range c.Streams {
c.Streams[i].DataYaml.ActivatedRules.CISK8S = uc.Streams[i].DataYaml.ActivatedRules.CISK8S
}

return nil
}

Expand Down
94 changes: 90 additions & 4 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ func (s *ConfigTestSuite) SetupTest() {

func (s *ConfigTestSuite) TestNew() {
var tests = []struct {
config string
expectedPatterns []string
config string
expected []string
}{
{
`
Expand All @@ -54,8 +54,9 @@ func (s *ConfigTestSuite) TestNew() {
- b
- c
- d
- e
`,
[]string{"a", "b", "c", "d"},
[]string{"a", "b", "c", "d", "e"},
},
}

Expand All @@ -66,7 +67,92 @@ func (s *ConfigTestSuite) TestNew() {
c, err := New(cfg)
s.NoError(err)

s.Equal(test.expectedPatterns, c.Streams[0].DataYaml.ActivatedRules.CISK8S)
s.Equal(test.expected, c.Streams[0].DataYaml.ActivatedRules.CISK8S)
}
}

func (s *ConfigTestSuite) TestUpdate() {
config := `
streams:
- data_yaml:
activated_rules:
cis_k8s:
- a
- b
- c
- d
- e`

var tests = []struct {
update string
expected []string
}{
{
`
streams:
- data_yaml:
activated_rules:
cis_k8s:
- a
- b
- c
- d
`,
[]string{"a", "b", "c", "d"},
},
{
`
streams:
- data_yaml:
activated_rules:
cis_k8s:
- b
- c
- d
- e
- f
`,
[]string{"b", "c", "d", "e", "f"},
},
{
`
streams:
- data_yaml:
activated_rules:
cis_k8s: []
`,
[]string{},
},
{
`
streams:
- data_yaml:
activated_rules:
cis_k8s:
- a
- b
- c
- d
- e
`,
[]string{"a", "b", "c", "d", "e"},
},
}

cfg, err := common.NewConfigFrom(config)
s.NoError(err)

c, err := New(cfg)
s.NoError(err)

for _, test := range tests {
cfg, err := common.NewConfigFrom(test.update)
s.NoError(err)

err = c.Update(cfg)
s.NoError(err)

s.Equal(test.expected, c.Streams[0].DataYaml.ActivatedRules.CISK8S)
}
}

Expand Down

0 comments on commit f77bf0b

Please sign in to comment.