feat(backend): fail on unknown keys in the config file

This commit is contained in:
Łukasz Mierzwa
2020-09-27 19:40:32 +01:00
committed by Łukasz Mierzwa
parent 940eacd0ea
commit c8d706bb91
4 changed files with 56 additions and 1 deletions

View File

@@ -11,4 +11,4 @@ alertmanager:
authentication:
basicAuth:
users:
- foo: bar
- username: bar

View File

@@ -0,0 +1,26 @@
# Raises an error if --config.file points to a file that contains unknown keys
karma.bin-should-fail --log.format=text --log.config=false --check-config
! stdout .
! stderr 'msg="Configuration is valid"'
stderr 'msg="Failed to parse configuration file \\"karma.yaml\\": yaml: unmarshal errors:\\n line 5: field authorizationFoo not found in type config.configSchema"'
-- karma.yaml --
authentication:
header:
name: "X-User"
value_re: "(.+)"
authorizationFoo:
groups:
- name: admins
members:
- alice
- bob
- name: users
members:
- john
acl:
silences: acl.yaml
alertmanager:
servers:
- name: default
uri: https://localhost:9093

View File

@@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
@@ -123,6 +124,21 @@ func SetupFlags(f *pflag.FlagSet) {
f.String("ui.collapseGroups", "collapsedOnMobile", "Default state for alert groups")
}
func validateConfigFile(path string) error {
f, err := ioutil.ReadFile(path)
if err != nil {
return err
}
cfg := configSchema{}
err = yaml.UnmarshalStrict(f, &cfg)
if err != nil {
return err
}
return nil
}
func readConfigFile(k *koanf.Koanf, flags *pflag.FlagSet) (string, error) {
var configFile string
@@ -243,6 +259,12 @@ func (config *configSchema) Read(flags *pflag.FlagSet) (string, error) {
return "", fmt.Errorf("Failed to unmarshal configuration: %v", err)
}
if configFileUsed != "" {
if err := validateConfigFile(configFileUsed); err != nil {
return "", fmt.Errorf("Failed to parse configuration file %q: %v", configFileUsed, err)
}
}
if config.Authentication.Header.Name != "" && len(config.Authentication.BasicAuth.Users) > 0 {
return "", fmt.Errorf("Both authentication.basicAuth.users and authentication.header.name is set, only one can be enabled")
}

View File

@@ -330,3 +330,10 @@ func TestDefaultConfig(t *testing.T) {
t.Errorf("Wrong silence form config returned (-want +got):\n%s", diff)
}
}
func TestValidateConfigMissingFile(t *testing.T) {
err := validateConfigFile(("/foo/bar/xxx/yyy.yaml"))
if err == nil {
t.Errorf("validateConfigFile didn't return any error")
}
}