diff --git a/cmd/server/main.go b/cmd/server/main.go index bb6fcae83..c580909cb 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "io/ioutil" "math/rand" "os" "os/signal" @@ -221,6 +220,12 @@ func startServer(c *cli.Context) error { return err } + // validate API key length + err = conf.ValidateKeys() + if err != nil { + return err + } + if memProfile != "" { if f, err := os.Create(memProfile); err != nil { return err @@ -263,7 +268,7 @@ func getConfigString(configFile string, inConfigBody string) (string, error) { return inConfigBody, nil } - outConfigBody, err := ioutil.ReadFile(configFile) + outConfigBody, err := os.ReadFile(configFile) if err != nil { return "", err } diff --git a/pkg/config/config.go b/pkg/config/config.go index da7349155..cea2c4488 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -33,6 +33,11 @@ const ( StatsUpdateInterval = time.Second * 10 ) +var ( + ErrKeyFileIncorrectPermission = errors.New("key file must have 0600 permission") + ErrKeysNotSet = errors.New("one of key-file or keys must be provided") +) + type Config struct { Port uint32 `yaml:"port"` BindAddresses []string `yaml:"bind_addresses"` @@ -398,6 +403,41 @@ func (conf *Config) ToCLIFlagNames(existingFlags []cli.Flag) map[string]reflect. return flagNames } +func (conf *Config) ValidateKeys() error { + // prefer keyfile if set + if conf.KeyFile != "" { + if st, err := os.Stat(conf.KeyFile); err != nil { + return err + } else if st.Mode().Perm() != 0600 { + return ErrKeyFileIncorrectPermission + } + f, err := os.Open(conf.KeyFile) + if err != nil { + return err + } + defer func() { + _ = f.Close() + }() + decoder := yaml.NewDecoder(f) + if err = decoder.Decode(conf.Keys); err != nil { + return err + } + } + + if len(conf.Keys) == 0 { + return ErrKeysNotSet + } + + if !conf.Development { + for key, secret := range conf.Keys { + if len(secret) < 32 { + logger.Errorw("secret is too short, should be at least 32 characters for security", nil, "apiKey", key) + } + } + } + return nil +} + func GenerateCLIFlags(existingFlags []cli.Flag, hidden bool) ([]cli.Flag, error) { blankConfig := &Config{} flags := []cli.Flag{}