fix(osctl): avoid panic on empty 'talosconfig' (#725)

When talosconfig doesn't exist, `osctl` creates empty one behind the
scenes, but that leads to immediate panic if the command tries to build
osd client:

```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x11d6786]

goroutine 1 [running]:
github.com/talos-systems/talos/cmd/osctl/pkg/client.NewDefaultClientCredentials(0x7ffd720f5100, 0xb, 0xc000559ce8, 0x757014, 0xc0000d5500)
	/src/cmd/osctl/pkg/client/client.go:50 +0xa6
github.com/talos-systems/talos/cmd/osctl/cmd.setupClient(0x16ca3f0)
	/src/cmd/osctl/cmd/root.go:100 +0x3d
github.com/talos-systems/talos/cmd/osctl/cmd.glob..func22(0x24ad7c0, 0xc00058c240, 0x0, 0x3)
	/src/cmd/osctl/cmd/ps.go:32 +0x37
github.com/spf13/cobra.(*Command).execute(0x24ad7c0, 0xc0005f8a00, 0x3, 0x4, 0x24ad7c0, 0xc0005f8a00)
	/toolchain/gopath/pkg/mod/github.com/spf13/cobra@v0.0.3/command.go:766 +0x2ae
github.com/spf13/cobra.(*Command).ExecuteC(0x24ae140, 0x2507030, 0x162f2d7, 0xb)
	/toolchain/gopath/pkg/mod/github.com/spf13/cobra@v0.0.3/command.go:852 +0x2ec
github.com/spf13/cobra.(*Command).Execute(...)
	/toolchain/gopath/pkg/mod/github.com/spf13/cobra@v0.0.3/command.go:800
github.com/talos-systems/talos/cmd/osctl/cmd.Execute()
	/src/cmd/osctl/cmd/root.go:93 +0x24f
main.main()
	/src/cmd/osctl/main.go:10 +0x20
```

Fix that by returning explicit error:

```
error getting client credentials: 'context' key is not set in the config
```

Signed-off-by: Andrey Smirnov <smirnov.andrey@gmail.com>
This commit is contained in:
Andrey Smirnov
2019-06-07 17:40:28 +03:00
committed by GitHub
parent f200eb7a8a
commit f5969d2c6c

View File

@@ -47,20 +47,29 @@ func NewDefaultClientCredentials(p string) (creds *Credentials, err error) {
return return
} }
caBytes, err := base64.StdEncoding.DecodeString(c.Contexts[c.Context].CA) if c.Context == "" {
return nil, fmt.Errorf("'context' key is not set in the config")
}
context := c.Contexts[c.Context]
if context == nil {
return nil, fmt.Errorf("context %q is not defined in 'contexts' key in config", c.Context)
}
caBytes, err := base64.StdEncoding.DecodeString(context.CA)
if err != nil { if err != nil {
return return
} }
crtBytes, err := base64.StdEncoding.DecodeString(c.Contexts[c.Context].Crt) crtBytes, err := base64.StdEncoding.DecodeString(context.Crt)
if err != nil { if err != nil {
return return
} }
keyBytes, err := base64.StdEncoding.DecodeString(c.Contexts[c.Context].Key) keyBytes, err := base64.StdEncoding.DecodeString(context.Key)
if err != nil { if err != nil {
return return
} }
creds = &Credentials{ creds = &Credentials{
Target: c.Contexts[c.Context].Target, Target: context.Target,
ca: caBytes, ca: caBytes,
crt: crtBytes, crt: crtBytes,
key: keyBytes, key: keyBytes,