Skip to content
This repository has been archived by the owner on Sep 26, 2021. It is now read-only.

Commit

Permalink
Valid hostname check
Browse files Browse the repository at this point in the history
Signed-off-by: Simon Thulbourn <simon+github@thulbourn.com>
  • Loading branch information
Simon Thulbourn committed Jan 24, 2015
1 parent e819eb2 commit 7f708e4
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
11 changes: 9 additions & 2 deletions host.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
Expand All @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
39 changes: 39 additions & 0 deletions host_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
}

0 comments on commit 7f708e4

Please sign in to comment.