func Validate(policy *kyverno.ClusterPolicy, client *dclient.Client, mock bool, openAPIController *openapi.Controller) error {
	p := *policy
	namespacedPolicyBool := false
	clusterResources := make([]string, 0)
	if len(common.PolicyHasVariables(p)) > 0 {
		err := common.PolicyHasNonAllowedVariables(p)
		if err != nil {
			return fmt.Errorf("policy contains invalid variables: %s", err.Error())
		}
	}
	if len(p.Name) > 63 {
		return fmt.Errorf("invalid policy name %s: must be no more than 63 characters", p.Name)
	}
	if path, err := validateUniqueRuleName(p); err != nil {
		return fmt.Errorf("path: spec.%s: %v", path, err)
	}
	if p.Spec.Background == nil || *p.Spec.Background {
		if err := ContainsVariablesOtherThanObject(p); err != nil {
			return fmt.Errorf("only select variables are allowed in background mode. Set spec.background=false to disable background mode for this policy rule: %s ", err)
		}
	}
	if p.ObjectMeta.Namespace != "" {
		namespacedPolicyBool = true
	}
	var res []*metav1.APIResourceList
	if !mock && namespacedPolicyBool {
		var Empty struct{}
		clusterResourcesMap := make(map[string]*struct{})
		res, err := client.DiscoveryClient.DiscoveryCache().ServerPreferredResources()
		if err != nil {
			return err
		}
		for _, resList := range res {
			for _, r := range resList.APIResources {
				if !r.Namespaced {
					if _, ok := clusterResourcesMap[r.Kind]; !ok {
						clusterResourcesMap[r.Kind] = &Empty
					}
				}
			}
		}
		for k := range clusterResourcesMap {
			clusterResources = append(clusterResources, k)
		}
	}
	for i, rule := range p.Spec.Rules {
		if err := validateJSONPatchPathForForwardSlash(rule.Mutation.PatchesJSON6902); err != nil {
			return fmt.Errorf("path must begin with a forward slash: spec.rules[%d]: %s", i, err)
		}
		if jsonPatchOnPod(rule) {
			log.Log.V(1).Info("pods managed by workload controllers cannot be mutated using policies, use the auto-gen feature or write policies that match pod controllers")
		}
		if path, err := validateResources(rule); err != nil {
			return fmt.Errorf("path: spec.rules[%d].%s: %v", i, path, err)
		}
		if err := validateRuleType(rule); err != nil {
			return fmt.Errorf("path: spec.rules[%d]: %v", i, err)
		}
		err := validateElementInForEach(rule)
		if err != nil {
			return err
		}
		if err := validateRuleContext(rule); err != nil {
			return fmt.Errorf("path: spec.rules[%d]: %v", i, err)
		}
		if namespacedPolicyBool {
			return checkClusterResourceInMatchAndExclude(rule, clusterResources, mock, res)
		}
		if doMatchAndExcludeConflict(rule) {
			return fmt.Errorf("path: spec.rules[%v]: rule is matching an empty set", rule.Name)
		}
		if err := validateActions(i, &p.Spec.Rules[i], client, mock); err != nil {
			return err
		}
		if len(rule.MatchResources.Any) > 0 {
			for _, rmr := range rule.MatchResources.Any {
				if len(rmr.Kinds) == 0 {
					return validateMatchKindHelper(rule)
				}
			}
		} else if len(rule.MatchResources.All) > 0 {
			for _, rmr := range rule.MatchResources.All {
				if len(rmr.Kinds) == 0 {
					return validateMatchKindHelper(rule)
				}
			}
		} else {
			if len(rule.MatchResources.Kinds) == 0 {
				return validateMatchKindHelper(rule)
			}
		}
		if utils.ContainsString(rule.MatchResources.Kinds, "*") && (p.Spec.Background == nil || *p.Spec.Background) {
			return fmt.Errorf("wildcard policy not allowed in background mode. Set spec.background=false to disable background mode for this policy rule ")
		}
		if (utils.ContainsString(rule.MatchResources.Kinds, "*") && len(rule.MatchResources.Kinds) > 1) || (utils.ContainsString(rule.ExcludeResources.Kinds, "*") && len(rule.ExcludeResources.Kinds) > 1) {
			return fmt.Errorf("wildard policy can not deal more than one kind")
		}
		if utils.ContainsString(rule.MatchResources.Kinds, "*") || utils.ContainsString(rule.ExcludeResources.Kinds, "*") {
			if rule.HasGenerate() || rule.HasVerifyImages() || rule.Validation.ForEachValidation != nil {
				return fmt.Errorf("wildcard policy does not support rule type")
			}
			if rule.HasValidate() {
				if rule.Validation.Pattern != nil || rule.Validation.AnyPattern != nil {
					if !ruleOnlyDealsWithResourceMetaData(rule) {
						return fmt.Errorf("policy can only deal with the metadata field of the resource if" +
							" the rule does not match any kind")
					}
				}
				if rule.Validation.Deny != nil {
					kyvernoConditions, _ := utils.ApiextensionsJsonToKyvernoConditions(rule.Validation.Deny.AnyAllConditions)
					switch typedConditions := kyvernoConditions.(type) {
					case []kyverno.Condition:  
						for _, condition := range typedConditions {
							if !strings.Contains(condition.Key.(string), "request.object.metadata.") && (!common.WildCardAllowedVariables.MatchString(condition.Key.(string)) || strings.Contains(condition.Key.(string), "request.object.spec")) {
								return fmt.Errorf("policy can only deal with the metadata field of the resource if" +
									" the rule does not match any kind")
							}
						}
					}
				}
			}
			if rule.HasMutate() {
				if !ruleOnlyDealsWithResourceMetaData(rule) {
					return fmt.Errorf("policy can only deal with the metadata field of the resource if" +
						" the rule does not match any kind")
				}
			}
		}
		match := rule.MatchResources
		exclude := rule.ExcludeResources
		for _, value := range match.Any {
			err := validateKinds(value.ResourceDescription.Kinds, mock, client, p)
			if err != nil {
				return fmt.Errorf("the kind defined in the any match resource is invalid")
			}
		}
		for _, value := range match.All {
			err := validateKinds(value.ResourceDescription.Kinds, mock, client, p)
			if err != nil {
				return fmt.Errorf("the kind defined in the all match resource is invalid")
			}
		}
		for _, value := range exclude.Any {
			err := validateKinds(value.ResourceDescription.Kinds, mock, client, p)
			if err != nil {
				return fmt.Errorf("the kind defined in the any exclude resource is invalid")
			}
		}
		for _, value := range exclude.All {
			err := validateKinds(value.ResourceDescription.Kinds, mock, client, p)
			if err != nil {
				return fmt.Errorf("the kind defined in the all exclude resource is invalid")
			}
		}
		if !utils.ContainsString(rule.MatchResources.Kinds, "*") {
			err := validateKinds(rule.MatchResources.Kinds, mock, client, p)
			if err != nil {
				return errors.Wrapf(err, "match resource kind is invalid")
			}
			err = validateKinds(rule.ExcludeResources.Kinds, mock, client, p)
			if err != nil {
				return errors.Wrapf(err, "exclude resource kind is invalid")
			}
		}
		if !isLabelAndAnnotationsString(rule) {
			return fmt.Errorf("labels and annotations supports only string values, \"use double quotes around the non string values\"")
		}
		if !mock && rule.Generation.Clone.Name != "" {
			obj, err := client.GetResource("", rule.Generation.Kind, rule.Generation.Clone.Namespace, rule.Generation.Clone.Name)
			if err != nil {
				log.Log.Error(err, fmt.Sprintf("source resource %s/%s/%s not found.", rule.Generation.Kind, rule.Generation.Clone.Namespace, rule.Generation.Clone.Name))
				continue
			}
			updateSource := true
			label := obj.GetLabels()
			if len(label) == 0 {
				label = make(map[string]string)
				label["generate.kyverno.io/clone-policy-name"] = p.GetName()
			} else {
				if label["generate.kyverno.io/clone-policy-name"] != "" {
					policyNames := label["generate.kyverno.io/clone-policy-name"]
					if !strings.Contains(policyNames, p.GetName()) {
						policyNames = policyNames + "," + p.GetName()
						label["generate.kyverno.io/clone-policy-name"] = policyNames
					} else {
						updateSource = false
					}
				} else {
					label["generate.kyverno.io/clone-policy-name"] = p.GetName()
				}
			}
			if updateSource {
				log.Log.V(4).Info("updating existing clone source")
				obj.SetLabels(label)
				_, err = client.UpdateResource(obj.GetAPIVersion(), rule.Generation.Kind, rule.Generation.Clone.Namespace, obj, false)
				if err != nil {
					log.Log.Error(err, "failed to update source", "kind", obj.GetKind(), "name", obj.GetName(), "namespace", obj.GetNamespace())
					continue
				}
				log.Log.V(4).Info("updated source", "kind", obj.GetKind(), "name", obj.GetName(), "namespace", obj.GetNamespace())
			}
		}
	}
	if !mock {
		if err := openAPIController.ValidatePolicyFields(p); err != nil {
			return err
		}
	} else {
		if err := openAPIController.ValidatePolicyMutation(p); err != nil {
			return err
		}
	}
	return nil
}
Validate does some initial check to verify some conditions
- One operation per rule
- ResourceDescription mandatory checks
package policy
import (
	"encoding/json"
	"fmt"
	"reflect"
	"regexp"
	"strings"
	jsonpatch "github.com/evanphx/json-patch/v5"
	"github.com/jmespath/go-jmespath"
	kyverno "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
	comn "github.com/kyverno/kyverno/pkg/common"
	dclient "github.com/kyverno/kyverno/pkg/dclient"
	"github.com/kyverno/kyverno/pkg/engine"
	"github.com/kyverno/kyverno/pkg/engine/variables"
	"github.com/kyverno/kyverno/pkg/kyverno/common"
	"github.com/kyverno/kyverno/pkg/openapi"
	"github.com/kyverno/kyverno/pkg/utils"
	"github.com/minio/pkg/wildcard"
	errors "github.com/pkg/errors"
	rbacv1 "k8s.io/api/rbac/v1"
	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/yaml"
	log "sigs.k8s.io/controller-runtime/pkg/log"
)
func validateJSONPatchPathForForwardSlash(patch string) error {
	re, err := regexp.Compile("^/")
	if err != nil {
		return err
	}
	jsonPatch, err := yaml.ToJSON([]byte(patch))
	if err != nil {
		return err
	}
	decodedPatch, err := jsonpatch.DecodePatch(jsonPatch)
	if err != nil {
		return err
	}
	for _, operation := range decodedPatch {
		path, err := operation.Path()
		if err != nil {
			return err
		}
		val := re.MatchString(path)
		if !val {
			return fmt.Errorf("%s", path)
		}
	}
	return nil
}