| 1 |
/* |
| 2 |
Copyright 2015 The Kubernetes 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 validation |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"regexp" |
| 22 |
"unicode" |
| 23 |
|
| 24 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 25 |
"k8s.io/apimachinery/pkg/types" |
| 26 |
"k8s.io/apimachinery/pkg/util/sets" |
| 27 |
"k8s.io/apimachinery/pkg/util/validation" |
| 28 |
"k8s.io/apimachinery/pkg/util/validation/field" |
| 29 |
|
| 30 |
"k8s.io/utils/ptr" |
| 31 |
) |
| 32 |
|
| 33 |
// LabelSelectorValidationOptions is a struct that can be passed to ValidateLabelSelector to record the validate options |
| 34 |
type LabelSelectorValidationOptions struct { |
| 35 |
// Allow invalid label value in selector |
| 36 |
AllowInvalidLabelValueInSelector bool |
| 37 |
|
| 38 |
// Allows an operator that is not interpretable to pass validation. This is useful for cases where a broader check |
| 39 |
// can be performed, as in a *SubjectAccessReview |
| 40 |
AllowUnknownOperatorInRequirement bool |
| 41 |
} |
| 42 |
|
| 43 |
// LabelSelectorHasInvalidLabelValue returns true if the given selector contains an invalid label value in a match expression. |
| 44 |
// This is useful for determining whether AllowInvalidLabelValueInSelector should be set to true when validating an update |
| 45 |
// based on existing persisted invalid values. |
| 46 |
func LabelSelectorHasInvalidLabelValue(ps *metav1.LabelSelector) bool { |
| 47 |
if ps == nil { |
| 48 |
return false |
| 49 |
} |
| 50 |
for _, e := range ps.MatchExpressions { |
| 51 |
for _, v := range e.Values { |
| 52 |
if len(validation.IsValidLabelValue(v)) > 0 { |
| 53 |
return true |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
return false |
| 58 |
} |
| 59 |
|
| 60 |
// ValidateLabelSelector validate the LabelSelector according to the opts and returns any validation errors. |
| 61 |
// opts.AllowInvalidLabelValueInSelector is only expected to be set to true when required for backwards compatibility with existing invalid data. |
| 62 |
func ValidateLabelSelector(ps *metav1.LabelSelector, opts LabelSelectorValidationOptions, fldPath *field.Path) field.ErrorList { |
| 63 |
allErrs := field.ErrorList{} |
| 64 |
if ps == nil { |
| 65 |
return allErrs |
| 66 |
} |
| 67 |
allErrs = append(allErrs, ValidateLabels(ps.MatchLabels, fldPath.Child("matchLabels"))...) |
| 68 |
for i, expr := range ps.MatchExpressions { |
| 69 |
allErrs = append(allErrs, ValidateLabelSelectorRequirement(expr, opts, fldPath.Child("matchExpressions").Index(i))...) |
| 70 |
} |
| 71 |
return allErrs |
| 72 |
} |
| 73 |
|
| 74 |
// ValidateLabelSelectorRequirement validate the requirement according to the opts and returns any validation errors. |
| 75 |
// opts.AllowInvalidLabelValueInSelector is only expected to be set to true when required for backwards compatibility with existing invalid data. |
| 76 |
func ValidateLabelSelectorRequirement(sr metav1.LabelSelectorRequirement, opts LabelSelectorValidationOptions, fldPath *field.Path) field.ErrorList { |
| 77 |
allErrs := field.ErrorList{} |
| 78 |
switch sr.Operator { |
| 79 |
case metav1.LabelSelectorOpIn, metav1.LabelSelectorOpNotIn: |
| 80 |
if len(sr.Values) == 0 { |
| 81 |
allErrs = append(allErrs, field.Required(fldPath.Child("values"), "must be specified when `operator` is 'In' or 'NotIn'")) |
| 82 |
} |
| 83 |
case metav1.LabelSelectorOpExists, metav1.LabelSelectorOpDoesNotExist: |
| 84 |
if len(sr.Values) > 0 { |
| 85 |
allErrs = append(allErrs, field.Forbidden(fldPath.Child("values"), "may not be specified when `operator` is 'Exists' or 'DoesNotExist'")) |
| 86 |
} |
| 87 |
default: |
| 88 |
if !opts.AllowUnknownOperatorInRequirement { |
| 89 |
allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), sr.Operator, "not a valid selector operator")) |
| 90 |
} |
| 91 |
} |
| 92 |
allErrs = append(allErrs, ValidateLabelName(sr.Key, fldPath.Child("key"))...) |
| 93 |
if !opts.AllowInvalidLabelValueInSelector { |
| 94 |
for valueIndex, value := range sr.Values { |
| 95 |
for _, msg := range validation.IsValidLabelValue(value) { |
| 96 |
allErrs = append(allErrs, field.Invalid(fldPath.Child("values").Index(valueIndex), value, msg)) |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
return allErrs |
| 101 |
} |
| 102 |
|
| 103 |
// ValidateLabelName validates that the label name is correctly defined. |
| 104 |
func ValidateLabelName(labelName string, fldPath *field.Path) field.ErrorList { |
| 105 |
allErrs := field.ErrorList{} |
| 106 |
for _, msg := range validation.IsQualifiedName(labelName) { |
| 107 |
allErrs = append(allErrs, field.Invalid(fldPath, labelName, msg).WithOrigin("labelKey")) |
| 108 |
} |
| 109 |
return allErrs |
| 110 |
} |
| 111 |
|
| 112 |
// ValidateLabels validates that a set of labels are correctly defined. |
| 113 |
func ValidateLabels(labels map[string]string, fldPath *field.Path) field.ErrorList { |
| 114 |
allErrs := field.ErrorList{} |
| 115 |
for k, v := range labels { |
| 116 |
allErrs = append(allErrs, ValidateLabelName(k, fldPath)...) |
| 117 |
for _, msg := range validation.IsValidLabelValue(v) { |
| 118 |
allErrs = append(allErrs, field.Invalid(fldPath, v, msg)) |
| 119 |
} |
| 120 |
} |
| 121 |
return allErrs |
| 122 |
} |
| 123 |
|
| 124 |
// FieldSelectorValidationOptions is a struct that can be passed to ValidateFieldSelectorRequirement to record the validate options |
| 125 |
type FieldSelectorValidationOptions struct { |
| 126 |
// Allows an operator that is not interpretable to pass validation. This is useful for cases where a broader check |
| 127 |
// can be performed, as in a *SubjectAccessReview |
| 128 |
AllowUnknownOperatorInRequirement bool |
| 129 |
} |
| 130 |
|
| 131 |
// ValidateLabelSelectorRequirement validates the requirement according to the opts and returns any validation errors. |
| 132 |
func ValidateFieldSelectorRequirement(requirement metav1.FieldSelectorRequirement, opts FieldSelectorValidationOptions, fldPath *field.Path) field.ErrorList { |
| 133 |
allErrs := field.ErrorList{} |
| 134 |
|
| 135 |
if len(requirement.Key) == 0 { |
| 136 |
allErrs = append(allErrs, field.Required(fldPath.Child("key"), "must be specified")) |
| 137 |
} |
| 138 |
|
| 139 |
switch requirement.Operator { |
| 140 |
case metav1.FieldSelectorOpIn, metav1.FieldSelectorOpNotIn: |
| 141 |
if len(requirement.Values) == 0 { |
| 142 |
allErrs = append(allErrs, field.Required(fldPath.Child("values"), "must be specified when `operator` is 'In' or 'NotIn'")) |
| 143 |
} |
| 144 |
case metav1.FieldSelectorOpExists, metav1.FieldSelectorOpDoesNotExist: |
| 145 |
if len(requirement.Values) > 0 { |
| 146 |
allErrs = append(allErrs, field.Forbidden(fldPath.Child("values"), "may not be specified when `operator` is 'Exists' or 'DoesNotExist'")) |
| 147 |
} |
| 148 |
default: |
| 149 |
if !opts.AllowUnknownOperatorInRequirement { |
| 150 |
allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), requirement.Operator, "not a valid selector operator")) |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
return allErrs |
| 155 |
} |
| 156 |
|
| 157 |
func ValidateDeleteOptions(options *metav1.DeleteOptions) field.ErrorList { |
| 158 |
allErrs := field.ErrorList{} |
| 159 |
//lint:file-ignore SA1019 Keep validation for deprecated OrphanDependents option until it's being removed |
| 160 |
if options.OrphanDependents != nil && options.PropagationPolicy != nil { |
| 161 |
allErrs = append(allErrs, field.Invalid(field.NewPath("propagationPolicy"), options.PropagationPolicy, "orphanDependents and deletionPropagation cannot be both set")) |
| 162 |
} |
| 163 |
if options.PropagationPolicy != nil && |
| 164 |
*options.PropagationPolicy != metav1.DeletePropagationForeground && |
| 165 |
*options.PropagationPolicy != metav1.DeletePropagationBackground && |
| 166 |
*options.PropagationPolicy != metav1.DeletePropagationOrphan { |
| 167 |
allErrs = append(allErrs, field.NotSupported(field.NewPath("propagationPolicy"), options.PropagationPolicy, []string{string(metav1.DeletePropagationForeground), string(metav1.DeletePropagationBackground), string(metav1.DeletePropagationOrphan), "nil"})) |
| 168 |
} |
| 169 |
allErrs = append(allErrs, ValidateDryRun(field.NewPath("dryRun"), options.DryRun)...) |
| 170 |
allErrs = append(allErrs, ValidateIgnoreStoreReadError(field.NewPath("ignoreStoreReadErrorWithClusterBreakingPotential"), options)...) |
| 171 |
return allErrs |
| 172 |
} |
| 173 |
|
| 174 |
func ValidateCreateOptions(options *metav1.CreateOptions) field.ErrorList { |
| 175 |
allErrs := field.ErrorList{} |
| 176 |
allErrs = append(allErrs, ValidateFieldManager(options.FieldManager, field.NewPath("fieldManager"))...) |
| 177 |
allErrs = append(allErrs, ValidateDryRun(field.NewPath("dryRun"), options.DryRun)...) |
| 178 |
allErrs = append(allErrs, ValidateFieldValidation(field.NewPath("fieldValidation"), options.FieldValidation)...) |
| 179 |
return allErrs |
| 180 |
} |
| 181 |
|
| 182 |
func ValidateUpdateOptions(options *metav1.UpdateOptions) field.ErrorList { |
| 183 |
allErrs := field.ErrorList{} |
| 184 |
allErrs = append(allErrs, ValidateFieldManager(options.FieldManager, field.NewPath("fieldManager"))...) |
| 185 |
allErrs = append(allErrs, ValidateDryRun(field.NewPath("dryRun"), options.DryRun)...) |
| 186 |
allErrs = append(allErrs, ValidateFieldValidation(field.NewPath("fieldValidation"), options.FieldValidation)...) |
| 187 |
return allErrs |
| 188 |
} |
| 189 |
|
| 190 |
func ValidatePatchOptions(options *metav1.PatchOptions, patchType types.PatchType) field.ErrorList { |
| 191 |
allErrs := field.ErrorList{} |
| 192 |
switch patchType { |
| 193 |
case types.ApplyYAMLPatchType, types.ApplyCBORPatchType: |
| 194 |
if options.FieldManager == "" { |
| 195 |
// This field is defaulted to "kubectl" by kubectl, but HAS TO be explicitly set by controllers. |
| 196 |
allErrs = append(allErrs, field.Required(field.NewPath("fieldManager"), "is required for apply patch")) |
| 197 |
} |
| 198 |
default: |
| 199 |
if options.Force != nil { |
| 200 |
allErrs = append(allErrs, field.Forbidden(field.NewPath("force"), "may not be specified for non-apply patch")) |
| 201 |
} |
| 202 |
} |
| 203 |
allErrs = append(allErrs, ValidateFieldManager(options.FieldManager, field.NewPath("fieldManager"))...) |
| 204 |
allErrs = append(allErrs, ValidateDryRun(field.NewPath("dryRun"), options.DryRun)...) |
| 205 |
allErrs = append(allErrs, ValidateFieldValidation(field.NewPath("fieldValidation"), options.FieldValidation)...) |
| 206 |
return allErrs |
| 207 |
} |
| 208 |
|
| 209 |
var FieldManagerMaxLength = 128 |
| 210 |
|
| 211 |
// ValidateFieldManager valides that the fieldManager is the proper length and |
| 212 |
// only has printable characters. |
| 213 |
func ValidateFieldManager(fieldManager string, fldPath *field.Path) field.ErrorList { |
| 214 |
allErrs := field.ErrorList{} |
| 215 |
// the field can not be set as a `*string`, so a empty string ("") is |
| 216 |
// considered as not set and is defaulted by the rest of the process |
| 217 |
// (unless apply is used, in which case it is required). |
| 218 |
if len(fieldManager) > FieldManagerMaxLength { |
| 219 |
allErrs = append(allErrs, field.TooLong(fldPath, "" /*unused*/, FieldManagerMaxLength)) |
| 220 |
} |
| 221 |
// Verify that all characters are printable. |
| 222 |
for i, r := range fieldManager { |
| 223 |
if !unicode.IsPrint(r) { |
| 224 |
allErrs = append(allErrs, field.Invalid(fldPath, fieldManager, fmt.Sprintf("invalid character %#U (at position %d)", r, i))) |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
return allErrs |
| 229 |
} |
| 230 |
|
| 231 |
var allowedDryRunValues = sets.NewString(metav1.DryRunAll) |
| 232 |
|
| 233 |
// ValidateDryRun validates that a dryRun query param only contains allowed values. |
| 234 |
func ValidateDryRun(fldPath *field.Path, dryRun []string) field.ErrorList { |
| 235 |
allErrs := field.ErrorList{} |
| 236 |
if !allowedDryRunValues.HasAll(dryRun...) { |
| 237 |
allErrs = append(allErrs, field.NotSupported(fldPath, dryRun, allowedDryRunValues.List())) |
| 238 |
} |
| 239 |
return allErrs |
| 240 |
} |
| 241 |
|
| 242 |
var allowedFieldValidationValues = sets.NewString("", metav1.FieldValidationIgnore, metav1.FieldValidationWarn, metav1.FieldValidationStrict) |
| 243 |
|
| 244 |
// ValidateFieldValidation validates that a fieldValidation query param only contains allowed values. |
| 245 |
func ValidateFieldValidation(fldPath *field.Path, fieldValidation string) field.ErrorList { |
| 246 |
allErrs := field.ErrorList{} |
| 247 |
if !allowedFieldValidationValues.Has(fieldValidation) { |
| 248 |
allErrs = append(allErrs, field.NotSupported(fldPath, fieldValidation, allowedFieldValidationValues.List())) |
| 249 |
} |
| 250 |
return allErrs |
| 251 |
|
| 252 |
} |
| 253 |
|
| 254 |
const UninitializedStatusUpdateErrorMsg string = `must not update status when the object is uninitialized` |
| 255 |
|
| 256 |
// ValidateTableOptions returns any invalid flags on TableOptions. |
| 257 |
func ValidateTableOptions(opts *metav1.TableOptions) field.ErrorList { |
| 258 |
var allErrs field.ErrorList |
| 259 |
switch opts.IncludeObject { |
| 260 |
case metav1.IncludeMetadata, metav1.IncludeNone, metav1.IncludeObject, "": |
| 261 |
default: |
| 262 |
allErrs = append(allErrs, field.Invalid(field.NewPath("includeObject"), opts.IncludeObject, "must be 'Metadata', 'Object', 'None', or empty")) |
| 263 |
} |
| 264 |
return allErrs |
| 265 |
} |
| 266 |
|
| 267 |
const MaxSubresourceNameLength = 256 |
| 268 |
|
| 269 |
func ValidateManagedFields(fieldsList []metav1.ManagedFieldsEntry, fldPath *field.Path) field.ErrorList { |
| 270 |
var allErrs field.ErrorList |
| 271 |
for i, fields := range fieldsList { |
| 272 |
fldPath := fldPath.Index(i) |
| 273 |
switch fields.Operation { |
| 274 |
case metav1.ManagedFieldsOperationApply, metav1.ManagedFieldsOperationUpdate: |
| 275 |
default: |
| 276 |
allErrs = append(allErrs, field.Invalid(fldPath.Child("operation"), fields.Operation, "must be `Apply` or `Update`")) |
| 277 |
} |
| 278 |
if len(fields.FieldsType) > 0 && fields.FieldsType != "FieldsV1" { |
| 279 |
allErrs = append(allErrs, field.Invalid(fldPath.Child("fieldsType"), fields.FieldsType, "must be `FieldsV1`")) |
| 280 |
} |
| 281 |
allErrs = append(allErrs, ValidateFieldManager(fields.Manager, fldPath.Child("manager"))...) |
| 282 |
|
| 283 |
if len(fields.Subresource) > MaxSubresourceNameLength { |
| 284 |
allErrs = append(allErrs, field.TooLong(fldPath.Child("subresource"), "" /*unused*/, MaxSubresourceNameLength)) |
| 285 |
} |
| 286 |
} |
| 287 |
return allErrs |
| 288 |
} |
| 289 |
|
| 290 |
func ValidateConditions(conditions []metav1.Condition, fldPath *field.Path) field.ErrorList { |
| 291 |
var allErrs field.ErrorList |
| 292 |
|
| 293 |
conditionTypeToFirstIndex := map[string]int{} |
| 294 |
for i, condition := range conditions { |
| 295 |
if _, ok := conditionTypeToFirstIndex[condition.Type]; ok { |
| 296 |
allErrs = append(allErrs, field.Duplicate(fldPath.Index(i).Child("type"), condition.Type)) |
| 297 |
} else { |
| 298 |
conditionTypeToFirstIndex[condition.Type] = i |
| 299 |
} |
| 300 |
|
| 301 |
allErrs = append(allErrs, ValidateCondition(condition, fldPath.Index(i))...) |
| 302 |
} |
| 303 |
|
| 304 |
return allErrs |
| 305 |
} |
| 306 |
|
| 307 |
// validConditionStatuses is used internally to check validity and provide a good message |
| 308 |
var validConditionStatuses = sets.NewString(string(metav1.ConditionTrue), string(metav1.ConditionFalse), string(metav1.ConditionUnknown)) |
| 309 |
|
| 310 |
const ( |
| 311 |
maxReasonLen = 1 * 1024 |
| 312 |
maxMessageLen = 32 * 1024 |
| 313 |
) |
| 314 |
|
| 315 |
func ValidateCondition(condition metav1.Condition, fldPath *field.Path) field.ErrorList { |
| 316 |
var allErrs field.ErrorList |
| 317 |
|
| 318 |
// type is set and is a valid format |
| 319 |
allErrs = append(allErrs, ValidateLabelName(condition.Type, fldPath.Child("type"))...) |
| 320 |
|
| 321 |
// status is set and is an accepted value |
| 322 |
if !validConditionStatuses.Has(string(condition.Status)) { |
| 323 |
allErrs = append(allErrs, field.NotSupported(fldPath.Child("status"), condition.Status, validConditionStatuses.List())) |
| 324 |
} |
| 325 |
|
| 326 |
if condition.ObservedGeneration < 0 { |
| 327 |
allErrs = append(allErrs, field.Invalid(fldPath.Child("observedGeneration"), condition.ObservedGeneration, "must be greater than or equal to zero")) |
| 328 |
} |
| 329 |
|
| 330 |
if condition.LastTransitionTime.IsZero() { |
| 331 |
allErrs = append(allErrs, field.Required(fldPath.Child("lastTransitionTime"), "must be set")) |
| 332 |
} |
| 333 |
|
| 334 |
if len(condition.Reason) == 0 { |
| 335 |
allErrs = append(allErrs, field.Required(fldPath.Child("reason"), "must be set")) |
| 336 |
} else { |
| 337 |
for _, currErr := range isValidConditionReason(condition.Reason) { |
| 338 |
allErrs = append(allErrs, field.Invalid(fldPath.Child("reason"), condition.Reason, currErr)) |
| 339 |
} |
| 340 |
if len(condition.Reason) > maxReasonLen { |
| 341 |
allErrs = append(allErrs, field.TooLong(fldPath.Child("reason"), "" /*unused*/, maxReasonLen)) |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
if len(condition.Message) > maxMessageLen { |
| 346 |
allErrs = append(allErrs, field.TooLong(fldPath.Child("message"), "" /*unused*/, maxMessageLen)) |
| 347 |
} |
| 348 |
|
| 349 |
return allErrs |
| 350 |
} |
| 351 |
|
| 352 |
const conditionReasonFmt string = "[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?" |
| 353 |
const conditionReasonErrMsg string = "a condition reason must start with alphabetic character, optionally followed by a string of alphanumeric characters or '_,:', and must end with an alphanumeric character or '_'" |
| 354 |
|
| 355 |
var conditionReasonRegexp = regexp.MustCompile("^" + conditionReasonFmt + "$") |
| 356 |
|
| 357 |
// isValidConditionReason tests for a string that conforms to rules for condition reasons. This checks the format, but not the length. |
| 358 |
func isValidConditionReason(value string) []string { |
| 359 |
if !conditionReasonRegexp.MatchString(value) { |
| 360 |
return []string{validation.RegexError(conditionReasonErrMsg, conditionReasonFmt, "my_name", "MY_NAME", "MyName", "ReasonA,ReasonB", "ReasonA:ReasonB")} |
| 361 |
} |
| 362 |
return nil |
| 363 |
} |
| 364 |
|
| 365 |
// ValidateIgnoreStoreReadError validates that delete options are valid when |
| 366 |
// ignoreStoreReadErrorWithClusterBreakingPotential is enabled |
| 367 |
func ValidateIgnoreStoreReadError(fldPath *field.Path, options *metav1.DeleteOptions) field.ErrorList { |
| 368 |
allErrs := field.ErrorList{} |
| 369 |
if enabled := ptr.Deref[bool](options.IgnoreStoreReadErrorWithClusterBreakingPotential, false); !enabled { |
| 370 |
return allErrs |
| 371 |
} |
| 372 |
|
| 373 |
if len(options.DryRun) > 0 { |
| 374 |
allErrs = append(allErrs, field.Invalid(fldPath, true, "cannot be set together with .dryRun")) |
| 375 |
} |
| 376 |
if options.PropagationPolicy != nil { |
| 377 |
allErrs = append(allErrs, field.Invalid(fldPath, true, "cannot be set together with .propagationPolicy")) |
| 378 |
} |
| 379 |
//nolint:staticcheck // Keep validation for deprecated OrphanDependents option until it's being removed |
| 380 |
if options.OrphanDependents != nil { |
| 381 |
allErrs = append(allErrs, field.Invalid(fldPath, true, "cannot be set together with .orphanDependents")) |
| 382 |
} |
| 383 |
if options.GracePeriodSeconds != nil { |
| 384 |
allErrs = append(allErrs, field.Invalid(fldPath, true, "cannot be set together with .gracePeriodSeconds")) |
| 385 |
} |
| 386 |
if options.Preconditions != nil { |
| 387 |
allErrs = append(allErrs, field.Invalid(fldPath, true, "cannot be set together with .preconditions")) |
| 388 |
} |
| 389 |
|
| 390 |
return allErrs |
| 391 |
} |