Skip to content

Commit

Permalink
Added logic to check YAML before attempting YAML config load.
Browse files Browse the repository at this point in the history
  • Loading branch information
vr4manta committed Sep 3, 2024
1 parent 05745cd commit 44a5b89
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
9 changes: 8 additions & 1 deletion pkg/common/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,11 +255,18 @@ func (cfg *Config) FromEnv() error {
// ReadConfig parses vSphere cloud config file and stores it into VSphereConfig.
// Environment variables are also checked
func ReadConfig(byConfig []byte) (*Config, error) {
var cfg *Config

if len(byConfig) == 0 {
return nil, fmt.Errorf("Invalid YAML/INI file")
}

cfg, err := ReadConfigYAML(byConfig)
// Check to see if yaml file before calling parser to prevent unnecessary error messages.
isYAML, err := isConfigYaml(byConfig)
if isYAML {
cfg, err = ReadConfigYAML(byConfig)
}

if err != nil {
klog.Warningf("ReadConfigYAML failed: %s", err)

Expand Down
11 changes: 11 additions & 0 deletions pkg/common/config/config_yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,14 @@ func ReadConfigYAML(byConfig []byte) (*Config, error) {

return cfg.CreateConfig(), nil
}

func isConfigYaml(byConfig []byte) (bool, error) {
cfg := CommonConfigYAML{
Vcenter: make(map[string]*VirtualCenterConfigYAML),
}

if err := yaml.Unmarshal(byConfig, &cfg); err != nil {
return false, err
}
return true, nil
}
25 changes: 25 additions & 0 deletions pkg/common/config/config_yaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ vcenter:
secretNamespace: kube-system
`

const badConfigYAML = `
global:
server: 0.0.0.0
port: 443
user: password:
insecureFlag: true
datacenters:
- us-west
caFile: /some/path/to/a/ca.pem
`

func TestReadConfigYAMLGlobal(t *testing.T) {
_, err := ReadConfigYAML([]byte(""))
if err == nil {
Expand Down Expand Up @@ -137,3 +148,17 @@ func TestTenantRefsYAML(t *testing.T) {
t.Errorf("vcConfig3 SecretRef should be kube-system/eu-secret but actual=%s", vcConfig3.SecretRef)
}
}

func TestIsConfigYAML(t *testing.T) {
if ok, _ := isConfigYaml([]byte(basicConfigYAML)); !ok {
t.Error("YAML config should be valid")
}

if ok, _ := isConfigYaml([]byte(basicConfigINI)); ok {
t.Error("INI config should be invalid")
}

if ok, _ := isConfigYaml([]byte(badConfigYAML)); ok {
t.Error("Bad config YAML config should be invalid")
}
}

0 comments on commit 44a5b89

Please sign in to comment.