Add checks for readable kube config

This commit is contained in:
Ian Howell
2019-05-06 13:58:58 -05:00
parent 5e9a4029ec
commit b019ba757f
4 changed files with 62 additions and 2 deletions

View File

@@ -21,7 +21,7 @@ test: TESTFLAGS += -race -v
test: unit-tests
.PHONY: unit-tests
unit-tests:
unit-tests: build
@echo "Performing unit test step..."
@go test -run $(TESTS) $(PKG) $(TESTFLAGS)
@echo "All unit tests passed"

View File

@@ -7,6 +7,8 @@ import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"github.com/ian-howell/airshipadm/pkg/util"
)
// Client is a device which communicates with the Kubernetes API
@@ -24,10 +26,14 @@ func NewForConfig(kubeconfigFilepath string) (*Client, error) {
kubeconfigFilepath = filepath.Join(home, ".kube", "config")
}
if err := util.IsReadable(kubeconfigFilepath); err != nil {
return nil, errors.New("could not open " + kubeconfigFilepath + ": " + err.Error())
}
// use the current context in kubeconfigFilepath
config, err := clientcmd.BuildConfigFromFlags("", kubeconfigFilepath)
if err != nil {
return nil, err
return nil, errors.New("could not build kubernetes config: " + err.Error())
}
// create the clientset

14
pkg/util/util.go Normal file
View File

@@ -0,0 +1,14 @@
package util
import (
"os"
)
// IsReadable returns nil if the file at path is readable. An error is returned otherwise.
func IsReadable(path string) error {
f, err := os.Open(path)
if err != nil {
return err.(*os.PathError).Err
}
return f.Close()
}

40
pkg/util/util_test.go Normal file
View File

@@ -0,0 +1,40 @@
package util_test
import (
"io/ioutil"
"os"
"testing"
"github.com/ian-howell/airshipadm/pkg/util"
)
func TestIsReadable(t *testing.T) {
file, err := ioutil.TempFile(os.TempDir(), "airshipadm")
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
defer os.Remove(file.Name())
if err := util.IsReadable(file.Name()); err != nil {
t.Errorf("Unexpected error: %s", err.Error())
}
expected := "permission denied"
err = file.Chmod(0000)
if err != nil {
t.Fatalf("Unexpected error: %s", err.Error())
}
if err := util.IsReadable(file.Name()); err == nil {
t.Errorf("Expected '%s' error", expected)
} else if err.Error() != "permission denied" {
t.Errorf("Expected '%s' error, got '%s'", expected, err.Error())
}
expected = "no such file or directory"
os.Remove(file.Name())
if err := util.IsReadable(file.Name()); err == nil {
t.Errorf("Expected '%s' error", expected)
} else if err.Error() != expected {
t.Errorf("Expected '%s' error, got '%s'", expected, err.Error())
}
}