knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/apis/metadata_validation.go (about) 1 /* 2 Copyright 2019 The Knative Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package apis 18 19 import ( 20 "fmt" 21 22 "k8s.io/apimachinery/pkg/api/equality" 23 "k8s.io/apimachinery/pkg/api/validation" 24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 ) 26 27 const ( 28 // CreatorAnnotationSuffix is the suffix of the annotation key to describe 29 // the user that created the resource. 30 CreatorAnnotationSuffix = "/creator" 31 32 // UpdaterAnnotationSuffix is the suffix of the annotation key to describe 33 // the user who last modified the resource. 34 UpdaterAnnotationSuffix = "/lastModifier" 35 ) 36 37 // ValidateObjectMetadata validates that `metadata` stanza of the 38 // resources is correct. 39 func ValidateObjectMetadata(meta metav1.Object) *FieldError { 40 name := meta.GetName() 41 generateName := meta.GetGenerateName() 42 43 if generateName != "" { 44 msgs := validation.NameIsDNS1035Label(generateName, true) 45 46 if len(msgs) > 0 { 47 return &FieldError{ 48 Message: fmt.Sprintf("not a DNS 1035 label prefix: %v", msgs), 49 Paths: []string{"generateName"}, 50 } 51 } 52 } 53 54 if name != "" { 55 msgs := validation.NameIsDNS1035Label(name, false) 56 57 if len(msgs) > 0 { 58 return &FieldError{ 59 Message: fmt.Sprintf("not a DNS 1035 label: %v", msgs), 60 Paths: []string{"name"}, 61 } 62 } 63 } 64 65 if generateName == "" && name == "" { 66 return &FieldError{ 67 Message: "name or generateName is required", 68 Paths: []string{"name"}, 69 } 70 } 71 72 return nil 73 } 74 75 // ValidateCreatorAndModifier validates `metadata.annotation` 76 func ValidateCreatorAndModifier(oldSpec, newSpec interface{}, oldAnnotation, newAnnotation map[string]string, groupName string) *FieldError { 77 var errs *FieldError 78 if oldAnnotation[groupName+CreatorAnnotationSuffix] != newAnnotation[groupName+CreatorAnnotationSuffix] { 79 errs = errs.Also(&FieldError{ 80 Message: "annotation value is immutable", 81 Paths: []string{groupName + CreatorAnnotationSuffix}, 82 }) 83 } 84 85 if equality.Semantic.DeepEqual(oldSpec, newSpec) && oldAnnotation[groupName+UpdaterAnnotationSuffix] != newAnnotation[groupName+UpdaterAnnotationSuffix] { 86 errs = errs.Also(ErrInvalidValue(newAnnotation[groupName+UpdaterAnnotationSuffix], groupName+UpdaterAnnotationSuffix)) 87 } 88 return errs 89 }