...

Source file src/github.com/GoogleCloudPlatform/k8s-config-connector/pkg/webhook/resource_validator.go

Documentation: github.com/GoogleCloudPlatform/k8s-config-connector/pkg/webhook

     1  // Copyright 2022 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package webhook
    16  
    17  import (
    18  	"context"
    19  	"net/http"
    20  
    21  	"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/resourceoverrides"
    22  
    23  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    24  	"k8s.io/klog/v2"
    25  	"sigs.k8s.io/controller-runtime/pkg/client"
    26  	"sigs.k8s.io/controller-runtime/pkg/runtime/inject"
    27  	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    28  )
    29  
    30  type resourceValidatorHandler struct {
    31  	client client.Client
    32  }
    33  
    34  // resourceValidatorHandler implements inject.Client.
    35  var _ inject.Client = &resourceValidatorHandler{}
    36  
    37  func NewResourceValidatorHandler() *resourceValidatorHandler {
    38  	return &resourceValidatorHandler{}
    39  }
    40  
    41  // InjectClient injects the client into the noUnknownFieldsValidatorHandler
    42  func (a *resourceValidatorHandler) InjectClient(c client.Client) error {
    43  	a.client = c
    44  	return nil
    45  }
    46  
    47  func (a *resourceValidatorHandler) Handle(ctx context.Context, req admission.Request) admission.Response {
    48  	deserializer := codecs.UniversalDeserializer()
    49  	obj := &unstructured.Unstructured{}
    50  	if _, _, err := deserializer.Decode(req.AdmissionRequest.Object.Raw, nil, obj); err != nil {
    51  		klog.Error(err)
    52  		return admission.Errored(http.StatusBadRequest, err)
    53  	}
    54  	if err := resourceoverrides.Handler.ConfigValidate(obj); err != nil {
    55  		return admission.Errored(http.StatusForbidden, err)
    56  	}
    57  	return admission.ValidationResponse(true, "admission controller passed")
    58  }
    59  

View as plain text