pkg/types: safer typecasting for TextUnmarshaler when loading args
authorAithal <aithal@amazon.com>
Mon, 22 May 2017 20:09:19 +0000 (13:09 -0700)
committerAithal <aithal@amazon.com>
Mon, 22 May 2017 20:13:57 +0000 (13:13 -0700)
types.LoadArgs does an unsafe typecast for env args key value pairs.
This can cause a panic if the config type fields do not implement
the encoding.TextUnmarshaler interface. This commit modifies it to
do a safe type cast and return an error in such scenarios.

pkg/types/args.go
pkg/types/args_test.go

index 66dcf9e..e87c6b6 100644 (file)
@@ -85,8 +85,11 @@ func LoadArgs(args string, container interface{}) error {
                        unknownArgs = append(unknownArgs, pair)
                        continue
                }
-
-               u := keyField.Addr().Interface().(encoding.TextUnmarshaler)
+               keyFieldIface := keyField.Addr().Interface()
+               u, ok := keyFieldIface.(encoding.TextUnmarshaler)
+               if !ok {
+                       return fmt.Errorf("ARGS: '%s' cannot be unmarshalled from textual form for pair %q", keyField, pair)
+               }
                err := u.UnmarshalText([]byte(valueString))
                if err != nil {
                        return fmt.Errorf("ARGS: error parsing value of pair %q: %v)", pair, err)
index 3a53d9a..23772ca 100644 (file)
@@ -118,4 +118,15 @@ var _ = Describe("LoadArgs", func() {
                        Expect(err).NotTo(HaveOccurred())
                })
        })
+
+       Context("When known arguments are passed and cannot be unmarshalled", func() {
+               It("LoadArgs should fail", func() {
+                       conf := struct {
+                               IP IPNet
+                       }{}
+                       err := LoadArgs("IP=10.0.0.0/24", &conf)
+                       Expect(err).To(HaveOccurred())
+
+               })
+       })
 })