Merge pull request #399 from sthulb/allowed-names

Valid hostname check
This commit is contained in:
Evan Hazlett 2015-01-26 10:42:24 -05:00
commit 38eb438d6b
2 changed files with 48 additions and 2 deletions

11
host.go
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
host_test.go Normal file
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")
}
}
}