add relaxed env var name function

This commit is contained in:
HirazawaUi 2024-02-19 22:08:50 +08:00
parent bed8fed49f
commit 96a16a7bc9
2 changed files with 49 additions and 0 deletions

View File

@ -21,6 +21,7 @@ import (
"math"
"regexp"
"strings"
"unicode"
"k8s.io/apimachinery/pkg/util/validation/field"
netutils "k8s.io/utils/net"
@ -418,6 +419,9 @@ func IsHTTPHeaderName(value string) []string {
const envVarNameFmt = "[-._a-zA-Z][-._a-zA-Z0-9]*"
const envVarNameFmtErrMsg string = "a valid environment variable name must consist of alphabetic characters, digits, '_', '-', or '.', and must not start with a digit"
// TODO(hirazawaui): Rename this when the RelaxedEnvironmentVariableValidation gate is removed.
const relaxedEnvVarNameFmtErrMsg string = "a valid environment variable names must be printable ASCII characters other than '=' character"
var envVarNameRegexp = regexp.MustCompile("^" + envVarNameFmt + "$")
// IsEnvVarName tests if a string is a valid environment variable name.
@ -431,6 +435,24 @@ func IsEnvVarName(value string) []string {
return errs
}
// IsRelaxedEnvVarName tests if a string is a valid environment variable name.
func IsRelaxedEnvVarName(value string) []string {
var errs []string
if len(value) == 0 {
errs = append(errs, "environment variable name"+EmptyError())
}
for _, r := range value {
if r > unicode.MaxASCII || !unicode.IsPrint(r) || r == '=' {
errs = append(errs, relaxedEnvVarNameFmtErrMsg)
break
}
}
return errs
}
const configMapKeyFmt = `[-._a-zA-Z0-9]+`
const configMapKeyErrMsg string = "a valid config key must consist of alphanumeric characters, '-', '_' or '.'"

View File

@ -904,3 +904,30 @@ func TestIsDomainPrefixedPath(t *testing.T) {
}
}
}
func TestIsRelaxedEnvVarName(t *testing.T) {
goodValues := []string{
"-", ":", "_", "+a", ">a", "<a",
"a.", "a..", "*a", "%a", "?a",
"a:a", "a_a", "aAz", "~a", "|a",
"a0a", "a9", "/a", "a ", "#a",
"0a", "0 a", "'a", "(a", "@a",
}
for _, val := range goodValues {
if msgs := IsRelaxedEnvVarName(val); len(msgs) != 0 {
t.Errorf("expected true for '%s': %v", val, msgs)
}
}
badValues := []string{
"", "=", "a=", "1=a", "a=b", "#%=&&",
string(rune(1)) + "abc", string(rune(130)) + "abc",
"Ç ç", "Ä ä", "Ñ ñ", "Ø ø",
}
for _, val := range badValues {
if msgs := IsRelaxedEnvVarName(val); len(msgs) == 0 {
t.Errorf("expected false for '%s'", val)
}
}
}