diff --git a/pkg/apis/agones/v1/common.go b/pkg/apis/agones/v1/common.go index 4621e3c7c5..02815cdd21 100644 --- a/pkg/apis/agones/v1/common.go +++ b/pkg/apis/agones/v1/common.go @@ -17,6 +17,7 @@ package v1 import ( "fmt" + apivalidation "k8s.io/apimachinery/pkg/api/validation" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation" "k8s.io/apimachinery/pkg/runtime/schema" @@ -86,5 +87,16 @@ func validateObjectMeta(objMeta metav1.ObjectMeta) []metav1.StatusCause { }) } } + errs = apivalidation.ValidateAnnotations(objMeta.Annotations, + field.NewPath("annotations")) + if len(errs) != 0 { + for _, v := range errs { + causes = append(causes, metav1.StatusCause{ + Type: metav1.CauseTypeFieldValueInvalid, + Field: "annotations", + Message: v.Error(), + }) + } + } return causes } diff --git a/pkg/apis/agones/v1/gameserver_test.go b/pkg/apis/agones/v1/gameserver_test.go index 2fd7b2228b..48ee1ebf82 100644 --- a/pkg/apis/agones/v1/gameserver_test.go +++ b/pkg/apis/agones/v1/gameserver_test.go @@ -427,6 +427,33 @@ func TestGameServerValidate(t *testing.T) { assert.Len(t, causes, 1) assert.Equal(t, "labels", causes[0].Field) + gs.Spec.Template.ObjectMeta.Labels = make(map[string]string) + gs.Spec.Template.ObjectMeta.Labels["agones.dev/longValueKey"] = longName + causes, ok = gs.Validate() + assert.False(t, ok) + assert.Len(t, causes, 1) + assert.Equal(t, "labels", causes[0].Field) + + // Validate Labels and Annotations + gs.Spec.Template.ObjectMeta.Annotations = make(map[string]string) + gs.Spec.Template.ObjectMeta.Annotations[longName] = longName + causes, ok = gs.Validate() + assert.False(t, ok) + assert.Len(t, causes, 2) + + // No errors if valid Annotation was used + gs.Spec.Template.ObjectMeta.Labels = make(map[string]string) + gs.Spec.Template.ObjectMeta.Annotations = make(map[string]string) + gs.Spec.Template.ObjectMeta.Annotations["agones.dev/shortName"] = "shortValue" + causes, ok = gs.Validate() + assert.True(t, ok) + assert.Len(t, causes, 0) + + gs.Spec.Template.ObjectMeta.Annotations["agones.dev/shortName"] = longName + causes, ok = gs.Validate() + assert.True(t, ok) + assert.Len(t, causes, 0) + gs = GameServer{ Spec: GameServerSpec{ Ports: []GameServerPort{{Name: "one", PortPolicy: Passthrough, ContainerPort: 1294}, {PortPolicy: Passthrough, Name: "two", HostPort: 7890}}, diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go b/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go new file mode 100644 index 0000000000..9f20152e45 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go @@ -0,0 +1,18 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package validation contains generic api type validation functions. +package validation // import "k8s.io/apimachinery/pkg/api/validation" diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go b/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go new file mode 100644 index 0000000000..348cdc0873 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go @@ -0,0 +1,85 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package validation + +import ( + "strings" + + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +const IsNegativeErrorMsg string = `must be greater than or equal to 0` + +// ValidateNameFunc validates that the provided name is valid for a given resource type. +// Not all resources have the same validation rules for names. Prefix is true +// if the name will have a value appended to it. If the name is not valid, +// this returns a list of descriptions of individual characteristics of the +// value that were not valid. Otherwise this returns an empty list or nil. +type ValidateNameFunc func(name string, prefix bool) []string + +// NameIsDNSSubdomain is a ValidateNameFunc for names that must be a DNS subdomain. +func NameIsDNSSubdomain(name string, prefix bool) []string { + if prefix { + name = maskTrailingDash(name) + } + return validation.IsDNS1123Subdomain(name) +} + +// NameIsDNSLabel is a ValidateNameFunc for names that must be a DNS 1123 label. +func NameIsDNSLabel(name string, prefix bool) []string { + if prefix { + name = maskTrailingDash(name) + } + return validation.IsDNS1123Label(name) +} + +// NameIsDNS1035Label is a ValidateNameFunc for names that must be a DNS 952 label. +func NameIsDNS1035Label(name string, prefix bool) []string { + if prefix { + name = maskTrailingDash(name) + } + return validation.IsDNS1035Label(name) +} + +// ValidateNamespaceName can be used to check whether the given namespace name is valid. +// Prefix indicates this name will be used as part of generation, in which case +// trailing dashes are allowed. +var ValidateNamespaceName = NameIsDNSLabel + +// ValidateServiceAccountName can be used to check whether the given service account name is valid. +// Prefix indicates this name will be used as part of generation, in which case +// trailing dashes are allowed. +var ValidateServiceAccountName = NameIsDNSSubdomain + +// maskTrailingDash replaces the final character of a string with a subdomain safe +// value if is a dash. +func maskTrailingDash(name string) string { + if strings.HasSuffix(name, "-") { + return name[:len(name)-2] + "a" + } + return name +} + +// Validates that given value is not negative. +func ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + if value < 0 { + allErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg)) + } + return allErrs +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go b/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go new file mode 100644 index 0000000000..44b9b16006 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go @@ -0,0 +1,308 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package validation + +import ( + "fmt" + "strings" + + apiequality "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + v1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +const FieldImmutableErrorMsg string = `field is immutable` + +const totalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB + +// BannedOwners is a black list of object that are not allowed to be owners. +var BannedOwners = map[schema.GroupVersionKind]struct{}{ + {Group: "", Version: "v1", Kind: "Event"}: {}, +} + +// ValidateClusterName can be used to check whether the given cluster name is valid. +var ValidateClusterName = NameIsDNS1035Label + +// ValidateAnnotations validates that a set of annotations are correctly defined. +func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + var totalSize int64 + for k, v := range annotations { + for _, msg := range validation.IsQualifiedName(strings.ToLower(k)) { + allErrs = append(allErrs, field.Invalid(fldPath, k, msg)) + } + totalSize += (int64)(len(k)) + (int64)(len(v)) + } + if totalSize > (int64)(totalAnnotationSizeLimitB) { + allErrs = append(allErrs, field.TooLong(fldPath, "", totalAnnotationSizeLimitB)) + } + return allErrs +} + +func validateOwnerReference(ownerReference metav1.OwnerReference, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + gvk := schema.FromAPIVersionAndKind(ownerReference.APIVersion, ownerReference.Kind) + // gvk.Group is empty for the legacy group. + if len(gvk.Version) == 0 { + allErrs = append(allErrs, field.Invalid(fldPath.Child("apiVersion"), ownerReference.APIVersion, "version must not be empty")) + } + if len(gvk.Kind) == 0 { + allErrs = append(allErrs, field.Invalid(fldPath.Child("kind"), ownerReference.Kind, "kind must not be empty")) + } + if len(ownerReference.Name) == 0 { + allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), ownerReference.Name, "name must not be empty")) + } + if len(ownerReference.UID) == 0 { + allErrs = append(allErrs, field.Invalid(fldPath.Child("uid"), ownerReference.UID, "uid must not be empty")) + } + if _, ok := BannedOwners[gvk]; ok { + allErrs = append(allErrs, field.Invalid(fldPath, ownerReference, fmt.Sprintf("%s is disallowed from being an owner", gvk))) + } + return allErrs +} + +func ValidateOwnerReferences(ownerReferences []metav1.OwnerReference, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + controllerName := "" + for _, ref := range ownerReferences { + allErrs = append(allErrs, validateOwnerReference(ref, fldPath)...) + if ref.Controller != nil && *ref.Controller { + if controllerName != "" { + allErrs = append(allErrs, field.Invalid(fldPath, ownerReferences, + fmt.Sprintf("Only one reference can have Controller set to true. Found \"true\" in references for %v and %v", controllerName, ref.Name))) + } else { + controllerName = ref.Name + } + } + } + return allErrs +} + +// Validate finalizer names +func ValidateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + for _, msg := range validation.IsQualifiedName(stringValue) { + allErrs = append(allErrs, field.Invalid(fldPath, stringValue, msg)) + } + + return allErrs +} + +func ValidateNoNewFinalizers(newFinalizers []string, oldFinalizers []string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + extra := sets.NewString(newFinalizers...).Difference(sets.NewString(oldFinalizers...)) + if len(extra) != 0 { + allErrs = append(allErrs, field.Forbidden(fldPath, fmt.Sprintf("no new finalizers can be added if the object is being deleted, found new finalizers %#v", extra.List()))) + } + return allErrs +} + +func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + if !apiequality.Semantic.DeepEqual(oldVal, newVal) { + allErrs = append(allErrs, field.Invalid(fldPath, newVal, FieldImmutableErrorMsg)) + } + return allErrs +} + +// ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already +// been performed. +// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before. +func ValidateObjectMeta(objMeta *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList { + metadata, err := meta.Accessor(objMeta) + if err != nil { + allErrs := field.ErrorList{} + allErrs = append(allErrs, field.Invalid(fldPath, objMeta, err.Error())) + return allErrs + } + return ValidateObjectMetaAccessor(metadata, requiresNamespace, nameFn, fldPath) +} + +// ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already +// been performed. +// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before. +func ValidateObjectMetaAccessor(meta metav1.Object, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + + if len(meta.GetGenerateName()) != 0 { + for _, msg := range nameFn(meta.GetGenerateName(), true) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("generateName"), meta.GetGenerateName(), msg)) + } + } + // If the generated name validates, but the calculated value does not, it's a problem with generation, and we + // report it here. This may confuse users, but indicates a programming bug and still must be validated. + // If there are multiple fields out of which one is required then add an or as a separator + if len(meta.GetName()) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Child("name"), "name or generateName is required")) + } else { + for _, msg := range nameFn(meta.GetName(), false) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), meta.GetName(), msg)) + } + } + if requiresNamespace { + if len(meta.GetNamespace()) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Child("namespace"), "")) + } else { + for _, msg := range ValidateNamespaceName(meta.GetNamespace(), false) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("namespace"), meta.GetNamespace(), msg)) + } + } + } else { + if len(meta.GetNamespace()) != 0 { + allErrs = append(allErrs, field.Forbidden(fldPath.Child("namespace"), "not allowed on this type")) + } + } + if len(meta.GetClusterName()) != 0 { + for _, msg := range ValidateClusterName(meta.GetClusterName(), false) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("clusterName"), meta.GetClusterName(), msg)) + } + } + allErrs = append(allErrs, ValidateNonnegativeField(meta.GetGeneration(), fldPath.Child("generation"))...) + allErrs = append(allErrs, v1validation.ValidateLabels(meta.GetLabels(), fldPath.Child("labels"))...) + allErrs = append(allErrs, ValidateAnnotations(meta.GetAnnotations(), fldPath.Child("annotations"))...) + allErrs = append(allErrs, ValidateOwnerReferences(meta.GetOwnerReferences(), fldPath.Child("ownerReferences"))...) + allErrs = append(allErrs, ValidateInitializers(meta.GetInitializers(), fldPath.Child("initializers"))...) + allErrs = append(allErrs, ValidateFinalizers(meta.GetFinalizers(), fldPath.Child("finalizers"))...) + return allErrs +} + +func ValidateInitializers(initializers *metav1.Initializers, fldPath *field.Path) field.ErrorList { + var allErrs field.ErrorList + if initializers == nil { + return allErrs + } + for i, initializer := range initializers.Pending { + allErrs = append(allErrs, validation.IsFullyQualifiedName(fldPath.Child("pending").Index(i).Child("name"), initializer.Name)...) + } + allErrs = append(allErrs, validateInitializersResult(initializers.Result, fldPath.Child("result"))...) + return allErrs +} + +func validateInitializersResult(result *metav1.Status, fldPath *field.Path) field.ErrorList { + var allErrs field.ErrorList + if result == nil { + return allErrs + } + switch result.Status { + case metav1.StatusFailure: + default: + allErrs = append(allErrs, field.Invalid(fldPath.Child("status"), result.Status, "must be 'Failure'")) + } + return allErrs +} + +// ValidateFinalizers tests if the finalizers name are valid, and if there are conflicting finalizers. +func ValidateFinalizers(finalizers []string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + hasFinalizerOrphanDependents := false + hasFinalizerDeleteDependents := false + for _, finalizer := range finalizers { + allErrs = append(allErrs, ValidateFinalizerName(finalizer, fldPath)...) + if finalizer == metav1.FinalizerOrphanDependents { + hasFinalizerOrphanDependents = true + } + if finalizer == metav1.FinalizerDeleteDependents { + hasFinalizerDeleteDependents = true + } + } + if hasFinalizerDeleteDependents && hasFinalizerOrphanDependents { + allErrs = append(allErrs, field.Invalid(fldPath, finalizers, fmt.Sprintf("finalizer %s and %s cannot be both set", metav1.FinalizerOrphanDependents, metav1.FinalizerDeleteDependents))) + } + return allErrs +} + +// ValidateObjectMetaUpdate validates an object's metadata when updated +func ValidateObjectMetaUpdate(newMeta, oldMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList { + newMetadata, err := meta.Accessor(newMeta) + if err != nil { + allErrs := field.ErrorList{} + allErrs = append(allErrs, field.Invalid(fldPath, newMeta, err.Error())) + return allErrs + } + oldMetadata, err := meta.Accessor(oldMeta) + if err != nil { + allErrs := field.ErrorList{} + allErrs = append(allErrs, field.Invalid(fldPath, oldMeta, err.Error())) + return allErrs + } + return ValidateObjectMetaAccessorUpdate(newMetadata, oldMetadata, fldPath) +} + +func ValidateObjectMetaAccessorUpdate(newMeta, oldMeta metav1.Object, fldPath *field.Path) field.ErrorList { + var allErrs field.ErrorList + + // Finalizers cannot be added if the object is already being deleted. + if oldMeta.GetDeletionTimestamp() != nil { + allErrs = append(allErrs, ValidateNoNewFinalizers(newMeta.GetFinalizers(), oldMeta.GetFinalizers(), fldPath.Child("finalizers"))...) + } + + // Reject updates that don't specify a resource version + if len(newMeta.GetResourceVersion()) == 0 { + allErrs = append(allErrs, field.Invalid(fldPath.Child("resourceVersion"), newMeta.GetResourceVersion(), "must be specified for an update")) + } + + // Generation shouldn't be decremented + if newMeta.GetGeneration() < oldMeta.GetGeneration() { + allErrs = append(allErrs, field.Invalid(fldPath.Child("generation"), newMeta.GetGeneration(), "must not be decremented")) + } + + allErrs = append(allErrs, ValidateInitializersUpdate(newMeta.GetInitializers(), oldMeta.GetInitializers(), fldPath.Child("initializers"))...) + + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetName(), oldMeta.GetName(), fldPath.Child("name"))...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetNamespace(), oldMeta.GetNamespace(), fldPath.Child("namespace"))...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetUID(), oldMeta.GetUID(), fldPath.Child("uid"))...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetCreationTimestamp(), oldMeta.GetCreationTimestamp(), fldPath.Child("creationTimestamp"))...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionTimestamp(), oldMeta.GetDeletionTimestamp(), fldPath.Child("deletionTimestamp"))...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionGracePeriodSeconds(), oldMeta.GetDeletionGracePeriodSeconds(), fldPath.Child("deletionGracePeriodSeconds"))...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetClusterName(), oldMeta.GetClusterName(), fldPath.Child("clusterName"))...) + + allErrs = append(allErrs, v1validation.ValidateLabels(newMeta.GetLabels(), fldPath.Child("labels"))...) + allErrs = append(allErrs, ValidateAnnotations(newMeta.GetAnnotations(), fldPath.Child("annotations"))...) + allErrs = append(allErrs, ValidateOwnerReferences(newMeta.GetOwnerReferences(), fldPath.Child("ownerReferences"))...) + + return allErrs +} + +// ValidateInitializersUpdate checks the update of the metadata initializers field +func ValidateInitializersUpdate(newInit, oldInit *metav1.Initializers, fldPath *field.Path) field.ErrorList { + var allErrs field.ErrorList + switch { + case oldInit == nil && newInit != nil: + // Initializers may not be set on new objects + allErrs = append(allErrs, field.Invalid(fldPath, nil, "field is immutable once initialization has completed")) + case oldInit != nil && newInit == nil: + // this is a valid transition and means initialization was successful + case oldInit != nil && newInit != nil: + // validate changes to initializers + switch { + case oldInit.Result == nil && newInit.Result != nil: + // setting a result is allowed + allErrs = append(allErrs, validateInitializersResult(newInit.Result, fldPath.Child("result"))...) + case oldInit.Result != nil: + // setting Result implies permanent failure, and all future updates will be prevented + allErrs = append(allErrs, ValidateImmutableField(newInit.Result, oldInit.Result, fldPath.Child("result"))...) + default: + // leaving the result nil is allowed + } + } + return allErrs +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta_test.go b/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta_test.go new file mode 100644 index 0000000000..ebd6c7e7c7 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta_test.go @@ -0,0 +1,500 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package validation + +import ( + "math/rand" + "reflect" + "strings" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +const ( + maxLengthErrMsg = "must be no more than" + namePartErrMsg = "name part must consist of" + nameErrMsg = "a qualified name must consist of" +) + +// Ensure custom name functions are allowed +func TestValidateObjectMetaCustomName(t *testing.T) { + errs := ValidateObjectMeta( + &metav1.ObjectMeta{Name: "test", GenerateName: "foo"}, + false, + func(s string, prefix bool) []string { + if s == "test" { + return nil + } + return []string{"name-gen"} + }, + field.NewPath("field")) + if len(errs) != 1 { + t.Fatalf("unexpected errors: %v", errs) + } + if !strings.Contains(errs[0].Error(), "name-gen") { + t.Errorf("unexpected error message: %v", errs) + } +} + +// Ensure namespace names follow dns label format +func TestValidateObjectMetaNamespaces(t *testing.T) { + errs := ValidateObjectMeta( + &metav1.ObjectMeta{Name: "test", Namespace: "foo.bar"}, + true, + func(s string, prefix bool) []string { + return nil + }, + field.NewPath("field")) + if len(errs) != 1 { + t.Fatalf("unexpected errors: %v", errs) + } + if !strings.Contains(errs[0].Error(), `Invalid value: "foo.bar"`) { + t.Errorf("unexpected error message: %v", errs) + } + maxLength := 63 + letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") + b := make([]rune, maxLength+1) + for i := range b { + b[i] = letters[rand.Intn(len(letters))] + } + errs = ValidateObjectMeta( + &metav1.ObjectMeta{Name: "test", Namespace: string(b)}, + true, + func(s string, prefix bool) []string { + return nil + }, + field.NewPath("field")) + if len(errs) != 2 { + t.Fatalf("unexpected errors: %v", errs) + } + if !strings.Contains(errs[0].Error(), "Invalid value") || !strings.Contains(errs[1].Error(), "Invalid value") { + t.Errorf("unexpected error message: %v", errs) + } +} + +func TestValidateObjectMetaOwnerReferences(t *testing.T) { + trueVar := true + falseVar := false + testCases := []struct { + description string + ownerReferences []metav1.OwnerReference + expectError bool + expectedErrorMessage string + }{ + { + description: "simple success - third party extension.", + ownerReferences: []metav1.OwnerReference{ + { + APIVersion: "customresourceVersion", + Kind: "customresourceKind", + Name: "name", + UID: "1", + }, + }, + expectError: false, + expectedErrorMessage: "", + }, + { + description: "simple failures - event shouldn't be set as an owner", + ownerReferences: []metav1.OwnerReference{ + { + APIVersion: "v1", + Kind: "Event", + Name: "name", + UID: "1", + }, + }, + expectError: true, + expectedErrorMessage: "is disallowed from being an owner", + }, + { + description: "simple controller ref success - one reference with Controller set", + ownerReferences: []metav1.OwnerReference{ + { + APIVersion: "customresourceVersion", + Kind: "customresourceKind", + Name: "name", + UID: "1", + Controller: &falseVar, + }, + { + APIVersion: "customresourceVersion", + Kind: "customresourceKind", + Name: "name", + UID: "2", + Controller: &trueVar, + }, + { + APIVersion: "customresourceVersion", + Kind: "customresourceKind", + Name: "name", + UID: "3", + Controller: &falseVar, + }, + { + APIVersion: "customresourceVersion", + Kind: "customresourceKind", + Name: "name", + UID: "4", + }, + }, + expectError: false, + expectedErrorMessage: "", + }, + { + description: "simple controller ref failure - two references with Controller set", + ownerReferences: []metav1.OwnerReference{ + { + APIVersion: "customresourceVersion", + Kind: "customresourceKind", + Name: "name", + UID: "1", + Controller: &falseVar, + }, + { + APIVersion: "customresourceVersion", + Kind: "customresourceKind", + Name: "name", + UID: "2", + Controller: &trueVar, + }, + { + APIVersion: "customresourceVersion", + Kind: "customresourceKind", + Name: "name", + UID: "3", + Controller: &trueVar, + }, + { + APIVersion: "customresourceVersion", + Kind: "customresourceKind", + Name: "name", + UID: "4", + }, + }, + expectError: true, + expectedErrorMessage: "Only one reference can have Controller set to true", + }, + } + + for _, tc := range testCases { + errs := ValidateObjectMeta( + &metav1.ObjectMeta{Name: "test", Namespace: "test", OwnerReferences: tc.ownerReferences}, + true, + func(s string, prefix bool) []string { + return nil + }, + field.NewPath("field")) + if len(errs) != 0 && !tc.expectError { + t.Errorf("unexpected error: %v in test case %v", errs, tc.description) + } + if len(errs) == 0 && tc.expectError { + t.Errorf("expect error in test case %v", tc.description) + } + if len(errs) != 0 && !strings.Contains(errs[0].Error(), tc.expectedErrorMessage) { + t.Errorf("unexpected error message: %v in test case %v", errs, tc.description) + } + } +} + +func TestValidateObjectMetaUpdateIgnoresCreationTimestamp(t *testing.T) { + if errs := ValidateObjectMetaUpdate( + &metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + &metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(10, 0))}, + field.NewPath("field"), + ); len(errs) != 1 { + t.Fatalf("unexpected errors: %v", errs) + } + if errs := ValidateObjectMetaUpdate( + &metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(10, 0))}, + &metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + field.NewPath("field"), + ); len(errs) != 1 { + t.Fatalf("unexpected errors: %v", errs) + } + if errs := ValidateObjectMetaUpdate( + &metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(10, 0))}, + &metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(11, 0))}, + field.NewPath("field"), + ); len(errs) != 1 { + t.Fatalf("unexpected errors: %v", errs) + } +} + +func TestValidateFinalizersUpdate(t *testing.T) { + testcases := map[string]struct { + Old metav1.ObjectMeta + New metav1.ObjectMeta + ExpectedErr string + }{ + "invalid adding finalizers": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a"}}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a", "y/b"}}, + ExpectedErr: "y/b", + }, + "invalid changing finalizers": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a"}}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/b"}}, + ExpectedErr: "x/b", + }, + "valid removing finalizers": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a", "y/b"}}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a"}}, + ExpectedErr: "", + }, + "valid adding finalizers for objects not being deleted": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Finalizers: []string{"x/a"}}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Finalizers: []string{"x/a", "y/b"}}, + ExpectedErr: "", + }, + } + for name, tc := range testcases { + errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field")) + if len(errs) == 0 { + if len(tc.ExpectedErr) != 0 { + t.Errorf("case: %q, expected error to contain %q", name, tc.ExpectedErr) + } + } else if e, a := tc.ExpectedErr, errs.ToAggregate().Error(); !strings.Contains(a, e) { + t.Errorf("case: %q, expected error to contain %q, got error %q", name, e, a) + } + } +} + +func TestValidateFinalizersPreventConflictingFinalizers(t *testing.T) { + testcases := map[string]struct { + ObjectMeta metav1.ObjectMeta + ExpectedErr string + }{ + "conflicting finalizers": { + ObjectMeta: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Finalizers: []string{metav1.FinalizerOrphanDependents, metav1.FinalizerDeleteDependents}}, + ExpectedErr: "cannot be both set", + }, + } + for name, tc := range testcases { + errs := ValidateObjectMeta(&tc.ObjectMeta, false, NameIsDNSSubdomain, field.NewPath("field")) + if len(errs) == 0 { + if len(tc.ExpectedErr) != 0 { + t.Errorf("case: %q, expected error to contain %q", name, tc.ExpectedErr) + } + } else if e, a := tc.ExpectedErr, errs.ToAggregate().Error(); !strings.Contains(a, e) { + t.Errorf("case: %q, expected error to contain %q, got error %q", name, e, a) + } + } +} + +func TestValidateObjectMetaUpdatePreventsDeletionFieldMutation(t *testing.T) { + now := metav1.NewTime(time.Unix(1000, 0).UTC()) + later := metav1.NewTime(time.Unix(2000, 0).UTC()) + gracePeriodShort := int64(30) + gracePeriodLong := int64(40) + + testcases := map[string]struct { + Old metav1.ObjectMeta + New metav1.ObjectMeta + ExpectedNew metav1.ObjectMeta + ExpectedErrs []string + }{ + "valid without deletion fields": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + ExpectedErrs: []string{}, + }, + "valid with deletion fields": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort}, + ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort}, + ExpectedErrs: []string{}, + }, + + "invalid set deletionTimestamp": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, + ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, + ExpectedErrs: []string{"field.deletionTimestamp: Invalid value: 1970-01-01 00:16:40 +0000 UTC: field is immutable"}, + }, + "invalid clear deletionTimestamp": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + ExpectedErrs: []string{"field.deletionTimestamp: Invalid value: \"null\": field is immutable"}, + }, + "invalid change deletionTimestamp": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &later}, + ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &later}, + ExpectedErrs: []string{"field.deletionTimestamp: Invalid value: 1970-01-01 00:33:20 +0000 UTC: field is immutable"}, + }, + + "invalid set deletionGracePeriodSeconds": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort}, + ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort}, + ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: 30: field is immutable"}, + }, + "invalid clear deletionGracePeriodSeconds": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, + ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: \"null\": field is immutable"}, + }, + "invalid change deletionGracePeriodSeconds": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodLong}, + ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodLong}, + ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: 40: field is immutable"}, + }, + } + + for k, tc := range testcases { + errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field")) + if len(errs) != len(tc.ExpectedErrs) { + t.Logf("%s: Expected: %#v", k, tc.ExpectedErrs) + t.Logf("%s: Got: %#v", k, errs) + t.Errorf("%s: expected %d errors, got %d", k, len(tc.ExpectedErrs), len(errs)) + continue + } + for i := range errs { + if errs[i].Error() != tc.ExpectedErrs[i] { + t.Errorf("%s: error #%d: expected %q, got %q", k, i, tc.ExpectedErrs[i], errs[i].Error()) + } + } + if !reflect.DeepEqual(tc.New, tc.ExpectedNew) { + t.Errorf("%s: Expected after validation:\n%#v\ngot\n%#v", k, tc.ExpectedNew, tc.New) + } + } +} + +func TestObjectMetaGenerationUpdate(t *testing.T) { + testcases := map[string]struct { + Old metav1.ObjectMeta + New metav1.ObjectMeta + ExpectedErrs []string + }{ + "invalid generation change - decremented": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 4}, + ExpectedErrs: []string{"field.generation: Invalid value: 4: must not be decremented"}, + }, + "valid generation change - incremented by one": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 1}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 2}, + ExpectedErrs: []string{}, + }, + "valid generation field - not updated": { + Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5}, + New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5}, + ExpectedErrs: []string{}, + }, + } + + for k, tc := range testcases { + errList := []string{} + errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field")) + if len(errs) != len(tc.ExpectedErrs) { + t.Logf("%s: Expected: %#v", k, tc.ExpectedErrs) + for _, err := range errs { + errList = append(errList, err.Error()) + } + t.Logf("%s: Got: %#v", k, errList) + t.Errorf("%s: expected %d errors, got %d", k, len(tc.ExpectedErrs), len(errs)) + continue + } + for i := range errList { + if errList[i] != tc.ExpectedErrs[i] { + t.Errorf("%s: error #%d: expected %q, got %q", k, i, tc.ExpectedErrs[i], errList[i]) + } + } + } +} + +// Ensure trailing slash is allowed in generate name +func TestValidateObjectMetaTrimsTrailingSlash(t *testing.T) { + errs := ValidateObjectMeta( + &metav1.ObjectMeta{Name: "test", GenerateName: "foo-"}, + false, + NameIsDNSSubdomain, + field.NewPath("field")) + if len(errs) != 0 { + t.Fatalf("unexpected errors: %v", errs) + } +} + +func TestValidateAnnotations(t *testing.T) { + successCases := []map[string]string{ + {"simple": "bar"}, + {"now-with-dashes": "bar"}, + {"1-starts-with-num": "bar"}, + {"1234": "bar"}, + {"simple/simple": "bar"}, + {"now-with-dashes/simple": "bar"}, + {"now-with-dashes/now-with-dashes": "bar"}, + {"now.with.dots/simple": "bar"}, + {"now-with.dashes-and.dots/simple": "bar"}, + {"1-num.2-num/3-num": "bar"}, + {"1234/5678": "bar"}, + {"1.2.3.4/5678": "bar"}, + {"UpperCase123": "bar"}, + {"a": strings.Repeat("b", totalAnnotationSizeLimitB-1)}, + { + "a": strings.Repeat("b", totalAnnotationSizeLimitB/2-1), + "c": strings.Repeat("d", totalAnnotationSizeLimitB/2-1), + }, + } + for i := range successCases { + errs := ValidateAnnotations(successCases[i], field.NewPath("field")) + if len(errs) != 0 { + t.Errorf("case[%d] expected success, got %#v", i, errs) + } + } + + nameErrorCases := []struct { + annotations map[string]string + expect string + }{ + {map[string]string{"nospecialchars^=@": "bar"}, namePartErrMsg}, + {map[string]string{"cantendwithadash-": "bar"}, namePartErrMsg}, + {map[string]string{"only/one/slash": "bar"}, nameErrMsg}, + {map[string]string{strings.Repeat("a", 254): "bar"}, maxLengthErrMsg}, + } + for i := range nameErrorCases { + errs := ValidateAnnotations(nameErrorCases[i].annotations, field.NewPath("field")) + if len(errs) != 1 { + t.Errorf("case[%d]: expected failure", i) + } else { + if !strings.Contains(errs[0].Detail, nameErrorCases[i].expect) { + t.Errorf("case[%d]: error details do not include %q: %q", i, nameErrorCases[i].expect, errs[0].Detail) + } + } + } + totalSizeErrorCases := []map[string]string{ + {"a": strings.Repeat("b", totalAnnotationSizeLimitB)}, + { + "a": strings.Repeat("b", totalAnnotationSizeLimitB/2), + "c": strings.Repeat("d", totalAnnotationSizeLimitB/2), + }, + } + for i := range totalSizeErrorCases { + errs := ValidateAnnotations(totalSizeErrorCases[i], field.NewPath("field")) + if len(errs) != 1 { + t.Errorf("case[%d] expected failure", i) + } + } +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/path/name.go b/vendor/k8s.io/apimachinery/pkg/api/validation/path/name.go new file mode 100644 index 0000000000..a50cd089df --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/validation/path/name.go @@ -0,0 +1,68 @@ +/* +Copyright 2015 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package path + +import ( + "fmt" + "strings" +) + +// NameMayNotBe specifies strings that cannot be used as names specified as path segments (like the REST API or etcd store) +var NameMayNotBe = []string{".", ".."} + +// NameMayNotContain specifies substrings that cannot be used in names specified as path segments (like the REST API or etcd store) +var NameMayNotContain = []string{"/", "%"} + +// IsValidPathSegmentName validates the name can be safely encoded as a path segment +func IsValidPathSegmentName(name string) []string { + for _, illegalName := range NameMayNotBe { + if name == illegalName { + return []string{fmt.Sprintf(`may not be '%s'`, illegalName)} + } + } + + var errors []string + for _, illegalContent := range NameMayNotContain { + if strings.Contains(name, illegalContent) { + errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent)) + } + } + + return errors +} + +// IsValidPathSegmentPrefix validates the name can be used as a prefix for a name which will be encoded as a path segment +// It does not check for exact matches with disallowed names, since an arbitrary suffix might make the name valid +func IsValidPathSegmentPrefix(name string) []string { + var errors []string + for _, illegalContent := range NameMayNotContain { + if strings.Contains(name, illegalContent) { + errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent)) + } + } + + return errors +} + +// ValidatePathSegmentName validates the name can be safely encoded as a path segment +func ValidatePathSegmentName(name string, prefix bool) []string { + if prefix { + return IsValidPathSegmentPrefix(name) + } else { + return IsValidPathSegmentName(name) + } +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/path/name_test.go b/vendor/k8s.io/apimachinery/pkg/api/validation/path/name_test.go new file mode 100644 index 0000000000..4289052738 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/validation/path/name_test.go @@ -0,0 +1,168 @@ +/* +Copyright 2015 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package path + +import ( + "strings" + "testing" +) + +func TestValidatePathSegmentName(t *testing.T) { + testcases := map[string]struct { + Name string + Prefix bool + ExpectedMsg string + }{ + "empty": { + Name: "", + Prefix: false, + ExpectedMsg: "", + }, + "empty,prefix": { + Name: "", + Prefix: true, + ExpectedMsg: "", + }, + + "valid": { + Name: "foo.bar.baz", + Prefix: false, + ExpectedMsg: "", + }, + "valid,prefix": { + Name: "foo.bar.baz", + Prefix: true, + ExpectedMsg: "", + }, + + // Make sure mixed case, non DNS subdomain characters are tolerated + "valid complex": { + Name: "sha256:ABCDEF012345@ABCDEF012345", + Prefix: false, + ExpectedMsg: "", + }, + // Make sure non-ascii characters are tolerated + "valid extended charset": { + Name: "Iñtërnâtiônàlizætiøn", + Prefix: false, + ExpectedMsg: "", + }, + + "dot": { + Name: ".", + Prefix: false, + ExpectedMsg: ".", + }, + "dot leading": { + Name: ".test", + Prefix: false, + ExpectedMsg: "", + }, + "dot,prefix": { + Name: ".", + Prefix: true, + ExpectedMsg: "", + }, + + "dot dot": { + Name: "..", + Prefix: false, + ExpectedMsg: "..", + }, + "dot dot leading": { + Name: "..test", + Prefix: false, + ExpectedMsg: "", + }, + "dot dot,prefix": { + Name: "..", + Prefix: true, + ExpectedMsg: "", + }, + + "slash": { + Name: "foo/bar", + Prefix: false, + ExpectedMsg: "/", + }, + "slash,prefix": { + Name: "foo/bar", + Prefix: true, + ExpectedMsg: "/", + }, + + "percent": { + Name: "foo%bar", + Prefix: false, + ExpectedMsg: "%", + }, + "percent,prefix": { + Name: "foo%bar", + Prefix: true, + ExpectedMsg: "%", + }, + } + + for k, tc := range testcases { + msgs := ValidatePathSegmentName(tc.Name, tc.Prefix) + if len(tc.ExpectedMsg) == 0 && len(msgs) > 0 { + t.Errorf("%s: expected no message, got %v", k, msgs) + } + if len(tc.ExpectedMsg) > 0 && len(msgs) == 0 { + t.Errorf("%s: expected error message, got none", k) + } + if len(tc.ExpectedMsg) > 0 && !strings.Contains(msgs[0], tc.ExpectedMsg) { + t.Errorf("%s: expected message containing %q, got %v", k, tc.ExpectedMsg, msgs[0]) + } + } +} + +func TestValidateWithMultiErrors(t *testing.T) { + testcases := map[string]struct { + Name string + Prefix bool + ExpectedMsg []string + }{ + "slash,percent": { + Name: "foo//bar%", + Prefix: false, + ExpectedMsg: []string{"may not contain '/'", "may not contain '%'"}, + }, + "slash,percent,prefix": { + Name: "foo//bar%", + Prefix: true, + ExpectedMsg: []string{"may not contain '/'", "may not contain '%'"}, + }, + } + + for k, tc := range testcases { + msgs := ValidatePathSegmentName(tc.Name, tc.Prefix) + if len(tc.ExpectedMsg) == 0 && len(msgs) > 0 { + t.Errorf("%s: expected no message, got %v", k, msgs) + } + if len(tc.ExpectedMsg) > 0 && len(msgs) == 0 { + t.Errorf("%s: expected error message, got none", k) + } + if len(tc.ExpectedMsg) > 0 { + for i := 0; i < len(tc.ExpectedMsg); i++ { + if msgs[i] != tc.ExpectedMsg[i] { + t.Errorf("%s: expected message containing %q, got %v", k, tc.ExpectedMsg[i], msgs[i]) + } + } + } + } +}