diff --git a/controllers/dns_test.go b/controllers/dns_test.go index e070cfed4..7d2892db0 100644 --- a/controllers/dns_test.go +++ b/controllers/dns_test.go @@ -400,6 +400,19 @@ func TestValidateDNSCreate(t *testing.T) { assert.NotNil(t, err) assert.Contains(t, err.Error(), "Field validation for 'Name' failed on the 'name_unique' tag") }) + t.Run("WhiteSpace", func(t *testing.T) { + entry := models.DNSEntry{Address: "10.10.10.5", Name: "white space", Network: "skynet"} + err := logic.ValidateDNSCreate(entry) + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "Field validation for 'Name' failed on the 'whitespace' tag") + }) + t.Run("AllSpaces", func(t *testing.T) { + entry := models.DNSEntry{Address: "10.10.10.5", Name: " ", Network: "skynet"} + err := logic.ValidateDNSCreate(entry) + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "Field validation for 'Name' failed on the 'whitespace' tag") + }) + } func createHost() { diff --git a/logic/dns.go b/logic/dns.go index 0991c8ce7..15c25deff 100644 --- a/logic/dns.go +++ b/logic/dns.go @@ -3,6 +3,7 @@ package logic import ( "encoding/json" "os" + "regexp" "sort" validator "github.com/go-playground/validator/v10" @@ -203,6 +204,11 @@ func ValidateDNSCreate(entry models.DNSEntry) error { v := validator.New() + _ = v.RegisterValidation("whitespace", func(f1 validator.FieldLevel) bool { + match, _ := regexp.MatchString(`\s`, entry.Name) + return !match + }) + _ = v.RegisterValidation("name_unique", func(fl validator.FieldLevel) bool { num, err := GetDNSEntryNum(entry.Name, entry.Network) return err == nil && num == 0 @@ -227,6 +233,11 @@ func ValidateDNSUpdate(change models.DNSEntry, entry models.DNSEntry) error { v := validator.New() + _ = v.RegisterValidation("whitespace", func(f1 validator.FieldLevel) bool { + match, _ := regexp.MatchString(`\s`, entry.Name) + return !match + }) + _ = v.RegisterValidation("name_unique", func(fl validator.FieldLevel) bool { //if name & net not changing name we are good if change.Name == entry.Name && change.Network == entry.Network { diff --git a/models/dnsEntry.go b/models/dnsEntry.go index 73373f1a1..11e9dd6b4 100644 --- a/models/dnsEntry.go +++ b/models/dnsEntry.go @@ -42,8 +42,8 @@ type DNSUpdate struct { // DNSEntry - a DNS entry represented as struct type DNSEntry struct { - Address string `json:"address" bson:"address" validate:"ip"` - Address6 string `json:"address6" bson:"address6"` - Name string `json:"name" bson:"name" validate:"required,name_unique,min=1,max=192"` - Network string `json:"network" bson:"network" validate:"network_exists"` + Address string `json:"address" validate:"ip"` + Address6 string `json:"address6"` + Name string `json:"name" validate:"required,name_unique,min=1,max=192,whitespace"` + Network string `json:"network" validate:"network_exists"` }