mirror of https://github.com/k3s-io/k3s
Add util to validate namespaced names
parent
4845e524af
commit
5ecce5d60c
|
@ -385,19 +385,7 @@ func ValidatePodSpec(spec *api.PodSpec) errs.ValidationErrorList {
|
|||
func validateLabels(labels map[string]string, field string) errs.ValidationErrorList {
|
||||
allErrs := errs.ValidationErrorList{}
|
||||
for k := range labels {
|
||||
var n, ns string
|
||||
parts := strings.Split(k, "/")
|
||||
switch len(parts) {
|
||||
case 1:
|
||||
n = parts[0]
|
||||
case 2:
|
||||
ns = parts[0]
|
||||
n = parts[1]
|
||||
default:
|
||||
allErrs = append(allErrs, errs.NewFieldInvalid(field, k, ""))
|
||||
continue
|
||||
}
|
||||
if (ns != "" && !util.IsDNSSubdomain(ns)) || !util.IsDNSLabel(n) {
|
||||
if !util.IsQualifiedName(k) {
|
||||
allErrs = append(allErrs, errs.NewFieldInvalid(field, k, ""))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -18,6 +18,7 @@ package util
|
|||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsDNSLabel tests for a string that conforms to the definition of a label in
|
||||
|
@ -82,3 +83,23 @@ func IsCIdentifier(value string) bool {
|
|||
func IsValidPortNum(port int) bool {
|
||||
return 0 < port && port < 65536
|
||||
}
|
||||
|
||||
// IsQualifiedName tests whether a string fits the "optionally-namespaced
|
||||
// name" pattern: [ DNS_SUBDOMAIN "/" ] DNS_LABEL
|
||||
func IsQualifiedName(value string) bool {
|
||||
var n, ns string
|
||||
parts := strings.Split(value, "/")
|
||||
switch len(parts) {
|
||||
case 1:
|
||||
n = parts[0]
|
||||
case 2:
|
||||
ns = parts[0]
|
||||
n = parts[1]
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if (ns != "" && !IsDNSSubdomain(ns)) || !IsDNSLabel(n) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
|
|
@ -153,3 +153,39 @@ func TestIsValidPortNum(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsQualifiedName(t *testing.T) {
|
||||
successCases := []string{
|
||||
"simple",
|
||||
"now-with-dashes",
|
||||
"1-starts-with-num",
|
||||
"1234",
|
||||
"simple/simple",
|
||||
"now-with-dashes/simple",
|
||||
"now-with-dashes/now-with-dashes",
|
||||
"now.with.dots/simple",
|
||||
"now-with.dashes-and.dots/simple",
|
||||
"1-num.2-num/3-num",
|
||||
"1234/5678",
|
||||
"1.2.3.4/5678",
|
||||
}
|
||||
for i := range successCases {
|
||||
if !IsQualifiedName(successCases[i]) {
|
||||
t.Errorf("case[%d] expected success", i)
|
||||
}
|
||||
}
|
||||
|
||||
errorCases := []string{
|
||||
"NoUppercase123",
|
||||
"nospecialchars%^=@",
|
||||
"cantendwithadash-",
|
||||
"-cantstartwithadash",
|
||||
"only/one/slash",
|
||||
strings.Repeat("a", 254),
|
||||
}
|
||||
for i := range errorCases {
|
||||
if IsQualifiedName(errorCases[i]) {
|
||||
t.Errorf("case[%d] expected failure", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue