1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-15 17:51:20 +00:00
kyverno/pkg/engine/validation.go

359 lines
12 KiB
Go
Raw Normal View History

2019-05-14 01:17:28 +00:00
package engine
import (
"fmt"
"reflect"
"strings"
2019-08-19 23:40:10 +00:00
"time"
2019-05-16 16:31:02 +00:00
2020-03-17 18:05:20 +00:00
"github.com/go-logr/logr"
gojmespath "github.com/jmespath/go-jmespath"
kyverno "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/engine/common"
"github.com/kyverno/kyverno/pkg/engine/context"
"github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/engine/utils"
"github.com/kyverno/kyverno/pkg/engine/validate"
"github.com/kyverno/kyverno/pkg/engine/variables"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2020-03-17 23:25:34 +00:00
"sigs.k8s.io/controller-runtime/pkg/log"
)
2019-09-03 22:48:13 +00:00
//Validate applies validation rules from policy on the resource
2020-12-23 23:10:07 +00:00
func Validate(policyContext *PolicyContext) (resp *response.EngineResponse) {
resp = &response.EngineResponse{}
2019-09-03 22:48:13 +00:00
startTime := time.Now()
2020-12-23 23:10:07 +00:00
logger := buildLogger(policyContext)
logger.V(4).Info("start policy processing", "startTime", startTime)
2020-05-05 15:28:02 +00:00
defer func() {
2020-12-23 23:10:07 +00:00
buildResponse(logger, policyContext, resp, startTime)
logger.V(4).Info("finished policy processing", "processingTime", resp.PolicyResponse.ProcessingTime.String(), "validationRulesApplied", resp.PolicyResponse.RulesAppliedCount)
2020-05-05 15:28:02 +00:00
}()
2020-12-24 02:46:12 +00:00
resp = validateResource(logger, policyContext)
return
2020-12-23 23:10:07 +00:00
}
func buildLogger(ctx *PolicyContext) logr.Logger {
logger := log.Log.WithName("EngineValidate").WithValues("policy", ctx.Policy.Name)
if reflect.DeepEqual(ctx.NewResource, unstructured.Unstructured{}) {
logger = logger.WithValues("kind", ctx.OldResource.GetKind(), "namespace", ctx.OldResource.GetNamespace(), "name", ctx.OldResource.GetName())
} else {
logger = logger.WithValues("kind", ctx.NewResource.GetKind(), "namespace", ctx.NewResource.GetNamespace(), "name", ctx.NewResource.GetName())
}
2020-12-23 23:10:07 +00:00
return logger
}
func buildResponse(logger logr.Logger, ctx *PolicyContext, resp *response.EngineResponse, startTime time.Time) {
if reflect.DeepEqual(resp, response.EngineResponse{}) {
return
2019-09-03 22:48:13 +00:00
}
2020-12-23 23:10:07 +00:00
if reflect.DeepEqual(resp.PatchedResource, unstructured.Unstructured{}) {
// for delete requests patched resource will be oldResource since newResource is empty
2020-12-24 02:51:07 +00:00
var resource unstructured.Unstructured = ctx.NewResource
2020-12-23 23:10:07 +00:00
if reflect.DeepEqual(ctx.NewResource, unstructured.Unstructured{}) {
resource = ctx.OldResource
}
2020-12-24 02:51:07 +00:00
resp.PatchedResource = resource
2020-05-05 13:49:47 +00:00
}
2020-05-05 15:28:02 +00:00
resp.PolicyResponse.Policy.Name = ctx.Policy.GetName()
resp.PolicyResponse.Policy.Namespace = ctx.Policy.GetNamespace()
2020-12-24 02:51:07 +00:00
resp.PolicyResponse.Resource.Name = resp.PatchedResource.GetName()
resp.PolicyResponse.Resource.Namespace = resp.PatchedResource.GetNamespace()
resp.PolicyResponse.Resource.Kind = resp.PatchedResource.GetKind()
resp.PolicyResponse.Resource.APIVersion = resp.PatchedResource.GetAPIVersion()
2020-12-24 02:46:12 +00:00
resp.PolicyResponse.ValidationFailureAction = ctx.Policy.Spec.ValidationFailureAction
resp.PolicyResponse.ProcessingTime = time.Since(startTime)
resp.PolicyResponse.PolicyExecutionTimestamp = startTime.Unix()
}
func incrementAppliedCount(resp *response.EngineResponse) {
resp.PolicyResponse.RulesAppliedCount++
}
2020-12-23 23:10:07 +00:00
func validateResource(log logr.Logger, ctx *PolicyContext) *response.EngineResponse {
resp := &response.EngineResponse{}
2020-12-23 23:10:07 +00:00
if ManagedPodResource(ctx.Policy, ctx.NewResource) {
log.V(5).Info("skip policy as direct changes to pods managed by workload controllers are not allowed", "policy", ctx.Policy.GetName())
return resp
}
2020-12-23 23:10:07 +00:00
ctx.JSONContext.Checkpoint()
defer ctx.JSONContext.Restore()
2020-12-23 23:10:07 +00:00
for _, rule := range ctx.Policy.Spec.Rules {
var err error
2019-10-21 21:22:31 +00:00
if !rule.HasValidate() {
2019-09-03 22:48:13 +00:00
continue
}
2019-11-12 05:06:09 +00:00
log = log.WithValues("rule", rule.Name)
if !matches(log, rule, ctx) {
continue
}
ctx.JSONContext.Restore()
if err := LoadContext(log, rule.Context, ctx.ResourceCache, ctx, rule.Name); err != nil {
if _, ok := err.(gojmespath.NotFoundError); ok {
log.V(3).Info("failed to load context", "reason", err.Error())
} else {
log.Error(err, "failed to load context")
}
2019-09-03 22:48:13 +00:00
continue
}
593 feature (#594) * initial commit * background policy validation * correct message * skip non-background policy process for add/update * add Generate Request CR * generate Request Generator Initial * test generate request CR generation * initial commit gr generator * generate controller initial framework * add crd for generate request * gr cleanup controller initial commit * cleanup controller initial * generate mid-commit * generate rule processing * create PV on generate error * embed resource type * testing phase 1- generate resources with variable substitution * fix tests * comment broken test #586 * add printer column for state * return if existing resource for clone * set resync time to 2 mins & remove resource version check in update handler for gr * generate events for reporting * fix logs * initial commit * fix trailing quote in patch * remove comments * initial condition (equal & notequal) * initial support for conditions * initial support fo conditions in generate * support precondition checks * cleanup * re-evaluate GR on namespace update using dynamic informers * add status for generated resources * display loaded variable SA * support delete cleanup of generate request main resources * fix log * remove namespace from SA username * support multiple variables per statement for scalar values * fix fail variables * add check for userInfo * validation checks for conditions * update policy * refactor logs * code review * add openapispec for clusterpolicy preconditions * Update documentation * CR fixes * documentation * CR fixes * update variable * fix logs * update policy * pre-defined variables (serviceAccountName & serviceAccountNamespace) * update test
2020-01-07 23:13:57 +00:00
log.V(3).Info("matched validate rule")
ruleCopy := rule.DeepCopy()
ruleCopy.AnyAllConditions, err = variables.SubstituteAllInPreconditions(log, ctx.JSONContext, ruleCopy.AnyAllConditions)
if err != nil {
log.V(4).Info("failed to substitute vars in preconditions, skip current rule", "rule name", rule.Name)
return nil
}
preconditions, err := transformConditions(ruleCopy.AnyAllConditions)
if err != nil {
log.V(2).Info("wrongfully configured data", "reason", err.Error())
continue
}
Feature/cosign (#2078) * add image verification * inline policy list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * cosign version and dependencies updates Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add registry initialization Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add build tag to exclude k8schain for cloud providers Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add build tag to exclude k8schain for cloud providers Signed-off-by: Jim Bugwadia <jim@nirmata.com> * generate deep copy and other fixtures Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix deep copy issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * mutate images to add digest Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add certificates to Kyverno container for HTTPS lookups Signed-off-by: Jim Bugwadia <jim@nirmata.com> * align flag syntax Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update docs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update dependencies Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update dependencies Signed-off-by: Jim Bugwadia <jim@nirmata.com> * patch image with digest and fix checks Signed-off-by: Jim Bugwadia <jim@nirmata.com> * hardcode image for demos Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add default registry (docker.io) before calling reference.Parse Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix definition Signed-off-by: Jim Bugwadia <jim@nirmata.com> * increase webhook timeout Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix args Signed-off-by: Jim Bugwadia <jim@nirmata.com> * run gofmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * rename for clarity Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix HasImageVerify check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * align make test commands Signed-off-by: Jim Bugwadia <jim@nirmata.com> * align make test commands Signed-off-by: Jim Bugwadia <jim@nirmata.com> * align make test commands Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter error Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * handle API conflict and retry Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix reviewdog issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix make for unit tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * improve error message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix durations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * handle errors in tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * print policy name Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add retries and duration to error log Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix time check in tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * round creation times in test Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix retry loop Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove timing check for policy creation Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix e2e error - policy not found Signed-off-by: Shuting Zhao <shutting06@gmail.com> * update string comparison method Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix test Generate_Namespace_Label_Actions Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add debug info for e2e tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix error Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix generate bug Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add check for update operations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * increase time for deleteing a resource Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix check Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Shuting Zhao <shutting06@gmail.com>
2021-07-10 01:01:46 +00:00
2020-12-23 23:10:07 +00:00
// evaluate pre-conditions
if !variables.EvaluateConditions(log, ctx.JSONContext, preconditions) {
2020-03-17 18:05:20 +00:00
log.V(4).Info("resource fails the preconditions")
593 feature (#594) * initial commit * background policy validation * correct message * skip non-background policy process for add/update * add Generate Request CR * generate Request Generator Initial * test generate request CR generation * initial commit gr generator * generate controller initial framework * add crd for generate request * gr cleanup controller initial commit * cleanup controller initial * generate mid-commit * generate rule processing * create PV on generate error * embed resource type * testing phase 1- generate resources with variable substitution * fix tests * comment broken test #586 * add printer column for state * return if existing resource for clone * set resync time to 2 mins & remove resource version check in update handler for gr * generate events for reporting * fix logs * initial commit * fix trailing quote in patch * remove comments * initial condition (equal & notequal) * initial support for conditions * initial support fo conditions in generate * support precondition checks * cleanup * re-evaluate GR on namespace update using dynamic informers * add status for generated resources * display loaded variable SA * support delete cleanup of generate request main resources * fix log * remove namespace from SA username * support multiple variables per statement for scalar values * fix fail variables * add check for userInfo * validation checks for conditions * update policy * refactor logs * code review * add openapispec for clusterpolicy preconditions * Update documentation * CR fixes * documentation * CR fixes * update variable * fix logs * update policy * pre-defined variables (serviceAccountName & serviceAccountNamespace) * update test
2020-01-07 23:13:57 +00:00
continue
}
if rule.Validation.Pattern != nil || rule.Validation.AnyPattern != nil {
if *ruleCopy, err = substituteAll(log, ctx, *ruleCopy, resp); err != nil {
continue
}
ruleResponse := validateResourceWithRule(log, ctx, *ruleCopy)
if ruleResponse != nil {
if !common.IsConditionalAnchorError(ruleResponse.Message) {
incrementAppliedCount(resp)
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResponse)
}
2020-12-23 23:10:07 +00:00
}
} else if rule.Validation.Deny != nil {
ruleCopy.Validation.Deny.AnyAllConditions, err = variables.SubstituteAllInPreconditions(log, ctx.JSONContext, ruleCopy.Validation.Deny.AnyAllConditions)
if err != nil {
log.V(4).Info("failed to substitute vars in preconditions, skip current rule", "rule name", rule.Name)
continue
}
if *ruleCopy, err = substituteAll(log, ctx, *ruleCopy, resp); err != nil {
continue
}
denyConditions, err := transformConditions(ruleCopy.Validation.Deny.AnyAllConditions)
if err != nil {
log.V(2).Info("wrongfully configured data", "reason", err.Error())
continue
}
deny := variables.EvaluateConditions(log, ctx.JSONContext, denyConditions)
2020-12-23 23:10:07 +00:00
ruleResp := response.RuleResponse{
Name: ruleCopy.Name,
2020-12-23 23:10:07 +00:00
Type: utils.Validation.String(),
Message: ruleCopy.Validation.Message,
2020-12-23 23:10:07 +00:00
Success: !deny,
2020-04-14 15:17:12 +00:00
}
2020-12-23 23:10:07 +00:00
incrementAppliedCount(resp)
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, ruleResp)
}
2020-05-05 13:49:47 +00:00
}
2020-12-23 23:10:07 +00:00
2020-05-05 13:49:47 +00:00
return resp
}
func validateResourceWithRule(log logr.Logger, ctx *PolicyContext, rule kyverno.Rule) (resp *response.RuleResponse) {
2020-12-23 23:10:07 +00:00
if reflect.DeepEqual(ctx.OldResource, unstructured.Unstructured{}) {
resp := validatePatterns(log, ctx.JSONContext, ctx.NewResource, rule)
return &resp
}
if reflect.DeepEqual(ctx.NewResource, unstructured.Unstructured{}) {
log.V(3).Info("skipping validation on deleted resource")
return nil
}
2020-12-23 23:10:07 +00:00
oldResp := validatePatterns(log, ctx.JSONContext, ctx.OldResource, rule)
newResp := validatePatterns(log, ctx.JSONContext, ctx.NewResource, rule)
if isSameRuleResponse(oldResp, newResp) {
log.V(3).Info("skipping modified resource as validation results have not changed")
return nil
}
return &newResp
2020-12-23 23:10:07 +00:00
}
2020-05-05 13:49:47 +00:00
2020-12-23 23:10:07 +00:00
// matches checks if either the new or old resource satisfies the filter conditions defined in the rule
func matches(logger logr.Logger, rule kyverno.Rule, ctx *PolicyContext) bool {
err := MatchesResourceDescription(ctx.NewResource, rule, ctx.AdmissionInfo, ctx.ExcludeGroupRole, ctx.NamespaceLabels)
2020-12-23 23:10:07 +00:00
if err == nil {
return true
}
2020-12-23 23:10:07 +00:00
if !reflect.DeepEqual(ctx.OldResource, unstructured.Unstructured{}) {
err := MatchesResourceDescription(ctx.OldResource, rule, ctx.AdmissionInfo, ctx.ExcludeGroupRole, ctx.NamespaceLabels)
2020-12-23 23:10:07 +00:00
if err == nil {
return true
2019-09-03 22:48:13 +00:00
}
}
logger.V(4).Info("resource does not match rule", "reason", err.Error())
2020-12-23 23:10:07 +00:00
return false
}
2020-12-23 23:10:07 +00:00
func isSameRuleResponse(r1 response.RuleResponse, r2 response.RuleResponse) bool {
if r1.Name != r2.Name {
return false
}
2020-12-23 23:10:07 +00:00
if r1.Type != r2.Type {
return false
}
2020-12-23 23:10:07 +00:00
if r1.Message != r2.Message {
return false
}
2020-12-23 23:10:07 +00:00
if r1.Success != r2.Success {
return false
}
return true
2019-09-03 22:48:13 +00:00
}
2019-08-21 19:38:15 +00:00
// validatePatterns validate pattern and anyPattern
2020-03-17 18:05:20 +00:00
func validatePatterns(log logr.Logger, ctx context.EvalInterface, resource unstructured.Unstructured, rule kyverno.Rule) (resp response.RuleResponse) {
2019-08-24 01:34:23 +00:00
startTime := time.Now()
logger := log.WithValues("rule", rule.Name, "name", resource.GetName(), "kind", resource.GetKind())
logger.V(5).Info("start processing rule", "startTime", startTime)
resp.Name = rule.Name
resp.Type = utils.Validation.String()
2019-08-24 01:34:23 +00:00
defer func() {
resp.RuleStats.ProcessingTime = time.Since(startTime)
resp.RuleStats.RuleExecutionTimestamp = startTime.Unix()
logger.V(4).Info("finished processing rule", "processingTime", resp.RuleStats.ProcessingTime.String())
2019-08-24 01:34:23 +00:00
}()
2020-02-14 19:59:28 +00:00
validationRule := rule.Validation.DeepCopy()
if validationRule.Pattern != nil {
pattern := validationRule.Pattern
2020-03-17 18:05:20 +00:00
if path, err := validate.ValidateResourceWithPattern(logger, resource.Object, pattern); err != nil {
logger.V(3).Info("validation failed", "path", path, "error", err.Error())
2020-02-14 19:59:28 +00:00
resp.Success = false
resp.Message = buildErrorMessage(rule, path)
2020-02-14 19:59:28 +00:00
return resp
}
2020-03-17 18:05:20 +00:00
logger.V(4).Info("successfully processed rule")
resp.Success = true
resp.Message = fmt.Sprintf("validation rule '%s' passed.", rule.Name)
return resp
}
2020-02-14 19:59:28 +00:00
if validationRule.AnyPattern != nil {
var failedAnyPatternsErrors []error
var err error
2020-11-14 00:25:51 +00:00
anyPatterns, err := rule.Validation.DeserializeAnyPattern()
if err != nil {
resp.Success = false
resp.Message = fmt.Sprintf("failed to deserialize anyPattern, expected type array: %v", err)
2020-11-14 00:25:51 +00:00
return resp
}
for idx, pattern := range anyPatterns {
path, err := validate.ValidateResourceWithPattern(logger, resource.Object, pattern)
2020-02-14 19:59:28 +00:00
if err == nil {
resp.Success = true
resp.Message = fmt.Sprintf("validation rule '%s' anyPattern[%d] passed.", rule.Name, idx)
return resp
}
logger.V(4).Info("validation rule failed", "anyPattern[%d]", idx, "path", path)
patternErr := fmt.Errorf("Rule %s[%d] failed at path %s.", rule.Name, idx, path)
2020-02-14 19:59:28 +00:00
failedAnyPatternsErrors = append(failedAnyPatternsErrors, patternErr)
}
2020-02-14 19:59:28 +00:00
// Any Pattern validation errors
if len(failedAnyPatternsErrors) > 0 {
var errorStr []string
for _, err := range failedAnyPatternsErrors {
errorStr = append(errorStr, err.Error())
}
log.V(4).Info(fmt.Sprintf("Validation rule '%s' failed. %s", rule.Name, errorStr))
resp.Success = false
resp.Message = buildAnyPatternErrorMessage(rule, errorStr)
2020-02-14 19:59:28 +00:00
return resp
}
2019-08-21 19:38:15 +00:00
}
return resp
}
func buildErrorMessage(rule kyverno.Rule, path string) string {
if rule.Validation.Message == "" {
return fmt.Sprintf("validation error: rule %s failed at path %s", rule.Name, path)
}
if strings.HasSuffix(rule.Validation.Message, ".") {
return fmt.Sprintf("validation error: %s Rule %s failed at path %s", rule.Validation.Message, rule.Name, path)
}
return fmt.Sprintf("validation error: %s. Rule %s failed at path %s", rule.Validation.Message, rule.Name, path)
}
func buildAnyPatternErrorMessage(rule kyverno.Rule, errors []string) string {
errStr := strings.Join(errors, " ")
if rule.Validation.Message == "" {
return fmt.Sprintf("validation error: %s", errStr)
}
if strings.HasSuffix(rule.Validation.Message, ".") {
return fmt.Sprintf("validation error: %s %s", rule.Validation.Message, errStr)
}
return fmt.Sprintf("validation error: %s. %s", rule.Validation.Message, errStr)
}
func substituteAll(log logr.Logger, ctx *PolicyContext, rule kyverno.Rule, resp *response.EngineResponse) (kyverno.Rule, error) {
var err error
if rule, err = variables.SubstituteAllInRule(log, ctx.JSONContext, rule); err != nil {
ruleResp := response.RuleResponse{
Name: rule.Name,
Type: utils.Validation.String(),
Message: fmt.Sprintf("variable substitution failed for rule %s: %s", rule.Name, err.Error()),
Success: true,
}
incrementAppliedCount(resp)
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, ruleResp)
switch err.(type) {
case gojmespath.NotFoundError:
log.V(2).Info("failed to substitute variables, skip current rule", "info", err.Error(), "rule name", rule.Name)
default:
log.Error(err, "failed to substitute variables, skip current rule", "rule name", rule.Name)
}
return rule, err
}
return rule, nil
}