From 7f708e48c2c69c7e18ebe88c8dbb6f7a0a1d3577 Mon Sep 17 00:00:00 2001 From: Simon Thulbourn Date: Fri, 23 Jan 2015 22:28:49 +0000 Subject: [PATCH] Valid hostname check Signed-off-by: Simon Thulbourn --- host.go | 11 +++++++++-- host_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 host_test.go diff --git a/host.go b/host.go index 61f4145c9c..2475cabca0 100644 --- a/host.go +++ b/host.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "errors" "fmt" "io/ioutil" "net" @@ -16,8 +17,9 @@ import ( ) var ( - validHostNameChars = `[a-zA-Z0-9_]` + validHostNameChars = `[a-zA-Z0-9\-\.]` validHostNamePattern = regexp.MustCompile(`^` + validHostNameChars + `+$`) + ErrInvalidHostname = errors.New("Invalid hostname specified") ) type Host struct { @@ -78,7 +80,7 @@ func LoadHost(name string, storePath string) (*Host, error) { func ValidateHostName(name string) (string, error) { if !validHostNamePattern.MatchString(name) { - return name, fmt.Errorf("Invalid host name %q, it must match %s", name, validHostNamePattern) + return name, ErrInvalidHostname } return name, nil } @@ -262,6 +264,11 @@ DOCKER_TLS=no`, opts, machineCaCertPath, machineServerCertPath, machineServerKey } func (h *Host) Create(name string) error { + name, err := ValidateHostName(name) + if err != nil { + return err + } + if err := h.Driver.Create(); err != nil { return err } diff --git a/host_test.go b/host_test.go new file mode 100644 index 0000000000..c08d24c2e0 --- /dev/null +++ b/host_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "testing" +) + +func TestValidateHostnameValid(t *testing.T) { + hosts := []string{ + "zomg", + "test-ing", + "some.h0st", + } + + for _, v := range hosts { + h, err := ValidateHostName(v) + if err != nil { + t.Fatal("Invalid hostname") + } + + if h != v { + t.Fatal("Hostname doesn't match") + } + } +} + +func TestValidateHostnameInvalid(t *testing.T) { + hosts := []string{ + "zom_g", + "test$ing", + "somešŸ˜„host", + } + + for _, v := range hosts { + _, err := ValidateHostName(v) + if err == nil { + t.Fatal("No error returned") + } + } +}