mirror of https://github.com/k3s-io/k3s
GCE: Fix Valid() to check for proper region/zone names
parent
47b89aaf8f
commit
a2b222c94e
|
@ -18,6 +18,7 @@ package meta
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// Key for a GCP resource.
|
||||
|
@ -39,6 +40,11 @@ const (
|
|||
Global = "global"
|
||||
)
|
||||
|
||||
var (
|
||||
// locationRegexp is the format of regions/zone names in GCE.
|
||||
locationRegexp = regexp.MustCompile("^[a-z](?:[-a-z0-9]+)?$")
|
||||
)
|
||||
|
||||
// ZonalKey returns the key for a zonal resource.
|
||||
func ZonalKey(name, zone string) *Key {
|
||||
return &Key{name, zone, ""}
|
||||
|
@ -79,10 +85,16 @@ func (k Key) String() string {
|
|||
}
|
||||
|
||||
// Valid is true if the key is valid.
|
||||
func (k *Key) Valid(typeName string) bool {
|
||||
func (k *Key) Valid() bool {
|
||||
if k.Zone != "" && k.Region != "" {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case k.Region != "":
|
||||
return locationRegexp.Match([]byte(k.Region))
|
||||
case k.Zone != "":
|
||||
return locationRegexp.Match([]byte(k.Zone))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
|
|
|
@ -59,17 +59,18 @@ func TestKeyValid(t *testing.T) {
|
|||
|
||||
for _, tc := range []struct {
|
||||
key *Key
|
||||
typeName string
|
||||
want bool
|
||||
}{
|
||||
// Note: these test cases need to be synchronized with the
|
||||
// actual settings for each type.
|
||||
{GlobalKey("abc"), "UrlMap", true},
|
||||
{&Key{"abc", zone, region}, "UrlMap", false},
|
||||
{GlobalKey("abc"), true},
|
||||
{RegionalKey("abc", region), true},
|
||||
{ZonalKey("abc", zone), true},
|
||||
{RegionalKey("abc", "/invalid/"), false},
|
||||
{ZonalKey("abc", "/invalid/"), false},
|
||||
{&Key{"abc", zone, region}, false},
|
||||
} {
|
||||
valid := tc.key.Valid(tc.typeName)
|
||||
if valid != tc.want {
|
||||
t.Errorf("key %+v, type %v; key.Valid() = %v, want %v", tc.key, tc.typeName, valid, tc.want)
|
||||
got := tc.key.Valid()
|
||||
if got != tc.want {
|
||||
t.Errorf("key %+v; key.Valid() = %v, want %v", tc.key, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue