Skip to content
This repository has been archived by the owner on Nov 22, 2022. It is now read-only.

Commit

Permalink
Merge pull request #518 from maxice8/hostname-validator
Browse files Browse the repository at this point in the history
Hostname validator
  • Loading branch information
maxice8 authored Jan 6, 2021
2 parents 880db38 + d39c408 commit 1c17a7d
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 3 deletions.
8 changes: 5 additions & 3 deletions commands/auth/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"io/ioutil"
"regexp"
"strings"

"github.com/AlecAivazis/survey/v2"
Expand Down Expand Up @@ -251,12 +252,13 @@ func loginRun() error {
}

func hostnameValidator(v interface{}) error {
val := v.(string)
val := fmt.Sprint(v)
if len(strings.TrimSpace(val)) < 1 {
return errors.New("a value is required")
}
if strings.ContainsRune(val, '/') || strings.ContainsRune(val, ':') {
return errors.New("invalid hostname")
re := regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9-.]*$`)
if !re.MatchString(val) {
return fmt.Errorf("invalid hostname %q", val)
}
return nil
}
Expand Down
75 changes: 75 additions & 0 deletions commands/auth/login/login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,78 @@ func Test_NewCmdLogin(t *testing.T) {
})
}
}

func Test_hostnameValidator(t *testing.T) {
testMap := make(map[string]string)
testMap["profclems"] = "glab"

testCases := []struct {
name string
hostname interface{}
expected string
}{
{
name: "valid",
hostname: "localhost",
},
{
name: "valid-default-value",
hostname: "gitlab.com",
},
{
name: "valid-external-instance-alpine",
hostname: "gitlab.alpinelinux.org",
},
{
name: "valid-external-instance-freedesktop",
hostname: "gitlab.freedesktop.org",
},
{
name: "valid-external-instance-gnome",
hostname: "gitlab.gnome.org",
},
{
name: "valid-external-instance-debian",
hostname: "salsa.debian.org",
},
{
name: "empty",
hostname: "",
expected: "a value is required",
},
{
name: "invalid-hostname-slash",
hostname: "local/host",
expected: `invalid hostname "local/host"`,
},
{
name: "invalid-hostname-colon",
hostname: "local:host",
expected: `invalid hostname "local:host"`,
},
{
name: "valid-with-int-type",
hostname: 10,
},
{
name: "valid-with-slice-string-type",
hostname: []string{"local", "host"},
expected: `invalid hostname "[local host]"`,
},
{
name: "invalid-with-map-type",
hostname: testMap,
expected: `invalid hostname "map[profclems:glab]"`,
},
}
for _, tC := range testCases {
t.Run(tC.name, func(t *testing.T) {
err := hostnameValidator(tC.hostname)
if tC.expected == "" {
assert.NoError(t, err)
} else {
assert.EqualError(t, err, tC.expected)
}
})
}
}

0 comments on commit 1c17a7d

Please sign in to comment.