Valid hostname check

Signed-off-by: Simon Thulbourn <simon+github@thulbourn.com>
This commit is contained in:
Simon Thulbourn
2015-01-23 22:28:49 +00:00
parent e819eb2fc7
commit 7f708e48c2
2 changed files with 48 additions and 2 deletions
+9 -2
View File
@@ -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
}
+39
View File
@@ -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")
}
}
}