secretstore_validator.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package v1beta1
  13. import (
  14. "context"
  15. "errors"
  16. "fmt"
  17. "regexp"
  18. "k8s.io/apimachinery/pkg/runtime"
  19. "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
  20. )
  21. var _ admission.CustomValidator = &GenericStoreValidator{}
  22. const (
  23. errInvalidStore = "invalid store"
  24. )
  25. type GenericStoreValidator struct{}
  26. // ValidateCreate implements webhook.Validator so a webhook will be registered for the type.
  27. func (r *GenericStoreValidator) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) {
  28. st, ok := obj.(GenericStore)
  29. if !ok {
  30. return nil, errors.New(errInvalidStore)
  31. }
  32. return validateStore(st)
  33. }
  34. // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type.
  35. func (r *GenericStoreValidator) ValidateUpdate(_ context.Context, _, newObj runtime.Object) (admission.Warnings, error) {
  36. st, ok := newObj.(GenericStore)
  37. if !ok {
  38. return nil, errors.New(errInvalidStore)
  39. }
  40. return validateStore(st)
  41. }
  42. // ValidateDelete implements webhook.Validator so a webhook will be registered for the type.
  43. func (r *GenericStoreValidator) ValidateDelete(_ context.Context, _ runtime.Object) (admission.Warnings, error) {
  44. return nil, nil
  45. }
  46. func validateStore(store GenericStore) (admission.Warnings, error) {
  47. if err := validateConditions(store); err != nil {
  48. return nil, err
  49. }
  50. provider, err := GetProvider(store)
  51. if err != nil {
  52. return nil, err
  53. }
  54. return provider.ValidateStore(store)
  55. }
  56. func validateConditions(store GenericStore) error {
  57. var errs error
  58. for ci, condition := range store.GetSpec().Conditions {
  59. for ri, r := range condition.NamespaceRegexes {
  60. if _, err := regexp.Compile(r); err != nil {
  61. errs = errors.Join(errs, fmt.Errorf("failed to compile %dth namespace regex in %dth condition: %w", ri, ci, err))
  62. }
  63. }
  64. }
  65. return errs
  66. }