diff --git a/pkg/event/events.go b/pkg/event/events.go index dd37fa73a0..f955262e46 100644 --- a/pkg/event/events.go +++ b/pkg/event/events.go @@ -125,3 +125,35 @@ func NewBackgroundSuccessEvent(policy, rule string, source Source, r *unstructur return events } + +func NewPolicyExceptionEvent(engineResponse *response.EngineResponse, ruleResp *response.RuleResponse) Info { + var messageBuilder strings.Builder + defer messageBuilder.Reset() + + exceptionName, exceptionNamespace := getExceptionEventInfoFromRuleResponseMsg(ruleResp.Message) + + fmt.Fprintf(&messageBuilder, "resource %s was skipped from rule %s due to policy exception %s/%s", engineResponse.PatchedResource.GetName(), ruleResp.Name, exceptionNamespace, exceptionName) + + return Info{ + Kind: getPolicyKind(engineResponse.Policy), + Name: engineResponse.PolicyResponse.Policy.Name, + Namespace: engineResponse.PolicyResponse.Policy.Namespace, + Reason: PolicySkipped.String(), + Message: messageBuilder.String(), + } +} + +func getExceptionEventInfoFromRuleResponseMsg(message string) (name string, namespace string) { + key := message[strings.LastIndex(message, " ")+1:] + arr := strings.Split(key, "/") + + if len(arr) > 1 { + namespace = arr[0] + name = arr[1] + } else { + namespace = "" + name = arr[0] + } + + return name, namespace +} diff --git a/pkg/webhooks/utils/event.go b/pkg/webhooks/utils/event.go index 4c11a4f7ab..1163eddffd 100644 --- a/pkg/webhooks/utils/event.go +++ b/pkg/webhooks/utils/event.go @@ -1,6 +1,8 @@ package utils import ( + "strings" + "github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/event" ) @@ -34,6 +36,14 @@ func GenerateEvents(engineResponses []*response.EngineResponse, blocked bool) [] events = append(events, e) } } + } else if er.IsSkipped() { // Handle PolicyException Event + for i, ruleResp := range er.PolicyResponse.Rules { + isException := strings.Contains(ruleResp.Message, "rule skipped due to policy exception") + if ruleResp.Status == response.RuleStatusSkip && !blocked && isException { + e := event.NewPolicyExceptionEvent(er, &er.PolicyResponse.Rules[i]) + events = append(events, e) + } + } } else if !er.IsSkipped() { e := event.NewPolicyAppliedEvent(event.AdmissionController, er) events = append(events, e)