From 408c00ae93f261d8c9b76b34b3f85ca02dfa3afb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Charles-Edouard=20Br=C3=A9t=C3=A9ch=C3=A9?=
 <charles.edouard@nirmata.com>
Date: Wed, 31 May 2023 16:05:49 +0200
Subject: [PATCH] fix: protect managed resource not considering other
 components (#7363)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
---
 pkg/webhooks/handlers/protect.go | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/pkg/webhooks/handlers/protect.go b/pkg/webhooks/handlers/protect.go
index 174fffa5de..4e5e08526e 100644
--- a/pkg/webhooks/handlers/protect.go
+++ b/pkg/webhooks/handlers/protect.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"errors"
 	"fmt"
+	"strings"
 	"time"
 
 	"github.com/go-logr/logr"
@@ -16,7 +17,7 @@ import (
 
 const namespaceControllerUsername = "system:serviceaccount:kube-system:namespace-controller"
 
-var kyvernoUsername = fmt.Sprintf("system:serviceaccount:%s:%s", config.KyvernoNamespace(), config.KyvernoServiceAccountName())
+var kyvernoUsernamePrefix = fmt.Sprintf("system:serviceaccount:%s:", config.KyvernoNamespace())
 
 func (inner AdmissionHandler) WithProtection(enabled bool) AdmissionHandler {
 	if !enabled {
@@ -39,7 +40,7 @@ func (inner AdmissionHandler) withProtection() AdmissionHandler {
 		for _, resource := range []unstructured.Unstructured{newResource, oldResource} {
 			resLabels := resource.GetLabels()
 			if resLabels[kyvernov1.LabelAppManagedBy] == kyvernov1.ValueKyvernoApp {
-				if request.UserInfo.Username != kyvernoUsername {
+				if !strings.HasPrefix(request.UserInfo.Username, kyvernoUsernamePrefix) {
 					logger.V(2).Info("access to the resource not authorized, this is a kyverno managed resource and should be altered only by kyverno")
 					return admissionutils.Response(request.UID, errors.New("A kyverno managed resource can only be modified by kyverno"))
 				}