From 34e99466a6a0a201d36249bf4d64bd8c0abc178c Mon Sep 17 00:00:00 2001 From: jgsqware Date: Fri, 15 Apr 2016 08:29:33 +0200 Subject: [PATCH] config: not properly loaded error When a wrong config file was used, it result in a panic. Adding some check condition to validate the Unmarshaled configuration before using it fixes #134 --- config/config.go | 6 +++++- config/config_test.go | 41 +++++++++++++++++++++++++++++++++++++++++ utils/errors/errors.go | 3 +++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 config/config_test.go diff --git a/config/config.go b/config/config.go index 9a1bac71..d2921f00 100644 --- a/config/config.go +++ b/config/config.go @@ -19,6 +19,7 @@ import ( "os" "time" + cerrors "github.com/coreos/clair/utils/errors" "github.com/fernet/fernet-go" "gopkg.in/yaml.v2" ) @@ -111,7 +112,10 @@ func Load(path string) (config *Config, err error) { return } config = &cfgFile.Clair - + if config.API == nil || config.Database == nil || config.Notifier == nil || config.Updater == nil { + err = cerrors.ErrConfigNotLoaded + return + } // Generate a pagination key if none is provided. if config.API.PaginationKey == "" { var key fernet.Key diff --git a/config/config_test.go b/config/config_test.go new file mode 100644 index 00000000..958d7e99 --- /dev/null +++ b/config/config_test.go @@ -0,0 +1,41 @@ +package config + +import ( + "io/ioutil" + "log" + "os" + "testing" + + cerrors "github.com/coreos/clair/utils/errors" + "github.com/stretchr/testify/assert" +) + +const wrongConfig = ` +dummyKey: + wrong:true +` + +func TestLoadWrongConfiguration(t *testing.T) { + tmpfile, err := ioutil.TempFile("", "clair-config") + if err != nil { + log.Fatal(err) + } + + defer os.Remove(tmpfile.Name()) // clean up + + if _, err := tmpfile.Write([]byte(wrongConfig)); err != nil { + log.Fatal(err) + } + if err := tmpfile.Close(); err != nil { + log.Fatal(err) + } + + _, err = Load(tmpfile.Name()) + + assert.EqualError(t, err, cerrors.ErrConfigNotLoaded.Error()) +} + +func TestLoad(t *testing.T) { + _, err := Load("../config.example.yaml") + assert.NoError(t, err) +} diff --git a/utils/errors/errors.go b/utils/errors/errors.go index 65508f2b..ed4234da 100644 --- a/utils/errors/errors.go +++ b/utils/errors/errors.go @@ -29,6 +29,9 @@ var ( // ErrCouldNotParse is returned when a fetcher fails to parse the update data. ErrCouldNotParse = errors.New("updater/fetchers: could not parse") + + //ErrConfigNotLoaded is returned when the configuration file is not loaded properly + ErrConfigNotLoaded = errors.New("could not load configuration properly") ) // ErrBadRequest occurs when a method has been passed an inappropriate argument.