Skip to content

Commit

Permalink
add relaxed env var name function
Browse files Browse the repository at this point in the history
  • Loading branch information
HirazawaUi committed Mar 5, 2024
1 parent bed8fed commit 96a16a7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
22 changes: 22 additions & 0 deletions staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"math"
"regexp"
"strings"
"unicode"

"k8s.io/apimachinery/pkg/util/validation/field"
netutils "k8s.io/utils/net"
Expand Down Expand Up @@ -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.
Expand All @@ -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 '.'"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

0 comments on commit 96a16a7

Please sign in to comment.