2019-07-15 16:07:56 -07:00
|
|
|
package webhooks
|
|
|
|
|
|
|
|
import (
|
2021-07-09 18:01:46 -07:00
|
|
|
"fmt"
|
2020-02-29 22:39:27 +05:30
|
|
|
"reflect"
|
2020-01-16 11:57:28 -08:00
|
|
|
"time"
|
|
|
|
|
2021-07-09 18:01:46 -07:00
|
|
|
"github.com/kyverno/kyverno/pkg/common"
|
|
|
|
|
2021-05-15 19:15:04 +05:30
|
|
|
"github.com/go-logr/logr"
|
2020-10-07 11:12:31 -07:00
|
|
|
kyverno "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
|
|
|
|
v1 "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
|
|
|
|
"github.com/kyverno/kyverno/pkg/engine"
|
|
|
|
"github.com/kyverno/kyverno/pkg/engine/response"
|
|
|
|
engineutils "github.com/kyverno/kyverno/pkg/engine/utils"
|
2021-05-15 19:15:04 +05:30
|
|
|
"github.com/kyverno/kyverno/pkg/metrics"
|
2021-07-23 21:46:50 +05:30
|
|
|
policyExecutionDuration "github.com/kyverno/kyverno/pkg/metrics/policyexecutionduration"
|
|
|
|
policyResults "github.com/kyverno/kyverno/pkg/metrics/policyresults"
|
2021-06-10 07:04:10 +05:30
|
|
|
"github.com/kyverno/kyverno/pkg/utils"
|
2021-07-09 18:01:46 -07:00
|
|
|
"github.com/pkg/errors"
|
2019-07-15 16:07:56 -07:00
|
|
|
v1beta1 "k8s.io/api/admission/v1beta1"
|
2021-06-10 07:04:10 +05:30
|
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
2020-01-06 19:24:24 -08:00
|
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
2019-07-15 16:07:56 -07:00
|
|
|
)
|
|
|
|
|
2021-07-09 18:01:46 -07:00
|
|
|
func (ws *WebhookServer) applyMutatePolicies(request *v1beta1.AdmissionRequest, policyContext *engine.PolicyContext, policies []*v1.ClusterPolicy, ts int64, logger logr.Logger) []byte {
|
|
|
|
var mutateEngineResponses []*response.EngineResponse
|
|
|
|
|
2021-07-23 21:46:50 +05:30
|
|
|
mutatePatches, mutateEngineResponses := ws.handleMutation(request, policyContext, policies)
|
2021-07-09 18:01:46 -07:00
|
|
|
logger.V(6).Info("", "generated patches", string(mutatePatches))
|
|
|
|
|
|
|
|
admissionReviewLatencyDuration := int64(time.Since(time.Unix(ts, 0)))
|
2021-07-23 21:46:50 +05:30
|
|
|
go registerAdmissionReviewDurationMetricMutate(logger, *ws.promConfig.Metrics, string(request.Operation), mutateEngineResponses, admissionReviewLatencyDuration)
|
|
|
|
go registerAdmissionRequestsMetricMutate(logger, *ws.promConfig.Metrics, string(request.Operation), mutateEngineResponses)
|
2021-07-09 18:01:46 -07:00
|
|
|
|
|
|
|
return mutatePatches
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleMutation handles mutating webhook admission request
|
2021-05-15 23:33:41 +05:30
|
|
|
// return value: generated patches, triggered policies, engine responses correspdonding to the triggered policies
|
2021-07-09 18:01:46 -07:00
|
|
|
func (ws *WebhookServer) handleMutation(
|
2020-05-17 14:37:05 -07:00
|
|
|
request *v1beta1.AdmissionRequest,
|
2021-07-09 18:01:46 -07:00
|
|
|
policyContext *engine.PolicyContext,
|
2021-07-23 21:46:50 +05:30
|
|
|
policies []*kyverno.ClusterPolicy) ([]byte, []*response.EngineResponse) {
|
2020-05-17 14:37:05 -07:00
|
|
|
|
2020-07-02 12:49:10 -07:00
|
|
|
if len(policies) == 0 {
|
2021-07-23 21:46:50 +05:30
|
|
|
return nil, nil
|
2020-07-02 12:49:10 -07:00
|
|
|
}
|
|
|
|
|
2020-05-17 14:37:05 -07:00
|
|
|
resourceName := request.Kind.Kind + "/" + request.Name
|
|
|
|
if request.Namespace != "" {
|
|
|
|
resourceName = request.Namespace + "/" + resourceName
|
|
|
|
}
|
|
|
|
|
2021-05-13 12:03:13 -07:00
|
|
|
logger := ws.log.WithValues("action", "mutate", "resource", resourceName, "operation", request.Operation, "gvk", request.Kind.String())
|
2021-07-09 18:01:46 -07:00
|
|
|
|
|
|
|
patchedResource := request.Object.Raw
|
2021-06-10 07:04:10 +05:30
|
|
|
newR, oldR, err := utils.ExtractResources(patchedResource, request)
|
|
|
|
if err != nil {
|
|
|
|
// as resource cannot be parsed, we skip processing
|
|
|
|
logger.Error(err, "failed to extract resource")
|
2021-07-23 21:46:50 +05:30
|
|
|
return nil, nil
|
2021-06-10 07:04:10 +05:30
|
|
|
}
|
|
|
|
var deletionTimeStamp *metav1.Time
|
|
|
|
if reflect.DeepEqual(newR, unstructured.Unstructured{}) {
|
|
|
|
deletionTimeStamp = newR.GetDeletionTimestamp()
|
|
|
|
} else {
|
|
|
|
deletionTimeStamp = oldR.GetDeletionTimestamp()
|
|
|
|
}
|
2019-08-23 18:34:23 -07:00
|
|
|
|
2021-06-10 07:04:10 +05:30
|
|
|
if deletionTimeStamp != nil && request.Operation == v1beta1.Update {
|
2021-07-23 21:46:50 +05:30
|
|
|
return nil, nil
|
2021-06-10 07:04:10 +05:30
|
|
|
}
|
2019-08-09 12:59:37 -07:00
|
|
|
var patches [][]byte
|
2020-12-23 15:10:07 -08:00
|
|
|
var engineResponses []*response.EngineResponse
|
2020-06-25 17:24:10 -07:00
|
|
|
|
2019-11-08 18:57:27 -08:00
|
|
|
for _, policy := range policies {
|
2021-07-09 18:01:46 -07:00
|
|
|
if !policy.HasMutate() {
|
2019-08-09 12:59:37 -07:00
|
|
|
continue
|
2019-07-15 16:07:56 -07:00
|
|
|
}
|
2020-05-17 14:37:05 -07:00
|
|
|
|
2021-07-09 18:01:46 -07:00
|
|
|
logger.V(3).Info("applying policy mutate rules", "policy", policy.Name)
|
|
|
|
policyContext.Policy = *policy
|
|
|
|
engineResponse, policyPatches, err := ws.applyMutation(request, policyContext, logger)
|
2020-03-04 19:27:08 +05:30
|
|
|
if err != nil {
|
2021-07-09 18:01:46 -07:00
|
|
|
// TODO report errors in engineResponse and record in metrics
|
|
|
|
logger.Error(err, "mutate error")
|
2020-03-04 19:27:08 +05:30
|
|
|
continue
|
|
|
|
}
|
2020-05-17 14:37:05 -07:00
|
|
|
|
2020-06-30 11:53:27 -07:00
|
|
|
if len(policyPatches) > 0 {
|
|
|
|
patches = append(patches, policyPatches...)
|
|
|
|
rules := engineResponse.GetSuccessRules()
|
2020-07-09 11:48:34 -07:00
|
|
|
logger.Info("mutation rules from policy applied successfully", "policy", policy.Name, "rules", rules)
|
2020-05-15 13:11:28 -07:00
|
|
|
}
|
2020-01-15 18:15:48 -08:00
|
|
|
|
|
|
|
policyContext.NewResource = engineResponse.PatchedResource
|
2020-06-01 19:37:48 -07:00
|
|
|
engineResponses = append(engineResponses, engineResponse)
|
2021-05-15 19:15:04 +05:30
|
|
|
|
2021-07-23 21:46:50 +05:30
|
|
|
// registering the kyverno_policy_results_total metric concurrently
|
|
|
|
go ws.registerPolicyResultsMetricMutation(logger, string(request.Operation), *policy, *engineResponse)
|
2021-05-15 21:34:26 +05:30
|
|
|
|
2021-07-23 21:46:50 +05:30
|
|
|
// registering the kyverno_policy_execution_duration_seconds metric concurrently
|
|
|
|
go ws.registerPolicyExecutionDurationMetricMutate(logger, string(request.Operation), *policy, *engineResponse)
|
2019-07-15 16:07:56 -07:00
|
|
|
}
|
|
|
|
|
2019-10-07 18:31:14 -07:00
|
|
|
// generate annotations
|
2020-03-17 11:05:20 -07:00
|
|
|
if annPatches := generateAnnotationPatches(engineResponses, logger); annPatches != nil {
|
2019-10-07 18:31:14 -07:00
|
|
|
patches = append(patches, annPatches)
|
|
|
|
}
|
|
|
|
|
2020-02-19 19:24:34 -08:00
|
|
|
// REPORTING EVENTS
|
|
|
|
// Scenario 1:
|
2020-06-30 11:53:27 -07:00
|
|
|
// some/all policies failed to apply on the resource. a policy violation is generated.
|
2020-02-19 19:24:34 -08:00
|
|
|
// create an event on the resource and the policy that failed
|
|
|
|
// Scenario 2:
|
2020-06-30 11:53:27 -07:00
|
|
|
// all policies were applied successfully.
|
2020-02-19 19:24:34 -08:00
|
|
|
// create an event on the resource
|
2019-08-09 12:59:37 -07:00
|
|
|
// ADD EVENTS
|
2020-03-17 11:05:20 -07:00
|
|
|
events := generateEvents(engineResponses, false, (request.Operation == v1beta1.Update), logger)
|
2019-08-26 13:34:42 -07:00
|
|
|
ws.eventGen.Add(events...)
|
|
|
|
|
2020-01-15 21:46:58 -08:00
|
|
|
// debug info
|
2020-01-16 11:57:28 -08:00
|
|
|
func() {
|
|
|
|
if len(patches) != 0 {
|
2020-03-17 11:05:20 -07:00
|
|
|
logger.V(4).Info("JSON patches generated")
|
2020-01-16 11:57:28 -08:00
|
|
|
}
|
2020-01-15 21:46:58 -08:00
|
|
|
|
2020-01-16 11:57:28 -08:00
|
|
|
// if any of the policies fails, print out the error
|
2020-12-01 22:50:40 -08:00
|
|
|
if !isResponseSuccessful(engineResponses) {
|
2021-03-16 00:34:21 +02:00
|
|
|
logger.Error(errors.New(getErrorMsg(engineResponses)), "failed to apply mutation rules on the resource, reporting policy violation")
|
2020-01-16 11:57:28 -08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// patches holds all the successful patches, if no patch is created, it returns nil
|
2021-07-23 21:46:50 +05:30
|
|
|
return engineutils.JoinPatches(patches), engineResponses
|
2019-07-15 16:07:56 -07:00
|
|
|
}
|
2020-02-29 22:39:27 +05:30
|
|
|
|
2021-07-09 18:01:46 -07:00
|
|
|
func (ws *WebhookServer) applyMutation(request *v1beta1.AdmissionRequest, policyContext *engine.PolicyContext, logger logr.Logger) (*response.EngineResponse, [][]byte, error) {
|
|
|
|
if request.Kind.Kind != "Namespace" && request.Namespace != "" {
|
|
|
|
policyContext.NamespaceLabels = common.GetNamespaceSelectorsFromNamespaceLister(
|
|
|
|
request.Kind.Kind, request.Namespace, ws.nsLister, logger)
|
|
|
|
}
|
|
|
|
|
|
|
|
engineResponse := engine.Mutate(policyContext)
|
|
|
|
policyPatches := engineResponse.GetPatches()
|
|
|
|
|
|
|
|
if !engineResponse.IsSuccessful() && len(engineResponse.GetFailedRules()) > 0 {
|
|
|
|
return nil, nil, fmt.Errorf("failed to apply policy %s rules %v", policyContext.Policy.Name, engineResponse.GetFailedRules())
|
|
|
|
}
|
|
|
|
|
|
|
|
err := ws.openAPIController.ValidateResource(*engineResponse.PatchedResource.DeepCopy(), engineResponse.PatchedResource.GetAPIVersion(), engineResponse.PatchedResource.GetKind())
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, errors.Wrapf(err, "failed to validate resource mutated by policy %s", policyContext.Policy.Name)
|
|
|
|
}
|
|
|
|
|
|
|
|
return engineResponse, policyPatches, nil
|
|
|
|
}
|
|
|
|
|
2021-07-23 21:46:50 +05:30
|
|
|
func (ws *WebhookServer) registerPolicyResultsMetricMutation(logger logr.Logger, resourceRequestOperation string, policy kyverno.ClusterPolicy, engineResponse response.EngineResponse) {
|
|
|
|
resourceRequestOperationPromAlias, err := policyResults.ParseResourceRequestOperation(resourceRequestOperation)
|
2021-05-15 19:15:04 +05:30
|
|
|
if err != nil {
|
2021-07-23 21:46:50 +05:30
|
|
|
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.Name)
|
2021-05-15 19:15:04 +05:30
|
|
|
}
|
2021-07-23 21:46:50 +05:30
|
|
|
if err := policyResults.ParsePromMetrics(*ws.promConfig.Metrics).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, resourceRequestOperationPromAlias); err != nil {
|
|
|
|
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.Name)
|
2021-05-15 19:15:04 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-23 21:46:50 +05:30
|
|
|
func (ws *WebhookServer) registerPolicyExecutionDurationMetricMutate(logger logr.Logger, resourceRequestOperation string, policy kyverno.ClusterPolicy, engineResponse response.EngineResponse) {
|
|
|
|
resourceRequestOperationPromAlias, err := policyExecutionDuration.ParseResourceRequestOperation(resourceRequestOperation)
|
2021-05-15 21:34:26 +05:30
|
|
|
if err != nil {
|
2021-07-23 21:46:50 +05:30
|
|
|
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.Name)
|
2021-05-15 21:34:26 +05:30
|
|
|
}
|
2021-07-23 21:46:50 +05:30
|
|
|
if err := policyExecutionDuration.ParsePromMetrics(*ws.promConfig.Metrics).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", resourceRequestOperationPromAlias); err != nil {
|
|
|
|
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.Name)
|
2021-05-15 21:34:26 +05:30
|
|
|
}
|
|
|
|
}
|