2019-05-14 01:17:28 +00:00
|
|
|
package engine
|
|
|
|
|
2019-05-14 15:10:25 +00:00
|
|
|
import (
|
2019-06-20 15:21:55 +00:00
|
|
|
"fmt"
|
|
|
|
"reflect"
|
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"
|
2019-11-13 21:41:08 +00:00
|
|
|
kyverno "github.com/nirmata/kyverno/pkg/api/kyverno/v1"
|
2019-12-31 01:08:50 +00:00
|
|
|
"github.com/nirmata/kyverno/pkg/engine/context"
|
|
|
|
"github.com/nirmata/kyverno/pkg/engine/response"
|
2020-01-08 01:06:17 +00:00
|
|
|
"github.com/nirmata/kyverno/pkg/engine/utils"
|
2019-12-31 01:08:50 +00:00
|
|
|
"github.com/nirmata/kyverno/pkg/engine/validate"
|
2020-01-07 23:13:57 +00:00
|
|
|
"github.com/nirmata/kyverno/pkg/engine/variables"
|
2019-08-13 18:32:12 +00:00
|
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
2020-03-17 23:25:34 +00:00
|
|
|
"sigs.k8s.io/controller-runtime/pkg/log"
|
2019-05-14 15:10:25 +00:00
|
|
|
)
|
|
|
|
|
2019-09-03 22:48:13 +00:00
|
|
|
//Validate applies validation rules from policy on the resource
|
2020-05-05 15:28:02 +00:00
|
|
|
func Validate(policyContext PolicyContext) (resp response.EngineResponse) {
|
2019-09-03 22:48:13 +00:00
|
|
|
startTime := time.Now()
|
2019-11-09 02:57:27 +00:00
|
|
|
policy := policyContext.Policy
|
2019-11-13 21:13:07 +00:00
|
|
|
newR := policyContext.NewResource
|
|
|
|
oldR := policyContext.OldResource
|
2019-12-31 01:08:50 +00:00
|
|
|
ctx := policyContext.Context
|
2019-11-13 21:13:07 +00:00
|
|
|
admissionInfo := policyContext.AdmissionInfo
|
2020-05-19 07:14:23 +00:00
|
|
|
logger := log.Log.WithName("Validate").WithValues("policy", policy.Name)
|
|
|
|
|
|
|
|
if reflect.DeepEqual(newR, unstructured.Unstructured{}) {
|
|
|
|
logger = logger.WithValues("kind", oldR.GetKind(), "namespace", oldR.GetNamespace(), "name", oldR.GetName())
|
|
|
|
} else {
|
|
|
|
logger = logger.WithValues("kind", newR.GetKind(), "namespace", newR.GetNamespace(), "name", newR.GetName())
|
|
|
|
}
|
|
|
|
|
2020-03-17 18:05:20 +00:00
|
|
|
logger.V(4).Info("start processing", "startTime", startTime)
|
2019-11-13 21:13:07 +00:00
|
|
|
|
2020-05-05 15:28:02 +00:00
|
|
|
defer func() {
|
|
|
|
if reflect.DeepEqual(resp, response.EngineResponse{}) {
|
|
|
|
return
|
|
|
|
}
|
2020-05-05 18:22:52 +00:00
|
|
|
var resource unstructured.Unstructured
|
2020-05-05 15:28:02 +00:00
|
|
|
if reflect.DeepEqual(resp.PatchedResource, unstructured.Unstructured{}) {
|
|
|
|
// for delete requests patched resource will be oldR since newR is empty
|
|
|
|
if reflect.DeepEqual(newR, unstructured.Unstructured{}) {
|
2020-05-05 18:22:52 +00:00
|
|
|
resource = oldR
|
2020-05-05 15:28:02 +00:00
|
|
|
} else {
|
2020-05-05 18:22:52 +00:00
|
|
|
resource = newR
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for i := range resp.PolicyResponse.Rules {
|
|
|
|
messageInterface, err := variables.SubstituteVars(logger, ctx, resp.PolicyResponse.Rules[i].Message)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
2020-05-05 15:28:02 +00:00
|
|
|
}
|
2020-05-05 18:22:52 +00:00
|
|
|
resp.PolicyResponse.Rules[i].Message, _ = messageInterface.(string)
|
2020-05-05 15:28:02 +00:00
|
|
|
}
|
2020-05-05 18:22:52 +00:00
|
|
|
resp.PatchedResource = resource
|
|
|
|
startResultResponse(&resp, policy, resource)
|
|
|
|
endResultResponse(logger, &resp, startTime)
|
2020-05-05 15:28:02 +00:00
|
|
|
}()
|
|
|
|
|
2020-05-07 09:08:15 +00:00
|
|
|
// If request is delete, newR will be empty
|
|
|
|
if reflect.DeepEqual(newR, unstructured.Unstructured{}) {
|
|
|
|
return *isRequestDenied(logger, ctx, policy, oldR, admissionInfo)
|
2020-06-24 17:26:04 +00:00
|
|
|
}
|
|
|
|
|
2020-06-30 18:53:27 +00:00
|
|
|
if denyResp := isRequestDenied(logger, ctx, policy, newR, admissionInfo); !denyResp.IsSuccessful() {
|
2020-06-24 17:26:04 +00:00
|
|
|
return *denyResp
|
2019-09-03 22:48:13 +00:00
|
|
|
}
|
2020-04-22 14:45:16 +00:00
|
|
|
|
2020-05-05 13:49:47 +00:00
|
|
|
if reflect.DeepEqual(oldR, unstructured.Unstructured{}) {
|
2020-05-05 15:28:02 +00:00
|
|
|
return *validateResource(logger, ctx, policy, newR, admissionInfo)
|
2020-05-05 13:49:47 +00:00
|
|
|
}
|
2020-05-05 15:28:02 +00:00
|
|
|
|
2020-05-05 13:49:47 +00:00
|
|
|
oldResponse := validateResource(logger, ctx, policy, oldR, admissionInfo)
|
|
|
|
newResponse := validateResource(logger, ctx, policy, newR, admissionInfo)
|
|
|
|
if !isSameResponse(oldResponse, newResponse) {
|
|
|
|
return *newResponse
|
2019-11-13 21:13:07 +00:00
|
|
|
}
|
2020-05-05 13:49:47 +00:00
|
|
|
return response.EngineResponse{}
|
2019-11-13 21:13:07 +00:00
|
|
|
}
|
|
|
|
|
2020-01-10 01:44:11 +00:00
|
|
|
func startResultResponse(resp *response.EngineResponse, policy kyverno.ClusterPolicy, newR unstructured.Unstructured) {
|
|
|
|
// set policy information
|
|
|
|
resp.PolicyResponse.Policy = policy.Name
|
|
|
|
// resource details
|
|
|
|
resp.PolicyResponse.Resource.Name = newR.GetName()
|
|
|
|
resp.PolicyResponse.Resource.Namespace = newR.GetNamespace()
|
|
|
|
resp.PolicyResponse.Resource.Kind = newR.GetKind()
|
|
|
|
resp.PolicyResponse.Resource.APIVersion = newR.GetAPIVersion()
|
|
|
|
resp.PolicyResponse.ValidationFailureAction = policy.Spec.ValidationFailureAction
|
|
|
|
}
|
|
|
|
|
2020-03-17 18:05:20 +00:00
|
|
|
func endResultResponse(log logr.Logger, resp *response.EngineResponse, startTime time.Time) {
|
2020-01-10 01:44:11 +00:00
|
|
|
resp.PolicyResponse.ProcessingTime = time.Since(startTime)
|
2020-03-17 18:05:20 +00:00
|
|
|
log.V(4).Info("finshed processing", "processingTime", resp.PolicyResponse.ProcessingTime, "validationRulesApplied", resp.PolicyResponse.RulesAppliedCount)
|
2020-01-10 01:44:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func incrementAppliedCount(resp *response.EngineResponse) {
|
2020-01-24 20:05:53 +00:00
|
|
|
// rules applied successfully count
|
2020-01-10 01:44:11 +00:00
|
|
|
resp.PolicyResponse.RulesAppliedCount++
|
|
|
|
}
|
|
|
|
|
2020-05-05 13:49:47 +00:00
|
|
|
func isRequestDenied(log logr.Logger, ctx context.EvalInterface, policy kyverno.ClusterPolicy, resource unstructured.Unstructured, admissionInfo kyverno.RequestInfo) *response.EngineResponse {
|
2019-12-31 01:08:50 +00:00
|
|
|
resp := &response.EngineResponse{}
|
2020-05-07 09:08:15 +00:00
|
|
|
|
2019-09-03 22:48:13 +00:00
|
|
|
for _, rule := range policy.Spec.Rules {
|
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
|
|
|
|
2020-02-07 09:15:43 +00:00
|
|
|
if err := MatchesResourceDescription(resource, rule, admissionInfo); err != nil {
|
2020-05-19 07:14:23 +00:00
|
|
|
log.V(4).Info("resource fails the match description", "reason", err.Error())
|
2019-09-03 22:48:13 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-01-07 23:13:57 +00:00
|
|
|
|
2020-04-14 15:17:12 +00:00
|
|
|
preconditionsCopy := copyConditions(rule.Conditions)
|
2020-05-05 13:49:47 +00:00
|
|
|
|
2020-04-14 15:17:12 +00:00
|
|
|
if !variables.EvaluateConditions(log, ctx, preconditionsCopy) {
|
2020-03-17 18:05:20 +00:00
|
|
|
log.V(4).Info("resource fails the preconditions")
|
2020-01-07 23:13:57 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-04-14 15:17:12 +00:00
|
|
|
if rule.Validation.Deny != nil {
|
2020-04-18 12:56:09 +00:00
|
|
|
denyConditionsCopy := copyConditions(rule.Validation.Deny.Conditions)
|
2020-05-06 14:16:32 +00:00
|
|
|
if len(rule.Validation.Deny.Conditions) == 0 || variables.EvaluateConditions(log, ctx, denyConditionsCopy) {
|
2020-04-14 15:17:12 +00:00
|
|
|
ruleResp := response.RuleResponse{
|
|
|
|
Name: rule.Name,
|
|
|
|
Type: utils.Validation.String(),
|
|
|
|
Message: rule.Validation.Message,
|
|
|
|
Success: false,
|
|
|
|
}
|
|
|
|
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, ruleResp)
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-05-05 13:49:47 +00:00
|
|
|
}
|
|
|
|
return resp
|
|
|
|
}
|
|
|
|
|
|
|
|
func validateResource(log logr.Logger, ctx context.EvalInterface, policy kyverno.ClusterPolicy, resource unstructured.Unstructured, admissionInfo kyverno.RequestInfo) *response.EngineResponse {
|
|
|
|
resp := &response.EngineResponse{}
|
2020-06-24 17:26:04 +00:00
|
|
|
|
2020-06-25 16:52:54 +00:00
|
|
|
if autoGenAnnotationApplied(resource) && policy.HasAutoGenAnnotation() {
|
2020-06-24 17:26:04 +00:00
|
|
|
return resp
|
|
|
|
}
|
|
|
|
|
2020-05-05 13:49:47 +00:00
|
|
|
for _, rule := range policy.Spec.Rules {
|
|
|
|
if !rule.HasValidate() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// check if the resource satisfies the filter conditions defined in the rule
|
|
|
|
// TODO: this needs to be extracted, to filter the resource so that we can avoid passing resources that
|
2020-05-19 20:04:06 +00:00
|
|
|
// dont satisfy a policy rule resource description
|
2020-05-05 13:49:47 +00:00
|
|
|
if err := MatchesResourceDescription(resource, rule, admissionInfo); err != nil {
|
2020-05-19 00:11:08 +00:00
|
|
|
log.V(4).Info("resource fails the match description", "reason", err.Error())
|
2020-05-05 13:49:47 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// operate on the copy of the conditions, as we perform variable substitution
|
|
|
|
preconditionsCopy := copyConditions(rule.Conditions)
|
|
|
|
// evaluate pre-conditions
|
|
|
|
// - handle variable subsitutions
|
|
|
|
if !variables.EvaluateConditions(log, ctx, preconditionsCopy) {
|
|
|
|
log.V(4).Info("resource fails the preconditions")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if rule.Validation.Pattern != nil || rule.Validation.AnyPattern != nil {
|
|
|
|
ruleResponse := validatePatterns(log, ctx, resource, rule)
|
|
|
|
incrementAppliedCount(resp)
|
|
|
|
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, ruleResponse)
|
2019-09-03 22:48:13 +00:00
|
|
|
}
|
2020-04-22 14:45:16 +00:00
|
|
|
|
2019-09-03 22:48:13 +00:00
|
|
|
}
|
2019-12-31 01:08:50 +00:00
|
|
|
return resp
|
2019-11-13 21:13:07 +00:00
|
|
|
}
|
2019-10-16 03:56:41 +00:00
|
|
|
|
2019-12-31 01:08:50 +00:00
|
|
|
func isSameResponse(oldResponse, newResponse *response.EngineResponse) bool {
|
2020-01-24 20:05:53 +00:00
|
|
|
// if the response are same then return true
|
2019-11-13 21:13:07 +00:00
|
|
|
return isSamePolicyResponse(oldResponse.PolicyResponse, newResponse.PolicyResponse)
|
2019-10-16 03:56:41 +00:00
|
|
|
|
2019-11-13 21:13:07 +00:00
|
|
|
}
|
|
|
|
|
2019-12-31 01:08:50 +00:00
|
|
|
func isSamePolicyResponse(oldPolicyRespone, newPolicyResponse response.PolicyResponse) bool {
|
2019-11-13 21:13:07 +00:00
|
|
|
// can skip policy and resource checks as they will be same
|
|
|
|
// compare rules
|
|
|
|
return isSameRules(oldPolicyRespone.Rules, newPolicyResponse.Rules)
|
|
|
|
}
|
|
|
|
|
2019-12-31 01:08:50 +00:00
|
|
|
func isSameRules(oldRules []response.RuleResponse, newRules []response.RuleResponse) bool {
|
2019-11-13 21:13:07 +00:00
|
|
|
if len(oldRules) != len(newRules) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// as the rules are always processed in order the indices wil be same
|
|
|
|
for idx, oldrule := range oldRules {
|
|
|
|
newrule := newRules[idx]
|
|
|
|
// Name
|
|
|
|
if oldrule.Name != newrule.Name {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// Type
|
|
|
|
if oldrule.Type != newrule.Type {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// Message
|
|
|
|
if oldrule.Message != newrule.Message {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// skip patches
|
|
|
|
if oldrule.Success != newrule.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()
|
2020-03-17 18:05:20 +00:00
|
|
|
logger := log.WithValues("rule", rule.Name)
|
|
|
|
logger.V(4).Info("start processing rule", "startTime", startTime)
|
2019-12-31 01:08:50 +00:00
|
|
|
resp.Name = rule.Name
|
2020-01-08 01:06:17 +00:00
|
|
|
resp.Type = utils.Validation.String()
|
2019-08-24 01:34:23 +00:00
|
|
|
defer func() {
|
2019-12-31 01:08:50 +00:00
|
|
|
resp.RuleStats.ProcessingTime = time.Since(startTime)
|
2020-05-26 17:36:56 +00:00
|
|
|
logger.V(4).Info("finished processing rule", "processingTime", resp.RuleStats.ProcessingTime)
|
2019-08-24 01:34:23 +00:00
|
|
|
}()
|
2020-05-26 17:36:56 +00:00
|
|
|
|
2020-02-14 19:59:28 +00:00
|
|
|
// work on a copy of validation rule
|
|
|
|
validationRule := rule.Validation.DeepCopy()
|
2019-08-09 19:59:37 +00:00
|
|
|
|
2019-08-24 01:34:23 +00:00
|
|
|
// either pattern or anyPattern can be specified in Validation rule
|
2020-02-14 19:59:28 +00:00
|
|
|
if validationRule.Pattern != nil {
|
|
|
|
// substitute variables in the pattern
|
|
|
|
pattern := validationRule.Pattern
|
|
|
|
var err error
|
2020-03-17 18:05:20 +00:00
|
|
|
if pattern, err = variables.SubstituteVars(logger, ctx, pattern); err != nil {
|
2020-02-14 19:59:28 +00:00
|
|
|
// variable subsitution failed
|
|
|
|
resp.Success = false
|
|
|
|
resp.Message = fmt.Sprintf("Validation error: %s; Validation rule '%s' failed. '%s'",
|
|
|
|
rule.Validation.Message, rule.Name, err)
|
2019-12-31 01:08:50 +00:00
|
|
|
return resp
|
2019-06-26 01:16:02 +00:00
|
|
|
}
|
2020-01-10 01:44:11 +00:00
|
|
|
|
2020-03-17 18:05:20 +00:00
|
|
|
if path, err := validate.ValidateResourceWithPattern(logger, resource.Object, pattern); err != nil {
|
2020-02-14 19:59:28 +00:00
|
|
|
// validation failed
|
|
|
|
resp.Success = false
|
2020-05-20 20:43:12 +00:00
|
|
|
resp.Message = fmt.Sprintf("Validation error: %s; Validation rule %s failed at path %s",
|
2020-02-14 19:59:28 +00:00
|
|
|
rule.Validation.Message, rule.Name, path)
|
|
|
|
return resp
|
|
|
|
}
|
2020-01-24 20:05:53 +00:00
|
|
|
// rule application successful
|
2020-03-17 18:05:20 +00:00
|
|
|
logger.V(4).Info("successfully processed rule")
|
2019-12-31 01:08:50 +00:00
|
|
|
resp.Success = true
|
|
|
|
resp.Message = fmt.Sprintf("Validation rule '%s' succeeded.", rule.Name)
|
|
|
|
return resp
|
2019-05-14 15:10:25 +00:00
|
|
|
}
|
|
|
|
|
2020-02-14 19:59:28 +00:00
|
|
|
if validationRule.AnyPattern != nil {
|
|
|
|
var failedSubstitutionsErrors []error
|
|
|
|
var failedAnyPatternsErrors []error
|
|
|
|
var err error
|
|
|
|
for idx, pattern := range validationRule.AnyPattern {
|
2020-03-17 18:05:20 +00:00
|
|
|
if pattern, err = variables.SubstituteVars(logger, ctx, pattern); err != nil {
|
2020-02-14 19:59:28 +00:00
|
|
|
// variable subsitution failed
|
|
|
|
failedSubstitutionsErrors = append(failedSubstitutionsErrors, err)
|
|
|
|
continue
|
|
|
|
}
|
2020-03-17 18:05:20 +00:00
|
|
|
_, err := validate.ValidateResourceWithPattern(logger, resource.Object, pattern)
|
2020-02-14 19:59:28 +00:00
|
|
|
if err == nil {
|
2019-12-31 01:08:50 +00:00
|
|
|
resp.Success = true
|
2020-02-14 19:59:28 +00:00
|
|
|
resp.Message = fmt.Sprintf("Validation rule '%s' anyPattern[%d] succeeded.", rule.Name, idx)
|
2019-12-31 01:08:50 +00:00
|
|
|
return resp
|
2019-09-05 19:44:38 +00:00
|
|
|
}
|
2020-03-17 18:05:20 +00:00
|
|
|
logger.V(4).Info(fmt.Sprintf("validation rule failed for anyPattern[%d]", idx), "message", rule.Validation.Message)
|
2020-02-14 19:59:28 +00:00
|
|
|
patternErr := fmt.Errorf("anyPattern[%d] failed; %s", idx, err)
|
|
|
|
failedAnyPatternsErrors = append(failedAnyPatternsErrors, patternErr)
|
2019-09-05 19:44:38 +00:00
|
|
|
}
|
2019-11-05 01:54:06 +00:00
|
|
|
|
2020-02-14 19:59:28 +00:00
|
|
|
// Subsitution falures
|
|
|
|
if len(failedSubstitutionsErrors) > 0 {
|
|
|
|
resp.Success = false
|
2020-02-27 00:41:48 +00:00
|
|
|
resp.Message = fmt.Sprintf("Substitutions failed: %v", failedSubstitutionsErrors)
|
2019-12-31 01:08:50 +00:00
|
|
|
return resp
|
2019-08-21 19:38:15 +00:00
|
|
|
}
|
2020-01-10 01:44:11 +00:00
|
|
|
|
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())
|
|
|
|
}
|
|
|
|
resp.Success = false
|
2020-03-20 18:43:21 +00:00
|
|
|
log.V(4).Info(fmt.Sprintf("Validation rule '%s' failed. %s", rule.Name, errorStr))
|
2020-03-16 08:38:13 +00:00
|
|
|
if rule.Validation.Message == "" {
|
|
|
|
resp.Message = fmt.Sprintf("Validation rule '%s' has failed", rule.Name)
|
|
|
|
} else {
|
|
|
|
resp.Message = rule.Validation.Message
|
|
|
|
}
|
2020-02-14 19:59:28 +00:00
|
|
|
return resp
|
2020-01-10 01:44:11 +00:00
|
|
|
}
|
2019-08-21 19:38:15 +00:00
|
|
|
}
|
2019-12-31 01:08:50 +00:00
|
|
|
return response.RuleResponse{}
|
2019-05-15 16:25:49 +00:00
|
|
|
}
|