From 08aca1c2c92aba2ba7b299e099048eda5d94237f Mon Sep 17 00:00:00 2001 From: Vince Prignano Date: Mon, 27 Sep 2021 11:58:34 -0700 Subject: [PATCH] :sparkles: Allow webhooks to register custom validators/defaulter types This changeset allows our webhook builder to take in a handler any other struct other than a runtime.Object. Today having an object as the primary source of truth for both Defaulting and Validators makes API types carry a lot of information and business logic alongside their definitions. Moreover, lots of folks in the past have asked for ways to have an external type to handle these operations and use a controller runtime client for validations. This change brings a new way to register webhooks, which admission.For handler any type (struct) can be a defaulting or validating handler for a runtime Object. Signed-off-by: Vince Prignano --- pkg/builder/webhook.go | 78 ++++++++++--- pkg/webhook/admission/defaulter_handler.go | 84 ++++++++++++++ pkg/webhook/admission/validator_handler.go | 125 +++++++++++++++++++++ pkg/webhook/alias.go | 6 + 4 files changed, 275 insertions(+), 18 deletions(-) create mode 100644 pkg/webhook/admission/defaulter_handler.go create mode 100644 pkg/webhook/admission/validator_handler.go diff --git a/pkg/builder/webhook.go b/pkg/builder/webhook.go index d24877d303..a7458f86ce 100644 --- a/pkg/builder/webhook.go +++ b/pkg/builder/webhook.go @@ -17,6 +17,7 @@ limitations under the License. package builder import ( + "errors" "net/http" "net/url" "strings" @@ -32,10 +33,12 @@ import ( // WebhookBuilder builds a Webhook. type WebhookBuilder struct { - apiType runtime.Object - gvk schema.GroupVersionKind - mgr manager.Manager - config *rest.Config + apiType runtime.Object + withDefaulter admission.WithDefaulter + withValidator admission.WithValidator + gvk schema.GroupVersionKind + mgr manager.Manager + config *rest.Config } // WebhookManagedBy allows inform its manager.Manager. @@ -53,6 +56,18 @@ func (blder *WebhookBuilder) For(apiType runtime.Object) *WebhookBuilder { return blder } +// WithDefaulter takes a admission.WithDefaulter interface, a MutatingWebhook will be wired for this type. +func (blder *WebhookBuilder) WithDefaulter(defaulter admission.WithDefaulter) *WebhookBuilder { + blder.withDefaulter = defaulter + return blder +} + +// WithValidator takes a admission.WithValidator interface, a ValidatingWebhook will be wired for this type. +func (blder *WebhookBuilder) WithValidator(validator admission.WithValidator) *WebhookBuilder { + blder.withValidator = validator + return blder +} + // Complete builds the webhook. func (blder *WebhookBuilder) Complete() error { // Set the Config @@ -69,9 +84,13 @@ func (blder *WebhookBuilder) loadRestConfig() { } func (blder *WebhookBuilder) registerWebhooks() error { + typ, err := blder.getType() + if err != nil { + return err + } + // Create webhook(s) for each type - var err error - blder.gvk, err = apiutil.GVKForObject(blder.apiType, blder.mgr.GetScheme()) + blder.gvk, err = apiutil.GVKForObject(typ, blder.mgr.GetScheme()) if err != nil { return err } @@ -88,12 +107,7 @@ func (blder *WebhookBuilder) registerWebhooks() error { // registerDefaultingWebhook registers a defaulting webhook if th. func (blder *WebhookBuilder) registerDefaultingWebhook() { - defaulter, isDefaulter := blder.apiType.(admission.Defaulter) - if !isDefaulter { - log.Info("skip registering a mutating webhook, admission.Defaulter interface is not implemented", "GVK", blder.gvk) - return - } - mwh := admission.DefaultingWebhookFor(defaulter) + mwh := blder.getDefaultingWebhook() if mwh != nil { path := generateMutatePath(blder.gvk) @@ -108,13 +122,21 @@ func (blder *WebhookBuilder) registerDefaultingWebhook() { } } -func (blder *WebhookBuilder) registerValidatingWebhook() { - validator, isValidator := blder.apiType.(admission.Validator) - if !isValidator { - log.Info("skip registering a validating webhook, admission.Validator interface is not implemented", "GVK", blder.gvk) - return +func (blder *WebhookBuilder) getDefaultingWebhook() *admission.Webhook { + if defaulter := blder.withDefaulter; defaulter != nil { + return admission.WithCustomDefaulter(blder.apiType, defaulter) + } + if defaulter, ok := blder.apiType.(admission.Defaulter); ok { + return admission.DefaultingWebhookFor(defaulter) } - vwh := admission.ValidatingWebhookFor(validator) + log.Info( + "skip registering a mutating webhook, object does not implement admission.Defaulter or WithDefaulter wasn't called", + "GVK", blder.gvk) + return nil +} + +func (blder *WebhookBuilder) registerValidatingWebhook() { + vwh := blder.getValidatingWebhook() if vwh != nil { path := generateValidatePath(blder.gvk) @@ -129,6 +151,19 @@ func (blder *WebhookBuilder) registerValidatingWebhook() { } } +func (blder *WebhookBuilder) getValidatingWebhook() *admission.Webhook { + if validator := blder.withValidator; validator != nil { + return admission.WithCustomValidator(blder.apiType, validator) + } + if validator, ok := blder.apiType.(admission.Validator); ok { + return admission.ValidatingWebhookFor(validator) + } + log.Info( + "skip registering a validating webhook, object does not implement admission.Validator or WithValidator wasn't called", + "GVK", blder.gvk) + return nil +} + func (blder *WebhookBuilder) registerConversionWebhook() error { ok, err := conversion.IsConvertible(blder.mgr.GetScheme(), blder.apiType) if err != nil { @@ -145,6 +180,13 @@ func (blder *WebhookBuilder) registerConversionWebhook() error { return nil } +func (blder *WebhookBuilder) getType() (runtime.Object, error) { + if blder.apiType != nil { + return blder.apiType, nil + } + return nil, errors.New("For() must be called with a valid object") +} + func (blder *WebhookBuilder) isAlreadyHandled(path string) bool { if blder.mgr.GetWebhookServer().WebhookMux == nil { return false diff --git a/pkg/webhook/admission/defaulter_handler.go b/pkg/webhook/admission/defaulter_handler.go new file mode 100644 index 0000000000..9defbd53e3 --- /dev/null +++ b/pkg/webhook/admission/defaulter_handler.go @@ -0,0 +1,84 @@ +/* +Copyright 2018 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 admission + +import ( + "context" + "encoding/json" + goerrors "errors" + "net/http" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime" +) + +// WithDefaulter defines functions for setting defaults on resources. +type WithDefaulter interface { + Default(ctx context.Context, obj runtime.Object) error +} + +// WithCustomDefaulter creates a new Webhook for a WithDefaulter interface. +func WithCustomDefaulter(obj runtime.Object, defaulter WithDefaulter) *Webhook { + return &Webhook{ + Handler: &defaulterForType{object: obj, defaulter: defaulter}, + } +} + +type defaulterForType struct { + defaulter WithDefaulter + object runtime.Object + decoder *Decoder +} + +var _ DecoderInjector = &defaulterForType{} + +func (h *defaulterForType) InjectDecoder(d *Decoder) error { + h.decoder = d + return nil +} + +// Handle handles admission requests. +func (h *defaulterForType) Handle(ctx context.Context, req Request) Response { + if h.defaulter == nil { + panic("defaulter should never be nil") + } + if h.object == nil { + panic("object should never be nil") + } + + // Get the object in the request + obj := h.object.DeepCopyObject() + if err := h.decoder.Decode(req, obj); err != nil { + return Errored(http.StatusBadRequest, err) + } + + // Default the object + if err := h.defaulter.Default(ctx, obj); err != nil { + var apiStatus apierrors.APIStatus + if goerrors.As(err, &apiStatus) { + return validationResponseFromStatus(false, apiStatus.Status()) + } + return Denied(err.Error()) + } + marshalled, err := json.Marshal(obj) + if err != nil { + return Errored(http.StatusInternalServerError, err) + } + + // Create the patch + return PatchResponseFromRaw(req.Object.Raw, marshalled) +} diff --git a/pkg/webhook/admission/validator_handler.go b/pkg/webhook/admission/validator_handler.go new file mode 100644 index 0000000000..6cbb84662b --- /dev/null +++ b/pkg/webhook/admission/validator_handler.go @@ -0,0 +1,125 @@ +/* +Copyright 2018 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 admission + +import ( + "context" + goerrors "errors" + "net/http" + + v1 "k8s.io/api/admission/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime" +) + +// WithValidator defines functions for validating an operation. +type WithValidator interface { + ValidateCreate(ctx context.Context, obj runtime.Object) error + ValidateUpdate(ctx context.Context, old runtime.Object, new runtime.Object) error + ValidateDelete(ctx context.Context, obj runtime.Object) error +} + +// WithCustomValidator creates a new Webhook for validating the provided type. +func WithCustomValidator(obj runtime.Object, validator WithValidator) *Webhook { + return &Webhook{ + Handler: &validatorForType{object: obj, validator: validator}, + } +} + +type validatorForType struct { + validator WithValidator + object runtime.Object + decoder *Decoder +} + +var _ DecoderInjector = &validatorForType{} + +// InjectDecoder injects the decoder into a validatingHandler. +func (h *validatorForType) InjectDecoder(d *Decoder) error { + h.decoder = d + return nil +} + +// Handle handles admission requests. +func (h *validatorForType) Handle(ctx context.Context, req Request) Response { + if h.validator == nil { + panic("validator should never be nil") + } + if h.object == nil { + panic("object should never be nil") + } + + // Get the object in the request + obj := h.object.DeepCopyObject() + if req.Operation == v1.Create { + err := h.decoder.Decode(req, obj) + if err != nil { + return Errored(http.StatusBadRequest, err) + } + + err = h.validator.ValidateCreate(ctx, obj) + if err != nil { + var apiStatus apierrors.APIStatus + if goerrors.As(err, &apiStatus) { + return validationResponseFromStatus(false, apiStatus.Status()) + } + return Denied(err.Error()) + } + } + + if req.Operation == v1.Update { + oldObj := obj.DeepCopyObject() + + err := h.decoder.DecodeRaw(req.Object, obj) + if err != nil { + return Errored(http.StatusBadRequest, err) + } + err = h.decoder.DecodeRaw(req.OldObject, oldObj) + if err != nil { + return Errored(http.StatusBadRequest, err) + } + + err = h.validator.ValidateUpdate(ctx, oldObj, obj) + if err != nil { + var apiStatus apierrors.APIStatus + if goerrors.As(err, &apiStatus) { + return validationResponseFromStatus(false, apiStatus.Status()) + } + return Denied(err.Error()) + } + } + + if req.Operation == v1.Delete { + // In reference to PR: https://github.com/kubernetes/kubernetes/pull/76346 + // OldObject contains the object being deleted + err := h.decoder.DecodeRaw(req.OldObject, obj) + if err != nil { + return Errored(http.StatusBadRequest, err) + } + + err = h.validator.ValidateDelete(ctx, obj) + if err != nil { + var apiStatus apierrors.APIStatus + if goerrors.As(err, &apiStatus) { + return validationResponseFromStatus(false, apiStatus.Status()) + } + return Denied(err.Error()) + } + } + + return Allowed("") +} diff --git a/pkg/webhook/alias.go b/pkg/webhook/alias.go index 1a831016af..3c54137255 100644 --- a/pkg/webhook/alias.go +++ b/pkg/webhook/alias.go @@ -29,6 +29,12 @@ type Defaulter = admission.Defaulter // Validator defines functions for validating an operation. type Validator = admission.Validator +// WithDefaulter defines functions for setting defaults on resources. +type WithDefaulter = admission.WithDefaulter + +// WithValidator defines functions for validating an operation. +type WithValidator = admission.WithValidator + // AdmissionRequest defines the input for an admission handler. // It contains information to identify the object in // question (group, version, kind, resource, subresource,